forked from sdercolin/utaformatix3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConfigurationEditor.kt
574 lines (531 loc) · 19.2 KB
/
ConfigurationEditor.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
package ui
import csstype.px
import emotion.react.css
import kotlinx.browser.window
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import model.ExportResult
import model.Feature
import model.FeatureConfig
import model.Format
import model.JapaneseLyricsType
import model.Project
import model.TICKS_IN_FULL_NOTE
import mui.material.Button
import mui.material.ButtonColor
import mui.material.ButtonVariant
import org.w3c.dom.get
import process.RESTS_FILLING_MAX_LENGTH_DENOMINATOR_DEFAULT
import process.evalFractionOrNull
import process.fillRests
import process.lyrics.LyricsMappingRequest
import process.lyrics.LyricsReplacementRequest
import process.lyrics.chinese.convertChineseLyricsToPinyin
import process.lyrics.japanese.convertJapaneseLyrics
import process.lyrics.mapLyrics
import process.lyrics.replaceLyrics
import process.phonemes.PhonemesMappingRequest
import process.phonemes.mapPhonemes
import process.projectZoomFactorOptions
import process.zoom
import react.ChildrenBuilder
import react.Props
import react.dom.html.ReactHTML.div
import react.useMemo
import react.useState
import ui.common.DialogErrorState
import ui.common.DialogWarningState
import ui.common.ProgressProps
import ui.common.SubState
import ui.common.errorDialog
import ui.common.progress
import ui.common.scopedFC
import ui.common.title
import ui.common.warningDialog
import ui.configuration.ChinesePinyinConversionBlock
import ui.configuration.JapaneseLyricsConversionBlock
import ui.configuration.LyricsMappingBlock
import ui.configuration.LyricsReplacementBlock
import ui.configuration.PhonemesConversionBlock
import ui.configuration.PitchConversionBlock
import ui.configuration.ProjectSplitBlock
import ui.configuration.ProjectZoomBlock
import ui.configuration.SlightRestsFillingBlock
import ui.strings.Strings
import ui.strings.string
import util.runCatchingCancellable
import util.runIf
import util.runIfAllNotNull
val ConfigurationEditor = scopedFC<ConfigurationEditorProps> { props, scope ->
var progress by useState(ProgressProps.Initial)
val currentConfigs = useMemo {
val configs = window.localStorage["currentConfigs"]?.let {
json.decodeFromString<Configs>(it)
}
if (configs != null) console.log("Restored configs from localStorage", configs)
configs
}
val (japaneseLyricsConversion, setJapaneseLyricsConversion) = useState {
currentConfigs?.japaneseLyricsConversion?.let {
return@useState it
}
val japaneseLyricsAnalysedType =
props.projects.map { it.japaneseLyricsType }.distinct().singleOrNull() ?: JapaneseLyricsType.Unknown
val doJapaneseLyricsConversion = japaneseLyricsAnalysedType != JapaneseLyricsType.Unknown
val fromLyricsType: JapaneseLyricsType?
val toLyricsType: JapaneseLyricsType?
if (doJapaneseLyricsConversion) {
fromLyricsType = japaneseLyricsAnalysedType
toLyricsType = japaneseLyricsAnalysedType.findBestConversionTargetIn(props.outputFormat)
} else {
fromLyricsType = null
toLyricsType = null
}
JapaneseLyricsConversionState(
doJapaneseLyricsConversion,
japaneseLyricsAnalysedType,
fromLyricsType,
toLyricsType,
)
}
val (chinesePinyinConversion, setChinesePinyinConversion) = useState {
currentConfigs?.chinesePinyinConversion?.let {
return@useState it
}
ChinesePinyinConversionState(
isOn = false,
)
}
val (lyricsReplacement, setLyricsReplacement) = useState {
currentConfigs?.lyricsReplacement?.let {
return@useState it
}
val preset = LyricsReplacementRequest.getPreset(props.projects.first().format, props.outputFormat)
if (preset == null) {
LyricsReplacementState(false, LyricsReplacementRequest())
} else {
LyricsReplacementState(true, preset)
}
}
val (lyricsMapping, setLyricsMapping) = useState {
currentConfigs?.lyricsMapping?.let {
return@useState it
}
LyricsMappingState(
isOn = false,
presetName = null,
request = LyricsMappingRequest(),
)
}
val (slightRestsFilling, setSlightRestsFilling) = useState {
currentConfigs?.slightRestsFilling?.let {
return@useState it
}
SlightRestsFillingState(
true,
RESTS_FILLING_MAX_LENGTH_DENOMINATOR_DEFAULT,
)
}
val (pitchConversion, setPitchConversion) = useState {
val isOn = currentConfigs?.pitchConversion?.isOn
val hasPitchData = props.projects.any { Feature.ConvertPitch.isAvailable(it) }
val isPitchConversionAvailable = hasPitchData &&
props.outputFormat.availableFeaturesForGeneration.contains(Feature.ConvertPitch)
PitchConversionState(
isAvailable = isPitchConversionAvailable,
isOn = isOn ?: isPitchConversionAvailable,
)
}
val (projectZoom, setProjectZoom) = useState {
currentConfigs?.projectZoom?.let {
return@useState it
}
ProjectZoomState(
isOn = false,
factor = projectZoomFactorOptions.first(),
hasWarning = false,
)
}
val (projectSplit, setProjectSplit) = useState {
val projectSplit = currentConfigs?.projectSplit
ProjectSplitState(
isAvailable = props.outputFormat.availableFeaturesForGeneration.contains(Feature.SplitProject),
isOn = projectSplit?.isOn ?: false,
maxTrackCountInput = projectSplit?.maxTrackCountInput
?: FeatureConfig.SplitProject.getDefault(props.outputFormat).maxTrackCount.toString(),
)
}
val (phonemesConversion, setPhonemesConversion) = useState {
currentConfigs?.phonemesConversion?.let {
return@useState it
}
val hasPhonemes = props.projects.any { Feature.ConvertPhonemes.isAvailable(it) }
val isAvailable = hasPhonemes &&
props.outputFormat.availableFeaturesForGeneration.contains(Feature.ConvertPhonemes)
// Enable for VOCALOID -> VOCALOID or UfData by default
val enabledFormats = Format.vocaloidFormats.plus(Format.UfData)
val isOn = isAvailable && (
(
props.projects.all { it.format in enabledFormats } &&
props.outputFormat in enabledFormats
) ||
props.projects.all { it.format == props.outputFormat }
)
PhonemesConversionState(
isAvailable = isAvailable,
isOn = isOn,
useMapping = false,
mappingPresetName = null,
mappingRequest = PhonemesMappingRequest(),
)
}
var dialogError by useState(DialogErrorState())
fun isReady() = listOf(
japaneseLyricsConversion,
chinesePinyinConversion,
lyricsReplacement,
lyricsMapping,
slightRestsFilling,
pitchConversion,
projectZoom,
projectSplit,
).all { it.isReady }
fun closeErrorDialog() {
dialogError = dialogError.copy(isShowing = false)
}
title(Strings.ConfigurationEditorCaption)
JapaneseLyricsConversionBlock {
this.projects = props.projects
this.outputFormat = props.outputFormat
initialState = japaneseLyricsConversion
submitState = setJapaneseLyricsConversion
}
ChinesePinyinConversionBlock {
initialState = chinesePinyinConversion
submitState = setChinesePinyinConversion
}
LyricsReplacementBlock {
initialState = lyricsReplacement
submitState = setLyricsReplacement
}
LyricsMappingBlock {
initialState = lyricsMapping
submitState = setLyricsMapping
}
if (phonemesConversion.isAvailable) PhonemesConversionBlock {
this.sourceFormat = props.projects.first().format
this.targetFormat = props.outputFormat
initialState = phonemesConversion
submitState = setPhonemesConversion
}
SlightRestsFillingBlock {
initialState = slightRestsFilling
submitState = setSlightRestsFilling
}
if (pitchConversion.isAvailable) PitchConversionBlock {
initialState = pitchConversion
submitState = setPitchConversion
}
ProjectZoomBlock {
this.projects = props.projects
initialState = projectZoom
submitState = setProjectZoom
}
if (projectSplit.isAvailable) ProjectSplitBlock {
initialState = projectSplit
submitState = setProjectSplit
}
buildNextButton(
scope,
props,
isEnabled = isReady(),
japaneseLyricsConversion,
chinesePinyinConversion,
lyricsReplacement,
lyricsMapping,
slightRestsFilling,
pitchConversion,
projectZoom,
projectSplit,
phonemesConversion,
setProgress = { progress = it },
onDialogError = { dialogError = it },
)
errorDialog(
state = dialogError,
close = { closeErrorDialog() },
)
progress(progress)
multipleModeWarning(props.projects, props.outputFormat)
}
private fun ChildrenBuilder.buildNextButton(
scope: CoroutineScope,
props: ConfigurationEditorProps,
isEnabled: Boolean,
japaneseLyricsConversion: JapaneseLyricsConversionState,
chinesePinyinConversion: ChinesePinyinConversionState,
lyricsReplacement: LyricsReplacementState,
lyricsMapping: LyricsMappingState,
slightRestsFilling: SlightRestsFillingState,
pitchConversion: PitchConversionState,
projectZoom: ProjectZoomState,
projectSplit: ProjectSplitState,
phonemesConversion: PhonemesConversionState,
setProgress: (ProgressProps) -> Unit,
onDialogError: (DialogErrorState) -> Unit,
) {
div {
css {
marginTop = 48.px
}
Button {
color = ButtonColor.primary
variant = ButtonVariant.contained
disabled = !isEnabled
onClick = {
process(
scope,
props,
japaneseLyricsConversion,
chinesePinyinConversion,
lyricsReplacement,
lyricsMapping,
slightRestsFilling,
pitchConversion,
projectZoom,
projectSplit,
phonemesConversion,
setProgress,
onDialogError,
)
}
+string(Strings.NextButton)
}
}
}
private fun process(
scope: CoroutineScope,
props: ConfigurationEditorProps,
japaneseLyricsConversion: JapaneseLyricsConversionState,
chinesePinyinConversion: ChinesePinyinConversionState,
lyricsReplacement: LyricsReplacementState,
lyricsMapping: LyricsMappingState,
slightRestsFilling: SlightRestsFillingState,
pitchConversion: PitchConversionState,
projectZoom: ProjectZoomState,
projectSplit: ProjectSplitState,
phonemesConversion: PhonemesConversionState,
setProgress: (ProgressProps) -> Unit,
onDialogError: (DialogErrorState) -> Unit,
) {
scope.launch {
runCatchingCancellable {
val format = props.outputFormat
val results = props.projects.mapIndexed { index, inputProject ->
setProgress(ProgressProps(isShowing = true, total = props.projects.size, current = index + 1))
val project = inputProject
.runIf(japaneseLyricsConversion.isOn) {
val fromType = japaneseLyricsConversion.fromType
val toType = japaneseLyricsConversion.toType
runIfAllNotNull(fromType, toType) { nonNullFromType, nonNullToType ->
convertJapaneseLyrics(copy(japaneseLyricsType = nonNullFromType), nonNullToType, format)
}
}
.runIf(chinesePinyinConversion.isOn) {
convertChineseLyricsToPinyin(this)
}
.runIf(lyricsReplacement.isOn) {
replaceLyrics(lyricsReplacement.request)
}
.runIf(lyricsMapping.isOn) {
mapLyrics(lyricsMapping.request)
}
.runIf(slightRestsFilling.isOn) {
fillRests(slightRestsFilling.excludedMaxLength)
}
.runIf(projectZoom.isOn) {
zoom(projectZoom.factorValue)
}
.mapPhonemes(phonemesConversion.resolvedMappingRequest)
val featureConfigs = buildList {
if (pitchConversion.isOn) add(FeatureConfig.ConvertPitch)
if (projectSplit.isOn) add(FeatureConfig.SplitProject(projectSplit.maxTrackCountInput.toInt()))
}.filter {
it.type.isAvailable.invoke(project) &&
format.availableFeaturesForGeneration.contains(it.type)
}
delay(100)
val result = format.generator.invoke(project, featureConfigs)
console.log("Finished processing project ${project.name}. ${index + 1}/${props.projects.size}")
result
}
val currentConfigs = Configs(
japaneseLyricsConversion,
chinesePinyinConversion,
lyricsReplacement,
lyricsMapping,
slightRestsFilling,
pitchConversion,
projectZoom,
projectSplit,
phonemesConversion,
)
window.localStorage.setItem("currentConfigs", json.encodeToString(currentConfigs))
// adjust results to make every fileName unique
val adjustedResults = results.mapIndexed { index, result ->
val fileName = result.fileName
val adjustedFileName = if (results.any { it != result && it.fileName == fileName }) {
val extension = fileName.substringAfterLast(".")
val name = fileName.substringBeforeLast(".")
"$name-$index.$extension"
} else {
fileName
}
ExportResult(blob = result.blob, fileName = adjustedFileName, notifications = result.notifications)
}
props.onFinished.invoke(adjustedResults, format)
}.onFailure { t ->
console.log(t)
setProgress(ProgressProps.Initial)
onDialogError(
DialogErrorState(
isShowing = true,
title = string(Strings.ProcessErrorDialogTitle),
message = t.stackTraceToString(),
),
)
}
}
}
private fun ChildrenBuilder.multipleModeWarning(projects: List<Project>, outputFormat: Format) {
val shouldWarn = useMemo(projects, outputFormat) {
projects.size > 1 && projects.first().format.multipleFile && outputFormat.multipleFile.not()
}
val (closed, setClosed) = useState(false)
warningDialog(
id = "isMultipleModeForSingleFileFormat",
state = DialogWarningState(
isShowing = shouldWarn && !closed,
title = string(Strings.MultipleModeForMultipleFileFormatWarningTitle),
message = string(Strings.MultipleModeForMultipleFileFormatWarningDescription),
),
close = { setClosed(true) },
)
}
private val json = Json {
ignoreUnknownKeys = true
}
external interface ConfigurationEditorProps : Props {
var projects: List<Project>
var outputFormat: Format
var onFinished: (List<ExportResult>, Format) -> Unit
}
@Serializable
data class JapaneseLyricsConversionState(
val isOn: Boolean,
val detectedType: JapaneseLyricsType,
val fromType: JapaneseLyricsType?,
val toType: JapaneseLyricsType?,
) : SubState() {
override val isReady: Boolean get() = if (isOn) fromType != null && toType != null else true
}
@Serializable
data class ChinesePinyinConversionState(
val isOn: Boolean,
) : SubState()
@Serializable
data class LyricsReplacementState(
val isOn: Boolean,
val request: LyricsReplacementRequest,
) : SubState() {
override val isReady: Boolean get() = if (isOn) request.isValid else true
}
@Serializable
data class LyricsMappingState(
val isOn: Boolean,
val presetName: String?,
val request: LyricsMappingRequest,
) : SubState() {
override val isReady: Boolean get() = if (isOn) request.isValid else true
fun updatePresetName() = when {
presetName == null -> this
LyricsMappingRequest.findPreset(presetName) == request -> this
else -> copy(presetName = null)
}
}
@Serializable
data class PhonemesConversionState(
val isAvailable: Boolean,
val isOn: Boolean,
val useMapping: Boolean,
val mappingPresetName: String?,
val mappingRequest: PhonemesMappingRequest,
) : SubState() {
override val isReady: Boolean get() = if (isAvailable && isOn && useMapping) mappingRequest.isValid else true
val resolvedMappingRequest: PhonemesMappingRequest?
get() = if (isOn) {
if (useMapping) {
mappingRequest
} else {
PhonemesMappingRequest("")
}
} else {
null
}
fun updatePresetName() = when {
mappingPresetName == null -> this
PhonemesMappingRequest.findPreset(mappingPresetName) == mappingRequest -> this
else -> copy(mappingPresetName = null)
}
}
@Serializable
data class SlightRestsFillingState(
val isOn: Boolean,
val excludedMaxLengthDenominator: Int,
) : SubState() {
val excludedMaxLength: Long
get() = (TICKS_IN_FULL_NOTE / excludedMaxLengthDenominator).toLong()
}
@Serializable
data class PitchConversionState(
val isAvailable: Boolean,
val isOn: Boolean,
) : SubState()
@Serializable
data class ProjectZoomState(
val isOn: Boolean,
val factor: String,
val hasWarning: Boolean,
) : SubState() {
val factorValue: Double
get() = factor.evalFractionOrNull()!!
}
@Serializable
data class ProjectSplitState(
val isAvailable: Boolean,
val isOn: Boolean,
val maxTrackCountInput: String,
) : SubState() {
override val isReady: Boolean
get() = if (isOn) {
val maxTrackCount = maxTrackCountInput.toIntOrNull()
maxTrackCount != null && maxTrackCount > 0
} else true
}
@Serializable
data class Configs(
val japaneseLyricsConversion: JapaneseLyricsConversionState,
val chinesePinyinConversion: ChinesePinyinConversionState,
val lyricsReplacement: LyricsReplacementState,
val lyricsMapping: LyricsMappingState,
val slightRestsFilling: SlightRestsFillingState,
val pitchConversion: PitchConversionState,
val projectZoom: ProjectZoomState,
val projectSplit: ProjectSplitState,
val phonemesConversion: PhonemesConversionState,
)