Skip to content

Commit 0769131

Browse files
committed
Change the handling of out-of-bounds canvas
1 parent 3574b7b commit 0769131

File tree

2 files changed

+346
-78
lines changed
  • mosaic-runtime/src

2 files changed

+346
-78
lines changed

mosaic-runtime/src/commonMain/kotlin/com/jakewharton/mosaic/canvas.kt

+21-5
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,6 @@ internal interface TextCanvas {
2525
operator fun get(row: Int, column: Int): TextPixel
2626
}
2727

28-
private val blankPixel = TextPixel(' ')
29-
3028
internal class TextSurface(
3129
override val width: Int,
3230
override val height: Int,
@@ -37,19 +35,32 @@ internal class TextSurface(
3735

3836
private val cells = Array(width * height) { TextPixel(' ') }
3937

38+
/**
39+
* It is used in places where the [TextPixel] state is not important
40+
* and it can change.
41+
*/
42+
private val reusableDirtyPixel: TextPixel = newBlankPixel
43+
44+
/**
45+
* It is used in places where it is important that the [TextPixel]
46+
* has its original state and **will not change**.
47+
*/
48+
private val reusableBlankPixel: TextPixel = newBlankPixel
49+
4050
override operator fun get(row: Int, column: Int): TextPixel {
4151
val x = translationX + column
4252
val y = row + translationY
43-
check(x in 0 until width)
44-
check(y in 0 until height)
53+
if (x >= width || y >= height || x < 0 || y < 0) {
54+
return reusableDirtyPixel
55+
}
4556
return cells[y * width + x]
4657
}
4758

4859
fun appendRowTo(appendable: Appendable, row: Int) {
4960
// Reused heap allocation for building ANSI attributes inside the loop.
5061
val attributes = mutableIntListOf()
5162

52-
var lastPixel = blankPixel
63+
var lastPixel = reusableBlankPixel
5364

5465
val rowStart = row * width
5566
val rowStop = rowStart + width
@@ -165,6 +176,11 @@ internal class TextSurface(
165176
}
166177
}
167178

179+
/**
180+
* Returns always a new blank [TextPixel].
181+
*/
182+
private inline val newBlankPixel: TextPixel get() = TextPixel(' ')
183+
168184
internal class TextPixel(var codePoint: Int) {
169185
var background: Color = Color.Unspecified
170186
var foreground: Color = Color.Unspecified

0 commit comments

Comments
 (0)