Updated all code that used deprecated Kotlin APIs.

This commit is contained in:
Daan Vanden Bosch 2021-05-11 17:51:26 +02:00
parent 89b88a0a2d
commit fab1f90975
28 changed files with 159 additions and 127 deletions

View File

@ -316,20 +316,20 @@ class LineTokenizer {
val ident = slice()
value = ident
if (ident.getCodePointAt(0) !in ('a'.toInt())..('z'.toInt())) {
if (ident.getCodePointAt(0) !in 'a'.code..'z'.code) {
type = Token.InvalidIdent
return
}
for (i in 1 until ident.length) {
when (ident.getCodePointAt(i)) {
in ('0'.toInt())..('9'.toInt()),
in ('a'.toInt())..('z'.toInt()),
('_').toInt(),
('=').toInt(),
('<').toInt(),
('>').toInt(),
('!').toInt(),
in '0'.code..'9'.code,
in 'a'.code..'z'.code,
'_'.code,
'='.code,
'<'.code,
'>'.code,
'!'.code,
-> {
// Valid character.
}

View File

@ -35,7 +35,7 @@ fun assemble(
val warnings = result.problems.count { it.severity == Severity.Warning }
val errors = result.problems.count { it.severity == Severity.Error }
"Assembly finished in ${time.inMilliseconds}ms with $warnings warnings and $errors errors."
"Assembly finished in ${time.inWholeMilliseconds}ms with $warnings warnings and $errors errors."
}
return result

View File

@ -43,7 +43,7 @@ class InstructionSegment(
srcLoc: SegmentSrcLoc = SegmentSrcLoc(mutableListOf()),
) : Segment(SegmentType.Instructions, labels, srcLoc) {
override fun size(dcGcFormat: Boolean): Int =
instructions.sumBy { it.getSize(dcGcFormat) }
instructions.sumOf { it.getSize(dcGcFormat) }
override fun copy(): InstructionSegment =
InstructionSegment(

View File

@ -1,6 +1,5 @@
package world.phantasmal.lib.cursor
import kotlin.experimental.and
import kotlin.math.min
abstract class AbstractWritableCursor
@ -42,7 +41,7 @@ protected constructor(protected val offset: Int) : WritableCursor {
buildString {
for (i in 0 until maxByteLength) {
// Use Byte instead of UByte for better KJS perf.
val codePoint = (byte().toShort() and 0xFF).toChar()
val codePoint = (byte().toInt() and 0xFF).toChar()
if (nullTerminated && codePoint == '\u0000') {
if (dropRemaining) {
@ -65,7 +64,7 @@ protected constructor(protected val offset: Int) : WritableCursor {
val len = maxByteLength / 2
for (i in 0 until len) {
val codePoint = short().toChar()
val codePoint = short().toInt().toChar()
if (nullTerminated && codePoint == '\u0000') {
if (dropRemaining) {
@ -151,7 +150,7 @@ protected constructor(protected val offset: Int) : WritableCursor {
val len = min(byteLength, str.length)
for (i in 0 until len) {
writeByte(str[i].toByte())
writeByte(str[i].code.toByte())
}
val padLen = byteLength - len
@ -170,7 +169,7 @@ protected constructor(protected val offset: Int) : WritableCursor {
val len = min(maxLen, str.length)
for (i in 0 until len) {
writeShort(str[i].toShort())
writeShort(str[i].code.toShort())
}
val padLen = maxLen - len

View File

@ -94,13 +94,15 @@ fun parseDat(cursor: Cursor): DatFile {
3 -> parseEvents(entitiesCursor, areaId, events)
else -> {
// Unknown entity types 4 and 5 (challenge mode).
unknowns.add(DatUnknown(
unknowns.add(
DatUnknown(
entityType,
totalSize,
areaId,
entitiesSize,
data = cursor.byteArray(entitiesSize),
))
)
)
}
}
@ -129,10 +131,12 @@ private fun parseEntities(
val entityCount = cursor.size / entitySize
repeat(entityCount) {
entities.add(DatEntity(
entities.add(
DatEntity(
areaId,
data = cursor.buffer(entitySize),
))
)
)
}
}
@ -169,7 +173,8 @@ private fun parseEvents(cursor: Cursor, areaId: Int, events: MutableList<DatEven
mutableListOf()
}
events.add(DatEvent(
events.add(
DatEvent(
id,
sectionId,
wave,
@ -177,7 +182,8 @@ private fun parseEvents(cursor: Cursor, areaId: Int, events: MutableList<DatEven
actions,
areaId,
unknown,
))
)
)
}
if (cursor.position != actionsOffset) {
@ -212,25 +218,33 @@ private fun parseEventActions(cursor: Cursor): MutableList<DatEventAction> {
(1).toByte() -> break@outer
EVENT_ACTION_SPAWN_NPCS ->
actions.add(DatEventAction.SpawnNpcs(
actions.add(
DatEventAction.SpawnNpcs(
sectionId = cursor.short(),
appearFlag = cursor.short(),
))
)
)
EVENT_ACTION_UNLOCK ->
actions.add(DatEventAction.Unlock(
actions.add(
DatEventAction.Unlock(
doorId = cursor.short(),
))
)
)
EVENT_ACTION_LOCK ->
actions.add(DatEventAction.Lock(
actions.add(
DatEventAction.Lock(
doorId = cursor.short(),
))
)
)
EVENT_ACTION_TRIGGER_EVENT ->
actions.add(DatEventAction.TriggerEvent(
actions.add(
DatEventAction.TriggerEvent(
eventId = cursor.int(),
))
)
)
else -> {
logger.warn { "Unexpected event action type ${type}." }
@ -246,7 +260,7 @@ fun writeDat(dat: DatFile): Buffer {
val buffer = Buffer.withCapacity(
dat.objs.size * (16 + OBJECT_BYTE_SIZE) +
dat.npcs.size * (16 + NPC_BYTE_SIZE) +
dat.unknowns.sumBy { it.totalSize },
dat.unknowns.sumOf { it.totalSize },
endianness = Endianness.Little,
)
val cursor = buffer.cursor()

View File

@ -159,7 +159,7 @@ fun parseQstToQuest(cursor: Cursor, lenient: Boolean = false): PwResult<QuestDat
var binFile: QstContainedFile? = null
for (file in files) {
val fileName = file.filename.trim().toLowerCase()
val fileName = file.filename.trim().lowercase()
if (fileName.endsWith(".dat")) {
datFile = file

View File

@ -79,7 +79,7 @@ actual class Buffer private constructor(
val len = maxByteLength / 2
for (i in 0 until len) {
val codePoint = getShort(offset + i * 2).toChar()
val codePoint = getShort(offset + i * 2).toInt().toChar()
if (nullTerminated && codePoint == '0') {
break
@ -211,7 +211,7 @@ actual class Buffer private constructor(
val buf = withSize(str.length, endianness)
for (i in 0 until buf.size) {
buf.setByte(i, str[i].toByte())
buf.setByte(i, str[i].code.toByte())
}
return buf

View File

@ -1,9 +1,11 @@
package world.phantasmal.testUtils
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.promise
internal actual fun testAsync(block: suspend () -> Unit): dynamic =
@OptIn(DelicateCoroutinesApi::class)
GlobalScope.promise { block() }
internal actual fun canExecuteSlowTests(): Boolean = false

View File

@ -171,7 +171,7 @@ class AsmAnalyser {
}
fun getCompletions(requestId: Int, lineNo: Int, col: Int): Response.GetCompletions {
val text = getLine(lineNo)?.take(col)?.trim()?.toLowerCase() ?: ""
val text = getLine(lineNo)?.take(col)?.trim()?.lowercase() ?: ""
val completions: List<CompletionItem> = when {
KEYWORD_REGEX.matches(text) -> KEYWORD_SUGGESTIONS

View File

@ -80,7 +80,7 @@ class AsmServer(
}
logger.trace {
"Processed ${messages.size} assembly changes in ${time.inMilliseconds}ms."
"Processed ${messages.size} assembly changes in ${time.inWholeMilliseconds}ms."
}
}
}
@ -102,7 +102,7 @@ class AsmServer(
}
}
logger.trace { "Processed ${message::class.simpleName} in ${time.inMilliseconds}ms." }
logger.trace { "Processed ${message::class.simpleName} in ${time.inWholeMilliseconds}ms." }
}
private fun processRequest(message: Request) {

View File

@ -28,10 +28,10 @@ dependencies {
implementation(project(":webui"))
implementation(project(":web:shared"))
implementation("io.ktor:ktor-client-core-js:$ktorVersion")
implementation("io.ktor:ktor-client-serialization-js:$ktorVersion")
implementation("io.ktor:ktor-client-core:$ktorVersion")
implementation("io.ktor:ktor-client-serialization:$ktorVersion")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:$serializationVersion")
implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.1.1")
implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.2.0")
implementation(npm("golden-layout", "^1.5.9"))
// Can't upgrade monaco-editor until https://github.com/microsoft/monaco-editor/issues/2466 is
// fixed.

View File

@ -65,7 +65,7 @@ class Application(
{
MainContentWidget(
mainContentController,
tools.map { it.toolType to it::initialize }.toMap()
tools.associate { it.toolType to it::initialize },
)
}
)
@ -83,7 +83,7 @@ class Application(
}
private fun keydown(e: KeyboardEvent) {
if (e.ctrlKey && !e.altKey && e.key.toUpperCase() == "Z") {
if (e.ctrlKey && !e.altKey && e.key.uppercase() == "Z") {
e.preventDefault()
}
}

View File

@ -15,7 +15,7 @@ class PwToolButton(
private val toggled: Observable<Boolean>,
private val onMouseDown: () -> Unit,
) : Control(visible = trueCell(), enabled = trueCell(), tooltip = nullCell()) {
private val inputId = "pw-application-pw-tool-button-${tool.name.toLowerCase()}"
private val inputId = "pw-application-pw-tool-button-${tool.name.lowercase()}"
override fun Node.createElement() =
span {

View File

@ -239,7 +239,7 @@ class UiStore(private val applicationUrl: ApplicationUrl) : Store() {
if (e.ctrlKey) bindingParts.add("Ctrl")
if (e.altKey) bindingParts.add("Alt")
if (e.shiftKey) bindingParts.add("Shift")
bindingParts.add(e.key.toUpperCase())
bindingParts.add(e.key.uppercase())
val binding = bindingParts.joinToString("-")

View File

@ -8,6 +8,7 @@ import world.phantasmal.webui.controllers.Column
import world.phantasmal.webui.controllers.TableController
import world.phantasmal.webui.toRoundedString
import kotlin.time.Duration
import kotlin.time.DurationUnit.HOURS
class OptimizationResultController(
huntOptimizerStore: HuntOptimizerStore,
@ -28,7 +29,7 @@ class OptimizationResultController(
totalTime += optimalMethod.totalTime
}
listOf<Column<OptimalMethodModel>>(
listOf(
Column(
key = DIFF_COL,
title = "Difficulty",
@ -70,13 +71,13 @@ class OptimizationResultController(
title = "Total Hours",
width = 60,
textAlign = "right",
tooltip = { it.totalTime.inHours.toString() },
footer = cell(totalTime.inHours.toRoundedString(1)),
footerTooltip = cell(totalTime.inHours.toString()),
tooltip = { it.totalTime.toDouble(HOURS).toString() },
footer = cell(totalTime.toDouble(HOURS).toRoundedString(1)),
footerTooltip = cell(totalTime.toDouble(HOURS).toString()),
),
*Array(result.wantedItems.size) { index ->
val wanted = result.wantedItems[index]
val totalCount = result.optimalMethods.sumByDouble {
val totalCount = result.optimalMethods.sumOf {
it.itemTypeIdToCount[wanted.id] ?: .0
}

View File

@ -3,7 +3,8 @@ package world.phantasmal.web.huntOptimizer.persistence
import world.phantasmal.web.core.models.Server
import world.phantasmal.web.core.persistence.Persister
import world.phantasmal.web.huntOptimizer.models.HuntMethodModel
import kotlin.time.hours
import kotlin.time.Duration
import kotlin.time.DurationUnit.HOURS
class HuntMethodPersister : Persister() {
suspend fun persistMethodUserTimes(huntMethods: List<HuntMethodModel>, server: Server) {
@ -11,7 +12,7 @@ class HuntMethodPersister : Persister() {
for (method in huntMethods) {
method.userTime.value?.let { userTime ->
userTimes[method.id] = userTime.inHours
userTimes[method.id] = userTime.toDouble(HOURS)
}
}
@ -22,7 +23,7 @@ class HuntMethodPersister : Persister() {
loadForServer<Map<String, Double>>(server, METHOD_USER_TIMES_KEY)?.let { userTimes ->
for (method in huntMethods) {
userTimes[method.id]?.let { userTime ->
method.setUserTime(userTime.hours)
method.setUserTime(Duration.hours(userTime))
}
}
}

View File

@ -19,7 +19,6 @@ import kotlin.collections.component1
import kotlin.collections.component2
import kotlin.collections.set
import kotlin.time.Duration
import kotlin.time.minutes
class HuntMethodStore(
private val uiStore: UiStore,
@ -109,8 +108,8 @@ class HuntMethodStore(
}
companion object {
private val DEFAULT_DURATION = 30.minutes
private val DEFAULT_GOVERNMENT_TEST_DURATION = 45.minutes
private val DEFAULT_LARGE_ENEMY_COUNT_DURATION = 45.minutes
private val DEFAULT_DURATION = Duration.minutes(30)
private val DEFAULT_GOVERNMENT_TEST_DURATION = Duration.minutes(45)
private val DEFAULT_LARGE_ENEMY_COUNT_DURATION = Duration.minutes(45)
}
}

View File

@ -27,6 +27,7 @@ import world.phantasmal.web.shared.dto.ItemType
import world.phantasmal.web.shared.dto.SectionId
import world.phantasmal.webui.obj
import world.phantasmal.webui.stores.Store
import kotlin.time.DurationUnit.HOURS
private val logger = KotlinLogging.logger {}
@ -233,9 +234,8 @@ class HuntOptimizerStore(
for (sectionId in SectionId.VALUES) {
// Will contain an entry per wanted item dropped by enemies in this method/
// difficulty/section ID combo.
val variable: dynamic = obj {
time = method.time.value.inHours
}
val time = method.time.value.toDouble(HOURS)
val variable: dynamic = obj { this.time = time }
// Only add the variable if the method provides at least 1 item we want.
var addVariable = false

View File

@ -18,6 +18,7 @@ import world.phantasmal.webui.formatAsHoursAndMinutes
import world.phantasmal.webui.toRoundedString
import world.phantasmal.webui.widgets.Table
import world.phantasmal.webui.widgets.Widget
import kotlin.time.DurationUnit.HOURS
class OptimizationResultWidget(private val ctrl: OptimizationResultController) : Widget() {
override fun Node.createElement() =
@ -26,7 +27,8 @@ class OptimizationResultWidget(private val ctrl: OptimizationResultController) :
h2 { textContent = "Ideal Combination of Methods" }
addWidget(Table(
addWidget(
Table(
ctrl = ctrl,
className = "pw-hunt-optimizer-optimization-result-table",
renderCell = { optimalMethod, column ->
@ -45,7 +47,8 @@ class OptimizationResultWidget(private val ctrl: OptimizationResultController) :
}
TIME_PER_RUN_COL -> optimalMethod.methodTime.formatAsHoursAndMinutes()
RUNS_COL -> optimalMethod.runs.toRoundedString(1)
TOTAL_TIME_COL -> optimalMethod.totalTime.inHours.toRoundedString(1)
TOTAL_TIME_COL ->
optimalMethod.totalTime.toDouble(HOURS).toRoundedString(1)
else -> {
optimalMethod.itemTypeIdToCount[column.key.toInt()]
?.toRoundedString(2)
@ -53,14 +56,16 @@ class OptimizationResultWidget(private val ctrl: OptimizationResultController) :
}
}
},
))
)
)
}
companion object {
init {
@Suppress("CssUnusedSymbol", "CssUnresolvedCustomProperty")
// language=css
style("""
style(
"""
.pw-hunt-optimizer-optimization-result {
flex-grow: 1;
display: flex;
@ -74,7 +79,8 @@ class OptimizationResultWidget(private val ctrl: OptimizationResultController) :
border-top: var(--pw-border);
border-left: var(--pw-border);
}
""".trimIndent())
""".trimIndent()
)
}
}
}

View File

@ -1,6 +1,5 @@
package world.phantasmal.web.questEditor.asm.monaco
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.promise
import world.phantasmal.web.externals.monacoEditor.*
import world.phantasmal.web.questEditor.asm.AsmAnalyser
@ -8,14 +7,15 @@ import world.phantasmal.web.shared.messages.CompletionItemType
import world.phantasmal.webui.obj
import kotlin.js.Promise
class AsmCompletionItemProvider(private val analyser: AsmAnalyser) : CompletionItemProvider {
class AsmCompletionItemProvider(private val analyser: AsmAnalyser) :
MonacoProvider(), CompletionItemProvider {
override fun provideCompletionItems(
model: ITextModel,
position: Position,
context: CompletionContext,
token: CancellationToken,
): Promise<CompletionList> =
GlobalScope.promise {
scope.promise {
val completions = analyser.getCompletions(
position.lineNumber,
position.column,

View File

@ -1,19 +1,19 @@
package world.phantasmal.web.questEditor.asm.monaco
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.promise
import world.phantasmal.web.externals.monacoEditor.*
import world.phantasmal.web.questEditor.asm.AsmAnalyser
import world.phantasmal.webui.obj
import kotlin.js.Promise
class AsmDefinitionProvider(private val analyser: AsmAnalyser) : DefinitionProvider {
class AsmDefinitionProvider(private val analyser: AsmAnalyser) :
MonacoProvider(), DefinitionProvider {
override fun provideDefinition(
model: ITextModel,
position: Position,
token: CancellationToken,
): Promise<Array<LocationLink>?> =
GlobalScope.promise {
scope.promise {
val defs = analyser.getDefinition(position.lineNumber, position.column)
Array(defs.size) {

View File

@ -1,19 +1,19 @@
package world.phantasmal.web.questEditor.asm.monaco
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.promise
import world.phantasmal.web.externals.monacoEditor.*
import world.phantasmal.web.questEditor.asm.AsmAnalyser
import world.phantasmal.webui.obj
import kotlin.js.Promise
class AsmDocumentHighlightProvider(private val analyser: AsmAnalyser) : DocumentHighlightProvider {
class AsmDocumentHighlightProvider(private val analyser: AsmAnalyser) :
MonacoProvider(), DocumentHighlightProvider {
override fun provideDocumentHighlights(
model: ITextModel,
position: Position,
token: CancellationToken
): Promise<Array<DocumentHighlight>> =
GlobalScope.promise {
scope.promise {
val highlights = analyser.getHighlights(position.lineNumber, position.column)
Array(highlights.size) {

View File

@ -1,6 +1,5 @@
package world.phantasmal.web.questEditor.asm.monaco
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.promise
import world.phantasmal.web.externals.monacoEditor.CancellationToken
import world.phantasmal.web.externals.monacoEditor.DocumentSymbol
@ -10,14 +9,15 @@ import world.phantasmal.web.questEditor.asm.AsmAnalyser
import world.phantasmal.webui.obj
import kotlin.js.Promise
class AsmDocumentSymbolProvider(private val asmAnalyser: AsmAnalyser) : DocumentSymbolProvider {
class AsmDocumentSymbolProvider(private val asmAnalyser: AsmAnalyser) :
MonacoProvider(), DocumentSymbolProvider {
override val displayName: String? = null
override fun provideDocumentSymbols(
model: ITextModel,
token: CancellationToken
): Promise<Array<DocumentSymbol>> =
GlobalScope.promise {
scope.promise {
val labels = asmAnalyser.getLabels()
Array(labels.size) { index ->

View File

@ -1,6 +1,5 @@
package world.phantasmal.web.questEditor.asm.monaco
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.promise
import world.phantasmal.web.externals.monacoEditor.CancellationToken
import world.phantasmal.web.externals.monacoEditor.HoverProvider
@ -11,13 +10,14 @@ import world.phantasmal.webui.obj
import kotlin.js.Promise
import world.phantasmal.web.externals.monacoEditor.Hover as MonacoHover
class AsmHoverProvider(private val analyser: AsmAnalyser) : HoverProvider {
class AsmHoverProvider(private val analyser: AsmAnalyser) :
MonacoProvider(), HoverProvider {
override fun provideHover(
model: ITextModel,
position: Position,
token: CancellationToken,
): Promise<MonacoHover?> =
GlobalScope.promise {
scope.promise {
analyser.getHover(position.lineNumber, position.column)?.let { hover ->
obj<MonacoHover> {
contents = Array(hover.contents.size) { i ->

View File

@ -1,6 +1,5 @@
package world.phantasmal.web.questEditor.asm.monaco
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.promise
import world.phantasmal.web.externals.monacoEditor.*
import world.phantasmal.web.questEditor.asm.AsmAnalyser
@ -8,7 +7,8 @@ import world.phantasmal.webui.obj
import kotlin.js.Promise
import world.phantasmal.web.externals.monacoEditor.SignatureHelp as MonacoSigHelp
class AsmSignatureHelpProvider(private val analyser: AsmAnalyser) : SignatureHelpProvider {
class AsmSignatureHelpProvider(private val analyser: AsmAnalyser) :
MonacoProvider(), SignatureHelpProvider {
override val signatureHelpTriggerCharacters: Array<String> =
arrayOf(" ", ",")
@ -21,7 +21,7 @@ class AsmSignatureHelpProvider(private val analyser: AsmAnalyser) : SignatureHel
token: CancellationToken,
context: SignatureHelpContext,
): Promise<SignatureHelpResult?> =
GlobalScope.promise {
scope.promise {
analyser.getSignatureHelp(position.lineNumber, position.column)
?.let { sigHelp ->
val monacoSigHelp = obj<MonacoSigHelp> {

View File

@ -0,0 +1,9 @@
package world.phantasmal.web.questEditor.asm.monaco
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
abstract class MonacoProvider {
protected val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
}

View File

@ -82,7 +82,7 @@ class ViewerToolbarController(private val store: ViewerStore) : Controller() {
try {
for (file in files) {
val extension = file.extension()?.toLowerCase()
val extension = file.extension()?.lowercase()
val cursor = file.cursor(Endianness.Little)
var fileResult: PwResult<*>

View File

@ -6,7 +6,6 @@ import world.phantasmal.observable.cell.nullCell
import world.phantasmal.observable.cell.trueCell
import world.phantasmal.webui.formatAsHoursAndMinutes
import kotlin.time.Duration
import kotlin.time.minutes
class DurationInput(
visible: Cell<Boolean> = trueCell(),
@ -43,11 +42,11 @@ class DurationInput(
val minutes = minutesStr.toIntOrNull()
if (hours != null && minutes != null) {
return (hours * 60 + minutes).minutes
return Duration.minutes(hours * 60 + minutes)
}
}
return input.value.toIntOrNull()?.minutes ?: Duration.ZERO
return input.value.toIntOrNull()?.let(Duration::minutes) ?: Duration.ZERO
}
override fun setInputValue(input: HTMLInputElement, value: Duration) {
@ -58,11 +57,13 @@ class DurationInput(
init {
@Suppress("CssUnusedSymbol")
// language=css
style("""
style(
"""
.pw-duration-input-inner {
text-align: center;
}
""".trimIndent())
""".trimIndent()
)
}
}
}