Skip to content

Commit

Permalink
fallback if alternative file does not exist
Browse files Browse the repository at this point in the history
  • Loading branch information
windymelt committed Feb 5, 2024
1 parent 3cf6d88 commit 47561a6
Showing 1 changed file with 40 additions and 3 deletions.
43 changes: 40 additions & 3 deletions src/main/scala/com/github/windymelt/zmm/domain/model/Filter.scala
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package com.github.windymelt.zmm.domain.model
package com.github.windymelt.zmm
package domain.model

import cats.data.Kleisli
import cats.implicits._
import scala.jdk.CollectionConverters.ConcurrentMapHasAsScala

object Filter {
def talkingMouthFilter: Filter[Seq] = Kleisli { (ctx: Context) =>
Expand All @@ -11,11 +13,13 @@ object Filter {
val ExtRe = """(.+)\.(.+)""".r.anchored

// この関数に通すと口を閉じる
// 口を閉じている立ち絵のファイルが存在する場合はそれを利用する。存在しない場合は元々の画像にフォールバックする
// TODO: CharacterConfigにもtachieUrlがあるけど?
val swapTachie: Context => Context = ctx =>
ctx.copy(tachieUrl = ctx.tachieUrl.map {
case ExtRe(file: String, ext: String) =>
s"${file}!.$ext"
case originalPath @ ExtRe(file: String, ext: String) =>
val alternativePath = s"${file}!.$ext"
alternativeFileIfExists(originalPath, alternativePath)
})

val spokenCtxs = vs.map { v =>
Expand All @@ -40,6 +44,39 @@ object Filter {
}
}

private val ExtRe = """(.+)\.(.+)""".r.anchored

// caution: invokes side effect.
private def alternativeFileIfExists(
originalPath: String,
alternativePath: String
): String = originalPath match {
case originalPath @ ExtRe(file: String, ext: String) =>
tachieExistenceCache.get(alternativePath) match {
case Some(true) => alternativePath
case Some(false) => originalPath
case None =>
val pathToFind = os.pwd / os.RelPath(
util.PathAlias.resolve(
alternativePath,
"ffmpeg" /* ffmpeg refers `./`. we should define stub Purpose */
)
)
if (os.exists(pathToFind)) {
tachieExistenceCache += alternativePath -> true
alternativePath
} else {
// fallback to original path.
tachieExistenceCache += alternativePath -> false
originalPath
}
}
case _ => ??? // should not be reached
}

private val tachieExistenceCache =
new java.util.concurrent.ConcurrentHashMap[String, Boolean]().asScala

private def shouldCloseMouth(vowel: String): Boolean =
vowel.toLowerCase match {
case "u" => true
Expand Down

0 comments on commit 47561a6

Please sign in to comment.