-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathText.kt
344 lines (313 loc) · 11.5 KB
/
Text.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
/*
* This file is part of PolyUI
* PolyUI - Fast and lightweight UI framework
* Copyright (C) 2023-2024 Polyfrost and its contributors.
* <https://polyfrost.org> <https://github.com/Polyfrost/polui-jvm>
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* PolyUI is licensed under the terms of version 3 of the GNU Lesser
* General Public License as published by the Free Software Foundation,
* AND the simple request that you adequately accredit us if you use PolyUI.
* See details here <https://github.com/Polyfrost/polyui-jvm/ACCREDITATION.md>.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License. If not, see <https://www.gnu.org/licenses/>.
*/
package org.polyfrost.polyui.component.impl
import org.jetbrains.annotations.ApiStatus
import org.polyfrost.polyui.PolyUI
import org.polyfrost.polyui.component.Component
import org.polyfrost.polyui.component.Drawable
import org.polyfrost.polyui.data.Font
import org.polyfrost.polyui.event.Event
import org.polyfrost.polyui.input.Translator
import org.polyfrost.polyui.renderer.Renderer
import org.polyfrost.polyui.unit.Align
import org.polyfrost.polyui.unit.AlignDefault
import org.polyfrost.polyui.unit.Vec2
import org.polyfrost.polyui.unit.by
import org.polyfrost.polyui.utils.*
open class Text(text: Translator.Text, font: Font? = null, fontSize: Float = 12f, at: Vec2 = Vec2.ZERO, alignment: Align = AlignDefault, visibleSize: Vec2 = Vec2.ZERO, focusable: Boolean = false, limited: Boolean = false, vararg children: Component?) :
Drawable(children = children, at, alignment, visibleSize = visibleSize, focusable = focusable) {
constructor(text: String, font: Font? = null, fontSize: Float = 12f, at: Vec2 = Vec2.ZERO, alignment: Align = AlignDefault, visibleSize: Vec2 = Vec2.ZERO, focusable: Boolean = false, limited: Boolean = false, vararg children: Component?) :
this(Translator.Text.Simple(text), font, fontSize, at, alignment, visibleSize, focusable, limited, children = children)
init {
require(fontSize > 0f) { "Font size must be greater than 0" }
if (limited) {
require(visibleSize.isPositive && visibleSize.y >= fontSize) { "visibleSize must be set and have a height larger than the fontSize" }
@Suppress("LeakingThis") // reason: this is safe as the only overrider is TextInput, and we don't do any unsafe operations
shouldScroll = false
}
}
/**
* Mode that this text was created in. Must be one of [UNLIMITED], [WRAP], [SCROLLING_SINGLE_LINE], [LIMITED_WRAP].
* @since 1.4.1
*/
protected val mode = if (!visibleSize.isPositive) UNLIMITED else if (limited) LIMITED else when (visibleSize.y) {
0f -> WRAP
fontSize -> SCROLLING_SINGLE_LINE
else -> LIMITED_WRAP
}
/**
* @since 1.0.6
*/
var strikethrough = false
/**
* @since 1.0.6
*/
var underline = false
// asm: initially it is a dummy object to save need for a field
// it is immediately overwritten by setup()
private var _text = text
set(value) {
if (field == value) return
field = value
if (initialized) updateTextBounds()
}
open var text: String
get() = _text.string
set(value) {
if (_text.string == value) return
val old = _text.string
_text.string = value
if (initialized) {
updateTextBounds()
if (hasListenersFor(Event.Change.Text::class.java)) {
val ev = Event.Change.Text(value)
accept(ev)
if (ev.cancelled) {
// fuck. never mind!
_text.string = old
updateTextBounds()
return
}
}
}
}
/**
* A list of the lines of this text, and their corresponding width.
*/
protected val lines = ArrayList<Line>(/* initialCapacity = */ when (mode) {
WRAP, LIMITED_WRAP, LIMITED -> (visibleSize.y / fontSize).toInt()
else -> 1
}
)
@ApiStatus.Internal
@get:JvmName("getFontOrNull")
@set:JvmName("setFontInternal")
var _font: Font? = font
set(value) {
if (field == value) return
field = value
if (initialized) updateTextBounds()
}
var font: Font
inline get() = _font ?: throw UninitializedPropertyAccessException("font")
set(value) {
_font = value
spacing = (font.lineSpacing - 1f) * fontSize
}
/**
* The weight of the [font].
*
* Setting of this value only works if this font is a member of a family.
* @since 1.0.7
*/
var fontWeight: Font.Weight
inline get() = font.weight
set(value) {
val fam = font.family
if (fam == null) {
PolyUI.LOGGER.error("cannot set font weight on $this: Font was not created in a family")
return
}
font = fam.get(value, italic)
}
/**
* `true` if [font] is italic
*
* Setting of this value only works if this font is a member of a family.
* @since 1.0.7
*/
var italic: Boolean
inline get() = font.italic
set(value) {
val fam = font.family
if (fam == null) {
PolyUI.LOGGER.error("cannot set italic on $this: Font was not created in a family")
return
}
font = fam.get(fontWeight, value)
}
/**
* Tracker for the unscaled [fontSize]. You should set this instead of font size in most cases.
* @since 1.2.0
*/
var uFontSize = fontSize
set(value) {
if (field == value) return
field = value
fontSize = if (initialized) value * (polyUI.size.y / polyUI.iSize.y) else value
if (_font != null) spacing = (font.lineSpacing - 1f) * value
}
/**
* Internal, scaled font size. You probably should be using [uFontSize] instead, as this is an internal object.
*/
@ApiStatus.Internal
var fontSize = fontSize
set(value) {
if (field == value) return
field = value
if (initialized) updateTextBounds()
}
protected var spacing = 0f
private set
override fun render() {
var y = this.y
val strikethrough = strikethrough
val underline = underline
lines.fastEach { (it, bounds) ->
val (width, height) = bounds
renderer.text(font, x, y, it, color, fontSize)
if (strikethrough) {
val hf = y + height / 2f
renderer.line(x, hf, x + width, hf, color, 1f)
}
if (underline) {
val ff = y + height - spacing - 2f
renderer.line(x, ff, x + width, ff, color, 1f)
}
y += height + spacing
}
}
override fun rescale0(scaleX: Float, scaleY: Float, withChildren: Boolean) {
super.rescale0(scaleX, scaleY, withChildren)
fontSize *= scaleY
}
@Suppress("deprecation_error")
override fun setup(polyUI: PolyUI): Boolean {
if (initialized) return false
palette = polyUI.colors.text.primary
if (_text !is Translator.Text.Dont) {
_text = if (_text is Translator.Text.Formatted) {
polyUI.translator.translate(_text.string, *(_text as Translator.Text.Formatted).args)
} else {
polyUI.translator.translate(_text.string)
}
// asm: in translation files \\n is used for new line for some reason
text = text.replace("\\n", "\n")
}
if (_font == null) font = polyUI.fonts.regular
updateTextBounds(polyUI.renderer)
super.setup(polyUI)
return true
}
open fun updateTextBounds(renderer: Renderer = this.renderer) {
lines.clear()
if (text.isEmpty()) {
lines.add(Line("", (1f by fontSize)))
width = 1f
height = fontSize
return
}
val mode = mode
val maxWidth = when (mode) {
LIMITED, WRAP, LIMITED_WRAP -> visibleSize.x
else -> 0f
}
text.wrap(maxWidth, renderer, font, fontSize, lines)
var w = 0f
var h = 0f
var i = 0
lines.fastEach { (str, bounds) ->
w = kotlin.math.max(w, bounds.x)
h += bounds.y + spacing
if (mode == LIMITED && h >= visibleSize.y - fontSize) {
h -= spacing
// safe to not re-measure as we know the bounds will contain it.
// also won't co-mod thanks to fastEach
lines[i] = Line(str.truncate(renderer, font, fontSize, w), bounds)
lines.cut(0, i)
width = w
height = h
visHeight = h
return
}
i++
}
h -= spacing
width = w
height = h
when (mode) {
WRAP -> visHeight = h
LIMITED_WRAP, SCROLLING_SINGLE_LINE -> tryMakeScrolling()
}
renders = renders
}
@Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("calculateSize")
override fun calculateSize(): Vec2 {
updateTextBounds()
return size
}
override fun fixVisibleSize() {
// due to how we use the scrolling mechanic, this method is not needed.
}
override fun debugString() =
"""
lines: ${lines.size}, mode=${getModeName(mode)}
underline=$underline; strike=$strikethrough; italic=$italic
font: ${font.resourcePath.substringAfterLast('/')}; size: $fontSize; weight: $fontWeight
"""
companion object Mode {
/**
* Text can expand without any limits.
*
* Specified by a `null` [Drawable.visibleSize].
* @since 1.4.1
*/
const val UNLIMITED: Byte = 0
/**
* Text can expand infinitely vertically, but has a horizontal (wrap) limit.
*
* Specified by a [Drawable.visibleSize] of `Vec2(wrapLimit, 0f)`
* @since 1.4.1
*/
const val WRAP: Byte = 1
/**
* [WRAP], but has a limited amount of vertical lines.
*
* Specified by a [Drawable.visibleSize] of `Vec2(wrapLimit, maxHeight)`
* @since 1.4.1
*/
const val LIMITED_WRAP: Byte = 2
/**
* A single line of text which will scroll indefinitely.
*
* Specified by a [Drawable.visibleSize] of `Vec2(width, fontSize)`
* @since 1.4.1
*/
const val SCROLLING_SINGLE_LINE: Byte = 3
/**
* Some text which is **not allowed to scroll**. It is instead trimmed using [truncate].
*/
const val LIMITED: Byte = 4
/**
* Return the name of the given constant.
*/
@JvmStatic
fun getModeName(mode: Byte) = when (mode) {
UNLIMITED -> "UNLIMITED"
WRAP -> "WRAP"
LIMITED_WRAP -> "LIMITED_WRAP"
SCROLLING_SINGLE_LINE -> "SCROLLING_SINGLE_LINE"
LIMITED -> "LIMITED"
else -> throw IllegalArgumentException("invalid mode $mode")
}
}
}