diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..e3d9c3c
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,2 @@
+# Preserve the line endings generated by the Gradle Windows wrapper.
+gradlew.bat text eol=crlf
diff --git a/.github/workflows/deploy.yaml b/.github/workflows/deploy.yaml
index 6784e48..e2a85c8 100644
--- a/.github/workflows/deploy.yaml
+++ b/.github/workflows/deploy.yaml
@@ -3,103 +3,178 @@ name: Deployment
on:
push:
tags:
- # ドットをエスケープしなくていい(正規表現でない)
+ # ここは glob。タグの書式は parse_version で検証する。
- 'v[0-9]+.[0-9]+.[0-9]+*'
workflow_dispatch:
+ inputs:
+ tag:
+ description: 'ビルドする既存のタグ(例: v1.2.3-rc.1)'
+ required: true
+ type: string
+
+permissions:
+ contents: read
jobs:
- parse_version: # プッシュされたタグの文字列からバージョンをパースする
+ parse_version:
+ if: github.event_name != 'push' || !github.event.deleted
runs-on: ubuntu-latest
+ timeout-minutes: 5
outputs:
+ tag: ${{ steps.parse.outputs.tag }}
full_version: ${{ steps.parse.outputs.full_version }}
version: ${{ steps.parse.outputs.version }}
- major: ${{ steps.parse.outputs.major }}
- minor: ${{ steps.parse.outputs.minor }}
- patch: ${{ steps.parse.outputs.patch }}
- suffix: ${{ steps.parse.outputs.suffix }}
+ commit: ${{ steps.parse.outputs.commit }}
+ prerelease: ${{ steps.parse.outputs.prerelease }}
steps:
- - name: Parse version from tag
+ - name: Validate tag and resolve commit
id: parse
+ env:
+ DISPATCH_TAG: ${{ inputs.tag }}
+ GH_TOKEN: ${{ github.token }}
run: |
- FULL_VERSION=${GITHUB_REF#refs/tags/v}
- VERSION=$(echo $FULL_VERSION | cut -d'-' -f1)
- SUFFIX=$(echo $FULL_VERSION | cut -s -d'-' -f2-)
- echo "full_version=$FULL_VERSION" >> $GITHUB_OUTPUT
- echo "version=$VERSION" >> $GITHUB_OUTPUT
- echo "major=$(echo $VERSION | cut -d. -f1)" >> $GITHUB_OUTPUT
- echo "minor=$(echo $VERSION | cut -d. -f2)" >> $GITHUB_OUTPUT
- echo "patch=$(echo $VERSION | cut -d. -f3)" >> $GITHUB_OUTPUT
- echo "suffix=$SUFFIX" >> $GITHUB_OUTPUT
- make: # タグから識別したバージョン情報に基づくアプリケーションを生成する
+ set -euo pipefail
+ if [[ "$GITHUB_EVENT_NAME" == 'workflow_dispatch' ]]; then
+ TAG=$DISPATCH_TAG
+ else
+ [[ "$GITHUB_REF" == refs/tags/* ]] || { echo 'A release requires a tag.' >&2; exit 1; }
+ TAG=${GITHUB_REF#refs/tags/}
+ fi
+ VERSION_PATTERN='^v([0-9]+)\.([0-9]+)\.([0-9]+)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$'
+ [[ "$TAG" =~ $VERSION_PATTERN ]] || { echo 'Invalid release tag.' >&2; exit 1; }
+ VERSION=${BASH_REMATCH[1]}.${BASH_REMATCH[2]}.${BASH_REMATCH[3]}
+ PRERELEASE=false
+ if [[ -n "${BASH_REMATCH[4]}" ]]; then PRERELEASE=true; fi
+ COMMIT=$(gh api "repos/$GITHUB_REPOSITORY/commits/refs/tags/$TAG" --jq .sha)
+ [[ "$COMMIT" =~ ^[0-9a-f]{40}$ ]] || { echo 'Could not resolve tag commit.' >&2; exit 1; }
+ if [[ "$GITHUB_EVENT_NAME" == 'push' && "$COMMIT" != "$GITHUB_SHA" ]]; then
+ echo 'Release tag no longer points to the pushed commit.' >&2
+ exit 1
+ fi
+ printf '%s\n' "tag=$TAG" "full_version=${TAG#v}" "version=$VERSION" \
+ "commit=$COMMIT" "prerelease=$PRERELEASE" >> "$GITHUB_OUTPUT"
+
+ make:
+ needs: parse_version
+ runs-on: ${{ matrix.os }}
+ timeout-minutes: 60
strategy:
+ fail-fast: false
matrix:
- # WindowsランナーはWiX Toolset 3.14.1.8722入り
- # MacOSはIntel CPU(macos-13)とApple Silicon CPU(macos-14)
- # https://docs.github.com/ja/actions/using-github-hosted-runners/about-github-hosted-runners/about-github-hosted-runners
- os: [windows-latest, macos-13, macos-14]
- runs-on: ${{ matrix.os }}
- needs: parse_version
+ include:
+ - os: windows-2025
+ target: windows-x64
+ extension: exe
+ arch_suffix: ''
+ - os: macos-15-intel
+ target: macos-x86_64
+ extension: dmg
+ arch_suffix: -x86_64
+ - os: macos-15
+ target: macos-arm64
+ extension: dmg
+ arch_suffix: -arm64
+ env:
+ APP_VERSION: ${{ needs.parse_version.outputs.full_version }}
steps:
- name: Checkout source
- uses: actions/checkout@v4
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ ref: ${{ needs.parse_version.outputs.commit }}
+ persist-credentials: false
- name: Setup JDK
- uses: actions/setup-java@v4
+ uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0
with:
- java-version: 21.0.1
+ java-version: '25'
distribution: 'temurin'
+ check-latest: true
- name: Setup Gradle
- uses: gradle/actions/setup-gradle@v3
- - name: Make an application for Windows
- if: (matrix.os == 'windows-latest')
- run: .\gradlew.bat "-Papp.version=${{ needs.parse_version.outputs.full_version }}" make
- - name: Make an application
- if: (matrix.os != 'windows-latest')
- run: ./gradlew "-Papp.version=${{ needs.parse_version.outputs.full_version }}" make
- - name: Rename an application for Windows
- if: (matrix.os == 'windows-latest')
- shell: bash
- run: |
- mv '.\build\app\Twitch Chat Viewer-${{ needs.parse_version.outputs.version }}.exe' '.\build\app\Twitch Chat Viewer-${{ needs.parse_version.outputs.full_version }}.exe'
- - name: Rename an application for Intel Mac
- if: (matrix.os == 'macos-13')
- shell: bash
- run: |
- mv "build/app/Twitch Chat Viewer-${{ needs.parse_version.outputs.version }}.dmg" "build/app/Twitch Chat Viewer-${{ needs.parse_version.outputs.full_version }}-x86_64.dmg"
- - name: Rename an application for Apple Silicon Mac
- if: (matrix.os == 'macos-14')
- shell: bash
- run: |
- mv "build/app/Twitch Chat Viewer-${{ needs.parse_version.outputs.version }}.dmg" "build/app/Twitch Chat Viewer-${{ needs.parse_version.outputs.full_version }}-arm64.dmg"
- - name: Detect asset file for Windows
- if: (matrix.os == 'windows-latest')
+ uses: gradle/actions/setup-gradle@3f5f9adaf7d9fecd50b5935e54106014257a94e6 # v6.4.0
+ with:
+ cache-provider: basic
+ cache-read-only: true
+ - name: Build Windows installer
+ if: runner.os == 'Windows'
shell: pwsh
- run: |
- echo "asset_path=build\app\$(Get-ChildItem -name .\build\app)" >> $env:GITHUB_ENV
- echo "asset_name=$(Get-ChildItem -name .\build\app)" >> $env:GITHUB_ENV
- - name: Detect asset file
- if: (matrix.os != 'windows-latest')
+ run: .\gradlew.bat "-Papp.version=$env:APP_VERSION" make
+ - name: Build macOS installer
+ if: runner.os == 'macOS'
+ run: ./gradlew "-Papp.version=$APP_VERSION" make
+ - name: Prepare installer for upload
+ id: installer
shell: bash
+ env:
+ NATIVE_VERSION: ${{ needs.parse_version.outputs.version }}
+ EXTENSION: ${{ matrix.extension }}
+ ARCH_SUFFIX: ${{ matrix.arch_suffix }}
run: |
- echo "asset_path=build/app/$(ls build/app)" >> $GITHUB_ENV
- echo "asset_name=$(ls build/app)" >> $GITHUB_ENV
- - name: Upload artifacts
- uses: actions/upload-artifact@v4 # https://github.com/actions/upload-artifact
+ source="build/app/Twitch Chat Viewer-$NATIVE_VERSION.$EXTENSION"
+ target="build/distribution/Twitch Chat Viewer-$APP_VERSION$ARCH_SUFFIX.$EXTENSION"
+ if [[ ! -f "$source" || ! -s "$source" ]]; then
+ echo "Missing or empty installer: $source" >&2
+ exit 1
+ fi
+ mkdir -p build/distribution
+ cp -- "$source" "$target"
+ printf 'path=%s\n' "$target" >> "$GITHUB_OUTPUT"
+ - name: Upload installer
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
- name: ${{ env.asset_name }}
- path: ${{ env.asset_path }}
+ name: installer-${{ matrix.target }}
+ path: ${{ steps.installer.outputs.path }}
+ if-no-files-found: error
+ overwrite: true
compression-level: 0
+ - name: Upload packaging log on failure
+ if: failure()
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ with:
+ name: packaging-log-${{ matrix.target }}
+ path: build/reports/packaging/make.log
+ if-no-files-found: ignore
+ overwrite: true
+
release:
+ needs: [make, parse_version]
runs-on: ubuntu-latest
- needs: make
+ timeout-minutes: 15
+ permissions:
+ contents: write
+ concurrency:
+ group: deployment-${{ needs.parse_version.outputs.tag }}
+ cancel-in-progress: false
steps:
- - name: Download Artifacts
- uses: actions/download-artifact@v4.1.8
+ - name: Download installers
+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
+ pattern: installer-*
+ merge-multiple: true
path: build/distribution/
- - name: Create Release
- uses: softprops/action-gh-release@v2 # https://github.com/softprops/action-gh-release
+ - name: Verify release target
+ id: verify
env:
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token
+ GH_TOKEN: ${{ github.token }}
+ TAG: ${{ needs.parse_version.outputs.tag }}
+ COMMIT: ${{ needs.parse_version.outputs.commit }}
+ run: |
+ current=$(gh api "repos/$GITHUB_REPOSITORY/commits/refs/tags/$TAG" --jq .sha)
+ if [[ "$current" != "$COMMIT" ]]; then
+ echo "Tag $TAG changed during the build." >&2
+ exit 1
+ fi
+ published_tags=$(gh api --paginate "repos/$GITHUB_REPOSITORY/releases" --jq '.[] | select(.draft | not) | .tag_name')
+ if grep -Fxq -- "$TAG" <<< "$published_tags"; then
+ echo "Release $TAG is already published; its assets will not be modified." >&2
+ exit 1
+ fi
+ - name: Create or update draft release
+ uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2
with:
- draft: true # ドラフトリリースとし、公開は手動で行う
- files: build/distribution/**
+ tag_name: ${{ needs.parse_version.outputs.tag }}
+ draft: true # 公開は手動で行う。
+ prerelease: ${{ needs.parse_version.outputs.prerelease == 'true' }}
+ fail_on_unmatched_files: true
+ files: |
+ build/distribution/*-x86_64.dmg
+ build/distribution/*-arm64.dmg
+ build/distribution/*.exe
diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml
index a5c8a09..901ad5a 100644
--- a/.github/workflows/test.yaml
+++ b/.github/workflows/test.yaml
@@ -7,18 +7,39 @@ on:
- "**/*.md"
- "docs/**"
+permissions:
+ contents: read
+
jobs:
build:
runs-on: ubuntu-latest
+ timeout-minutes: 30
steps:
- name: Checkout source
- uses: actions/checkout@v4
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
- name: Setup JDK
- uses: actions/setup-java@v4
+ uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0
with:
- java-version: 21.0.1
+ java-version: '25'
distribution: 'temurin'
+ check-latest: true
- name: Setup Gradle
- uses: gradle/actions/setup-gradle@v3
- - name: Test with Gradle
- run: ./gradlew test
\ No newline at end of file
+ uses: gradle/actions/setup-gradle@3f5f9adaf7d9fecd50b5935e54106014257a94e6 # v6.4.0
+ with:
+ cache-provider: basic
+ - name: Test Gradle build logic
+ run: ./gradlew -p buildSrc test
+ - name: Test application
+ run: ./gradlew test
+ - name: Upload test reports on failure
+ if: failure()
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ with:
+ name: test-reports
+ path: |
+ build/reports/tests/test
+ buildSrc/build/reports/tests/test
+ if-no-files-found: ignore
+ overwrite: true
diff --git a/.gitignore b/.gitignore
index d3ed74e..9c8d8b3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -38,4 +38,15 @@ bin/
### Mac OS ###
.DS_Store
-userinfo
\ No newline at end of file
+userinfo
+
+# ローカル専用の開発資料
+/docs/architecture.md
+/docs/development.md
+/docs/technical-debt*.md
+/docs/internal/
+
+# AI
+.agents
+.opencode
+AGENTS.md
\ No newline at end of file
diff --git a/.java-version b/.java-version
new file mode 100644
index 0000000..7273c0f
--- /dev/null
+++ b/.java-version
@@ -0,0 +1 @@
+25
diff --git a/README.md b/README.md
index ce77103..2dac4e6 100644
--- a/README.md
+++ b/README.md
@@ -1,13 +1,15 @@
# Twitch Chat Viewer
-[](https://github.com/k7t3/TwitchChatViewer/actions/workflows/test.yaml)
[](https://opensource.org/licenses/Apache-2.0)
このアプリケーションはライブストリーミングサービス[Twitch](https://www.twitch.tv/)の非公式チャットビューアです。
-[使用方法](docs/usage.md)
+## ダウンロードと使い方
+
+[リリースページ](https://github.com/k7t3/TwitchChatViewer/releases)から、お使いの OS に合ったインストーラーをダウンロードしてください。
+初回起動時の Twitch 認証やチャットの開き方は、[使用方法](docs/usage.md)をご覧ください。
## 主な機能
@@ -41,6 +43,8 @@
### チャットメッセージのフィルタリング
* 特定のユーザーのメッセージを非表示にしたり、正規表現を使用してフィルタリングできます。
-## License
+## プライバシーとライセンス
-詳細は [LICENSE](LICENSE.md) を参照してください。
\ No newline at end of file
+- [プライバシーポリシー](docs/license.md#privacy-policy)
+- [アプリケーションのライセンス](LICENSE.md)
+- [使用ライブラリとライセンス](docs/external-libraries.md)
diff --git a/build.gradle b/build.gradle
index a1fe365..8c5f0a8 100644
--- a/build.gradle
+++ b/build.gradle
@@ -1,3 +1,10 @@
+import com.github.k7t3.tcv.build.JdkModulesTask
+import com.github.k7t3.tcv.build.JdkToolTask
+import com.github.k7t3.tcv.build.NativePackageTask
+import com.github.k7t3.tcv.build.PackagePlan
+import org.gradle.api.artifacts.component.ModuleComponentIdentifier
+import org.gradle.process.CommandLineArgumentProvider
+
plugins {
id 'application'
id 'org.openjfx.javafxplugin' version '0.1.0'
@@ -6,193 +13,204 @@ plugins {
group = 'io.github.k7t3'
version = project.findProperty("app.version") ?: '1.0.0-dev'
+PackagePlan.nativeVersion(version.toString())
repositories {
mavenCentral()
}
-java {
- sourceCompatibility = JavaVersion.VERSION_21
- targetCompatibility = JavaVersion.VERSION_21
-}
+def javaFeature = libs.versions.java.get().toInteger()
+java { toolchain { languageVersion = JavaLanguageVersion.of(javaFeature) } }
-compileJava {
- options.encoding = 'UTF-8'
-}
-
-compileTestJava {
+tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8'
+ options.release = javaFeature
}
javafx {
- version = '22.0.1'
+ version = libs.versions.javafx.get()
modules = [ 'javafx.controls', 'javafx.fxml', 'javafx.swing' ]
}
application {
mainClass = 'com.github.k7t3.tcv.view.Launcher'
applicationName = 'Twitch Chat Viewer'
+ applicationDefaultJvmArgs = ['--enable-native-access=ALL-UNNAMED']
+}
+
+configurations {
+ mockitoAgent { canBeConsumed = false; transitive = false }
+ runtimeClasspath {
+ // 旧Helix builderの設定依存は、上流SDKとの比較テスト側だけで使用する。
+ exclude group: 'commons-configuration', module: 'commons-configuration'
+ exclude group: 'commons-lang', module: 'commons-lang'
+ exclude group: 'commons-logging', module: 'commons-logging'
+ }
}
dependencies {
// Logger
- implementation 'org.slf4j:slf4j-api:2.0.11'
- implementation 'org.slf4j:slf4j-jdk14:2.0.11'
+ implementation libs.slf4j.api
+ implementation libs.slf4j.jdk14
// Twitchクライアント
- // TODO 必要なモジュールのみにする
- implementation 'com.github.twitch4j:twitch4j:1.21.0'
+ implementation libs.twitch.auth
+ implementation libs.twitch.chat
+ implementation libs.twitch.common
+ implementation(libs.twitch.helix) {
+ exclude group: 'io.github.openfeign', module: 'feign-hystrix'
+ }
+ implementation libs.feign.core
+ implementation libs.feign.jackson
+ implementation libs.feign.okhttp
+ implementation libs.bucket4j
// キャッシュ
- implementation 'com.github.ben-manes.caffeine:caffeine:3.1.8'
+ implementation libs.caffeine
// 永続化
- implementation 'org.xerial:sqlite-jdbc:3.45.3.0'
+ implementation libs.sqlite
// Twitch認証用のQRコード生成
- implementation 'com.google.zxing:javase:3.5.3'
+ implementation libs.zxing
// AtlantaFXと同じアイコンパックを使用する
- implementation 'io.github.mkpaz:atlantafx-base:2.0.1'
- implementation 'org.kordamp.ikonli:ikonli-javafx:12.3.1'
- implementation 'org.kordamp.ikonli:ikonli-feather-pack:12.3.1'
- implementation 'org.kordamp.ikonli:ikonli-material2-pack:12.3.1'
+ implementation libs.atlantafx
+ implementation libs.ikonli.javafx
+ implementation libs.ikonli.feather
+ implementation libs.ikonli.material2
// アイコンパック
- implementation 'org.kordamp.ikonli:ikonli-fontawesome5-pack:12.3.1'
+ implementation libs.ikonli.fontawesome5
// MVVM
- implementation "de.saxsys:mvvmfx:1.8.0"
+ implementation libs.mvvmfx
// チャットビュー用のVirtualFlow
- implementation 'org.fxmisc.flowless:flowless:0.7.2'
+ implementation libs.flowless
// テスト
- testImplementation platform('org.junit:junit-bom:5.9.1')
- testImplementation 'org.junit.jupiter:junit-jupiter'
+ testImplementation platform(libs.junit.bom)
+ testImplementation libs.junit.jupiter
+ testRuntimeOnly libs.junit.launcher
- testImplementation 'org.testfx:testfx-junit5:4.0.18'
- testImplementation 'org.testfx:openjfx-monocle:21.0.2' // headless
+ testImplementation libs.testfx.junit5
- testImplementation 'org.assertj:assertj-core:3.13.2'
- testImplementation 'org.hamcrest:hamcrest:2.1'
+ testImplementation libs.assertj
+ testImplementation libs.hamcrest
- testImplementation 'org.mockito:mockito-core:5.11.0'
+ testImplementation libs.mockito
+ // 上流SDKとのHTTP契約比較だけは、従来のコマンド実行をテスト側で維持する。
+ testImplementation libs.twitch.helix
+ mockitoAgent libs.mockito
}
-// SSL通信のためにjdk.crypto.ecモジュールが必要
-// https://stackoverflow.com/questions/63932217/java-ssl-handshake-failure-if-app-built-with-jpackage
-def cryptoPackage = 'jdk.crypto.ec'
-
-def jdkModules = ''
-tasks.register('checkJDKModules', Exec) {
- dependsOn jar, copyDependencies, copyJavaFXModules
+// 配布入力を専用ディレクトリに同期する。古いアプリ JAR や依存 JAR を混入させない。
+def javafxArtifacts = configurations.runtimeClasspath.incoming.artifactView {
+ componentFilter { id -> id instanceof ModuleComponentIdentifier && id.group == 'org.openjfx' }
+}.files
+def applicationArtifacts = configurations.runtimeClasspath.incoming.artifactView {
+ componentFilter { id -> !(id instanceof ModuleComponentIdentifier && id.group == 'org.openjfx') }
+}.files
+
+def packageInput = tasks.register('copyDependencies', Sync) {
+ from applicationArtifacts
+ from tasks.named('jar', Jar).flatMap { it.archiveFile }
+ from('LICENSE.md')
+ from('src/main/packaging')
+ from('docs') { include 'license.md', 'external-libraries.md', 'licenses/**'; into 'docs' }
+ into layout.buildDirectory.dir('packaging/input')
+}
- // プラットフォームに依存したクラスパスのセパレータ
- var s = org.gradle.internal.os.OperatingSystem.current().isWindows()
- ? ';'
- : ':'
+def javafxInput = tasks.register('copyJavaFXModules', Sync) {
+ from javafxArtifacts
+ into layout.buildDirectory.dir('packaging/javafx')
+}
- commandLine 'jdeps',
- '--add-modules', 'ALL-MODULE-PATH',
- '--multi-release', '9',
- '--ignore-missing-deps',
- '--print-module-deps',
- '--class-path', "build/libs/*${s}build/javafx/*",
- "build/libs/${-> tasks.jar.archiveFile.get().asFile.name}"
+def packageJava = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(javaFeature) }
+tasks.withType(JdkToolTask).configureEach { javaFeatureVersion = javaFeature }
+def moduleCheck = tasks.register('checkJDKModules', JdkModulesTask) {
+ dependsOn packageInput, javafxInput
+ javaLauncher = packageJava
+ inputDirectory = layout.buildDirectory.dir('packaging/input')
+ moduleDirectory = layout.buildDirectory.dir('packaging/javafx')
+ mainJar = tasks.named('jar', Jar).flatMap { it.archiveFileName }
+ javafxModules = javafx.modules
+ modulesFile = layout.buildDirectory.file('packaging/jdk-modules.txt')
+}
- standardOutput = new ByteArrayOutputStream()
- ext.output = { return standardOutput.toString().trim() }
- doLast {
- jdkModules = output()
- if (!jdkModules.contains(cryptoPackage)) {
- jdkModules += ',' + cryptoPackage
- }
- }
+def packagePlatform = PackagePlan.Platform.fromOsName(System.getProperty('os.name'))
+tasks.withType(NativePackageTask).configureEach {
+ group = 'distribution'
+ dependsOn moduleCheck
+ javaLauncher = packageJava
+ inputDirectory = layout.buildDirectory.dir('packaging/input')
+ moduleDirectory = layout.buildDirectory.dir('packaging/javafx')
+ modulesFile = moduleCheck.flatMap { it.modulesFile }
+ mainJar = tasks.named('jar', Jar).flatMap { it.archiveFileName }
+ mainClass = application.mainClass
+ fullVersion = project.version.toString()
+ platformName = packagePlatform.name()
+ projectRoot = layout.projectDirectory
+ packageResources.from(layout.projectDirectory.file('docs/license.md'),
+ layout.projectDirectory.file("src/main/resources/icons/${packagePlatform.iconName()}"))
+ logFile = layout.buildDirectory.file("reports/packaging/${name}.log")
}
-tasks.register('copyDependencies', Copy) {
- from configurations.runtimeClasspath
- into 'build/libs'
- exclude 'javafx-**'
+tasks.register('make', NativePackageTask) {
+ description = '現在の OS 向けインストーラーを生成する'
+ appImage = false
+ outputDirectory = layout.buildDirectory.dir('app')
}
-tasks.register('copyJavaFXModules', Copy) {
- from configurations.runtimeClasspath
- into 'build/javafx'
- include 'javafx-**'
+tasks.register('appImage', NativePackageTask) {
+ description = 'インストール不要のアプリケーションイメージを生成する'
+ appImage = true
+ outputDirectory = layout.buildDirectory.dir('app-image')
}
-def deployDir = 'build/app'
-tasks.register('make', Exec) {
- group = 'distribution'
- description = 'アプリケーションパッケージを生成するタスク'
- dependsOn checkJDKModules
+abstract class MockitoAgentProvider implements CommandLineArgumentProvider {
+ @InputFiles
+ @PathSensitive(PathSensitivity.RELATIVE)
+ abstract ConfigurableFileCollection getAgentJar()
- doFirst {
- delete deployDir
- }
+ @Override Iterable asArguments() { ["-javaagent:${agentJar.singleFile.absolutePath}"] }
+}
- ArrayList commandArgs = [
- 'jpackage',
- '--verbose',
- '--name', 'Twitch Chat Viewer',
- '--description', 'Chat Viewer for twitch.tv',
- '--copyright', 'Copyright (c) 2024 k7t3. All rights reserved.',
- '--vendor', 'k7t3',
- // バージョンの末尾に文字があると違反になるため取り除く処置
- '--app-version', version.toString().replaceAll('\\D+$', ''),
- '--dest', deployDir,
- '--module-path', 'build/javafx',
- '--add-modules', "${-> jdkModules},${javafx.modules.join(',')}",
- '--input', 'build/libs',
- '--main-jar', "${-> tasks.jar.archiveFile.get().asFile.name}",
- '--main-class', application.mainClass.get(),
- '--license-file', 'docs/license.md',
- '--java-options', "'-Dapp.version=${version}'"
- ]
-
- def os = org.gradle.internal.os.OperatingSystem.current()
-
- if (os.isWindows()) {
- commandArgs.addAll('--type', 'exe')
- commandArgs.addAll('--icon', 'src/main/resources/icons/TwitchChatViewer.ico')
- commandArgs.addAll('--win-shortcut')
- commandArgs.addAll('--win-menu')
- commandArgs.addAll('--win-menu-group', 'TwitchChatViewer')
- commandArgs.addAll('--win-per-user-install')
- commandArgs.addAll('--win-shortcut-prompt')
- commandArgs.addAll('--win-upgrade-uuid', 'b78817e8-f9b8-4650-bf0a-34bca5ff4106')
- commandArgs.addAll('--win-help-url', 'https://github.com/k7t3/TwitchChatViewer')
- commandArgs.addAll('--win-update-url', 'https://github.com/k7t3/TwitchChatViewer/releases')
- }
- else if (os.isMacOsX()) {
- commandArgs.addAll('--type', 'dmg')
- commandArgs.addAll('--icon', 'src/main/resources/icons/TwitchChatViewer.icns')
- commandArgs.addAll('--mac-package-identifier', 'TwitchChatViewer')
- }
- else if (os.isLinux()) {
- commandArgs.addAll('--type', 'deb')
- commandArgs.addAll('--icon', 'src/main/resources/icons/TwitchChatViewer-64.png')
- commandArgs.addAll('--linux-menu-group', 'Network')
- commandArgs.addAll('--linux-rpm-license-type', 'Apache-2.0')
- commandArgs.addAll('--linux-shortcut')
- }
+abstract class ProductionClasspathProvider implements CommandLineArgumentProvider {
+ @InputFiles
+ @PathSensitive(PathSensitivity.RELATIVE)
+ abstract ConfigurableFileCollection getRuntimeClasspath()
- commandLine commandArgs
+ @Override Iterable asArguments() { ["-Dtcv.test.production.classpath=${runtimeClasspath.asPath}"] }
}
test {
- if (!project.hasProperty("headless") || project.headless == "true") {
- // execute TestFX Tests headless -- switch off by using ./gradlew -Pheadless=false
- systemProperty("testfx.robot", "glass")
- systemProperty("testfx.headless", "true")
+ def headlessMode = !project.hasProperty('headless') || project.headless == 'true'
+ // GUI の toolkit とウィンドウの状態をテストクラス間で共有しない。
+ forkEvery = headlessMode ? 0 : 1
+ systemProperty('tcv.test.headless', headlessMode.toString())
+ systemProperty('testfx.robot', 'glass')
+ // TestFX's legacy bootstrap selects Monocle; the toolkit now owns headless mode.
+ systemProperty('testfx.headless', 'false')
+ jvmArgs '--enable-native-access=ALL-UNNAMED'
+ jvmArgumentProviders.add(objects.newInstance(MockitoAgentProvider).tap {
+ agentJar.from(configurations.mockitoAgent)
+ })
+ jvmArgumentProviders.add(objects.newInstance(ProductionClasspathProvider).tap {
+ runtimeClasspath.from(sourceSets.main.runtimeClasspath)
+ })
+ if (headlessMode) {
+ systemProperty('glass.platform', 'headless')
+ systemProperty('java.awt.headless', 'true')
systemProperty("prism.order", "sw")
- systemProperty("prism.text", "t2k")
- systemProperty("headless.geometry", "1600x1200-32")
}
- useJUnitPlatform()
-}
\ No newline at end of file
+ useJUnitPlatform {
+ if (!providers.gradleProperty('osKeychainTests').map { it.toBoolean() }.getOrElse(false)) {
+ excludeTags 'os-keychain'
+ }
+ }
+}
diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle
new file mode 100644
index 0000000..2667cc9
--- /dev/null
+++ b/buildSrc/build.gradle
@@ -0,0 +1,21 @@
+plugins { id 'groovy' }
+
+repositories { mavenCentral() }
+
+def javaFeature = libs.versions.java.get().toInteger()
+java { toolchain { languageVersion = JavaLanguageVersion.of(javaFeature) } }
+tasks.withType(JavaCompile).configureEach {
+ options.encoding = 'UTF-8'
+ options.release = javaFeature
+}
+
+dependencies {
+ implementation gradleApi()
+ implementation localGroovy()
+ testImplementation platform(libs.junit.bom)
+ testImplementation libs.junit.jupiter
+ testImplementation libs.assertj
+ testRuntimeOnly libs.junit.launcher
+}
+
+test { useJUnitPlatform() }
diff --git a/buildSrc/settings.gradle b/buildSrc/settings.gradle
new file mode 100644
index 0000000..e753c9d
--- /dev/null
+++ b/buildSrc/settings.gradle
@@ -0,0 +1,7 @@
+rootProject.name = 'buildSrc'
+
+dependencyResolutionManagement {
+ versionCatalogs {
+ libs { from(files('../gradle/libs.versions.toml')) }
+ }
+}
diff --git a/buildSrc/src/main/groovy/com/github/k7t3/tcv/build/JdkModulesTask.groovy b/buildSrc/src/main/groovy/com/github/k7t3/tcv/build/JdkModulesTask.groovy
new file mode 100644
index 0000000..874f475
--- /dev/null
+++ b/buildSrc/src/main/groovy/com/github/k7t3/tcv/build/JdkModulesTask.groovy
@@ -0,0 +1,48 @@
+package com.github.k7t3.tcv.build
+
+import org.gradle.api.file.DirectoryProperty
+import org.gradle.api.file.RegularFileProperty
+import org.gradle.api.provider.ListProperty
+import org.gradle.api.provider.Property
+import org.gradle.api.tasks.*
+import org.gradle.work.DisableCachingByDefault
+import java.nio.charset.StandardCharsets
+import java.nio.file.Files
+
+@DisableCachingByDefault(because = 'Invokes the selected native JDK tool')
+abstract class JdkModulesTask extends JdkToolTask {
+ @InputDirectory @PathSensitive(PathSensitivity.RELATIVE) abstract DirectoryProperty getInputDirectory()
+ @InputDirectory @PathSensitive(PathSensitivity.RELATIVE) abstract DirectoryProperty getModuleDirectory()
+ @Input abstract Property getMainJar()
+ @Input abstract ListProperty getJavafxModules()
+ @OutputFile abstract RegularFileProperty getModulesFile()
+ @Override protected String getToolName() { 'jdeps' }
+
+ @TaskAction void inspectModules() {
+ verifyToolchain()
+ def output = new ByteArrayOutputStream()
+ def errors = new ByteArrayOutputStream()
+ def toolExecutable = executable
+ def result = execOperations.exec {
+ executable = toolExecutable
+ args '--module-path', moduleDirectory.get().asFile.absolutePath,
+ '--add-modules', 'ALL-MODULE-PATH', '--multi-release', javaFeatureVersion.get().toString(),
+ '--ignore-missing-deps', '--print-module-deps',
+ '--class-path', new File(inputDirectory.get().asFile, '*').absolutePath,
+ inputDirectory.file(mainJar).get().asFile.absolutePath
+ standardOutput = output
+ errorOutput = errors
+ ignoreExitValue = true
+ }
+ if (result.exitValue != 0) {
+ logger.error(output.toString(StandardCharsets.UTF_8))
+ logger.error(errors.toString(StandardCharsets.UTF_8))
+ result.assertNormalExitValue()
+ }
+ def modules = PackagePlan.modules(output.toString(StandardCharsets.UTF_8), javafxModules.get())
+ def target = modulesFile.get().asFile.toPath()
+ Files.createDirectories(target.parent)
+ Files.writeString(target, modules.join(',') + '\n', StandardCharsets.UTF_8)
+ logger.lifecycle("Runtime modules: ${modules.join(',')}")
+ }
+}
diff --git a/buildSrc/src/main/groovy/com/github/k7t3/tcv/build/JdkToolTask.groovy b/buildSrc/src/main/groovy/com/github/k7t3/tcv/build/JdkToolTask.groovy
new file mode 100644
index 0000000..78d16d1
--- /dev/null
+++ b/buildSrc/src/main/groovy/com/github/k7t3/tcv/build/JdkToolTask.groovy
@@ -0,0 +1,32 @@
+package com.github.k7t3.tcv.build
+
+import org.gradle.api.DefaultTask
+import org.gradle.api.GradleException
+import org.gradle.api.provider.Property
+import org.gradle.api.tasks.Internal
+import org.gradle.api.tasks.Input
+import org.gradle.api.tasks.Nested
+import org.gradle.jvm.toolchain.JavaLauncher
+import org.gradle.process.ExecOperations
+import javax.inject.Inject
+
+/** コンパイル・テストと同じ toolchain の JDK ツールを使う。 */
+abstract class JdkToolTask extends DefaultTask {
+ @Nested abstract Property getJavaLauncher()
+ @Input abstract Property getJavaFeatureVersion()
+ @Inject protected abstract ExecOperations getExecOperations()
+ @Internal protected abstract String getToolName()
+
+ @Internal String getExecutable() {
+ def suffix = System.getProperty('os.name').toLowerCase(Locale.ROOT).startsWith('windows') ? '.exe' : ''
+ javaLauncher.get().metadata.installationPath.file("bin/${toolName}${suffix}").asFile.absolutePath
+ }
+
+ protected void verifyToolchain() {
+ def metadata = javaLauncher.get().metadata
+ if (metadata.languageVersion.asInt() != javaFeatureVersion.get() || !new File(executable).isFile()) {
+ throw new GradleException("${toolName} requires a complete Java ${javaFeatureVersion.get()} JDK: ${metadata.installationPath}")
+ }
+ logger.lifecycle("${toolName}: ${executable} (Java ${metadata.javaRuntimeVersion})")
+ }
+}
diff --git a/buildSrc/src/main/groovy/com/github/k7t3/tcv/build/NativePackageTask.groovy b/buildSrc/src/main/groovy/com/github/k7t3/tcv/build/NativePackageTask.groovy
new file mode 100644
index 0000000..f3bce61
--- /dev/null
+++ b/buildSrc/src/main/groovy/com/github/k7t3/tcv/build/NativePackageTask.groovy
@@ -0,0 +1,64 @@
+package com.github.k7t3.tcv.build
+
+import org.gradle.api.GradleException
+import org.gradle.api.file.ConfigurableFileCollection
+import org.gradle.api.file.DirectoryProperty
+import org.gradle.api.file.RegularFileProperty
+import org.gradle.api.provider.Property
+import org.gradle.api.tasks.*
+import org.gradle.work.DisableCachingByDefault
+import java.nio.charset.StandardCharsets
+import java.nio.file.Files
+
+@DisableCachingByDefault(because = 'Native packaging also depends on external OS tools')
+abstract class NativePackageTask extends JdkToolTask {
+ @InputDirectory @PathSensitive(PathSensitivity.RELATIVE) abstract DirectoryProperty getInputDirectory()
+ @InputDirectory @PathSensitive(PathSensitivity.RELATIVE) abstract DirectoryProperty getModuleDirectory()
+ @InputFile @PathSensitive(PathSensitivity.NONE) abstract RegularFileProperty getModulesFile()
+ @Input abstract Property getMainJar()
+ @Input abstract Property getMainClass()
+ @Input abstract Property getFullVersion()
+ @Input abstract Property getPlatformName()
+ @Input abstract Property getAppImage()
+ @Internal abstract DirectoryProperty getProjectRoot()
+ @InputFiles @PathSensitive(PathSensitivity.RELATIVE) abstract ConfigurableFileCollection getPackageResources()
+ @OutputDirectory abstract DirectoryProperty getOutputDirectory()
+ @LocalState abstract RegularFileProperty getLogFile()
+ @Override protected String getToolName() { 'jpackage' }
+
+ NativePackageTask() {
+ // WiX / hdiutil / dpkg と署名環境は Gradle の入力だけでは追跡できない。
+ outputs.upToDateWhen { false }
+ }
+
+ @TaskAction void createPackage() {
+ verifyToolchain()
+ def platform = PackagePlan.Platform.valueOf(platformName.get())
+ def modules = PackagePlan.modules(Files.readString(modulesFile.get().asFile.toPath()).trim(), [])
+ def input = new PackagePlan.Inputs(platform, appImage.get(), fullVersion.get(),
+ inputDirectory.get().asFile.toPath(), moduleDirectory.get().asFile.toPath(),
+ mainJar.get(), mainClass.get(), projectRoot.get().asFile.toPath(), modules)
+ PackagePlan.validateInputs(input)
+ def log = logFile.get().asFile.toPath()
+ def toolExecutable = executable
+ Files.createDirectories(log.parent)
+ def produced = PackageOutput.produce(outputDirectory.get().asFile.toPath(), { staging ->
+ Files.newOutputStream(log).withCloseable { stream ->
+ def result = execOperations.exec {
+ executable = toolExecutable
+ args PackagePlan.arguments(input, staging)
+ standardOutput = stream
+ errorOutput = stream
+ ignoreExitValue = true
+ }
+ if (result.exitValue != 0) {
+ throw new GradleException("jpackage failed (${result.exitValue}); see ${log.toAbsolutePath()}")
+ }
+ }
+ } as PackageOutput.Generator)
+ logger.lifecycle("Created package: ${produced.output()}; log: ${log.toAbsolutePath()}")
+ produced.cleanupFailures().each { cleanup ->
+ logger.warn("Package was created, but cleanup failed for owned directory ${cleanup.directory()}", cleanup.failure())
+ }
+ }
+}
diff --git a/buildSrc/src/main/java/com/github/k7t3/tcv/build/LinuxGlibcRequirement.java b/buildSrc/src/main/java/com/github/k7t3/tcv/build/LinuxGlibcRequirement.java
new file mode 100644
index 0000000..91cdb51
--- /dev/null
+++ b/buildSrc/src/main/java/com/github/k7t3/tcv/build/LinuxGlibcRequirement.java
@@ -0,0 +1,135 @@
+package com.github.k7t3.tcv.build;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+import java.util.regex.Pattern;
+import java.util.zip.ZipFile;
+
+/** 解決済みの対象OS/CPU向けJavaFX JARから、ELF64の強いGLIBCバージョン参照を読む。 */
+final class LinuxGlibcRequirement {
+ private static final int VERSION_NEEDS = 0x6ffffffe;
+ private static final int WEAK_VERSION = 2;
+ private static final Pattern GLIBC_VERSION = Pattern.compile("GLIBC_(\\d+(?:\\.\\d+)+)");
+ private LinuxGlibcRequirement() {}
+
+ /** 解析不能なネイティブ資源は、要件を省略せずIOExceptionで報告する。 */
+ static Optional minimumVersion(Path moduleDirectory) throws IOException {
+ Version highest = null;
+ try (var files = Files.list(moduleDirectory)) {
+ for (var path : files.filter(file -> file.getFileName().toString().endsWith(".jar")).sorted().toList()) {
+ try (var archive = new ZipFile(path.toFile())) {
+ var entries = archive.entries();
+ while (entries.hasMoreElements()) {
+ var entry = entries.nextElement();
+ if (entry.isDirectory() || !entry.getName().endsWith(".so")) continue;
+ try (var input = archive.getInputStream(entry)) {
+ highest = maximum(highest, read(input.readAllBytes()));
+ } catch (IOException failure) {
+ throw new IOException("Cannot inspect native ABI: " + path + "!/" + entry.getName(), failure);
+ }
+ }
+ }
+ }
+ }
+ return Optional.ofNullable(highest).map(Version::text);
+ }
+
+ private static Version read(byte[] bytes) throws IOException {
+ try {
+ if (bytes.length < 64 || bytes[0] != 0x7f || bytes[1] != 'E' || bytes[2] != 'L'
+ || bytes[3] != 'F' || bytes[4] != 2 || bytes[5] != 1)
+ throw new IOException("Expected a little-endian ELF64 native resource");
+ var data = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
+ var table = Math.toIntExact(data.getLong(40));
+ var entrySize = Short.toUnsignedInt(data.getShort(58));
+ var count = Short.toUnsignedInt(data.getShort(60));
+ if (entrySize < 64 || count == 0) throw new IOException("ELF section headers unavailable");
+ range(table, Math.multiplyExact(entrySize, count), bytes.length);
+ Version highest = null;
+ // 未使用の文字列や定義を拾わず、SHT_GNU_verneedとそのVernauxだけを辿る。
+ for (var i = 0; i < count; i++) {
+ var header = table + i * entrySize;
+ if (data.getInt(header + 4) != VERSION_NEEDS) continue;
+ var linked = data.getInt(header + 40);
+ if (linked < 0 || linked >= count) throw new IOException("Invalid ELF version string-table link");
+ var stringHeader = table + linked * entrySize;
+ if (data.getInt(stringHeader + 4) != 3) throw new IOException("ELF version link is not a string table");
+ var strings = section(data, stringHeader);
+ var needs = section(data, header);
+ var record = needs.offset();
+ while (record < needs.end()) {
+ range(record, 16, needs.end());
+ if (data.getShort(record) != 1) throw new IOException("Unsupported ELF version-needs revision");
+ var versions = Short.toUnsignedInt(data.getShort(record + 2));
+ var auxiliary = Math.addExact(record, unsigned(data, record + 8));
+ for (var j = 0; j < versions; j++) {
+ range(auxiliary, 16, needs.end());
+ var name = string(bytes, strings, unsigned(data, auxiliary + 8));
+ var match = GLIBC_VERSION.matcher(name);
+ if ((data.getShort(auxiliary + 4) & WEAK_VERSION) == 0) {
+ if (match.matches()) highest = maximum(highest, new Version(match.group(1)));
+ else if (name.startsWith("GLIBC_")) throw new IOException("Unsupported GLIBC version requirement: " + name);
+ }
+ var next = unsigned(data, auxiliary + 12);
+ if (j + 1 < versions && next < 16) throw new IOException("Truncated ELF auxiliary version chain");
+ auxiliary = Math.addExact(auxiliary, next);
+ }
+ var next = unsigned(data, record + 12);
+ if (next == 0) break;
+ if (next < 16) throw new IOException("Invalid ELF version-needs chain");
+ record = Math.addExact(record, next);
+ range(record, 16, needs.end());
+ }
+ }
+ return highest;
+ } catch (IndexOutOfBoundsException | ArithmeticException | NumberFormatException failure) {
+ throw new IOException("Invalid ELF native version metadata", failure);
+ }
+ }
+
+ private static Section section(ByteBuffer data, int header) throws IOException {
+ var offset = Math.toIntExact(data.getLong(header + 24));
+ var size = Math.toIntExact(data.getLong(header + 32));
+ range(offset, size, data.limit());
+ return new Section(offset, size);
+ }
+
+ private static String string(byte[] bytes, Section table, int index) throws IOException {
+ if (index < 0 || index >= table.size()) throw new IOException("Invalid ELF version string index");
+ var start = table.offset() + index;
+ var end = start;
+ while (end < table.end() && bytes[end] != 0) end++;
+ if (end == table.end()) throw new IOException("Unterminated ELF version string");
+ return new String(bytes, start, end - start, StandardCharsets.US_ASCII);
+ }
+
+ private static int unsigned(ByteBuffer data, int offset) { return Math.toIntExact(Integer.toUnsignedLong(data.getInt(offset))); }
+
+ private static void range(int offset, int size, int limit) throws IOException {
+ if (offset < 0 || size < 0 || offset > limit || size > limit - offset) throw new IOException("ELF metadata range outside section");
+ }
+
+ private static Version maximum(Version left, Version right) {
+ return right == null || left != null && left.compareTo(right) >= 0 ? left : right;
+ }
+
+ private record Section(int offset, int size) { int end() { return offset + size; } }
+
+ private record Version(String text, List parts) implements Comparable {
+ Version(String text) { this(text, Arrays.stream(text.split("\\.")).map(Integer::parseInt).toList()); }
+ @Override public int compareTo(Version other) {
+ for (var i = 0; i < Math.max(parts.size(), other.parts.size()); i++) {
+ var comparison = Integer.compare(i < parts.size() ? parts.get(i) : 0, i < other.parts.size() ? other.parts.get(i) : 0);
+ if (comparison != 0) return comparison;
+ }
+ return 0;
+ }
+ }
+}
diff --git a/buildSrc/src/main/java/com/github/k7t3/tcv/build/PackageOutput.java b/buildSrc/src/main/java/com/github/k7t3/tcv/build/PackageOutput.java
new file mode 100644
index 0000000..d2de95a
--- /dev/null
+++ b/buildSrc/src/main/java/com/github/k7t3/tcv/build/PackageOutput.java
@@ -0,0 +1,111 @@
+package com.github.k7t3.tcv.build;
+
+import java.io.IOException;
+import java.nio.file.AtomicMoveNotSupportedException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.LinkOption;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.UUID;
+
+/** 公開前の失敗では直前の成果物を残し、公開後の削除失敗は公開結果に付記する。 */
+public final class PackageOutput {
+ private PackageOutput() {}
+ @FunctionalInterface public interface Generator { void generate(Path staging) throws Exception; }
+ @FunctionalInterface interface Mover { void move(Path source, Path target) throws IOException; }
+ @FunctionalInterface interface Remover { void remove(Path path) throws IOException; }
+
+ /** 公開済み出力と、呼出側が報告する削除失敗。 */
+ public record Result(Path output, List cleanupFailures) {
+ public Result { Objects.requireNonNull(output); cleanupFailures = List.copyOf(cleanupFailures); }
+ }
+
+ /** 削除できず残った自己所有領域と元のI/O失敗。 */
+ public record CleanupFailure(Path directory, IOException failure) {
+ public CleanupFailure { Objects.requireNonNull(directory); Objects.requireNonNull(failure); }
+ }
+
+ public static Result produce(Path output, Generator generator) throws Exception { return produce(output, generator, PackageOutput::move); }
+
+ static Result produce(Path output, Generator generator, Mover mover) throws Exception {
+ return produce(output, generator, mover, PackageOutput::deleteTree);
+ }
+
+ static Result produce(Path output, Generator generator, Mover mover, Remover remover) throws Exception {
+ var destination = output.toAbsolutePath().normalize();
+ if (destination.getParent() == null || (Files.exists(destination, LinkOption.NOFOLLOW_LINKS)
+ && !Files.isDirectory(destination, LinkOption.NOFOLLOW_LINKS))) {
+ throw new IllegalArgumentException("package output must be an owned directory: " + destination);
+ }
+ Files.createDirectories(destination.getParent());
+ var staging = Files.createTempDirectory(destination.getParent(), ".tcv-package-");
+ var cleanupFailures = new ArrayList();
+ boolean published = false;
+ Throwable failure = null;
+ try {
+ generator.generate(staging);
+ try (var generated = Files.list(staging)) {
+ if (generated.findAny().isEmpty()) throw new IOException("generator produced no package");
+ }
+ publish(staging, destination, mover, remover, cleanupFailures);
+ published = true;
+ } catch (Exception | Error original) {
+ failure = original;
+ throw original;
+ } finally {
+ try { remover.remove(staging); }
+ catch (IOException cleanup) {
+ if (failure != null) failure.addSuppressed(cleanup);
+ else if (published) cleanupFailures.add(new CleanupFailure(staging, cleanup));
+ else throw cleanup;
+ }
+ }
+ return new Result(destination, cleanupFailures);
+ }
+
+ private static void publish(Path staging, Path destination, Mover mover, Remover remover,
+ List cleanupFailures) throws IOException {
+ var backup = destination.getParent().resolve(".tcv-previous-" + UUID.randomUUID());
+ var previous = Files.exists(destination, LinkOption.NOFOLLOW_LINKS);
+ if (previous) mover.move(destination, backup);
+ try { mover.move(staging, destination); }
+ catch (IOException | RuntimeException | Error original) {
+ if (previous) {
+ try { mover.move(backup, destination); }
+ catch (IOException | RuntimeException | Error restore) {
+ if (restore != original) original.addSuppressed(restore);
+ original.addSuppressed(new IOException("Previous package remains at " + backup));
+ }
+ }
+ throw original;
+ }
+ if (previous) {
+ try { remover.remove(backup); }
+ catch (IOException cleanup) { cleanupFailures.add(new CleanupFailure(backup, cleanup)); }
+ }
+ }
+
+ private static void move(Path source, Path target) throws IOException {
+ try { Files.move(source, target, StandardCopyOption.ATOMIC_MOVE); }
+ catch (AtomicMoveNotSupportedException unsupported) { Files.move(source, target); }
+ }
+
+ private static void deleteTree(Path path) throws IOException {
+ if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) return;
+ Files.walkFileTree(path, new SimpleFileVisitor<>() {
+ @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
+ Files.delete(file); return FileVisitResult.CONTINUE;
+ }
+ @Override public FileVisitResult postVisitDirectory(Path directory, IOException failure) throws IOException {
+ if (failure != null) throw failure;
+ Files.delete(directory); return FileVisitResult.CONTINUE;
+ }
+ });
+ }
+}
diff --git a/buildSrc/src/main/java/com/github/k7t3/tcv/build/PackagePlan.java b/buildSrc/src/main/java/com/github/k7t3/tcv/build/PackagePlan.java
new file mode 100644
index 0000000..181efd2
--- /dev/null
+++ b/buildSrc/src/main/java/com/github/k7t3/tcv/build/PackagePlan.java
@@ -0,0 +1,115 @@
+package com.github.k7t3.tcv.build;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import java.util.TreeSet;
+import java.util.regex.Pattern;
+
+/** jpackage の引数を不変の入力から組み立てる。外部コマンドや既存の配布物には作用しない。 */
+public final class PackagePlan {
+ private static final Pattern VERSION = Pattern.compile("([0-9]+)\\.([0-9]+)\\.([0-9]+)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?");
+ private static final Pattern MODULE = Pattern.compile("[A-Za-z_][A-Za-z0-9_.]*");
+
+ private PackagePlan() {}
+
+ public enum Platform {
+ WINDOWS("exe", "TwitchChatViewer.ico"), MAC("dmg", "TwitchChatViewer.icns"), LINUX("deb", "TwitchChatViewer-64.png");
+ private final String installer;
+ private final String icon;
+ Platform(String installer, String icon) { this.installer = installer; this.icon = icon; }
+ public String installerType() { return installer; }
+ public String iconName() { return icon; }
+ public static Platform fromOsName(String name) {
+ var value = name.toLowerCase(Locale.ROOT);
+ if (value.startsWith("windows")) return WINDOWS;
+ if (value.startsWith("mac")) return MAC;
+ if (value.startsWith("linux")) return LINUX;
+ throw new IllegalArgumentException("unsupported packaging OS: " + name);
+ }
+ }
+
+ public record Inputs(Platform platform, boolean appImage, String fullVersion, Path inputDirectory, Path moduleDirectory,
+ String mainJar, String mainClass, Path projectRoot, List modules) {
+ public Inputs { modules = List.copyOf(modules); }
+ }
+
+ public static String nativeVersion(String version) {
+ var matcher = VERSION.matcher(version == null ? "" : version);
+ if (!matcher.matches()) throw new IllegalArgumentException("invalid application version: " + version);
+ return matcher.group(1) + "." + matcher.group(2) + "." + matcher.group(3);
+ }
+
+ public static List modules(String output, List javafx) {
+ if (output == null || output.isBlank()) throw new IllegalArgumentException("jdeps returned no modules");
+ var modules = new TreeSet();
+ for (var name : output.trim().split(",", -1)) {
+ if (!MODULE.matcher(name).matches()) throw new IllegalArgumentException("invalid jdeps module: " + name);
+ modules.add(name);
+ }
+ for (var name : javafx) {
+ if (!MODULE.matcher(name).matches()) throw new IllegalArgumentException("invalid javafx module: " + name);
+ modules.add(name);
+ }
+ modules.add("jdk.crypto.ec");
+ return List.copyOf(modules);
+ }
+
+ public static void validateInputs(Inputs input) {
+ nativeVersion(input.fullVersion());
+ var jar = input.mainJar();
+ if (jar == null || jar.isBlank() || jar.contains("/") || jar.contains("\\") || jar.equals(".") || jar.equals(".."))
+ throw new IllegalArgumentException("main JAR must be an input file name");
+ if (!Files.isRegularFile(input.inputDirectory().resolve(jar))) throw new IllegalArgumentException("missing main JAR: " + jar);
+ if (!Files.isRegularFile(input.inputDirectory().resolve("key-storage.properties")))
+ throw new IllegalArgumentException("missing key storage launcher configuration");
+ if (!Files.isDirectory(input.moduleDirectory())) throw new IllegalArgumentException("missing JavaFX module directory");
+ if (!Files.isRegularFile(input.projectRoot().resolve("docs/license.md"))) throw new IllegalArgumentException("missing package license");
+ if (!Files.isRegularFile(icon(input))) throw new IllegalArgumentException("missing package icon: " + icon(input));
+ modules(String.join(",", input.modules()), List.of());
+ }
+
+ private static Path icon(Inputs input) { return input.projectRoot().resolve("src/main/resources/icons").resolve(input.platform().iconName()); }
+
+ /**
+ * 検証済みの入力から引数を組み立て、Linuxインストーラーには対象JavaFXのGLIBC要件も加える。
+ * @param input 配布対象と入力ファイル
+ * @param output 自己所有の生成先
+ * @return 呼出側が変更できない引数一覧
+ * @throws IOException Linuxネイティブ資源の読取・ABI解析に失敗した場合
+ */
+ public static List arguments(Inputs input, Path output) throws IOException {
+ validateInputs(input);
+ var args = new ArrayList<>(List.of(
+ "--verbose", "--type", input.appImage() ? "app-image" : input.platform().installerType(),
+ "--name", "Twitch Chat Viewer", "--description", "Chat Viewer for twitch.tv",
+ "--copyright", "Copyright (c) 2024 k7t3. All rights reserved.", "--vendor", "k7t3",
+ "--app-version", nativeVersion(input.fullVersion()), "--dest", output.toString(),
+ "--module-path", input.moduleDirectory().toString(), "--add-modules", String.join(",", modules(String.join(",", input.modules()), List.of())),
+ "--input", input.inputDirectory().toString(), "--main-jar", input.mainJar(), "--main-class", input.mainClass(),
+ "--add-launcher", "Twitch Key Storage=" + input.inputDirectory().resolve("key-storage.properties"),
+ "--java-options", "-Dapp.version=" + input.fullVersion(),
+ "--java-options", "--enable-native-access=javafx.graphics,ALL-UNNAMED", "--icon", icon(input).toString()));
+ if (input.platform() == Platform.MAC) args.addAll(List.of("--mac-package-identifier", "TwitchChatViewer"));
+ if (!input.appImage()) {
+ args.addAll(List.of("--license-file", input.projectRoot().resolve("docs/license.md").toString()));
+ switch (input.platform()) {
+ case WINDOWS -> args.addAll(List.of("--win-shortcut", "--win-menu", "--win-menu-group", "TwitchChatViewer", "--win-per-user-install",
+ "--win-shortcut-prompt", "--win-upgrade-uuid", "b78817e8-f9b8-4650-bf0a-34bca5ff4106", "--win-help-url",
+ "https://github.com/k7t3/TwitchChatViewer", "--win-update-url", "https://github.com/k7t3/TwitchChatViewer/releases"));
+ case LINUX -> {
+ var dependencies = new ArrayList<>(List.of("libsecret-1-0 (>= 0.19.0)", "libgtk-3-0 (>= 3.20.0)", "libxtst6"));
+ LinuxGlibcRequirement.minimumVersion(input.moduleDirectory())
+ .ifPresent(version -> dependencies.add("libc6 (>= " + version + ")"));
+ args.addAll(List.of("--linux-menu-group", "Network", "--linux-rpm-license-type", "Apache-2.0", "--linux-shortcut",
+ "--linux-package-deps", String.join(", ", dependencies)));
+ }
+ case MAC -> {}
+ }
+ }
+ return List.copyOf(args);
+ }
+}
diff --git a/buildSrc/src/test/java/com/github/k7t3/tcv/build/LinuxGlibcRequirementTest.java b/buildSrc/src/test/java/com/github/k7t3/tcv/build/LinuxGlibcRequirementTest.java
new file mode 100644
index 0000000..8972f63
--- /dev/null
+++ b/buildSrc/src/test/java/com/github/k7t3/tcv/build/LinuxGlibcRequirementTest.java
@@ -0,0 +1,170 @@
+package com.github.k7t3.tcv.build;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+class LinuxGlibcRequirementTest {
+ @TempDir Path directory;
+
+ @Test
+ void theRequiredVersionComesFromTheHighestNativeReferenceAcrossModuleJars() throws Exception {
+ module("base.jar", elf("GLIBC_2.17", "GLIBC_2.9"));
+ module("graphics.jar", elf("GLIBC_2.38"));
+
+ var required = LinuxGlibcRequirement.minimumVersion(directory);
+
+ assertThat(required).contains("2.38");
+ }
+
+ @Test
+ void optionalWeakVersionsDoNotRaiseTheRequiredRuntimeVersion() throws Exception {
+ var data = ByteBuffer.wrap(elf("GLIBC_2.17", "GLIBC_9.99")).order(ByteOrder.LITTLE_ENDIAN);
+ var needs = Math.toIntExact(data.getLong(216));
+ data.putShort(needs + 16 + 16 + 4, (short) 2);
+ module("graphics.jar", data.array());
+
+ assertThat(LinuxGlibcRequirement.minimumVersion(directory)).contains("2.17");
+ }
+
+ @Test
+ void unknownGlibcRequirementsCannotSilentlyDeclareAnOlderRuntime() throws Exception {
+ module("graphics.jar", elf("GLIBC_2.17", "GLIBC_FUTURE"));
+
+ assertThatThrownBy(() -> LinuxGlibcRequirement.minimumVersion(directory))
+ .isInstanceOf(IOException.class)
+ .hasMessageContaining("graphics.jar!/libsample.so")
+ .hasRootCauseMessage("Unsupported GLIBC version requirement: GLIBC_FUTURE");
+ }
+
+ @Test
+ void unreferencedVersionTextDoesNotRaiseTheRuntimeRequirement() throws Exception {
+ var library = elf("GLIBC_2.17");
+ var extra = "GLIBC_99.0\0".getBytes(StandardCharsets.US_ASCII);
+ var withDebugText = Arrays.copyOf(library, library.length + extra.length);
+ System.arraycopy(extra, 0, withDebugText, library.length, extra.length);
+ module("graphics.jar", withDebugText);
+
+ assertThat(LinuxGlibcRequirement.minimumVersion(directory)).contains("2.17");
+ }
+
+ @Test
+ void modulesWithoutNativeLibrariesHaveNoAdditionalGlibcRequirement() throws Exception {
+ try (var archive = new ZipOutputStream(Files.newOutputStream(directory.resolve("controls.jar")))) {
+ archive.putNextEntry(new ZipEntry("fixture/Control.class"));
+ archive.write("GLIBC_99.0".getBytes(StandardCharsets.US_ASCII));
+ archive.closeEntry();
+ }
+
+ assertThat(LinuxGlibcRequirement.minimumVersion(directory)).isEmpty();
+ }
+
+ @ParameterizedTest(name = "{0}")
+ @MethodSource("malformedMetadata")
+ void malformedMetadataFailsWithTheArchiveAndResourceContext(String reason, byte[] bytes) throws Exception {
+ module("graphics.jar", bytes);
+
+ assertThatThrownBy(() -> LinuxGlibcRequirement.minimumVersion(directory))
+ .isInstanceOf(IOException.class)
+ .hasMessageContaining("graphics.jar!/libsample.so");
+ }
+
+ @Test
+ void theInstallerDeclaresTheAbiRequiredByItsResolvedJavafxModules() throws Exception {
+ module("graphics.jar", elf("GLIBC_2.17", "GLIBC_2.38"));
+ var input = Files.createDirectories(directory.resolve("input"));
+ Files.writeString(input.resolve("app.jar"), "synthetic application fixture");
+ Files.writeString(input.resolve("key-storage.properties"), "main-class=fixture.Helper");
+ Files.createDirectories(directory.resolve("docs"));
+ Files.writeString(directory.resolve("docs/license.md"), "synthetic license");
+ var icons = Files.createDirectories(directory.resolve("src/main/resources/icons"));
+ Files.writeString(icons.resolve("TwitchChatViewer-64.png"), "synthetic icon");
+ var plan = new PackagePlan.Inputs(PackagePlan.Platform.LINUX, false, "1.0.0", input, directory,
+ "app.jar", "fixture.Main", directory, List.of("java.base"));
+
+ var arguments = PackagePlan.arguments(plan, directory.resolve("output"));
+
+ assertThat(arguments).contains("--linux-package-deps");
+ assertThat(arguments.get(arguments.indexOf("--linux-package-deps") + 1))
+ .contains("libc6 (>= 2.38)");
+ }
+
+ private static Stream malformedMetadata() throws Exception {
+ var valid = elf("GLIBC_2.17", "GLIBC_2.38");
+ var header = ByteBuffer.wrap(valid).order(ByteOrder.LITTLE_ENDIAN);
+ var needs = Math.toIntExact(header.getLong(216));
+ var lastStringByte = Math.toIntExact(header.getLong(152) + header.getLong(160) - 1);
+ return Stream.of(
+ Arguments.of("truncated header", Arrays.copyOf(valid, 32)),
+ Arguments.of("unsupported byte order", changed(valid, data -> data.put(5, (byte) 2))),
+ Arguments.of("section-table overflow", changed(valid, data -> data.putLong(40, Long.MAX_VALUE))),
+ Arguments.of("invalid string-table link", changed(valid, data -> data.putInt(232, 99))),
+ Arguments.of("invalid version string index", changed(valid, data -> data.putInt(needs + 16 + 8, Integer.MAX_VALUE))),
+ Arguments.of("unterminated version string", changed(valid, data -> data.put(lastStringByte, (byte) 'x'))),
+ Arguments.of("truncated auxiliary chain", changed(valid, data -> data.putInt(needs + 16 + 12, 0))),
+ Arguments.of("unsupported numeric version", elf("GLIBC_2.99999999999999999999")));
+ }
+
+ private static byte[] changed(byte[] bytes, Consumer edit) {
+ var result = bytes.clone();
+ edit.accept(ByteBuffer.wrap(result).order(ByteOrder.LITTLE_ENDIAN));
+ return result;
+ }
+
+ private void module(String name, byte[] nativeLibrary) throws Exception {
+ try (var archive = new ZipOutputStream(Files.newOutputStream(directory.resolve(name)))) {
+ archive.putNextEntry(new ZipEntry("libsample.so"));
+ archive.write(nativeLibrary);
+ archive.closeEntry();
+ }
+ }
+
+ /** ELF64の公開ABIどおりに、文字列表と1件のVerneed/Vernaux列を持つfixtureを作る。 */
+ private static byte[] elf(String... versions) throws Exception {
+ var strings = new ByteArrayOutputStream();
+ strings.write(0);
+ strings.write("libc.so.6\0".getBytes(StandardCharsets.US_ASCII));
+ var names = new ArrayList();
+ for (var version : versions) {
+ names.add(strings.size());
+ strings.write((version + "\0").getBytes(StandardCharsets.US_ASCII));
+ }
+ var stringOffset = 256;
+ var needsOffset = (stringOffset + strings.size() + 7) / 8 * 8;
+ var needsSize = 16 + 16 * versions.length;
+ var data = ByteBuffer.allocate(needsOffset + needsSize).order(ByteOrder.LITTLE_ENDIAN);
+ data.put(new byte[]{0x7f, 'E', 'L', 'F', 2, 1, 1});
+ data.putShort(16, (short) 3).putShort(18, (short) 183).putInt(20, 1);
+ data.putLong(40, 64).putShort(52, (short) 64).putShort(58, (short) 64).putShort(60, (short) 3);
+ data.putInt(132, 3).putLong(152, stringOffset).putLong(160, strings.size());
+ data.putInt(196, 0x6ffffffe).putLong(216, needsOffset).putLong(224, needsSize).putInt(232, 1).putInt(236, 1);
+ data.position(stringOffset);
+ data.put(strings.toByteArray());
+ data.putShort(needsOffset, (short) 1).putShort(needsOffset + 2, (short) versions.length)
+ .putInt(needsOffset + 4, 1).putInt(needsOffset + 8, 16);
+ for (var i = 0; i < versions.length; i++) {
+ var auxiliary = needsOffset + 16 + i * 16;
+ data.putInt(auxiliary + 8, names.get(i)).putInt(auxiliary + 12, i + 1 == versions.length ? 0 : 16);
+ }
+ return data.array();
+ }
+}
diff --git a/buildSrc/src/test/java/com/github/k7t3/tcv/build/PackageOutputTest.java b/buildSrc/src/test/java/com/github/k7t3/tcv/build/PackageOutputTest.java
new file mode 100644
index 0000000..93f6665
--- /dev/null
+++ b/buildSrc/src/test/java/com/github/k7t3/tcv/build/PackageOutputTest.java
@@ -0,0 +1,125 @@
+package com.github.k7t3.tcv.build;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import java.io.IOException;
+import java.nio.file.DirectoryNotEmptyException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.concurrent.atomic.AtomicReference;
+import static org.assertj.core.api.Assertions.*;
+
+class PackageOutputTest {
+ @TempDir Path directory;
+
+ @Test
+ void aRetirementFailureReportsThePublishedPackageAndItsOwnedRemnant() throws Exception {
+ var output = previous();
+ Files.writeString(output.resolve("retained.dmg"), "remaining old package");
+ var failure = new DirectoryNotEmptyException("synthetic retired directory");
+ var retired = new AtomicReference();
+
+ var result = PackageOutput.produce(output, staging -> Files.writeString(staging.resolve("new.dmg"), "new"),
+ (source, target) -> Files.move(source, target, StandardCopyOption.ATOMIC_MOVE), path -> {
+ if (path.getFileName().toString().startsWith(".tcv-previous-")) {
+ retired.set(path);
+ Files.delete(path.resolve("previous.dmg"));
+ throw failure;
+ }
+ Files.deleteIfExists(path);
+ });
+
+ assertThat(result.output()).isEqualTo(output.toAbsolutePath().normalize());
+ assertThat(Files.readString(output.resolve("new.dmg"))).isEqualTo("new");
+ assertThat(result.cleanupFailures()).singleElement().satisfies(cleanup -> {
+ assertThat(cleanup.directory()).isEqualTo(retired.get());
+ assertThat(cleanup.failure()).isSameAs(failure);
+ });
+ assertThat(Files.readString(retired.get().resolve("retained.dmg"))).isEqualTo("remaining old package");
+ assertThat(retired.get().resolve("previous.dmg")).doesNotExist();
+ }
+
+ @Test
+ void aSuccessfulPackageReplacesThePreviousDirectoryAfterGeneration() throws Exception {
+ var output = previous();
+ PackageOutput.produce(output, stage -> {
+ assertThat(Files.readString(output.resolve("previous.dmg"))).isEqualTo("previous");
+ Files.writeString(stage.resolve("new.dmg"), "new");
+ });
+ assertThat(Files.readString(output.resolve("new.dmg"))).isEqualTo("new"); assertThat(output.resolve("previous.dmg")).doesNotExist();
+ assertNoTemporaryDirectories();
+ }
+
+ @ParameterizedTest @ValueSource(booleans = {false, true})
+ void aGeneratorFailureKeepsTheOldPackageAndRemovesOnlyItsOwnStaging(boolean error) throws Exception {
+ var output = previous(); Throwable failure = error ? new AssertionError("generator failed") : new IOException("generator failed");
+ assertThatThrownBy(() -> PackageOutput.produce(output, stage -> {
+ Files.writeString(stage.resolve("partial.dmg"), "partial");
+ if (failure instanceof Error fatal) throw fatal; throw (Exception) failure;
+ })).isSameAs(failure);
+ assertThat(Files.readString(output.resolve("previous.dmg"))).isEqualTo("previous"); assertNoTemporaryDirectories();
+ }
+
+ @Test
+ void publicationFailureRestoresThePreviousDirectoryAndPreservesTheCause() throws Exception {
+ var output = previous(); var failure = new IOException("publication failed");
+ assertThatThrownBy(() -> PackageOutput.produce(output, stage -> Files.writeString(stage.resolve("new.dmg"), "new"), (source, target) -> {
+ if (source.getFileName().toString().startsWith(".tcv-package-")) throw failure;
+ Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);
+ })).isSameAs(failure);
+ assertThat(Files.readString(output.resolve("previous.dmg"))).isEqualTo("previous"); assertNoTemporaryDirectories();
+ }
+
+ @Test
+ void failedRollbackKeepsTheBackupAndReportsItsLocationAlongsideTheOriginalFailures() throws Exception {
+ var output = previous(); var original = new IOException("publication failed"); var rollback = new IOException("restore failed");
+ assertThatThrownBy(() -> PackageOutput.produce(output, stage -> Files.writeString(stage.resolve("new.dmg"), "new"), (source, target) -> {
+ if (source.getFileName().toString().startsWith(".tcv-package-")) throw original;
+ if (source.getFileName().toString().startsWith(".tcv-previous-")) throw rollback;
+ Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);
+ })).isSameAs(original).satisfies(failure -> {
+ assertThat(failure.getSuppressed()).contains(rollback);
+ assertThat(failure.getSuppressed()).anySatisfy(suppressed -> assertThat(suppressed.getMessage()).contains("Previous package remains at"));
+ });
+ try (var children = Files.list(directory)) {
+ var backup = children.filter(path -> path.getFileName().toString().startsWith(".tcv-previous-")).findFirst().orElseThrow();
+ assertThat(Files.readString(backup.resolve("previous.dmg"))).isEqualTo("previous");
+ }
+ }
+
+ @Test
+ void aFirstFailedPackageDoesNotCreateAnEmptySuccessfulOutput() {
+ var output = directory.resolve("app"); var failure = new IOException("first package failed");
+ assertThatThrownBy(() -> PackageOutput.produce(output, stage -> { throw failure; })).isSameAs(failure);
+ assertThat(output).doesNotExist(); assertNoTemporaryDirectories();
+ }
+
+ @Test
+ void anEmptyGenerationDoesNotReplaceThePreviousPackage() throws Exception {
+ var output = previous();
+ assertThatThrownBy(() -> PackageOutput.produce(output, stage -> {}))
+ .isInstanceOf(IOException.class).hasMessageContaining("no package");
+ assertThat(Files.readString(output.resolve("previous.dmg"))).isEqualTo("previous");
+ assertNoTemporaryDirectories();
+ }
+
+ @Test
+ void anExistingNonDirectoryIsNeverReplaced() throws Exception {
+ var output = directory.resolve("app"); Files.writeString(output, "unrelated file");
+ assertThatThrownBy(() -> PackageOutput.produce(output, stage -> Files.writeString(stage.resolve("new.dmg"), "new")))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThat(Files.readString(output)).isEqualTo("unrelated file"); assertNoTemporaryDirectories();
+ }
+
+ private Path previous() throws Exception {
+ var output = directory.resolve("app"); Files.createDirectories(output); Files.writeString(output.resolve("previous.dmg"), "previous"); return output;
+ }
+ private void assertNoTemporaryDirectories() {
+ try (var children = Files.list(directory)) {
+ assertThat(children.filter(path -> path.getFileName().toString().startsWith(".tcv-")).toList()).isEmpty();
+ } catch (IOException failure) { throw new AssertionError(failure); }
+ }
+}
diff --git a/buildSrc/src/test/java/com/github/k7t3/tcv/build/PackagePlanTest.java b/buildSrc/src/test/java/com/github/k7t3/tcv/build/PackagePlanTest.java
new file mode 100644
index 0000000..b41fe7b
--- /dev/null
+++ b/buildSrc/src/test/java/com/github/k7t3/tcv/build/PackagePlanTest.java
@@ -0,0 +1,153 @@
+package com.github.k7t3.tcv.build;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.NullAndEmptySource;
+import org.junit.jupiter.params.provider.ValueSource;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import static org.assertj.core.api.Assertions.*;
+
+class PackagePlanTest {
+ @TempDir Path directory;
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void linuxInstallersRequireTheBinarySecretServiceLibrary(boolean image) throws Exception {
+ var arguments = PackagePlan.arguments(input(PackagePlan.Platform.LINUX, image), directory.resolve("package output"));
+
+ if (image) assertThat(arguments).doesNotContain("--linux-package-deps");
+ else {
+ assertThat(arguments).contains("--linux-package-deps");
+ assertThat(arguments.get(arguments.indexOf("--linux-package-deps") + 1))
+ .contains("libsecret-1-0 (>= 0.19.0)");
+ }
+ }
+
+ @Test
+ void linuxInstallersRequireTheGtkRuntimeUsedByJavafx() throws Exception {
+ var arguments = PackagePlan.arguments(input(PackagePlan.Platform.LINUX, false), directory.resolve("package output"));
+
+ assertThat(arguments).contains("--linux-package-deps");
+ assertThat(arguments.get(arguments.indexOf("--linux-package-deps") + 1))
+ .contains("libgtk-3-0 (>= 3.20.0)");
+ }
+
+ @Test
+ void linuxInstallersRequireTheXTestLibraryLoadedByJavafx() throws Exception {
+ var arguments = PackagePlan.arguments(input(PackagePlan.Platform.LINUX, false), directory.resolve("package output"));
+
+ assertThat(arguments).contains("--linux-package-deps");
+ assertThat(arguments.get(arguments.indexOf("--linux-package-deps") + 1))
+ .contains("libxtst6");
+ }
+
+ @ParameterizedTest
+ @CsvSource({"WINDOWS,true", "WINDOWS,false", "MAC,true", "MAC,false", "LINUX,true", "LINUX,false"})
+ void packagesIncludeASeparateSecretStorageLauncher(PackagePlan.Platform platform, boolean image) throws Exception {
+ var input = input(platform, image);
+
+ var arguments = PackagePlan.arguments(input, directory.resolve("package output"));
+
+ assertThat(arguments).containsSequence("--add-launcher", "Twitch Key Storage="
+ + input.inputDirectory().resolve("key-storage.properties"));
+ }
+
+ @ParameterizedTest
+ @CsvSource({"WINDOWS,true", "WINDOWS,false", "MAC,true", "MAC,false", "LINUX,true", "LINUX,false"})
+ void launchersEnableNativeAccessForJavafxAndClasspathLibraries(PackagePlan.Platform platform, boolean image) throws Exception {
+ assertThat(PackagePlan.arguments(input(platform, image), directory.resolve("package output")))
+ .containsSequence("--java-options", "--enable-native-access=javafx.graphics,ALL-UNNAMED");
+ }
+
+ @ParameterizedTest @CsvSource({"WINDOWS,exe,TwitchChatViewer.ico", "MAC,dmg,TwitchChatViewer.icns", "LINUX,deb,TwitchChatViewer-64.png"})
+ void nativePackagesKeepTheirPlatformOptionsAndPassUnquotedArguments(PackagePlan.Platform platform, String type, String icon) throws Exception {
+ var input = input(platform, false); var output = directory.resolve("native output");
+ var args = PackagePlan.arguments(input, output);
+ assertThat(args).containsSequence("--type", type).containsSequence("--app-version", "2.3.4")
+ .containsSequence("--java-options", "-Dapp.version=2.3.4-beta.2+42")
+ .containsSequence("--input", input.inputDirectory().toString()).containsSequence("--dest", output.toString())
+ .containsSequence("--main-jar", "tcv-2.3.4-beta.2+42.jar")
+ .containsSequence("--icon", input.projectRoot().resolve("src/main/resources/icons").resolve(icon).toString())
+ .containsSequence("--license-file", input.projectRoot().resolve("docs/license.md").toString());
+ assertThat(args.stream().noneMatch(argument -> argument.startsWith("'") || argument.startsWith("\""))).isTrue();
+ switch (platform) {
+ case WINDOWS -> assertThat(args).containsSequence("--win-upgrade-uuid", "b78817e8-f9b8-4650-bf0a-34bca5ff4106").contains("--win-per-user-install");
+ case MAC -> assertThat(args).containsSequence("--mac-package-identifier", "TwitchChatViewer");
+ case LINUX -> assertThat(args).containsSequence("--linux-menu-group", "Network").contains("--linux-shortcut");
+ }
+ }
+
+ @ParameterizedTest @ValueSource(strings = {"WINDOWS", "MAC", "LINUX"})
+ void applicationImagesUseLauncherOptionsAndOmitInstallerOnlyOptions(PackagePlan.Platform platform) throws Exception {
+ var args = PackagePlan.arguments(input(platform, true), directory.resolve("app image"));
+ assertThat(args).containsSequence("--type", "app-image").doesNotContain("--license-file", "--win-upgrade-uuid", "--win-menu", "--linux-shortcut");
+ if (platform == PackagePlan.Platform.MAC) assertThat(args).containsSequence("--mac-package-identifier", "TwitchChatViewer");
+ }
+
+ @ParameterizedTest @CsvSource({"1.0.0-dev,1.0.0", "2.3.4-rc.2+build.9,2.3.4", "2.3.4+build.9,2.3.4", "3.0.1,3.0.1"})
+ void nativeVersionsRemoveQualifiersIncludingThoseEndingInDigits(String full, String expected) {
+ assertThat(PackagePlan.nativeVersion(full)).isEqualTo(expected);
+ }
+
+ @ParameterizedTest @NullAndEmptySource @ValueSource(strings = {"v1.2.3", "1.2", "../1.2.3", "1.2.3$(command)", "1.2.3\n--type", "1.2.3-"})
+ void malformedVersionsAreRejectedBeforePackaging(String version) {
+ assertThatThrownBy(() -> PackagePlan.nativeVersion(version)).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("version");
+ }
+
+ @Test
+ void dependencyModulesAreDeduplicatedAndKeepCryptoAndJavafxRoots() {
+ assertThat(PackagePlan.modules("java.desktop,java.base,java.desktop\n", List.of("javafx.controls", "javafx.fxml", "javafx.swing")))
+ .containsExactly("java.base", "java.desktop", "javafx.controls", "javafx.fxml", "javafx.swing", "jdk.crypto.ec");
+ }
+
+ @ParameterizedTest @ValueSource(strings = {"", " ", "Warning: missing dependencies\njava.base", "java.base,--add-modules"})
+ void malformedDependencyOutputCannotBecomeLauncherArguments(String modules) {
+ assertThatThrownBy(() -> PackagePlan.modules(modules, List.of("javafx.controls"))).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("jdeps");
+ }
+
+ @Test
+ void missingInputsAndEscapingJarNamesAreRejected() throws Exception {
+ var input = input(PackagePlan.Platform.MAC, false); Files.delete(input.inputDirectory().resolve(input.mainJar()));
+ assertThatThrownBy(() -> PackagePlan.validateInputs(input)).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("main JAR");
+ var escaped = new PackagePlan.Inputs(input.platform(), false, input.fullVersion(), input.inputDirectory(), input.moduleDirectory(),
+ "../outside.jar", input.mainClass(), input.projectRoot(), input.modules());
+ assertThatThrownBy(() -> PackagePlan.arguments(escaped, directory)).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("main JAR");
+ }
+
+ @Test
+ void aMissingHelperConfigurationCannotProduceAPackageWithoutItsStorageLauncher() throws Exception {
+ var input = input(PackagePlan.Platform.MAC, true);
+ Files.delete(input.inputDirectory().resolve("key-storage.properties"));
+
+ assertThatThrownBy(() -> PackagePlan.arguments(input, directory.resolve("package output")))
+ .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("key storage launcher");
+ }
+
+ @Test
+ void platformDetectionDoesNotDependOnTheUsersLocaleAndRejectsUnknownSystems() {
+ var previous = Locale.getDefault();
+ try {
+ Locale.setDefault(Locale.forLanguageTag("tr-TR"));
+ assertThat(PackagePlan.Platform.fromOsName("WINDOWS 11")).isEqualTo(PackagePlan.Platform.WINDOWS);
+ assertThat(PackagePlan.Platform.fromOsName("Mac OS X")).isEqualTo(PackagePlan.Platform.MAC);
+ assertThat(PackagePlan.Platform.fromOsName("Linux")).isEqualTo(PackagePlan.Platform.LINUX);
+ assertThatThrownBy(() -> PackagePlan.Platform.fromOsName("Plan 9")).isInstanceOf(IllegalArgumentException.class);
+ } finally { Locale.setDefault(previous); }
+ }
+
+ private PackagePlan.Inputs input(PackagePlan.Platform platform, boolean appImage) throws Exception {
+ var root = directory.resolve("project with spaces"); var input = root.resolve("input"); var modules = root.resolve("javafx");
+ Files.createDirectories(input); Files.createDirectories(modules); Files.createDirectories(root.resolve("docs"));
+ Files.createDirectories(root.resolve("src/main/resources/icons"));
+ Files.writeString(input.resolve("tcv-2.3.4-beta.2+42.jar"), "application"); Files.writeString(root.resolve("docs/license.md"), "license");
+ Files.writeString(input.resolve("key-storage.properties"), "main-class=com.github.k7t3.tcv.app.secure.SecretStoreHelper\n");
+ for (var icon : List.of("TwitchChatViewer.ico", "TwitchChatViewer.icns", "TwitchChatViewer-64.png")) Files.writeString(root.resolve("src/main/resources/icons").resolve(icon), "icon");
+ return new PackagePlan.Inputs(platform, appImage, "2.3.4-beta.2+42", input, modules, "tcv-2.3.4-beta.2+42.jar",
+ "com.github.k7t3.tcv.view.Launcher", root, List.of("java.base", "javafx.controls", "jdk.crypto.ec"));
+ }
+}
diff --git a/docs/external-libraries.md b/docs/external-libraries.md
index f4b9cfa..677e666 100644
--- a/docs/external-libraries.md
+++ b/docs/external-libraries.md
@@ -14,18 +14,6 @@ License: CC BY-SA 4.0
## License
-```yaml
-Name: Apollo GraphQL Java libraries
-URL: https://github.com/apollographql/apollo-kotlin
-License: MIT
-```
-
-```yaml
-Name: UUID (com.benasher44)
-URL: https://github.com/benasher44/uuid
-License: MIT
-```
-
```yaml
Name: JCommander
URL: https://github.com/cbeust/jcommander
@@ -92,18 +80,6 @@ URL: https://github.com/TakahikoKawasaki/nv-websocket-client
License: Apache-2.0
```
-```yaml
-Name: Netflix Archaius
-URL: https://github.com/Netflix/archaius
-License: Apache-2.0
-```
-
-```yaml
-Name: Hystrix
-URL: https://github.com/Netflix/Hystrix
-License: Apache-2.0
-```
-
```yaml
Name: OkHttp
URL: https://github.com/square/okhttp
@@ -116,24 +92,12 @@ URL: https://github.com/square/okio
License: Apache-2.0
```
-```yaml
-Name: Apache Commons Configuration
-URL: https://commons.apache.org/proper/commons-configuration/
-License: Apache-2.0
-```
-
```yaml
Name: Apache Commons IO
URL: https://commons.apache.org/proper/commons-io/
License: Apache-2.0
```
-```yaml
-Name: Apache Commons Lang
-URL: https://commons.apache.org/proper/commons-lang/
-License: Apache-2.0
-```
-
```yaml
Name: MVVMFX
URL: https://github.com/sialcasa/mvvmFX
@@ -158,18 +122,6 @@ URL: https://github.com/xanthic/cache
License: Apache-2.0
```
-```yaml
-Name: RxJava
-URL: https://github.com/ReactiveX/RxJava
-License: Apache-2.0
-```
-
-```yaml
-Name: Byte Buddy
-URL: https://github.com/raphw/byte-buddy
-License: Apache-2.0
-```
-
```yaml
Name: TypeTools
URL: https://github.com/jhalterman/typetools
@@ -182,24 +134,12 @@ URL: https://commons.apache.org/proper/commons-lang/
License: Apache-2.0
```
-```yaml
-Name: Checker Framework
-URL: https://github.com/typetools/checker-framework
-License: MIT
-```
-
```yaml
Name: Flowless
URL: https://github.com/FXMisc/Flowless
License: BSD-2-Clause
```
-```yaml
-Name: HdrHistogram
-URL: https://github.com/HdrHistogram/HdrHistogram
-License: BSD-2-Clause or Public Domain
-```
-
```yaml
Name: Kotlin Standard Library
URL: https://kotlinlang.org/
@@ -237,4 +177,27 @@ License: Apache-2.0
```
-[Format Reference](https://github.com/JabRef/jabref)
\ No newline at end of file
+[Format Reference](https://github.com/JabRef/jabref)
+```yaml
+Name: JAI Image I/O Core
+URL: https://github.com/jai-imageio/jai-imageio-core
+License: BSD 3-clause License w/nuclear disclaimer
+```
+
+```yaml
+Name: Doc Annotations
+URL: https://github.com/lestard/doc-annotations
+License: MIT
+```
+
+```yaml
+Name: JSpecify
+URL: https://jspecify.dev/
+License: Apache-2.0
+```
+
+```yaml
+Name: ReactFX
+URL: https://github.com/FXMisc/ReactFX
+License: BSD-2-Clause
+```
diff --git a/docs/licenses/jai-imageio.txt b/docs/licenses/jai-imageio.txt
new file mode 100644
index 0000000..c311718
--- /dev/null
+++ b/docs/licenses/jai-imageio.txt
@@ -0,0 +1,92 @@
+Copyright (c) 2005 Sun Microsystems, Inc.
+Copyright © 2010-2014 University of Manchester
+Copyright © 2010-2015 Stian Soiland-Reyes
+Copyright © 2015 Peter Hull
+All Rights Reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+- Redistribution of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+- Redistribution in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+Neither the name of Sun Microsystems, Inc. or the names of
+contributors may be used to endorse or promote products derived
+from this software without specific prior written permission.
+
+This software is provided "AS IS," without a warranty of any
+kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+You acknowledge that this software is not designed or intended for
+use in the design, construction, operation or maintenance of any
+nuclear facility.
+
+
+Copyright (c) 2005 Sun Microsystems, Inc.
+Copyright © 2010-2018 Stian Soiland-Reyes
+Copyright © 2015 Peter Hull
+Copyright © 2010-2018 University of Manchester
+Copyright © 2015 Yannick De Turck
+Copyright © 2015 Robin Stevens
+Copyright © 2015 Mark Carroll
+Copyright © 2015 Butch Howard
+Copyright © 2015-2016 Luca Bellonda
+Copyright © 2017 Ghislain Bonamy
+Copyright © 2017 Curtis Rueden
+Copyright © 2017 Roger Leigh
+Copyright © 2017 Mykola Pavluchynskyi
+Copyright © 2017 Sebastien Besson
+Copyright © 2018 Peter Jodeleit
+
+All Rights Reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+- Redistribution of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+- Redistribution in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+Neither the name of Sun Microsystems, Inc. or the names of
+contributors may be used to endorse or promote products derived
+from this software without specific prior written permission.
+
+This software is provided "AS IS," without a warranty of any
+kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
+WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
+EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
+NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
+USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
+ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
+CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
+REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
+INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+You acknowledge that this software is not designed or intended for
+use in the design, construction, operation or maintenance of any
+nuclear facility.
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
new file mode 100644
index 0000000..121a202
--- /dev/null
+++ b/gradle/libs.versions.toml
@@ -0,0 +1,49 @@
+[versions]
+java = "25"
+javafx = "27.0.1"
+junit = "6.1.3"
+mockito = "5.24.0"
+assertj = "3.27.7"
+testfx = "4.0.18"
+twitch4j = "1.27.0"
+feign = "13.9.3"
+bucket4j = "8.10.1"
+
+slf4j = "2.0.20"
+caffeine = "3.3.1"
+sqlite = "3.53.4.0"
+zxing = "3.5.4"
+atlantafx = "3.0.0"
+ikonli = "12.4.0"
+mvvmfx = "1.8.0"
+flowless = "0.7.4"
+hamcrest = "3.0"
+
+[libraries]
+junit-bom = { module = "org.junit:junit-bom", version.ref = "junit" }
+junit-jupiter = { module = "org.junit.jupiter:junit-jupiter" }
+junit-launcher = { module = "org.junit.platform:junit-platform-launcher" }
+mockito = { module = "org.mockito:mockito-core", version.ref = "mockito" }
+assertj = { module = "org.assertj:assertj-core", version.ref = "assertj" }
+testfx-junit5 = { module = "org.testfx:testfx-junit5", version.ref = "testfx" }
+twitch-auth = { module = "com.github.twitch4j:twitch4j-auth", version.ref = "twitch4j" }
+twitch-chat = { module = "com.github.twitch4j:twitch4j-chat", version.ref = "twitch4j" }
+twitch-common = { module = "com.github.twitch4j:twitch4j-common", version.ref = "twitch4j" }
+twitch-helix = { module = "com.github.twitch4j:twitch4j-helix", version.ref = "twitch4j" }
+feign-core = { module = "io.github.openfeign:feign-core", version.ref = "feign" }
+feign-jackson = { module = "io.github.openfeign:feign-jackson", version.ref = "feign" }
+feign-okhttp = { module = "io.github.openfeign:feign-okhttp", version.ref = "feign" }
+bucket4j = { module = "com.bucket4j:bucket4j_jdk8-core", version.ref = "bucket4j" }
+slf4j-api = { module = "org.slf4j:slf4j-api", version.ref = "slf4j" }
+slf4j-jdk14 = { module = "org.slf4j:slf4j-jdk14", version.ref = "slf4j" }
+caffeine = { module = "com.github.ben-manes.caffeine:caffeine", version.ref = "caffeine" }
+sqlite = { module = "org.xerial:sqlite-jdbc", version.ref = "sqlite" }
+zxing = { module = "com.google.zxing:javase", version.ref = "zxing" }
+atlantafx = { module = "io.github.mkpaz:atlantafx-base", version.ref = "atlantafx" }
+ikonli-javafx = { module = "org.kordamp.ikonli:ikonli-javafx", version.ref = "ikonli" }
+ikonli-feather = { module = "org.kordamp.ikonli:ikonli-feather-pack", version.ref = "ikonli" }
+ikonli-material2 = { module = "org.kordamp.ikonli:ikonli-material2-pack", version.ref = "ikonli" }
+ikonli-fontawesome5 = { module = "org.kordamp.ikonli:ikonli-fontawesome5-pack", version.ref = "ikonli" }
+mvvmfx = { module = "de.saxsys:mvvmfx", version.ref = "mvvmfx" }
+flowless = { module = "org.fxmisc.flowless:flowless", version.ref = "flowless" }
+hamcrest = { module = "org.hamcrest:hamcrest", version.ref = "hamcrest" }
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
index 249e583..9fa7f28 100644
Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
index 15fb9ed..5907d39 100644
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -1,6 +1,10 @@
-#Wed Jan 24 01:39:46 JST 2024
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
+distributionSha256Sum=21bd5da2de49b642904077f38c0efdc7778e92b3ed0889392dca61b97e389607
+distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-bin.zip
+networkTimeout=10000
+retries=0
+retryBackOffMs=500
+validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
diff --git a/gradlew b/gradlew
index 1b6c787..249efbb 100755
--- a/gradlew
+++ b/gradlew
@@ -1,7 +1,7 @@
#!/bin/sh
#
-# Copyright © 2015-2021 the original authors.
+# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -15,10 +15,12 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
+# SPDX-License-Identifier: Apache-2.0
+#
##############################################################################
#
-# Gradle start up script for POSIX generated by Gradle.
+# gradlew start up script for POSIX generated by Gradle.
#
# Important for running:
#
@@ -27,7 +29,7 @@
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
-# ksh Gradle
+# ksh gradlew
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
@@ -55,7 +57,7 @@
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
-# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
@@ -80,13 +82,11 @@ do
esac
done
-APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
-
-APP_NAME="Gradle"
+# This is normally unused
+# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
-
-# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
+APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
@@ -114,7 +114,6 @@ case "$( uname )" in #(
NONSTOP* ) nonstop=true ;;
esac
-CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
@@ -133,22 +132,29 @@ location of your Java installation."
fi
else
JAVACMD=java
- which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+ if ! command -v java >/dev/null 2>&1
+ then
+ die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
+ fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
+ # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
+ # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
@@ -165,7 +171,6 @@ fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
- CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
@@ -193,18 +198,27 @@ if "$cygwin" || "$msys" ; then
done
fi
-# Collect all arguments for the java command;
-# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
-# shell script including quotes and variable substitutions, so put them in
-# double quotes to make sure that they get re-expanded; and
-# * put everything else in single quotes, so that it's not re-expanded.
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Collect all arguments for the java command:
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
+# and any embedded shellness will be escaped.
+# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
+# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
- -classpath "$CLASSPATH" \
- org.gradle.wrapper.GradleWrapperMain \
+ -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
+# Stop when "xargs" is not available.
+if ! command -v xargs >/dev/null 2>&1
+then
+ die "xargs is not available"
+fi
+
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
diff --git a/gradlew.bat b/gradlew.bat
index ac1b06f..3185a43 100644
--- a/gradlew.bat
+++ b/gradlew.bat
@@ -1,89 +1,112 @@
-@rem
-@rem Copyright 2015 the original author or authors.
-@rem
-@rem Licensed under the Apache License, Version 2.0 (the "License");
-@rem you may not use this file except in compliance with the License.
-@rem You may obtain a copy of the License at
-@rem
-@rem https://www.apache.org/licenses/LICENSE-2.0
-@rem
-@rem Unless required by applicable law or agreed to in writing, software
-@rem distributed under the License is distributed on an "AS IS" BASIS,
-@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-@rem See the License for the specific language governing permissions and
-@rem limitations under the License.
-@rem
-
-@if "%DEBUG%" == "" @echo off
-@rem ##########################################################################
-@rem
-@rem Gradle startup script for Windows
-@rem
-@rem ##########################################################################
-
-@rem Set local scope for the variables with windows NT shell
-if "%OS%"=="Windows_NT" setlocal
-
-set DIRNAME=%~dp0
-if "%DIRNAME%" == "" set DIRNAME=.
-set APP_BASE_NAME=%~n0
-set APP_HOME=%DIRNAME%
-
-@rem Resolve any "." and ".." in APP_HOME to make it shorter.
-for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
-
-@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
-
-@rem Find java.exe
-if defined JAVA_HOME goto findJavaFromJavaHome
-
-set JAVA_EXE=java.exe
-%JAVA_EXE% -version >NUL 2>&1
-if "%ERRORLEVEL%" == "0" goto execute
-
-echo.
-echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
-
-goto fail
-
-:findJavaFromJavaHome
-set JAVA_HOME=%JAVA_HOME:"=%
-set JAVA_EXE=%JAVA_HOME%/bin/java.exe
-
-if exist "%JAVA_EXE%" goto execute
-
-echo.
-echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
-
-goto fail
-
-:execute
-@rem Setup the command line
-
-set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
-
-
-@rem Execute Gradle
-"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
-
-:end
-@rem End local scope for the variables with windows NT shell
-if "%ERRORLEVEL%"=="0" goto mainEnd
-
-:fail
-rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
-rem the _cmd.exe /c_ return code!
-if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
-exit /b 1
-
-:mainEnd
-if "%OS%"=="Windows_NT" endlocal
-
-:omega
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+@rem SPDX-License-Identifier: Apache-2.0
+@rem
+
+@if "%DEBUG%"=="" @echo off
+@rem ##########################################################################
+@rem
+@rem gradlew startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables, and ensure extensions are enabled
+setlocal EnableExtensions
+
+@rem Catch executions from older scripts and ensure they exit cleanly.
+@rem This can be removed once we can be reasonably confident that few people
+@rem will be migrating directly to this new wrapper.
+goto afterSafetyNet
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+goto exitWithErrorLevel
+:afterSafetyNet
+
+set DIRNAME=%~dp0
+if "%DIRNAME%"=="" set DIRNAME=.
+@rem This is normally unused
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if %ERRORLEVEL% equ 0 goto execute
+
+1>&2 echo.
+1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+1>&2 echo.
+1>&2 echo Please set the JAVA_HOME variable in your environment to match the
+1>&2 echo location of your Java installation.
+
+"%COMSPEC%" /c exit 1
+goto exitWithErrorLevel
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+1>&2 echo.
+1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+1>&2 echo.
+1>&2 echo Please set the JAVA_HOME variable in your environment to match the
+1>&2 echo location of your Java installation.
+
+"%COMSPEC%" /c exit 1
+goto exitWithErrorLevel
+
+:execute
+@rem Setup the command line
+
+
+
+@rem Execute gradlew
+@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
+@rem which allows us to clear the local environment before executing the java command
+endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel
+
+@rem This label must not be changed. We rely on old scripts being able to jump to this point.
+:exitWithErrorLevel
+@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
+"%COMSPEC%" /c exit %ERRORLEVEL%
diff --git a/settings.gradle b/settings.gradle
index cda4ead..5349110 100644
--- a/settings.gradle
+++ b/settings.gradle
@@ -1,2 +1 @@
rootProject.name = 'tcv'
-
diff --git a/src/main/java/com/github/k7t3/tcv/app/auth/AuthenticatorViewModel.java b/src/main/java/com/github/k7t3/tcv/app/auth/AuthenticatorViewModel.java
index 7023f33..5fe3feb 100644
--- a/src/main/java/com/github/k7t3/tcv/app/auth/AuthenticatorViewModel.java
+++ b/src/main/java/com/github/k7t3/tcv/app/auth/AuthenticatorViewModel.java
@@ -16,14 +16,15 @@
package com.github.k7t3.tcv.app.auth;
+import com.github.k7t3.tcv.app.service.BrowserActions;
import com.github.k7t3.tcv.app.model.AbstractViewModel;
-import com.github.k7t3.tcv.app.core.AppHelper;
+import com.github.k7t3.tcv.app.core.Resources;
import com.github.k7t3.tcv.app.event.LoginEvent;
import com.github.k7t3.tcv.app.service.FXTask;
import com.github.k7t3.tcv.domain.Twitch;
import com.github.k7t3.tcv.domain.TwitchLoader;
import com.github.k7t3.tcv.domain.auth.CredentialStore;
-import com.github.k7t3.tcv.domain.event.EventSubscribers;
+import com.github.k7t3.tcv.lifecycle.CloseActions;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
@@ -38,13 +39,18 @@
import javafx.scene.input.DataFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
-import java.awt.*;
-import java.io.IOException;
-import java.net.URI;
-import java.net.URISyntaxException;
import java.util.Map;
import java.util.Optional;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionStage;
+import java.util.concurrent.Executor;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.function.Supplier;
+import java.util.function.Consumer;
/**
* Twitchユーザー認証用ViewModel
@@ -68,43 +74,112 @@ public class AuthenticatorViewModel extends AbstractViewModel {
private static final int QRCODE_HEIGHT = 480;
private TwitchLoader twitchLoader;
+ private final Object authenticationLock = new Object();
+ private Object attempt;
+ private Twitch pendingClient;
private final ReadOnlyBooleanWrapper initialized = new ReadOnlyBooleanWrapper(false);
+ private final ReadOnlyBooleanWrapper busy = new ReadOnlyBooleanWrapper(false);
private final ReadOnlyStringWrapper userCode = new ReadOnlyStringWrapper();
private final ReadOnlyStringWrapper authUri = new ReadOnlyStringWrapper();
private final ReadOnlyStringWrapper error = new ReadOnlyStringWrapper();
private final ReadOnlyObjectWrapper qrcode = new ReadOnlyObjectWrapper<>();
- private final CredentialStore credentialStore;
+ private final Supplier loaderFactory;
+ private final Consumer authenticated;
+ private final Executor executor;
+ private final BrowserActions browsers;
+ private final List> tasks = new ArrayList<>();
+ private final Set
*/
public void openChannelPageOnBrowser() {
- var login = getBroadcaster().getUserLogin();
-
- var desktop = Desktop.getDesktop();
- if (!desktop.isSupported(Desktop.Action.BROWSE)) {
- return;
- }
-
- try {
- desktop.browse(new URI(CHANNEL_URL_FORMAT.formatted(login)));
- } catch (IOException | URISyntaxException e) {
- throw new RuntimeException(e);
- }
+ checkOpen();
+ browsers.open(CHANNEL_URL_FORMAT.formatted(getBroadcaster().getUserLogin()));
}
public FXTask joinChatAsync() {
- if (isChatJoined()) return FXTask.of(channel.getOrJoinChatRoom());
-
- var task = FXTask.task(() -> {
- channel.loadBadgesIfNotLoaded();
- return channel.getOrJoinChatRoom();
+ checkOpen();
+ var task = chatConnection.join();
+ if (observedJoin == task) return task;
+ observedJoin = task;
+ task.onDone(() -> {
+ if (!closed && chatConnection.isCurrentJoin(task)) chatJoinedWrapper().set(true);
+ });
+ task.onFailure(failure -> {
+ if (!closed && chatConnection.isCurrentJoin(task)) reportFailure.accept(failure);
});
- task.onDone(() -> chatJoinedWrapper().set(true));
- task.runAsync();
return task;
}
public FXTask leaveChatAsync() {
- if (!isChatJoined()) return FXTask.empty();
-
- if (chatJoined != null) {
- chatJoined.set(false);
- }
-
- var task = FXTask.task(() -> {
- channel.leaveChat();
- repository.releaseChannel(this);
+ if (chatJoined != null) chatJoined.set(false);
+ var task = chatConnection.leave();
+ if (observedLeave == task) return task;
+ observedLeave = task;
+ task.onFailure(failure -> {
+ if (!closed && chatConnection.isCurrentLeave(task)) reportFailure.accept(failure);
});
- task.runAsync();
-
return task;
}
+ public boolean isRetiring() { return closed || chatConnection.isRetiring(); }
+ CompletionStage retirement() { return chatConnection.retirement(); }
+
public ChannelChatBadgeStore getChatBadgeStore() {
return chatBadgeStore;
}
@@ -150,8 +153,9 @@ public ChannelChatBadgeStore getChatBadgeStore() {
public String getGameName() { return streamInfo == null ? "" : observableGameName().getValue(); }
private ReadOnlyObjectWrapper profileImageWrapper() {
+ checkOpen();
if (profileImage == null) {
- profileImage = new ReadOnlyObjectWrapper<>(new LazyImage(
+ profileImage = new ReadOnlyObjectWrapper<>(loadOwnedImage(
channel.getBroadcaster().getProfileImageUrl(),
64,
64
@@ -163,15 +167,57 @@ private ReadOnlyObjectWrapper profileImageWrapper() {
public LazyImage getProfileImage() { return profileImageWrapper().get(); }
private ReadOnlyObjectWrapper offlineImageWrapper() {
+ checkOpen();
if (offlineImage == null) {
offlineImage = new ReadOnlyObjectWrapper<>();
- channel.getBroadcaster().getOfflineImageUrl().ifPresent(url -> offlineImage.set(new Image(url, true)));
+ channel.getBroadcaster().getOfflineImageUrl().ifPresent(url -> {
+ offlineLoad = loadOwnedImage(url, 0, 0);
+ offlineImage.bind(offlineLoad.valueProperty());
+ });
}
return offlineImage;
}
public ReadOnlyObjectProperty offlineImageProperty() { return offlineImageWrapper().getReadOnlyProperty(); }
public Image getOfflineImage() { return offlineImageWrapper().get(); }
+ private LazyImage loadOwnedImage(String url, double width, double height) {
+ checkOpen();
+ var image = images.load(url, width, height);
+ if (closed) {
+ image.close();
+ checkOpen();
+ }
+ return image;
+ }
+
+ private void checkOpen() {
+ if (closed) throw new IllegalStateException("channel view model is closed");
+ }
+
+ /** FX 上で参加の取消と退出を要求し、所有画像・binding を解放する。通信の終了待ちはアプリ側が行う。 */
+ @Override
+ public void close() {
+ if (closed) return;
+ closed = true;
+ var profile = profileImage == null ? null : profileImage.get();
+ var offline = offlineLoad;
+ offlineLoad = null;
+ CloseActions.runAll(
+ chatConnection::close,
+ browsers::close,
+ () -> { if (chatJoined != null) chatJoined.set(false); },
+ () -> { if (profileImage != null) profileImage.set(null); },
+ () -> {
+ if (offlineImage != null) {
+ offlineImage.unbind();
+ offlineImage.set(null);
+ }
+ },
+ () -> { if (profile != null) profile.close(); },
+ () -> { if (offline != null) offline.close(); },
+ chatBadgeStore::close);
+ }
+
private ReadOnlyObjectWrapper streamInfoWrapper() {
if (streamInfo == null) {
streamInfo = new ReadOnlyObjectWrapper<>();
diff --git a/src/main/java/com/github/k7t3/tcv/app/chat/ChannelChatBadgeStore.java b/src/main/java/com/github/k7t3/tcv/app/chat/ChannelChatBadgeStore.java
index 7e1c8cc..af55c9b 100644
--- a/src/main/java/com/github/k7t3/tcv/app/chat/ChannelChatBadgeStore.java
+++ b/src/main/java/com/github/k7t3/tcv/app/chat/ChannelChatBadgeStore.java
@@ -17,6 +17,7 @@
package com.github.k7t3.tcv.app.chat;
import com.github.k7t3.tcv.app.image.LazyImage;
+import com.github.k7t3.tcv.app.image.ImageLoader;
import com.github.k7t3.tcv.app.service.CachedImageStore;
import com.github.k7t3.tcv.domain.channel.TwitchChannel;
import com.github.k7t3.tcv.domain.chat.ChatBadge;
@@ -27,16 +28,18 @@
public class ChannelChatBadgeStore extends CachedImageStore {
private final TwitchChannel channel;
+ private final ImageLoader images;
- public ChannelChatBadgeStore(TwitchChannel channel) {
+ public ChannelChatBadgeStore(TwitchChannel channel, ImageLoader images) {
super(8, Duration.ofMinutes(5));
this.channel = channel;
+ this.images = images;
}
@Override
protected @Nullable LazyImage loadImage(ChatBadge key) {
var url = channel.getBadgeUrl(key).orElse(null);
if (url == null) return null;
- return new LazyImage(url, 24, 24);
+ return images.load(url, 24, 24);
}
}
diff --git a/src/main/java/com/github/k7t3/tcv/app/chat/ChatDataViewModel.java b/src/main/java/com/github/k7t3/tcv/app/chat/ChatDataViewModel.java
index 5347b22..78ee9f0 100644
--- a/src/main/java/com/github/k7t3/tcv/app/chat/ChatDataViewModel.java
+++ b/src/main/java/com/github/k7t3/tcv/app/chat/ChatDataViewModel.java
@@ -21,14 +21,11 @@
import com.github.k7t3.tcv.app.chat.filter.KeywordFilterEntry;
import com.github.k7t3.tcv.app.chat.filter.UserFilterEntry;
import com.github.k7t3.tcv.app.emoji.ChatEmojiStore;
-import com.github.k7t3.tcv.app.event.KeywordFilteringEvent;
-import com.github.k7t3.tcv.app.event.UserFilteringEvent;
import com.github.k7t3.tcv.app.image.LazyImage;
import com.github.k7t3.tcv.domain.chat.ChatData;
import com.github.k7t3.tcv.domain.chat.ChatMessage;
import com.github.k7t3.tcv.domain.chat.ChatMessageFragment;
import com.github.k7t3.tcv.view.chat.ChatFont;
-import de.saxsys.mvvmfx.MvvmFX;
import de.saxsys.mvvmfx.ViewModel;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
@@ -188,8 +185,6 @@ public void keywordFilter() {
var filter = KeywordFilterEntry.exactMatch(message);
chatFilters.saveKeywordFilter(filter);
- var event = new KeywordFilteringEvent(filter);
- MvvmFX.getNotificationCenter().publish(event.getClass().getName(), event);
}
public void userFilter(String comment) {
@@ -197,8 +192,6 @@ public void userFilter(String comment) {
var filter = new UserFilterEntry(chat.userId(), chat.userName(), comment);
chatFilters.saveUserFilter(filter);
- var event = new UserFilteringEvent(filter);
- MvvmFX.getNotificationCenter().publish(event.getClass().getName(), event);
}
// ********** PROPERTIES **********
diff --git a/src/main/java/com/github/k7t3/tcv/app/chat/ChatEmoteStore.java b/src/main/java/com/github/k7t3/tcv/app/chat/ChatEmoteStore.java
index 784ff49..63bdb6b 100644
--- a/src/main/java/com/github/k7t3/tcv/app/chat/ChatEmoteStore.java
+++ b/src/main/java/com/github/k7t3/tcv/app/chat/ChatEmoteStore.java
@@ -17,6 +17,7 @@
package com.github.k7t3.tcv.app.chat;
import com.github.k7t3.tcv.app.image.LazyImage;
+import com.github.k7t3.tcv.app.image.ImageLoader;
import com.github.k7t3.tcv.app.service.CachedImageStore;
import java.time.Duration;
@@ -27,15 +28,17 @@
public class ChatEmoteStore extends CachedImageStore {
private static final String CDN_FORMAT = "https://static-cdn.jtvnw.net/emoticons/v2/%s/default/light/1.0";
+ private final ImageLoader images;
- public ChatEmoteStore() {
+ public ChatEmoteStore(ImageLoader images) {
super(100, Duration.ofMinutes(5));
+ this.images = images;
}
@Override
protected LazyImage loadImage(String key) {
var uri = CDN_FORMAT.formatted(key);
- return new LazyImage(uri, 0, 0);
+ return images.load(uri, 0, 0);
}
}
diff --git a/src/main/java/com/github/k7t3/tcv/app/chat/ChatResources.java b/src/main/java/com/github/k7t3/tcv/app/chat/ChatResources.java
new file mode 100644
index 0000000..7d05167
--- /dev/null
+++ b/src/main/java/com/github/k7t3/tcv/app/chat/ChatResources.java
@@ -0,0 +1,46 @@
+package com.github.k7t3.tcv.app.chat;
+
+import com.github.k7t3.tcv.app.chat.filter.ChatFilters;
+import com.github.k7t3.tcv.lifecycle.CloseActions;
+import com.github.k7t3.tcv.app.emoji.ChatEmojiStore;
+import com.github.k7t3.tcv.app.emoji.Emoji;
+import com.github.k7t3.tcv.app.image.ImageLoader;
+import com.github.k7t3.tcv.domain.chat.GlobalChatBadges;
+
+import java.util.Objects;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/** 初期ロードの結果、画像キャッシュと絵文字アーカイブを所有する。未採用の結果も所有者が閉じる。 */
+public final class ChatResources implements AutoCloseable {
+ private final Emoji emoji;
+ private final GlobalChatBadges badges;
+ private final ChatFilters.Snapshot filters;
+ private final GlobalChatBadgeStore badgeStore;
+ private final ChatEmoteStore emoteStore;
+ private final ChatEmojiStore emojiStore;
+ private final AtomicBoolean closed = new AtomicBoolean();
+
+ ChatResources(Emoji emoji, GlobalChatBadges badges, ChatFilters.Snapshot filters, ImageLoader images) {
+ this.emoji = Objects.requireNonNull(emoji);
+ this.badges = Objects.requireNonNull(badges);
+ this.filters = Objects.requireNonNull(filters);
+ badgeStore = new GlobalChatBadgeStore(badges, images);
+ emoteStore = new ChatEmoteStore(images);
+ emojiStore = new ChatEmojiStore(emoji, images);
+ }
+
+ Emoji emoji() { return emoji; }
+ GlobalChatBadges badges() { return badges; }
+ ChatFilters.Snapshot filters() { return filters; }
+ GlobalChatBadgeStore badgeStore() { return badgeStore; }
+ ChatEmoteStore emoteStore() { return emoteStore; }
+ ChatEmojiStore emojiStore() { return emojiStore; }
+
+ /** 画像の取消を要求してからアーカイブを一度だけ閉じる。 */
+ @Override
+ public void close() {
+ if (closed.compareAndSet(false, true)) {
+ CloseActions.runAll(badgeStore::close, emoteStore::close, emojiStore::close, emoji::close);
+ }
+ }
+}
diff --git a/src/main/java/com/github/k7t3/tcv/app/chat/ChatResourcesLoader.java b/src/main/java/com/github/k7t3/tcv/app/chat/ChatResourcesLoader.java
new file mode 100644
index 0000000..d1d0313
--- /dev/null
+++ b/src/main/java/com/github/k7t3/tcv/app/chat/ChatResourcesLoader.java
@@ -0,0 +1,69 @@
+package com.github.k7t3.tcv.app.chat;
+
+import com.github.k7t3.tcv.app.chat.filter.ChatFilters;
+import com.github.k7t3.tcv.app.emoji.Emoji;
+import com.github.k7t3.tcv.app.image.ImageLoader;
+import com.github.k7t3.tcv.domain.Twitch;
+import com.github.k7t3.tcv.domain.chat.GlobalChatBadges;
+
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.Objects;
+import java.util.function.Supplier;
+
+/** UI 状態を変更せず、チャットに必要なデータを読み込む。途中失敗時は開いたリソースを解放する。 */
+public final class ChatResourcesLoader {
+ /** 後始末の失敗を通常の取得失敗と区別する。原因とそのsuppressedに両方の失敗を保持する。 */
+ static final class CleanupFailure extends IllegalStateException {
+ private CleanupFailure(Throwable loadFailure) {
+ super("Failed to release chat resources after loading failed", loadFailure);
+ }
+ }
+
+ private final Supplier emojiFactory;
+ private final Supplier badgeLoader;
+ private final Supplier filterLoader;
+ private final ImageLoader images;
+
+ /** 取得に使うセッションと画像サービスを借用し、背景で読む入力を固定する。 */
+ public ChatResourcesLoader(Path applicationDirectory, Twitch twitch, Supplier filterLoader, ImageLoader images) {
+ this(() -> new Emoji(applicationDirectory), () -> {
+ var badges = new GlobalChatBadges();
+ badges.load(twitch);
+ return badges;
+ }, filterLoader, images);
+ }
+
+ ChatResourcesLoader(Supplier emojiFactory, Supplier badgeLoader,
+ Supplier filterLoader, ImageLoader images) {
+ this.emojiFactory = Objects.requireNonNull(emojiFactory);
+ this.badgeLoader = Objects.requireNonNull(badgeLoader);
+ this.filterLoader = Objects.requireNonNull(filterLoader);
+ this.images = Objects.requireNonNull(images);
+ }
+
+ /**
+ * 背景で取得し、返した資源の所有を呼出元へ移す。途中失敗では自身で解放する。
+ * @throws IOException アーカイブの配置・検証が失敗した場合
+ * @throws IllegalStateException 途中失敗の解放も失敗した場合。元の取得失敗を原因とし、
+ * そのsuppressedに解放失敗を保持する
+ */
+ public ChatResources load() throws IOException {
+ var emoji = Objects.requireNonNull(emojiFactory.get());
+ try {
+ if (!emoji.validateArchive()) {
+ emoji.extractArchive();
+ if (!emoji.validateArchive()) throw new IOException("emoji archive validation failed");
+ }
+ return new ChatResources(emoji, badgeLoader.get(), filterLoader.get(), images);
+ } catch (IOException | RuntimeException | Error failure) {
+ try {
+ emoji.close();
+ } catch (RuntimeException | Error cleanupFailure) {
+ if (cleanupFailure != failure) failure.addSuppressed(cleanupFailure);
+ throw new CleanupFailure(failure);
+ }
+ throw failure;
+ }
+ }
+}
diff --git a/src/main/java/com/github/k7t3/tcv/app/chat/ChatRoomContainerViewModel.java b/src/main/java/com/github/k7t3/tcv/app/chat/ChatRoomContainerViewModel.java
index 442dfd5..ae58c13 100644
--- a/src/main/java/com/github/k7t3/tcv/app/chat/ChatRoomContainerViewModel.java
+++ b/src/main/java/com/github/k7t3/tcv/app/chat/ChatRoomContainerViewModel.java
@@ -19,19 +19,17 @@
import com.github.k7t3.tcv.app.channel.TwitchChannelViewModel;
import com.github.k7t3.tcv.app.chat.filter.ChatFilters;
import com.github.k7t3.tcv.app.model.AbstractViewModel;
-import com.github.k7t3.tcv.app.core.AppHelper;
-import com.github.k7t3.tcv.app.core.OS;
-import com.github.k7t3.tcv.app.model.TypeSafeNotificationObserver;
+import com.github.k7t3.tcv.app.core.Resources;
import com.github.k7t3.tcv.app.emoji.ChatEmojiStore;
-import com.github.k7t3.tcv.app.emoji.Emoji;
import com.github.k7t3.tcv.app.event.ChatOpeningEvent;
import com.github.k7t3.tcv.app.event.KeywordFilteringEvent;
import com.github.k7t3.tcv.app.event.UserFilteringEvent;
import com.github.k7t3.tcv.app.reactive.ChatMessageSubscriber;
import com.github.k7t3.tcv.app.reactive.DownCastFXSubscriber;
import com.github.k7t3.tcv.app.service.FXTask;
+import com.github.k7t3.tcv.app.service.FXTaskGroup;
+import com.github.k7t3.tcv.lifecycle.CloseActions;
import com.github.k7t3.tcv.domain.channel.TwitchChannel;
-import com.github.k7t3.tcv.domain.chat.GlobalChatBadges;
import com.github.k7t3.tcv.domain.event.EventSubscribers;
import com.github.k7t3.tcv.domain.event.chat.*;
import com.github.k7t3.tcv.prefs.ChatPreferences;
@@ -44,17 +42,26 @@
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
+import javafx.concurrent.WorkerStateEvent;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
+import java.util.Objects;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionStage;
+import java.util.concurrent.Executor;
+import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
+import java.util.function.Supplier;
public class ChatRoomContainerViewModel extends AbstractViewModel {
+ private static final Logger LOGGER = LoggerFactory.getLogger(ChatRoomContainerViewModel.class);
+
private final ObservableList chatRoomList = FXCollections.observableArrayList(c -> new Observable[] { c.selectedProperty() });
private final ObservableList floatingChatRoomList = FXCollections.observableArrayList();
private final ObservableList allChatRooms = FXCollections.observableArrayList();
@@ -65,11 +72,24 @@ public class ChatRoomContainerViewModel extends AbstractViewModel {
private final ReadOnlyBooleanWrapper selectMode = new ReadOnlyBooleanWrapper(false);
private final ReadOnlyIntegerWrapper selectingCount = new ReadOnlyIntegerWrapper();
private final ReadOnlyBooleanWrapper loaded = new ReadOnlyBooleanWrapper(false);
+ private final ReadOnlyBooleanWrapper loading = new ReadOnlyBooleanWrapper(false);
+ private final ReadOnlyStringWrapper error = new ReadOnlyStringWrapper();
+ private final Supplier loadRequestFactory;
+ private final Executor executor;
+ private final Consumer> shutdownAwaiter;
+ private final Object loadLock = new Object();
+ private Object loadAttempt;
+ private FXTask activeLoad;
+ private ChatResources pendingResources;
+ private ChatResources resources;
+ private final List pendingChatOpenings = new ArrayList<>();
+
+ /** 読込開始時のFX上で固定したフィルターと背景の取得処理。 */
+ public record LoadRequest(ChatFilters filters, Callable loader) {}
private GlobalChatBadgeStore globalBadgeStore;
private ChatEmoteStore chatEmoteStore;
private final DefinedChatColors definedChatColors = new DefinedChatColors();
- private Emoji emoji;
private ChatEmojiStore emojiStore;
private ChatFilters chatFilters;
@@ -78,13 +98,16 @@ public class ChatRoomContainerViewModel extends AbstractViewModel {
private final BooleanProperty showBadges = new SimpleBooleanProperty(true);
private final ObjectProperty font = new SimpleObjectProperty<>(null);
- private final List> subscribers = new ArrayList<>();
-
- private TypeSafeNotificationObserver onChatOpened;
- private TypeSafeNotificationObserver onKeywordFiltered;
- private TypeSafeNotificationObserver onUserFiltered;
+ ChatRoomContainerViewModel(ChatFilters filters, Callable loader, Executor executor) {
+ this(() -> new LoadRequest(filters, loader), executor, ignored -> {});
+ }
- public ChatRoomContainerViewModel() {
+ /** 要求はFX上の読込開始時に固定し、取得は借用executorで実行する。結果の実解放を終了所有者へ登録する。 */
+ public ChatRoomContainerViewModel(Supplier loadRequestFactory, Executor executor,
+ Consumer> shutdownAwaiter) {
+ this.loadRequestFactory = Objects.requireNonNull(loadRequestFactory);
+ this.executor = Objects.requireNonNull(executor);
+ this.shutdownAwaiter = Objects.requireNonNull(shutdownAwaiter);
selectingCount.bind(Bindings.size(selectedList));
// 一つ以上選択されているときは選択モード
@@ -99,7 +122,7 @@ public void bindChatPreferences(ChatPreferences chatPreferences) {
chatCacheSize.bind(chatPreferences.chatCacheSizeProperty());
showUserName.bind(chatPreferences.showUserNameProperty());
showBadges.bind(chatPreferences.showBadgesProperty());
- font.bind(chatPreferences.fontProperty());
+ font.bind(chatPreferences.fontProperty().map(settings -> new ChatFont(settings.family(), settings.size())));
}
private void injectionItemListener(ListChangeListener.Change extends ChatRoomViewModel> c) {
@@ -111,20 +134,20 @@ private void injectionItemListener(ListChangeListener.Change extends ChatRoomV
}
}
- private FlowableSubscriber subscriber(Class type, Consumer consumer) {
- return new DownCastFXSubscriber<>(type, consumer);
+ private FlowableSubscriber subscriber(SessionSubscriptions subscriptions, Class type, Consumer consumer) {
+ return subscriptions.own(new DownCastFXSubscriber<>(type, consumer));
}
@Override
- public void subscribeEvents(EventSubscribers eventSubscribers) {
- var clearedSub = subscriber(ChatClearedEvent.class, this::onChatCleared);
- var deleteSub = subscriber(ChatMessageDeletedEvent.class, this::onMessageDeleted);
- var stateSub = subscriber(ChatRoomStateUpdatedEvent.class, this::onStateUpdated);
- var cheeredSub = subscriber(CheeredEvent.class, this::onCheered);
- var raidReceivedSub = subscriber(RaidReceivedEvent.class, this::onRaidReceived);
- var giftedSub = subscriber(UserGiftedSubscribeEvent.class, this::onGiftedSubs);
- var subsSub = subscriber(UserSubscribedEvent.class, this::onSubs);
- var chatSub = new ChatMessageSubscriber(this::onChatPosted);
+ protected void onSubscribeEvents(EventSubscribers eventSubscribers, SessionSubscriptions subscriptions) {
+ var clearedSub = subscriber(subscriptions, ChatClearedEvent.class, this::onChatCleared);
+ var deleteSub = subscriber(subscriptions, ChatMessageDeletedEvent.class, this::onMessageDeleted);
+ var stateSub = subscriber(subscriptions, ChatRoomStateUpdatedEvent.class, this::onStateUpdated);
+ var cheeredSub = subscriber(subscriptions, CheeredEvent.class, this::onCheered);
+ var raidReceivedSub = subscriber(subscriptions, RaidReceivedEvent.class, this::onRaidReceived);
+ var giftedSub = subscriber(subscriptions, UserGiftedSubscribeEvent.class, this::onGiftedSubs);
+ var subsSub = subscriber(subscriptions, UserSubscribedEvent.class, this::onSubs);
+ var chatSub = subscriptions.own(new ChatMessageSubscriber(this::onChatPosted));
eventSubscribers.subscribeChatEvent(clearedSub);
eventSubscribers.subscribeChatEvent(deleteSub);
@@ -135,24 +158,9 @@ public void subscribeEvents(EventSubscribers eventSubscribers) {
eventSubscribers.subscribeChatEvent(subsSub);
eventSubscribers.subscribeMessageEvent(chatSub);
- subscribers.addAll(List.of(
- clearedSub,
- deleteSub,
- stateSub,
- cheeredSub,
- raidReceivedSub,
- giftedSub,
- subsSub,
- chatSub
- ));
-
- onChatOpened = this::onChatOpened;
- onKeywordFiltered = this::onKeywordFiltered;
- onUserFiltered = this::onUserFiltered;
-
- subscribe(ChatOpeningEvent.class, onChatOpened);
- subscribe(KeywordFilteringEvent.class, onKeywordFiltered);
- subscribe(UserFilteringEvent.class, onUserFiltered);
+ subscriptions.subscribe(ChatOpeningEvent.class, this::onChatOpened);
+ subscriptions.subscribe(KeywordFilteringEvent.class, this::onKeywordFiltered);
+ subscriptions.subscribe(UserFilteringEvent.class, this::onUserFiltered);
}
private Optional find(TwitchChannel channel) {
@@ -221,6 +229,10 @@ private void onSubs(UserSubscribedEvent e) {
}
private void onChatOpened(ChatOpeningEvent e) {
+ if (!loaded.get()) {
+ pendingChatOpenings.add(e);
+ return;
+ }
switch (e.getChatOpenType()) {
case MERGED -> openChatRooms(e.getChannels());
case SEPARATED -> e.getChannels().forEach(this::openChatRoom);
@@ -231,45 +243,175 @@ public ObservableList getChatRoomList() {
return chatRoomList;
}
+ /**
+ * 初期データの取得を開始して結果を FX スレッドで反映する。FX スレッドから呼び出す。
+ * 実行中は同じタスクを返す。UI の準備完了は {@link #loadedProperty()}、失敗は {@link #errorProperty()} で確認する。
+ * @return データを取得するタスク
+ * @throws IllegalStateException このモデルが終了している場合
+ */
public FXTask loadAsync() {
+ if (isClosed()) throw new IllegalStateException("chat container is closed");
+ if (activeLoad != null) return activeLoad;
if (loaded.get()) return FXTask.empty();
- loaded.set(true);
-
- var helper = AppHelper.getInstance();
- var twitch = helper.getTwitch();
-
- chatFilters = helper.getChatFilters();
-
+ var request = loadRequestFactory.get();
+ loading.set(true);
+ error.set(null);
+ var token = new Object();
+ synchronized (loadLock) {
+ loadAttempt = token;
+ }
+ var drained = new CompletableFuture();
+ var executionClaimed = new AtomicBoolean();
var task = FXTask.task(() -> {
- var appDir = OS.current().getApplicationDirectory();
- emoji = new Emoji(appDir);
- emojiStore = new ChatEmojiStore(emoji);
-
- var eit = FXTask.task(() -> {
- if (!emoji.validateArchive()) {
- emoji.extractArchive();
- emoji.validateArchive();
+ final ChatResources result;
+ try { result = request.loader().call(); }
+ catch (ChatResourcesLoader.CleanupFailure failure) {
+ drained.completeExceptionally(failure);
+ throw failure;
+ }
+ synchronized (loadLock) {
+ if (isCurrentLoad(token)) {
+ pendingResources = result;
+ return null;
}
- return null;
- }).runAsync();
-
- var globalBadges = new GlobalChatBadges();
- var gbt = FXTask.task(() -> globalBadges.load(twitch)).runAsync();
- globalBadgeStore = new GlobalChatBadgeStore(globalBadges);
- chatEmoteStore = new ChatEmoteStore();
-
- var cft = FXTask.task(() -> chatFilters.loadAll()).runAsync();
-
- gbt.waitForDone();
- cft.waitForDone();
- eit.waitForDone();
-
+ }
+ try { result.close(); }
+ catch (RuntimeException | Error failure) {
+ // 取消済みTaskの例外には残らないため、実解放の所有者にも保持する。
+ drained.completeExceptionally(failure);
+ throw failure;
+ }
return null;
});
+ activeLoad = task;
+ task.onDone(() -> adoptResources(token, request.filters()));
+ task.addEventHandler(WorkerStateEvent.WORKER_STATE_FAILED, event -> failLoading(token));
+ task.addEventHandler(WorkerStateEvent.WORKER_STATE_CANCELLED, event -> {
+ if (isCurrentLoad(token)) resetLoading();
+ });
+ task.setFinally(() -> {
+ if (activeLoad == task) {
+ activeLoad = null;
+ loading.set(false);
+ }
+ });
+ task.completion().whenComplete((ignored, failure) -> {
+ // 未開始の取消とワーカーの開始のどちらかだけが、この実行を引き受ける。
+ if (task.isCancelled() && executionClaimed.compareAndSet(false, true)) drained.complete(null);
+ });
+ try {
+ shutdownAwaiter.accept(drained.minimalCompletionStage());
+ executor.execute(() -> {
+ if (!executionClaimed.compareAndSet(false, true)) return;
+ try { task.run(); }
+ finally { drained.complete(null); }
+ });
+ } catch (RuntimeException | Error rejected) {
+ LOGGER.error("Failed to start chat resource loading", rejected);
+ failLoading(token);
+ task.cancel();
+ drained.complete(null);
+ }
+ return task;
+ }
- task.runAsync();
+ private boolean isCurrentLoad(Object token) {
+ synchronized (loadLock) {
+ return !isClosed() && loadAttempt == token;
+ }
+ }
- return task;
+ private void adoptResources(Object token, ChatFilters filters) {
+ synchronized (loadLock) {
+ if (!isCurrentLoad(token)) return;
+ resources = pendingResources;
+ pendingResources = null;
+ }
+ try {
+ var result = resources;
+ filters.applySnapshot(result.filters());
+ if (!isCurrentLoad(token)) return;
+ chatFilters = filters;
+ globalBadgeStore = result.badgeStore();
+ chatEmoteStore = result.emoteStore();
+ emojiStore = result.emojiStore();
+ loaded.set(true);
+ } catch (RuntimeException failure) {
+ LOGGER.error("Failed to apply chat resources", failure);
+ failLoading(token);
+ return;
+ }
+ var openings = List.copyOf(pendingChatOpenings);
+ pendingChatOpenings.clear();
+ for (var opening : openings) {
+ if (!isCurrentLoad(token)) break;
+ onChatOpened(opening);
+ }
+ }
+
+ private void failLoading(Object token) {
+ if (!isCurrentLoad(token)) return;
+ resetLoading();
+ error.set(Resources.getString("chat.load.failed"));
+ }
+
+ private void resetLoading() {
+ final ChatResources pending;
+ final ChatResources adopted;
+ synchronized (loadLock) {
+ loadAttempt = null;
+ pending = pendingResources;
+ adopted = resources;
+ pendingResources = null;
+ resources = null;
+ }
+ var task = activeLoad;
+ activeLoad = null;
+ if (task != null) task.cancel();
+ loading.set(false);
+ loaded.set(false);
+ error.set(null);
+ chatFilters = null;
+ globalBadgeStore = null;
+ chatEmoteStore = null;
+ emojiStore = null;
+ releaseResources(pending);
+ if (adopted != pending) releaseResources(adopted);
+ }
+
+ private void releaseResources(ChatResources owned) {
+ if (owned == null) return;
+ var released = new CompletableFuture();
+ Runnable release = () -> {
+ try {
+ owned.close();
+ released.complete(null);
+ } catch (RuntimeException | Error failure) {
+ released.completeExceptionally(failure);
+ throw failure;
+ }
+ };
+ // 追跡の登録や借用workerの拒否でも実解放を続け、FX上ではI/Oを行わない。
+ CloseActions.runAll(
+ () -> shutdownAwaiter.accept(released.minimalCompletionStage()),
+ () -> {
+ try { executor.execute(release); }
+ catch (RuntimeException | Error rejected) {
+ LOGGER.warn("Chat resource release worker is unavailable", rejected);
+ try {
+ Thread.ofVirtual().name("TCV-Chat-Resources-Close").start(() -> {
+ try { release.run(); }
+ catch (RuntimeException | Error failure) {
+ LOGGER.error("Failed to release chat resources on fallback worker", failure);
+ }
+ });
+ } catch (RuntimeException | Error fallbackFailure) {
+ if (fallbackFailure != rejected) rejected.addSuppressed(fallbackFailure);
+ released.completeExceptionally(rejected);
+ throw rejected;
+ }
+ }
+ });
}
private void openChatRooms(List channels) {
@@ -312,7 +454,8 @@ private void openChatRooms(List channels) {
chatRooms,
emojiStore,
this,
- chatFilters
+ chatFilters,
+ chatCacheSize.get()
);
chatRooms.forEach(SingleChatRoomViewModel::joinChatAsync);
@@ -382,8 +525,8 @@ public void removeLast() {
if (chatRoomList.isEmpty()) return;
var last = getChatRoomList().getLast();
- last.leaveChatAsync();
chatRoomList.remove(last);
+ leaveRooms(List.of(last));
}
void popOutAsFloatableStage(ChatRoomViewModel chatRoom) {
@@ -415,7 +558,20 @@ public void unselectAll() {
*/
public void closeAll() {
var selectedList = new ArrayList<>(getSelectedList());
- selectedList.forEach(ChatRoomViewModel::leaveChatAsync);
+ chatRoomList.removeAll(selectedList);
+ leaveRooms(selectedList);
+ }
+
+ private void leaveRooms(List rooms) {
+ if (!rooms.isEmpty()) trackExit(FXTaskGroup.startAll(rooms, ChatRoomViewModel::leaveChatAsync));
+ }
+
+ /** 取消可能な UI の task と分離して、全子タスクの終端と失敗をアプリ終了まで所有する。 */
+ void trackExit(FXTaskGroup.Batch exits) {
+ shutdownAwaiter.accept(exits.settled());
+ exits.settled().whenComplete((ignored, failure) -> {
+ if (failure != null) LOGGER.error("Failed to leave chat rooms", failure);
+ });
}
/**
@@ -473,7 +629,8 @@ public void mergeSelectedChats() {
chatRooms,
emojiStore,
this,
- chatFilters
+ chatFilters,
+ chatCacheSize.get()
);
bindChatRoomProperties(chatRoomViewModel);
@@ -483,62 +640,40 @@ public void mergeSelectedChats() {
}
@Override
- public void onLogout() {
- subscribers.forEach(FlowableSubscriber::cancel);
- subscribers.clear();
-
- var singles = getChatRoomList();
- var floatings = getFloatingChatRoomList();
-
- var chatRooms = new ArrayList();
- chatRooms.addAll(singles);
- chatRooms.addAll(floatings);
-
- singles.clear();
- floatings.clear();
-
- chatRooms.forEach(ChatRoomViewModel::leaveChatAsync);
+ protected void onLoggedOut() {
+ releaseChatRooms();
+ }
- unsubscribe(onChatOpened);
- unsubscribe(onKeywordFiltered);
- unsubscribe(onUserFiltered);
- onChatOpened = null;
- onKeywordFiltered = null;
- onUserFiltered = null;
+ private void releaseChatRooms() {
+ pendingChatOpenings.clear();
+ var chatRooms = new ArrayList<>(chatRoomList);
+ chatRooms.addAll(floatingChatRoomList);
+ CloseActions.runAll(chatRoomList::clear, floatingChatRoomList::clear,
+ this::resetLoading, () -> leaveRooms(chatRooms));
}
/**
- * コンテナをクリアする。
- * チャットがすべてログアウトされるまでスレッドをブロックする。
+ * チャットの退出を開始する。完了待ちはアプリケーションのワーカー終了処理が行う。
*/
@Override
- public void close() {
- subscribers.forEach(FlowableSubscriber::cancel);
-
- var singles = getChatRoomList();
- var floatings = getFloatingChatRoomList();
-
- if (emoji != null) {
- emoji.close();
- }
-
- var chatRooms = new ArrayList();
- chatRooms.addAll(singles);
- chatRooms.addAll(floatings);
- chatRooms.stream().map(ChatRoomViewModel::leaveChatAsync).forEach(task -> {
- try {
- task.get(10, TimeUnit.SECONDS);
- } catch (InterruptedException | ExecutionException | TimeoutException ignored) {
- // no-op
- }
- });
+ protected void onClose() {
+ CloseActions.runAll(this::releaseChatRooms,
+ chatCacheSize::unbind, showUserName::unbind, showBadges::unbind, font::unbind);
}
// ******************** PROPERTIES ********************
+ /** すべてのリソースとフィルターを UI に反映し、チャットを開ける状態。 */
public ReadOnlyBooleanProperty loadedProperty() { return loaded.getReadOnlyProperty(); }
public boolean isLoaded() { return loaded.get(); }
+ /** キューでの待機を含む初期ロード中の状態。 */
+ public ReadOnlyBooleanProperty loadingProperty() { return loading.getReadOnlyProperty(); }
+ public boolean isLoading() { return loading.get(); }
+
+ public ReadOnlyStringProperty errorProperty() { return error.getReadOnlyProperty(); }
+ public String getError() { return error.get(); }
+
public ReadOnlyBooleanProperty selectModeProperty() { return selectMode.getReadOnlyProperty(); }
public boolean isSelectMode() { return selectMode.get(); }
diff --git a/src/main/java/com/github/k7t3/tcv/app/chat/ChatRoomViewModel.java b/src/main/java/com/github/k7t3/tcv/app/chat/ChatRoomViewModel.java
index 04579c1..eda9a7e 100644
--- a/src/main/java/com/github/k7t3/tcv/app/chat/ChatRoomViewModel.java
+++ b/src/main/java/com/github/k7t3/tcv/app/chat/ChatRoomViewModel.java
@@ -36,6 +36,7 @@
import org.slf4j.LoggerFactory;
import java.util.LinkedList;
+import java.util.List;
public abstract class ChatRoomViewModel {
@@ -155,9 +156,7 @@ private ChatDataViewModel createChatDataViewModel(TwitchChannelViewModel channel
}
public void addChat(ChatDataViewModel chat) {
- chat.visibleNameProperty().bind(showName);
- chat.visibleBadgeProperty().bind(showBadges);
- chat.fontProperty().bind(font);
+ bindPresentation(chat);
// 上限制限
if (getChatCacheSize() <= chatDataList.size()) {
@@ -166,11 +165,23 @@ public void addChat(ChatDataViewModel chat) {
chatDataList.add(chat);
}
+ /** 呼出元で選択した履歴を、このモデルの表示設定へ接続して置き換える。 */
+ protected final void replaceChatHistory(List history) {
+ var snapshot = List.copyOf(history);
+ snapshot.forEach(this::bindPresentation);
+ chatDataList.setAll(snapshot);
+ }
+
+ private void bindPresentation(ChatDataViewModel chat) {
+ chat.visibleNameProperty().bind(showName);
+ chat.visibleBadgeProperty().bind(showBadges);
+ chat.fontProperty().bind(font);
+ }
+
public void deleteChatMessage(String msgId) {
for (var item : chatDataList) {
if (item.getChatData().msgId().equalsIgnoreCase(msgId)) {
item.setDeleted(true);
- break;
}
}
}
diff --git a/src/main/java/com/github/k7t3/tcv/app/chat/GlobalChatBadgeStore.java b/src/main/java/com/github/k7t3/tcv/app/chat/GlobalChatBadgeStore.java
index 82120e7..ba2e5cb 100644
--- a/src/main/java/com/github/k7t3/tcv/app/chat/GlobalChatBadgeStore.java
+++ b/src/main/java/com/github/k7t3/tcv/app/chat/GlobalChatBadgeStore.java
@@ -17,6 +17,7 @@
package com.github.k7t3.tcv.app.chat;
import com.github.k7t3.tcv.app.image.LazyImage;
+import com.github.k7t3.tcv.app.image.ImageLoader;
import com.github.k7t3.tcv.app.service.CachedImageStore;
import com.github.k7t3.tcv.domain.chat.ChatBadge;
import com.github.k7t3.tcv.domain.chat.GlobalChatBadges;
@@ -26,17 +27,19 @@
public class GlobalChatBadgeStore extends CachedImageStore {
private final GlobalChatBadges globalBadges;
+ private final ImageLoader images;
- public GlobalChatBadgeStore(GlobalChatBadges globalChatBadges) {
+ public GlobalChatBadgeStore(GlobalChatBadges globalChatBadges, ImageLoader images) {
super(16, Duration.ofMinutes(5));
this.globalBadges = globalChatBadges;
+ this.images = images;
}
@Override
protected LazyImage loadImage(ChatBadge key) {
var url = globalBadges.getBadgeUrl(key.id(), key.version()).orElse(null);
if (url == null) return null;
- return new LazyImage(url, 0, 0);
+ return images.load(url, 0, 0);
}
}
diff --git a/src/main/java/com/github/k7t3/tcv/app/chat/MergedChatRoomViewModel.java b/src/main/java/com/github/k7t3/tcv/app/chat/MergedChatRoomViewModel.java
index 76b5970..77ec9fc 100644
--- a/src/main/java/com/github/k7t3/tcv/app/chat/MergedChatRoomViewModel.java
+++ b/src/main/java/com/github/k7t3/tcv/app/chat/MergedChatRoomViewModel.java
@@ -20,6 +20,7 @@
import com.github.k7t3.tcv.app.chat.filter.ChatFilters;
import com.github.k7t3.tcv.app.emoji.ChatEmojiStore;
import com.github.k7t3.tcv.app.service.FXTask;
+import com.github.k7t3.tcv.app.service.FXTaskGroup;
import com.github.k7t3.tcv.domain.channel.TwitchChannel;
import com.github.k7t3.tcv.domain.event.chat.ChatRoomStateUpdatedEvent;
import de.saxsys.mvvmfx.ViewModel;
@@ -28,10 +29,6 @@
import java.nio.charset.StandardCharsets;
import java.util.*;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
public class MergedChatRoomViewModel extends ChatRoomViewModel implements ViewModel {
@@ -48,9 +45,23 @@ public class MergedChatRoomViewModel extends ChatRoomViewModel implements ViewMo
ChatEmojiStore emojiCache,
ChatRoomContainerViewModel containerViewModel,
ChatFilters chatFilters
+ ) {
+ this(globalChatBadgeStore, emoteStore, definedChatColors, chatRooms, emojiCache, containerViewModel,
+ chatFilters, DEFAULT_ITEM_COUNT_LIMIT);
+ }
+
+ MergedChatRoomViewModel(
+ GlobalChatBadgeStore globalChatBadgeStore,
+ ChatEmoteStore emoteStore,
+ DefinedChatColors definedChatColors,
+ List chatRooms,
+ ChatEmojiStore emojiCache,
+ ChatRoomContainerViewModel containerViewModel,
+ ChatFilters chatFilters,
+ int initialLimit
) {
super(globalChatBadgeStore, emoteStore, definedChatColors, emojiCache, containerViewModel, chatFilters);
- setChatCacheSize(DEFAULT_ITEM_COUNT_LIMIT);
+ setChatCacheSize(initialLimit);
initChatRooms(chatRooms);
}
@@ -72,23 +83,7 @@ public String getIdentity() {
public void addChatRoom(SingleChatRoomViewModel chatRoom) {
var channel = chatRoom.getChannel();
-
- //
- // 追加するチャットルームが現在持っているチャットの情報をマージする
- // とりあえずすべてマージして最後に制限の個数で切り捨てる
- //
- var mergedChats = new ArrayList<>(getChatDataList());
- mergedChats.addAll(chatRoom.getChatDataList());
- mergedChats.sort(Comparator.comparing(o -> o.getChatData().firedAt()));
-
- var limit = getChatCacheSize();
- if (mergedChats.size() <= limit) {
- getChatDataList().setAll(mergedChats);
- } else {
- var subList = mergedChats.subList(mergedChats.size() - limit, mergedChats.size());
- getChatDataList().setAll(subList);
- }
-
+ mergeHistory(chatRoom.getChatDataList());
channels.put(channel, chatRoom);
}
@@ -125,7 +120,7 @@ public void separateChatRoom(SingleChatRoomViewModel chatRoom) {
.toList();
// 分離したチャンネルにチャット情報を渡す
- chatRoom.getChatDataList().setAll(chatList);
+ chatRoom.replaceChatHistory(chatList);
// 現在のチャットから削除
getChatDataList().removeAll(chatList);
@@ -142,38 +137,30 @@ public void closeChatRoom(SingleChatRoomViewModel chatRoom) {
channels.remove(channel);
+ chatRoom.leaveChatAsync();
onChannelRemoved();
}
public void aggregate(MergedChatRoomViewModel mergedChatRoom) {
if (this == mergedChatRoom) return;
-
+ var incoming = new HashMap();
for (var entry : mergedChatRoom.channels.entrySet()) {
- var channel = entry.getKey();
- var chatRoom = entry.getValue();
-
- if (channels.containsValue(chatRoom)) continue;
-
- //
- // 追加するチャットルームが現在持っているチャットの情報をマージする
- // とりあえずすべてマージして、最後に制限の個数で切り捨てる
- //
- var mergedChats = new ArrayList<>(getChatDataList());
- mergedChats.addAll(chatRoom.getChatDataList());
- mergedChats.sort(Comparator.comparing(o -> o.getChatData().firedAt()));
-
- var limit = getChatCacheSize();
- if (mergedChats.size() <= limit) {
- chatRoom.getChatDataList().setAll(mergedChats);
- } else {
- var subList = mergedChats.subList(mergedChats.size() - limit, mergedChats.size());
- chatRoom.getChatDataList().setAll(subList);
- }
-
- channels.put(channel, chatRoom);
- containerViewModel.getChatRoomList().remove(mergedChatRoom);
+ if (!channels.containsKey(entry.getKey())) incoming.put(entry.getKey(), entry.getValue());
}
+ var incomingHistory = mergedChatRoom.getChatDataList().stream()
+ .filter(chat -> incoming.containsKey(chat.getChannel()))
+ .toList();
+ mergeHistory(incomingHistory);
+ channels.putAll(incoming);
+ containerViewModel.getChatRoomList().remove(mergedChatRoom);
+ }
+ private void mergeHistory(List incoming) {
+ var mergedChats = new ArrayList<>(getChatDataList());
+ mergedChats.addAll(incoming);
+ mergedChats.sort(Comparator.comparing(chat -> chat.getChatData().firedAt()));
+ var begin = Math.max(0, mergedChats.size() - getChatCacheSize());
+ replaceChatHistory(mergedChats.subList(begin, mergedChats.size()));
}
public ObservableMap getChannels() {
@@ -193,11 +180,10 @@ public boolean accept(TwitchChannel channel) {
public void onStateUpdated(ChatRoomStateUpdatedEvent e) {
var chatRoom = e.getChatRoom();
- // ConcurrentModificationExceptionが内部で起こり得る?
channels.entrySet()
.stream()
- .filter(entry -> entry.getKey().getChannel().isChatJoined())
- .filter(entry -> entry.getKey().getChannel().getOrJoinChatRoom().equals(chatRoom))
+ .filter(entry -> entry.getKey().getChannel().getJoinedChatRoom()
+ .filter(current -> current == chatRoom).isPresent())
.findFirst()
.map(Map.Entry::getValue)
.ifPresent(chatRoomViewModel -> chatRoomViewModel.onStateUpdated(e));
@@ -221,28 +207,12 @@ public FXTask> joinChatAsync() {
@Override
public FXTask> leaveChatAsync() {
+ List.copyOf(channels.values()).forEach(SingleChatRoomViewModel::stopReceivingState);
containerViewModel.onLeft(this);
- // FIXME JavaFXのTaskをマージするには?
- var latch = new CountDownLatch(channels.size());
-
- channels.keySet().parallelStream().map(TwitchChannelViewModel::leaveChatAsync).forEach(task -> {
- try {
- task.get(30, TimeUnit.SECONDS);
- } catch (InterruptedException | ExecutionException | TimeoutException ignored) {
- // no-op
- } finally {
- latch.countDown();
- }
- });
-
- return FXTask.task(() -> {
- try {
- latch.await();
- } catch (InterruptedException ignored) {
- // no-op
- }
- });
+ var exits = FXTaskGroup.startAll(channels.keySet(), TwitchChannelViewModel::leaveChatAsync);
+ containerViewModel.trackExit(exits);
+ return exits.task();
}
}
diff --git a/src/main/java/com/github/k7t3/tcv/app/chat/SingleChatRoomViewModel.java b/src/main/java/com/github/k7t3/tcv/app/chat/SingleChatRoomViewModel.java
index 462b2cc..374f7cc 100644
--- a/src/main/java/com/github/k7t3/tcv/app/chat/SingleChatRoomViewModel.java
+++ b/src/main/java/com/github/k7t3/tcv/app/chat/SingleChatRoomViewModel.java
@@ -20,6 +20,7 @@
import com.github.k7t3.tcv.app.chat.filter.ChatFilters;
import com.github.k7t3.tcv.app.emoji.ChatEmojiStore;
import com.github.k7t3.tcv.app.service.FXTask;
+import com.github.k7t3.tcv.app.service.FXTaskGroup;
import com.github.k7t3.tcv.domain.channel.TwitchChannel;
import com.github.k7t3.tcv.domain.chat.ChatRoomState;
import com.github.k7t3.tcv.domain.event.chat.ChatRoomStateUpdatedEvent;
@@ -36,6 +37,7 @@
import java.util.Base64;
import java.util.HashSet;
import java.util.Objects;
+import java.util.List;
public class SingleChatRoomViewModel extends ChatRoomViewModel implements ViewModel {
@@ -44,6 +46,8 @@ public class SingleChatRoomViewModel extends ChatRoomViewModel implements ViewMo
private final ReadOnlyObjectWrapper channel;
private final ObservableSet roomStates = FXCollections.observableSet(new HashSet<>());
+ private boolean left;
+ private FXTask leaving;
SingleChatRoomViewModel(
ChatRoomContainerViewModel containerViewModel,
@@ -60,21 +64,25 @@ public class SingleChatRoomViewModel extends ChatRoomViewModel implements ViewMo
@Override
public FXTask> joinChatAsync() {
+ if (left) throw new IllegalStateException("chat room has been left");
var channel = getChannel();
return channel.joinChatAsync();
}
@Override
public FXTask leaveChatAsync() {
+ if (leaving != null) return leaving;
+ stopReceivingState();
var channel = getChannel();
-
- if (channel.isChatJoined()) {
- containerViewModel.onLeft(this);
- }
-
- return channel.leaveChatAsync();
+ containerViewModel.onLeft(this);
+ var exits = FXTaskGroup.startAll(List.of(channel), TwitchChannelViewModel::leaveChatAsync);
+ leaving = exits.task();
+ containerViewModel.trackExit(exits);
+ return exits.task();
}
+ void stopReceivingState() { left = true; }
+
@Override
public boolean accept(TwitchChannel channel) {
var viewModel = getChannel();
@@ -103,11 +111,13 @@ public ObservableSet getRoomStates() {
@Override
public void onStateUpdated(ChatRoomStateUpdatedEvent e) {
+ if (left) return;
var roomState = e.getState();
var active = e.isActive();
LOGGER.info("{} room state updated {}", getChannel().getUserLogin(), roomState);
Platform.runLater(() -> {
+ if (left || getChannel().getChannel().getJoinedChatRoom().orElse(null) != e.getChatRoom()) return;
if (active)
roomStates.add(roomState);
else
diff --git a/src/main/java/com/github/k7t3/tcv/app/chat/filter/ChatFilters.java b/src/main/java/com/github/k7t3/tcv/app/chat/filter/ChatFilters.java
index 4ad01ec..c96ddda 100644
--- a/src/main/java/com/github/k7t3/tcv/app/chat/filter/ChatFilters.java
+++ b/src/main/java/com/github/k7t3/tcv/app/chat/filter/ChatFilters.java
@@ -19,30 +19,77 @@
import com.github.k7t3.tcv.app.model.AbstractViewModel;
import com.github.k7t3.tcv.app.service.FXTask;
import com.github.k7t3.tcv.domain.chat.ChatData;
-import com.github.k7t3.tcv.domain.event.EventSubscribers;
import com.github.k7t3.tcv.entity.ChatKeywordFilterEntity;
import com.github.k7t3.tcv.entity.ChatUserFilterEntity;
-import com.github.k7t3.tcv.entity.service.ChatKeywordFilterEntityService;
-import com.github.k7t3.tcv.entity.service.ChatUserFilterEntityService;
+import com.github.k7t3.tcv.entity.service.ChatFilterEntityStore;
+import com.github.k7t3.tcv.app.event.KeywordFilteringEvent;
+import com.github.k7t3.tcv.app.event.UserFilteringEvent;
+import java.util.Set;
+import java.util.HashSet;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionStage;
+import java.util.concurrent.Executor;
+import java.util.concurrent.atomic.AtomicReference;
+
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
+import javafx.application.Platform;
import java.util.function.Predicate;
+import java.util.function.Consumer;
import java.util.regex.Pattern;
+import java.util.List;
public class ChatFilters extends AbstractViewModel {
- private final ChatKeywordFilterEntityService keywordService;
- private final ChatUserFilterEntityService userService;
+ /**
+ * UI のモデルを含まない、フィルターの読み込み結果。両リストは変更不可のコピーとして保持する。
+ * @param keywords キーワードフィルター
+ * @param users ユーザーフィルター
+ */
+ public record Snapshot(List keywords, List users, long revision) {
+ public Snapshot(List keywords, List users) { this(keywords, users, 0); }
+ public static Snapshot from(ChatFilterEntityStore.Snapshot snapshot) {
+ return new Snapshot(snapshot.keywords(), snapshot.users(), snapshot.revision());
+ }
+ public Snapshot {
+ keywords = List.copyOf(keywords);
+ users = List.copyOf(users);
+ }
+ }
+
+ private final ChatFilterEntityStore store;
+ private final Executor executor;
+ private final Consumer> shutdownAwaiter;
+ private final Consumer failures;
+ private final Object writesLock = new Object();
+ private final Set pendingWrites = new HashSet<>();
+ private long appliedRevision = -1;
+ private long session;
private final ObservableList keywordEntries = FXCollections.observableArrayList();
private final ObservableList userEntries = FXCollections.observableArrayList();
private final Predicate filter;
- public ChatFilters(ChatKeywordFilterEntityService keywordService, ChatUserFilterEntityService userService) {
- this.keywordService = keywordService;
- this.userService = userService;
+ private static final class Write {
+ final CompletableFuture settled = new CompletableFuture<>();
+ Throwable failure;
+ boolean ioFinished;
+ boolean errorObserved;
+ boolean retired;
+ }
+
+ /**
+ * 実行前に保存の終了をshutdownAwaiterへ登録する。executorは借用する。
+ * 返すTaskの取消で受付済みの書き込みを取り消さず、終了時は未通知の保存失敗を回収する。
+ */
+ public ChatFilters(ChatFilterEntityStore store, Executor executor, Consumer> shutdownAwaiter,
+ Consumer failures) {
+ this.store = java.util.Objects.requireNonNull(store);
+ this.executor = java.util.Objects.requireNonNull(executor);
+ this.shutdownAwaiter = java.util.Objects.requireNonNull(shutdownAwaiter);
+ this.failures = java.util.Objects.requireNonNull(failures);
filter = new KeywordFilter(keywordEntries).or(new UserFilter(userEntries));
}
@@ -58,59 +105,140 @@ public ObservableList getUserEntries() {
return userEntries;
}
- public void loadAll() {
- var ke = keywordService.retrieveAll().stream().map(this::fromKeywordEntity).toList();
- keywordEntries.setAll(ke);
+ /** UI 状態を変更せず永続化データを読み込む。バックグラウンドから呼び出せる。 */
+ public Snapshot readSnapshot() {
+ return Snapshot.from(store.read());
+ }
+
+ /**
+ * 読み込み結果から UI の項目を作成し、両一覧を置き換える。変換失敗時はいずれの一覧も変更しない。
+ * @param snapshot 読み込み済みのデータ
+ * @throws IllegalStateException FX スレッド以外から呼び出した場合
+ */
+ public void applySnapshot(Snapshot snapshot) {
+ if (!Platform.isFxApplicationThread()) throw new IllegalStateException("use the FX application thread");
+ if (isClosed() || snapshot.revision() < appliedRevision) return;
+ var owner = session;
+ var ke = snapshot.keywords().stream().map(this::fromKeywordEntity).toList();
- var ue = userService.retrieveAll()
+ var ue = snapshot.users()
.stream()
.map(u -> new UserFilterEntry(u.userId(), u.userName(), u.comment()))
.toList();
+ appliedRevision = snapshot.revision();
+ keywordEntries.setAll(ke);
+ if (isClosed() || session != owner || snapshot.revision() != appliedRevision) return;
userEntries.setAll(ue);
}
- public void saveUserFilter(UserFilterEntry entry) {
- FXTask.task(() -> userService.save(toUserEntity(entry))).onDone(e -> {
- if (userEntries.stream().noneMatch(e2 -> e2.getUserId().equals(entry.getUserId()))) {
- userEntries.add(entry);
- }
- }).runAsync();
+ /** 保存後の全体像を反映してから、既存メッセージにもフィルターを適用する。 */
+ public void applyCommittedSnapshot(ChatFilterEntityStore.Snapshot saved) {
+ if (!Platform.isFxApplicationThread()) throw new IllegalStateException("use the FX application thread");
+ if (isClosed() || saved.revision() < appliedRevision) return;
+ var owner = session;
+ applySnapshot(Snapshot.from(saved));
+ // 通知中に一覧が再入変更されても、列挙を壊さない。
+ for (var entry : List.copyOf(keywordEntries)) {
+ if (isClosed() || session != owner || saved.revision() != appliedRevision) return;
+ publish(new KeywordFilteringEvent(entry));
+ }
+ for (var entry : List.copyOf(userEntries)) {
+ if (isClosed() || session != owner || saved.revision() != appliedRevision) return;
+ publish(new UserFilteringEvent(entry));
+ }
}
- public FXTask deleteUserFilter(UserFilterEntry entry) {
- return FXTask.task(() -> userService.delete(toUserEntity(entry)))
- .onDone(entity -> userEntries.remove(entry))
- .runAsync();
+ /** 現在のセッションで受け付けた保存結果だけを反映する FX 用 callback。保存 I/O 自体は取り消さない。 */
+ public Consumer captureCommitHandler() {
+ if (!Platform.isFxApplicationThread()) throw new IllegalStateException("use the FX application thread");
+ var owner = session;
+ return saved -> { if (!isClosed() && session == owner) applyCommittedSnapshot(saved); };
}
- private ChatUserFilterEntity toUserEntity(UserFilterEntry entry) {
- return new ChatUserFilterEntity(entry.getUserId(), entry.getUserName(), entry.getComment());
+ public FXTask saveUserFilter(UserFilterEntry entry) {
+ var row = new ChatUserFilterEntity(entry.getUserId(), entry.getUserName(), entry.getComment());
+ return submit(new ChatFilterEntityStore.Changes(List.of(), Set.of(), List.of(row), Set.of()));
}
- public void saveKeywordFilter(KeywordFilterEntry entry) {
- if (entry.getFilterId() < 1) {
- var t = FXTask.task(() -> keywordService.insert(toKeywordEntity(entry)));
- t.onDone(id -> {
- entry.setFilterId(id);
- keywordEntries.add(entry);
- }).runAsync();
- } else {
- FXTask.task(() -> keywordService.update(toKeywordEntity(entry))).runAsync();
- }
+ public FXTask deleteUserFilter(UserFilterEntry entry) {
+ return submit(new ChatFilterEntityStore.Changes(List.of(), Set.of(), List.of(), Set.of(entry.getUserId())));
+ }
+
+ public FXTask saveKeywordFilter(KeywordFilterEntry entry) {
+ var row = new ChatKeywordFilterEntity(Math.max(0, entry.getFilterId()), entry.getFilterType().getType(), entry.getKeyword());
+ return submit(new ChatFilterEntityStore.Changes(List.of(row), Set.of(), List.of(), Set.of()));
+ }
+
+ public FXTask deleteKeywordFilter(KeywordFilterEntry entry) {
+ var deleted = entry.getFilterId() > 0 ? Set.of(entry.getFilterId()) : Set.of();
+ return submit(new ChatFilterEntityStore.Changes(List.of(), deleted, List.of(), Set.of()));
}
- public FXTask deleteKeywordFilter(KeywordFilterEntry entry) {
- return FXTask.task(() -> keywordService.delete(toKeywordEntity(entry)))
- .onDone(entity -> keywordEntries.remove(entry))
- .runAsync();
+ private FXTask submit(ChatFilterEntityStore.Changes changes) {
+ if (!Platform.isFxApplicationThread()) throw new IllegalStateException("use the FX application thread");
+ if (isClosed()) throw new IllegalStateException("chat filters are closed");
+ var owner = session;
+ var write = new Write();
+ synchronized (writesLock) { pendingWrites.add(write); }
+ var task = FXTask.task(() -> {
+ try { return store.save(changes, () -> {}); }
+ catch (RuntimeException | Error failure) {
+ synchronized (writesLock) { write.failure = failure; }
+ throw failure;
+ } finally {
+ synchronized (writesLock) {
+ write.ioFinished = true;
+ settle(write);
+ }
+ }
+ });
+ var applicationFailure = new AtomicReference();
+ var observation = FXTask.observation(() -> {
+ var failure = applicationFailure.get();
+ if (failure == null) failure = task.getException();
+ if (failure instanceof Exception exception) throw exception;
+ if (failure instanceof Error error) throw error;
+ return task.getValue();
+ });
+ var committed = captureCommitHandler();
+ task.onDone(saved -> {
+ try { committed.accept(saved); }
+ catch (RuntimeException | Error failure) {
+ applicationFailure.set(failure);
+ failures.accept(failure);
+ }
+ finally { observation.run(); }
+ });
+ task.onFailure(failure -> {
+ var visible = !isClosed() && session == owner;
+ synchronized (writesLock) {
+ if (visible) write.errorObserved = true;
+ settle(write);
+ }
+ try { if (visible) failures.accept(failure); }
+ finally { observation.run(); }
+ });
+ try {
+ shutdownAwaiter.accept(write.settled.minimalCompletionStage());
+ executor.execute(task);
+ } catch (RuntimeException | Error failure) {
+ synchronized (writesLock) {
+ write.ioFinished = true;
+ settle(write);
+ }
+ task.cancel();
+ observation.cancel();
+ throw failure;
+ }
+ return observation;
}
- private ChatKeywordFilterEntity toKeywordEntity(KeywordFilterEntry entry) {
- return new ChatKeywordFilterEntity(
- entry.getFilterId(),
- entry.getFilterType().getType(),
- entry.getKeyword()
- );
+ /** writesLock内で呼び、開いた画面が扱った失敗を終了時に再送出しない。 */
+ private void settle(Write write) {
+ if (!write.ioFinished) return;
+ if (write.failure == null || write.errorObserved) write.settled.complete(null);
+ else if (isClosed() || write.retired) write.settled.completeExceptionally(write.failure);
+ if (write.settled.isDone()) pendingWrites.remove(write);
}
private KeywordFilterEntry fromKeywordEntity(ChatKeywordFilterEntity entity) {
@@ -127,17 +255,24 @@ private KeywordFilterEntry fromKeywordEntity(ChatKeywordFilterEntity entity) {
}
@Override
- public void subscribeEvents(EventSubscribers eventSubscribers) {
- // no-op
- }
-
- @Override
- public void onLogout() {
+ protected void onLoggedOut() {
+ session++;
+ synchronized (writesLock) {
+ for (var write : List.copyOf(pendingWrites)) {
+ write.retired = true;
+ settle(write);
+ }
+ }
keywordEntries.clear();
userEntries.clear();
}
@Override
- public void close() {
+ protected void onClose() {
+ synchronized (writesLock) {
+ for (var write : List.copyOf(pendingWrites)) settle(write);
+ }
+ keywordEntries.clear();
+ userEntries.clear();
}
}
diff --git a/src/main/java/com/github/k7t3/tcv/app/chat/filter/KeywordFilterEntry.java b/src/main/java/com/github/k7t3/tcv/app/chat/filter/KeywordFilterEntry.java
index 6f91e44..0ea951b 100644
--- a/src/main/java/com/github/k7t3/tcv/app/chat/filter/KeywordFilterEntry.java
+++ b/src/main/java/com/github/k7t3/tcv/app/chat/filter/KeywordFilterEntry.java
@@ -48,8 +48,13 @@ public static KeywordFilterEntry exactMatch(String keyword) {
return new KeywordFilterEntry(KeywordFilterType.EXACT_MATCH, keyword, null);
}
+ /**
+ * 正規表現のフィルターを作成する。編集・保存用の文字列として元の式も保持する。
+ * @param pattern コンパイル済みの正規表現
+ * @return 正規表現のフィルター
+ */
public static KeywordFilterEntry regexMatch(Pattern pattern) {
- return new KeywordFilterEntry(KeywordFilterType.REGEXP, null, pattern);
+ return new KeywordFilterEntry(KeywordFilterType.REGEXP, pattern.pattern(), pattern);
}
private boolean startsWith(String message) {
diff --git a/src/main/java/com/github/k7t3/tcv/app/clip/ClipThumbnailStore.java b/src/main/java/com/github/k7t3/tcv/app/clip/ClipThumbnailStore.java
index e936a44..f6e2472 100644
--- a/src/main/java/com/github/k7t3/tcv/app/clip/ClipThumbnailStore.java
+++ b/src/main/java/com/github/k7t3/tcv/app/clip/ClipThumbnailStore.java
@@ -17,6 +17,7 @@
package com.github.k7t3.tcv.app.clip;
import com.github.k7t3.tcv.app.image.LazyImage;
+import com.github.k7t3.tcv.app.image.ImageLoader;
import com.github.k7t3.tcv.app.service.CachedImageStore;
import org.jetbrains.annotations.Nullable;
@@ -26,16 +27,18 @@ public class ClipThumbnailStore extends CachedImageStore {
private static final double THUMBNAIL_WIDTH = 128;
private static final double THUMBNAIL_HEIGHT = 128;
+ private final ImageLoader images;
- public ClipThumbnailStore() {
+ public ClipThumbnailStore(ImageLoader images) {
super(128, Duration.ofMinutes(5));
+ this.images = images;
}
@Override
protected @Nullable LazyImage loadImage(PostedClipItem key) {
var link = key.getThumbnailLink();
if (link == null) return null;
- return new LazyImage(link, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);
+ return images.load(link, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);
}
}
diff --git a/src/main/java/com/github/k7t3/tcv/app/clip/PostedClipItem.java b/src/main/java/com/github/k7t3/tcv/app/clip/PostedClipItem.java
index 84711c5..460aa7d 100644
--- a/src/main/java/com/github/k7t3/tcv/app/clip/PostedClipItem.java
+++ b/src/main/java/com/github/k7t3/tcv/app/clip/PostedClipItem.java
@@ -16,13 +16,10 @@
package com.github.k7t3.tcv.app.clip;
-import com.github.k7t3.tcv.app.core.AppHelper;
import com.github.k7t3.tcv.app.core.DesktopUtils;
import com.github.k7t3.tcv.app.image.LazyImage;
import com.github.k7t3.tcv.app.service.FXTask;
import com.github.k7t3.tcv.domain.channel.Broadcaster;
-import com.github.k7t3.tcv.domain.chat.ClipChatMessage;
-import com.github.k7t3.tcv.domain.chat.ClipFinder;
import com.github.k7t3.tcv.domain.clip.VideoClip;
import javafx.beans.property.ReadOnlyIntegerProperty;
import javafx.beans.property.ReadOnlyIntegerWrapper;
@@ -48,10 +45,13 @@ public class PostedClipItem {
private ReadOnlyObjectWrapper clip;
private final PostedClipRepository repository;
+ private final long scope;
+ private boolean retired;
public PostedClipItem(PostedClipRepository repository, String id, String url, VideoClip clip) {
if (!url.startsWith("https")) throw new IllegalArgumentException("illegal url: " + url);
this.repository = repository;
+ scope = repository.scope();
this.id.set(id);
this.url.set(url);
@@ -61,27 +61,15 @@ public PostedClipItem(PostedClipRepository repository, String id, String url, Vi
}
public FXTask> retry() {
- var helper = AppHelper.getInstance();
- var finder = new ClipFinder(helper.getTwitch());
- var url = getUrl();
-
- var task = FXTask.task(() -> finder.findClip(url).flatMap(ClipChatMessage::getClip).orElse(null));
- return task.onDone(c -> {
- if (c != null) {
- clip().set(c);
- }
- }).runAsync();
+ return repository.retry(this);
}
public void remove() {
- repository.getItems().remove(getId());
+ repository.remove(this);
}
public FXTask> browseClipPageAsync() {
- return FXTask.task(() -> {
- DesktopUtils.browse(getUrl());
- return null;
- }).runAsync();
+ return repository.browse(this);
}
public void copyClipURL() {
@@ -89,15 +77,20 @@ public void copyClipURL() {
}
public LazyImage getThumbnailImage() {
- return repository.getThumbnailStore().get(this);
+ return repository.getThumbnailImage(this);
}
public void onPosted(Broadcaster broadcaster) {
+ if (!repository.isActive(this)) return;
postedChannels.add(broadcaster);
lastPostedAt.set(LocalDateTime.now());
- times.set(times.get() + 1);
+ if (repository.isActive(this)) times.set(times.get() + 1);
}
+ long scope() { return scope; }
+ boolean isRetired() { return retired; }
+ void retire() { retired = true; }
+
public boolean isPosted(Broadcaster broadcaster) {
return postedChannels.contains(broadcaster);
}
@@ -121,7 +114,7 @@ private ReadOnlyObjectWrapper clip() {
}
public ReadOnlyObjectProperty clipProperty() { return clip().getReadOnlyProperty(); }
public VideoClip getClip() { return clip == null ? null : clip.get(); }
- private void setClip(VideoClip clip) { clip().set(clip); }
+ void setClip(VideoClip clip) { clip().set(clip); }
public ObservableValue observableThumbnailLink() { return clip().map(VideoClip::thumbnailUrl); }
String getThumbnailLink() { return observableThumbnailLink().getValue(); }
diff --git a/src/main/java/com/github/k7t3/tcv/app/clip/PostedClipRepository.java b/src/main/java/com/github/k7t3/tcv/app/clip/PostedClipRepository.java
index d0fe2fc..d9c9a59 100644
--- a/src/main/java/com/github/k7t3/tcv/app/clip/PostedClipRepository.java
+++ b/src/main/java/com/github/k7t3/tcv/app/clip/PostedClipRepository.java
@@ -16,96 +16,276 @@
package com.github.k7t3.tcv.app.clip;
-import com.github.k7t3.tcv.app.model.AbstractViewModel;
+import com.github.k7t3.tcv.app.service.BrowserActions;
import com.github.k7t3.tcv.app.event.ClipPostedAppEvent;
+import com.github.k7t3.tcv.app.image.ImageLoader;
+import com.github.k7t3.tcv.app.image.LazyImage;
+import com.github.k7t3.tcv.app.model.AbstractViewModel;
import com.github.k7t3.tcv.app.reactive.DownCastFXSubscriber;
+import com.github.k7t3.tcv.app.service.CachedImageStore;
+import com.github.k7t3.tcv.app.service.FXTask;
+import com.github.k7t3.tcv.domain.Twitch;
import com.github.k7t3.tcv.domain.channel.Broadcaster;
+import com.github.k7t3.tcv.domain.chat.ClipChatMessage;
+import com.github.k7t3.tcv.domain.chat.ClipFinder;
+import com.github.k7t3.tcv.domain.clip.VideoClip;
import com.github.k7t3.tcv.domain.event.EventSubscribers;
import com.github.k7t3.tcv.domain.event.chat.ChatRoomEvent;
import com.github.k7t3.tcv.domain.event.chat.ClipPostedEvent;
-import com.github.k7t3.tcv.reactive.FlowableSubscriber;
+import com.github.k7t3.tcv.lifecycle.CloseActions;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.NumberBinding;
import javafx.collections.FXCollections;
import javafx.collections.ObservableMap;
-
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import java.time.Duration;
+import java.util.IdentityHashMap;
import java.util.List;
+import java.util.Objects;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionStage;
+import java.util.concurrent.Executor;
+import java.util.function.BiFunction;
+import java.util.function.Consumer;
+/** 投稿項目と、そのセッションで開始したクリップ照会・画像を所有する。操作・反映は FX スレッドで行う。 */
public class PostedClipRepository extends AbstractViewModel {
-
+ private static final Logger LOGGER = LoggerFactory.getLogger(PostedClipRepository.class);
private final ObservableMap items = FXCollections.observableHashMap();
-
+ private final ObservableMap readOnlyItems = FXCollections.unmodifiableObservableMap(items);
+ private final IdentityHashMap requests = new IdentityHashMap<>();
+ private final ImageLoader images;
+ private final Executor executor;
+ private final BiFunction lookup;
+ private final Consumer> shutdownAwaiter;
+ private final Consumer failures;
+ private final BrowserActions browsers;
private ClipThumbnailStore thumbnailStore;
+ private CachedImageStore broadcasterImages;
+ private Twitch session;
+ private long scope;
+ private boolean imagesAvailable = true;
- private FlowableSubscriber subscriber;
+ public PostedClipRepository(ImageLoader images, Executor executor, Consumer> shutdownAwaiter,
+ Consumer failures) {
+ this(images, executor, (client, url) -> new ClipFinder(client).findClip(url)
+ .flatMap(ClipChatMessage::getClip).orElse(null), shutdownAwaiter, failures);
+ }
+
+ PostedClipRepository(ImageLoader images, Executor executor, BiFunction lookup,
+ Consumer> shutdownAwaiter, Consumer failures) {
+ this.images = Objects.requireNonNull(images);
+ this.executor = Objects.requireNonNull(executor);
+ this.lookup = Objects.requireNonNull(lookup);
+ this.shutdownAwaiter = Objects.requireNonNull(shutdownAwaiter);
+ this.failures = Objects.requireNonNull(failures);
+ browsers = new BrowserActions(executor, shutdownAwaiter, failures);
+ }
- public PostedClipRepository() {
+ public void setSession(Twitch twitch) {
+ if (isClosed()) throw new IllegalStateException("clip repository is closed");
+ Objects.requireNonNull(twitch);
+ if (session == twitch) return;
+ onLogout();
+ session = twitch;
+ imagesAvailable = true;
}
@Override
- public void subscribeEvents(EventSubscribers eventSubscribers) {
- subscriber = new DownCastFXSubscriber<>(ClipPostedEvent.class, this::onClipPostedEvent);
+ protected void onSubscribeEvents(EventSubscribers eventSubscribers, SessionSubscriptions subscriptions) {
+ var subscriber = subscriptions.own(new DownCastFXSubscriber(ClipPostedEvent.class, this::onClipPostedEvent));
eventSubscribers.subscribeChatEvent(subscriber);
}
- private void onClipPostedEvent(ClipPostedEvent e) {
- var chatRoom = e.getChatRoom();
- var broadcaster = chatRoom.getBroadcaster();
- var clipChatMessage = e.getClipChatMessage();
-
- var id = clipChatMessage.getId();
- var url = clipChatMessage.getEstimatedURL();
- var clip = clipChatMessage.getClip().orElse(null);
-
- var item = items.get(id);
+ private void onClipPostedEvent(ClipPostedEvent event) {
+ if (isClosed() || !imagesAvailable) return;
+ if (session != null && !event.getChatRoom().isOwnedBy(session)) return;
+ var message = event.getClipChatMessage();
+ var item = items.get(message.getId());
+ boolean created = item == null;
if (item == null) {
- item = new PostedClipItem(this, id, url, clip);
- item.onPosted(broadcaster);
- items.put(id, item);
+ item = new PostedClipItem(this, message.getId(), message.getEstimatedURL(), message.getClip().orElse(null));
+ item.onPosted(event.getChatRoom().getBroadcaster());
+ items.put(item.getId(), item);
} else {
- item.onPosted(broadcaster);
+ item.onPosted(event.getChatRoom().getBroadcaster());
+ if (message.getClip().isPresent() && isActive(item) && items.get(item.getId()) == item) {
+ var previous = requests.remove(item);
+ if (previous != null) previous.result.cancel(true);
+ invalidateThumbnail(item);
+ if (isActive(item) && items.get(item.getId()) == item) item.setClip(message.getClip().orElseThrow());
+ }
+ }
+ if (created && message.getClip().isEmpty() && session != null && isActive(item) && items.get(item.getId()) == item) {
+ lookup(item, false);
}
+ if (!isClosed() && imagesAvailable) publish(new ClipPostedAppEvent());
+ }
- publishEvent();
+ public ObservableMap getItems() { return readOnlyItems; }
+ public NumberBinding getCountBinding() { return Bindings.size(items); }
+
+ public List getPostedBroadcasters() {
+ return items.values().stream().flatMap(item -> item.getPostedChannels().stream()).distinct().toList();
}
- private void publishEvent() {
- publish(new ClipPostedAppEvent());
+ long scope() { return scope; }
+
+ boolean isActive(PostedClipItem item) {
+ return !isClosed() && imagesAvailable && !item.isRetired() && item.scope() == scope;
}
- public ObservableMap getItems() {
- return items;
+ private void requireActive(PostedClipItem item) {
+ if (!isActive(item)) throw new IllegalStateException("clip item is no longer active");
}
- public NumberBinding getCountBinding() {
- return Bindings.size(items);
+ private void requireOwned(PostedClipItem item) {
+ requireActive(item);
+ if (items.get(item.getId()) != item) throw new IllegalStateException("clip item is no longer owned");
}
- public List getPostedBroadcasters() {
- return items.values()
- .stream()
- .flatMap(p -> p.getPostedChannels().stream())
- .distinct()
- .toList();
+ FXTask retry(PostedClipItem item) {
+ return lookup(item, true);
}
- ClipThumbnailStore getThumbnailStore() {
- if (thumbnailStore == null) {
- thumbnailStore = new ClipThumbnailStore();
+ private FXTask lookup(PostedClipItem item, boolean notifyFailure) {
+ requireOwned(item);
+ if (session == null) throw new IllegalStateException("clip session is not available");
+ var previous = requests.get(item);
+ if (previous != null && !previous.result.isDone()) {
+ previous.notifyFailure |= notifyFailure;
+ return previous.result;
}
- return thumbnailStore;
+ var request = new Request(item, notifyFailure);
+ requests.put(item, request);
+ request.worker.cancelWhenCancelled(request.result);
+ request.result.cancelWhenCancelled(request.worker);
+ request.result.onFailure(failure -> {
+ if (!isCurrent(request)) return;
+ if (request.notifyFailure) failures.accept(failure);
+ else LOGGER.warn("clip lookup failed for {}", request.url, failure);
+ });
+ request.result.setFinally(() -> {
+ requests.remove(item, request);
+ request.worker.cancel(true);
+ });
+ request.worker.onDone(value -> { request.value = value; request.result.run(); });
+ request.worker.onFailure(failure -> { request.failure = failure; request.result.run(); });
+ try {
+ shutdownAwaiter.accept(request.drained.minimalCompletionStage());
+ executor.execute(() -> {
+ try { request.worker.run(); }
+ finally { request.drained.complete(null); }
+ });
+ } catch (RuntimeException | Error failure) {
+ request.failure = failure;
+ request.result.run();
+ request.worker.cancel(true);
+ request.drained.complete(null);
+ }
+ return request.result;
}
- @Override
- public void onLogout() {
- if (subscriber != null) {
- subscriber.cancel();
+ private boolean isCurrent(Request request) {
+ return isActive(request.item) && items.get(request.item.getId()) == request.item
+ && requests.get(request.item) == request && session == request.owner
+ && !request.result.isCancelled();
+ }
+
+ private final class Request {
+ final PostedClipItem item;
+ final Twitch owner = session;
+ final String url;
+ final CompletableFuture drained = new CompletableFuture<>();
+ final FXTask worker;
+ final FXTask result;
+ VideoClip value;
+ Throwable failure;
+ boolean notifyFailure;
+
+ Request(PostedClipItem item, boolean notifyFailure) {
+ this.item = item;
+ this.notifyFailure = notifyFailure;
+ url = item.getUrl();
+ worker = FXTask.task(() -> lookup.apply(owner, url));
+ result = FXTask.observation(() -> {
+ if (!isCurrent(this)) throw new CancellationException("clip lookup is no longer owned");
+ if (failure instanceof Error error) throw error;
+ if (failure instanceof Exception exception) throw exception;
+ if (value != null) {
+ invalidateThumbnail(item);
+ if (!isCurrent(this)) throw new CancellationException("clip lookup was retired during image release");
+ item.setClip(value);
+ }
+ return value;
+ });
}
- items.clear();
}
- @Override
- public void close() {
- // no-op
+ FXTask browse(PostedClipItem item) {
+ requireOwned(item);
+ return browsers.open(item.getUrl());
+ }
+
+ void remove(PostedClipItem item) {
+ if (items.get(item.getId()) != item) return;
+ item.retire();
+ var request = requests.remove(item);
+ CloseActions.runAll(
+ () -> { if (request != null) request.result.cancel(true); },
+ () -> items.remove(item.getId(), item),
+ () -> invalidateThumbnail(item));
+ }
+
+ private void invalidateThumbnail(PostedClipItem item) {
+ if (thumbnailStore != null) thumbnailStore.invalidate(item);
+ }
+
+ LazyImage getThumbnailImage(PostedClipItem item) {
+ requireActive(item);
+ if (thumbnailStore == null) thumbnailStore = new ClipThumbnailStore(images);
+ return thumbnailStore.get(item);
+ }
+
+ /** 30px の投稿先プロフィール画像。読込はこのリポジトリが所有する。 */
+ public LazyImage getBroadcasterImage(Broadcaster broadcaster) {
+ if (isClosed() || !imagesAvailable) throw new IllegalStateException("clip image scope is closed");
+ if (broadcasterImages == null) {
+ broadcasterImages = new CachedImageStore<>(64, Duration.ofMinutes(5)) {
+ @Override protected LazyImage loadImage(Broadcaster key) {
+ return images.load(key.getProfileImageUrl(), 30, 30);
+ }
+ };
+ }
+ return broadcasterImages.get(broadcaster);
+ }
+
+ @Override protected void onLoggedOut() { endScope(); }
+ @Override protected void onClose() { CloseActions.runAll(this::endScope, browsers::close); }
+
+ private void endScope() {
+ scope++;
+ session = null;
+ imagesAvailable = false;
+ items.values().forEach(PostedClipItem::retire);
+ var pending = List.copyOf(requests.values());
+ requests.clear();
+ CloseActions.runAll(
+ () -> CloseActions.runAll(pending.stream().map(request -> (Runnable) () -> request.result.cancel(true)).toArray(Runnable[]::new)),
+ browsers::cancelAll,
+ items::clear,
+ this::releaseImages);
+ }
+
+ private void releaseImages() {
+ var thumbnails = thumbnailStore;
+ var broadcasters = broadcasterImages;
+ thumbnailStore = null;
+ broadcasterImages = null;
+ CloseActions.runAll(
+ () -> { if (thumbnails != null) thumbnails.close(); },
+ () -> { if (broadcasters != null) broadcasters.close(); });
}
}
diff --git a/src/main/java/com/github/k7t3/tcv/app/core/AppHelper.java b/src/main/java/com/github/k7t3/tcv/app/core/AppHelper.java
index c8c6f24..bec5cf7 100644
--- a/src/main/java/com/github/k7t3/tcv/app/core/AppHelper.java
+++ b/src/main/java/com/github/k7t3/tcv/app/core/AppHelper.java
@@ -16,91 +16,173 @@
package com.github.k7t3.tcv.app.core;
+import com.github.k7t3.tcv.lifecycle.CloseActions;
+import com.github.k7t3.tcv.app.event.SessionInvalidatedEvent;
+import de.saxsys.mvvmfx.MvvmFX;
+import javafx.application.Platform;
+
import com.github.k7t3.tcv.app.chat.filter.ChatFilters;
import com.github.k7t3.tcv.app.group.ChannelGroupRepository;
+import com.github.k7t3.tcv.app.image.ImageLoader;
import com.github.k7t3.tcv.app.keyboard.KeyBindingCombinations;
-import com.github.k7t3.tcv.app.service.FXTask;
import com.github.k7t3.tcv.app.service.TaskWorker;
import com.github.k7t3.tcv.app.service.WindowBoundsService;
import com.github.k7t3.tcv.app.user.UserDataFile;
+import com.github.k7t3.tcv.app.prefs.SettingsSaveService;
+import com.github.k7t3.tcv.prefs.AppPreferences;
import com.github.k7t3.tcv.domain.Twitch;
+import com.github.k7t3.tcv.domain.channel.ChannelRepository;
import com.github.k7t3.tcv.domain.event.EventPublishers;
import com.github.k7t3.tcv.domain.event.EventSubscribers;
import com.github.k7t3.tcv.entity.service.ChannelGroupEntityService;
-import com.github.k7t3.tcv.entity.service.ChatKeywordFilterEntityService;
-import com.github.k7t3.tcv.entity.service.ChatUserFilterEntityService;
+import com.github.k7t3.tcv.entity.service.ChatFilterEntityStore;
+
import com.github.k7t3.tcv.entity.service.WindowBoundsEntityService;
import javafx.beans.property.*;
import javafx.stage.Stage;
import java.io.Closeable;
import java.util.Objects;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.CompletionStage;
+import java.util.concurrent.Executor;
+import java.util.function.Function;
+import java.util.function.Consumer;
public class AppHelper implements Closeable {
-
- private final ReadOnlyStringWrapper userId = new ReadOnlyStringWrapper();
- private final ReadOnlyStringWrapper userName = new ReadOnlyStringWrapper();
- private final ReadOnlyBooleanWrapper authorized = new ReadOnlyBooleanWrapper();
- private final ObjectProperty twitch = new SimpleObjectProperty<>();
-
private ObjectProperty primaryStage;
- private final EventPublishers publishers = new EventPublishers();
- private final EventSubscribers subscribers = new EventSubscribers(publishers);
+ private final EventPublishers publishers;
+ private final EventSubscribers subscribers;
+ private final TaskWorker worker;
+ private final Consumer failureHandler;
private UserDataFile userDataFile;
private ChannelGroupRepository channelGroupRepository;
private WindowBoundsService windowBoundsService;
private KeyBindingCombinations keyBindingCombinations;
+ private ChatFilterEntityStore chatFilterStore;
private ChatFilters chatFilters;
+ private final List> lifetimeReleases = new ArrayList<>();
+ private final List lifetimeReleaseFailures = new ArrayList<>();
+ private final Object lifecycleLock = new Object();
+ private ImageLoader imageLoader;
+ private boolean closed;
+ private boolean preparingShutdown;
+ private boolean uiModelsReleased;
+ private final ClientSessions sessions;
+ private final CompletableFuture applicationClosed = new CompletableFuture<>();
+ private Thread closingThread;
+
+ /** このアプリ専用のワーカーと発行元を新しく所有する。 */
+ public AppHelper(Consumer failureHandler) {
+ this(new TaskWorker(), new EventPublishers(), failureHandler);
+ }
+
+ /** 注入したワーカーと発行元を、このアプリケーションが終了まで所有する。 */
+ public AppHelper(TaskWorker worker, EventPublishers publishers, Consumer failureHandler) {
+ this(worker, publishers, client -> new ChannelRepository(client, publishers), failureHandler);
+ }
+
+ AppHelper(TaskWorker worker, EventPublishers publishers, Function channelFactory,
+ Consumer failureHandler) {
+ this.worker = Objects.requireNonNull(worker);
+ this.publishers = Objects.requireNonNull(publishers);
+ this.failureHandler = Objects.requireNonNull(failureHandler);
+ this.subscribers = new EventSubscribers(publishers);
+ this.sessions = new ClientSessions(command -> worker.getExecutor().execute(command), Platform::runLater,
+ channelFactory, this::publishSessionInvalidated);
+ }
+
+ private void publishSessionInvalidated() {
+ var event = new SessionInvalidatedEvent(sessions);
+ MvvmFX.getNotificationCenter().publish(SessionInvalidatedEvent.class.getName(), event);
+ }
- private AppHelper() {
- userId.bind(twitch.map(Twitch::getUserId));
- userName.bind(twitch.map(Twitch::getUserName));
- authorized.bind(twitch.isNotNull());
+ /** 現在セッションの操作・状態を借用する。終了はアプリ全体の所有者が行う。 */
+ public ClientSessions getClientSessions() {
+ synchronized (lifecycleLock) { checkOpen(); return sessions; }
}
public void setUserDataFile(UserDataFile userDataFile) {
- this.userDataFile = userDataFile;
+ synchronized (lifecycleLock) {
+ checkOpen();
+ Objects.requireNonNull(userDataFile);
+ if (this.userDataFile != null && this.userDataFile != userDataFile) {
+ throw new IllegalStateException("application already owns a user database");
+ }
+ this.userDataFile = userDataFile;
+ }
}
public UserDataFile getUserDataFile() {
- return userDataFile;
+ synchronized (lifecycleLock) { return userDataFile; }
}
public ChannelGroupRepository getChannelGroupRepository() {
- if (channelGroupRepository == null) {
- var userDataFile = getUserDataFile();
- var groupService = new ChannelGroupEntityService(userDataFile.getConnector());
- channelGroupRepository = new ChannelGroupRepository(groupService);
+ synchronized (lifecycleLock) {
+ checkOpen();
+ if (channelGroupRepository == null) {
+ var userDataFile = Objects.requireNonNull(getUserDataFile());
+ var groupService = new ChannelGroupEntityService(userDataFile.getConnector());
+ channelGroupRepository = new ChannelGroupRepository(groupService, worker.getExecutor(), this::awaitOnShutdown,
+ this::reportFailure);
+ channelGroupRepository.setEventSubscribers(subscribers);
+ }
+ return channelGroupRepository;
}
- return channelGroupRepository;
}
public WindowBoundsService getWindowBoundsService() {
- if (windowBoundsService == null) {
- var userDataFile = Objects.requireNonNull(getUserDataFile());
- var entityService = new WindowBoundsEntityService(userDataFile.getConnector());
- windowBoundsService = new WindowBoundsService(entityService);
+ synchronized (lifecycleLock) {
+ checkOpen();
+ if (windowBoundsService == null) {
+ var userDataFile = Objects.requireNonNull(getUserDataFile());
+ var entityService = new WindowBoundsEntityService(userDataFile.getConnector());
+ windowBoundsService = new WindowBoundsService(entityService, worker.getExecutor(), this::awaitOnShutdown);
+ }
+ return windowBoundsService;
}
- return windowBoundsService;
}
public KeyBindingCombinations getKeyBindingCombinations() {
- if (keyBindingCombinations == null) {
- keyBindingCombinations = new KeyBindingCombinations();
+ synchronized (lifecycleLock) {
+ checkOpen();
+ if (keyBindingCombinations == null) keyBindingCombinations = new KeyBindingCombinations();
+ return keyBindingCombinations;
}
- return keyBindingCombinations;
+ }
+
+ public ChatFilterEntityStore getChatFilterStore() {
+ synchronized (lifecycleLock) {
+ checkOpen();
+ if (chatFilterStore == null) chatFilterStore = new ChatFilterEntityStore(Objects.requireNonNull(getUserDataFile()).getConnector());
+ return chatFilterStore;
+ }
+ }
+
+ /** 設定キャッシュを構築する前に、接続済みDBの未完了投影を背景で復旧する。 */
+ public void recoverSettings(AppPreferences preferences) {
+ new SettingsSaveService(preferences, getChatFilterStore()).recover();
}
public ChatFilters getChatFilters() {
- if (chatFilters == null) {
- var userDataFile = Objects.requireNonNull(getUserDataFile());
- var a = new ChatKeywordFilterEntityService(userDataFile.getConnector());
- var b = new ChatUserFilterEntityService(userDataFile.getConnector());
- chatFilters = new ChatFilters(a, b);
+ synchronized (lifecycleLock) {
+ checkOpen();
+ if (chatFilters == null) {
+ chatFilters = new ChatFilters(getChatFilterStore(), worker.getExecutor(), this::awaitOnShutdown,
+ this::reportFailure);
+ chatFilters.setEventSubscribers(subscribers);
+ }
+ return chatFilters;
}
- return chatFilters;
+ }
+
+ private void reportFailure(Throwable failure) {
+ failureHandler.accept(failure);
}
public EventPublishers getPublishers() {
@@ -111,58 +193,157 @@ public EventSubscribers getSubscribers() {
return subscribers;
}
- public FXTask logoutAsync() {
- if (!isAuthorized()) return FXTask.empty();
-
- final var twitch = getTwitch();
- setTwitch(null);
+ /**
+ * アプリが所有する共有画像サービスを借用する。終了は AppHelper が行う。
+ * @return 共有画像サービス
+ * @throws IllegalStateException アプリが終了している場合
+ */
+ public ImageLoader getImageLoader() {
+ synchronized (lifecycleLock) {
+ checkOpen();
+ if (imageLoader == null) imageLoader = new ImageLoader(worker.getExecutor());
+ return imageLoader;
+ }
+ }
- var task = FXTask.task(twitch::logout);
- task.runAsync();
- return task;
+ public ChannelRepository getChannelRepository() {
+ synchronized (lifecycleLock) {
+ checkOpen();
+ return sessions.getChannelRepository();
+ }
}
- @Override
- public void close() {
- if (userDataFile != null) {
- userDataFile.closeDatabase();
+ public Executor getExecutor() {
+ synchronized (lifecycleLock) {
+ checkOpen();
+ return worker.getExecutor();
}
+ }
- var twitch = getTwitch();
- if (twitch != null) {
- twitch.close();
+ /** UI が開始前から所有する非同期解放を登録し、アプリ終了時に完了と失敗を回収する。 */
+ public void awaitOnShutdown(CompletionStage release) {
+ Objects.requireNonNull(release);
+ synchronized (lifecycleLock) {
+ checkOpen();
+ if (lifetimeReleases.contains(release)) return;
+ lifetimeReleases.add(release);
+ release.whenComplete((ignored, failure) -> {
+ synchronized (lifecycleLock) {
+ lifetimeReleases.remove(release);
+ if (failure != null) lifetimeReleaseFailures.add(unwrap(failure));
+ }
+ });
}
+ }
- var publishers = getPublishers();
- publishers.close();
+ public CompletionStage logoutAsync() {
+ return logoutAsync(() -> {});
+ }
- var worker = TaskWorker.getInstance();
- worker.close();
+ /** FX 側を切り離してから、捕捉した同じセッションを背景で終了する。観測の取消は解放に作用しない。 */
+ public CompletionStage logoutAsync(Runnable detachViews) {
+ synchronized (lifecycleLock) { checkOpen(); }
+ return sessions.logoutAsync(detachViews);
}
- public static AppHelper getInstance() {
- return Holder.INSTANCE;
+ /** FX 側の参照・購読を閉じ、新しいサービス取得を止める。UI 所有者が close の前に呼ぶ。 */
+ public void prepareShutdown() {
+ final ChannelGroupRepository groups;
+ final ChatFilters filters;
+ final WindowBoundsService bounds;
+ synchronized (lifecycleLock) {
+ preparingShutdown = true;
+ if (uiModelsReleased) return;
+ uiModelsReleased = true;
+ sessions.stopAccepting();
+ groups = channelGroupRepository;
+ filters = chatFilters;
+ bounds = windowBoundsService;
+ }
+ CloseActions.runAll(sessions::freezeCredentials, sessions::detachViews, () -> { if (groups != null) groups.close(); },
+ () -> { if (filters != null) filters.close(); }, () -> { if (bounds != null) bounds.close(); });
}
- private static class Holder {
- private static final AppHelper INSTANCE = new AppHelper();
+ @Override
+ public void close() {
+ final ImageLoader images;
+ final List> releases;
+ final List releaseFailures;
+ final boolean owner;
+ synchronized (lifecycleLock) {
+ if (closingThread == Thread.currentThread()) return;
+ owner = !closed;
+ if (owner) {
+ closed = true;
+ closingThread = Thread.currentThread();
+ sessions.stopAccepting();
+ }
+ images = imageLoader;
+ releases = List.copyOf(lifetimeReleases);
+ releaseFailures = List.copyOf(lifetimeReleaseFailures);
+ }
+ if (!owner) {
+ try { applicationClosed.join(); }
+ catch (CompletionException failure) { rethrow(unwrap(failure)); }
+ return;
+ }
+ try {
+ CloseActions.runAll(
+ this::prepareShutdown,
+ () -> { if (images != null) images.close(); },
+ worker::close,
+ () -> CloseActions.runAll(releases.stream().map(release -> (Runnable) () -> {
+ try { release.toCompletableFuture().join(); }
+ catch (CompletionException failure) { rethrow(unwrap(failure)); }
+ }).toArray(Runnable[]::new)),
+ () -> CloseActions.runAll(releaseFailures.stream().map(failure -> (Runnable) () -> rethrow(failure)).toArray(Runnable[]::new)),
+ sessions::close,
+ publishers::close,
+ () -> { if (userDataFile != null) userDataFile.closeDatabase(); }
+ );
+ applicationClosed.complete(null);
+ } catch (RuntimeException | Error failure) {
+ applicationClosed.completeExceptionally(failure);
+ throw failure;
+ } finally {
+ synchronized (lifecycleLock) { closingThread = null; }
+ }
}
+
// ########################################
// PROPERTIES
- public ReadOnlyStringProperty userIdProperty() { return userId.getReadOnlyProperty(); }
- public String getUserId() { return userId.get(); }
+ public ReadOnlyStringProperty userIdProperty() { return sessions.userIdProperty(); }
+ public String getUserId() { return sessions.getUserId(); }
+
+ public ReadOnlyStringProperty userNameProperty() { return sessions.userNameProperty(); }
+ public String getUserName() { return sessions.getUserName(); }
+
+ public ReadOnlyBooleanProperty authorizedProperty() { return sessions.authorizedProperty(); }
+ public boolean isAuthorized() { return sessions.isAuthorized(); }
- public ReadOnlyStringProperty userNameProperty() { return userName.getReadOnlyProperty(); }
- public String getUserName() { return userName.get(); }
+ public ReadOnlyObjectProperty twitchProperty() { return sessions.twitchProperty(); }
+ public Twitch getTwitch() { return sessions.getTwitch(); }
+ public void setTwitch(Twitch client) {
+ synchronized (lifecycleLock) { checkOpen(); }
+ sessions.adopt(client);
+ }
- public ReadOnlyBooleanProperty authorizedProperty() { return authorized.getReadOnlyProperty(); }
- public boolean isAuthorized() { return authorized.get(); }
+ private void checkOpen() {
+ if (closed || preparingShutdown) throw new IllegalStateException("application is closed");
+ }
- public ObjectProperty twitchProperty() { return twitch; }
- public Twitch getTwitch() { return twitch.get(); }
- public void setTwitch(Twitch twitch) { this.twitch.set(twitch); }
+ private static Throwable unwrap(Throwable failure) {
+ while (failure instanceof CompletionException && failure.getCause() != null) failure = failure.getCause();
+ return failure;
+ }
+
+ private static void rethrow(Throwable failure) {
+ if (failure instanceof RuntimeException exception) throw exception;
+ if (failure instanceof Error error) throw error;
+ throw new IllegalStateException(failure);
+ }
public ObjectProperty primaryStageProperty() {
if (primaryStage == null) primaryStage = new SimpleObjectProperty<>();
diff --git a/src/main/java/com/github/k7t3/tcv/app/core/ClientSession.java b/src/main/java/com/github/k7t3/tcv/app/core/ClientSession.java
new file mode 100644
index 0000000..206d70d
--- /dev/null
+++ b/src/main/java/com/github/k7t3/tcv/app/core/ClientSession.java
@@ -0,0 +1,93 @@
+package com.github.k7t3.tcv.app.core;
+
+import com.github.k7t3.tcv.domain.Twitch;
+import com.github.k7t3.tcv.domain.channel.ChannelRepository;
+import com.github.k7t3.tcv.lifecycle.CloseActions;
+
+import java.util.Objects;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.CompletionStage;
+
+/** 一回のログインで作成したドメインと SDK クライアントを、終了完了まで所有する。 */
+final class ClientSession implements AutoCloseable {
+ private final Twitch twitch;
+ private final ChannelRepository channels;
+ private final Object lifecycleLock = new Object();
+ private final CompletableFuture completed = new CompletableFuture<>();
+ private final CompletionStage result = completed.minimalCompletionStage();
+ private boolean logoutRequested;
+ private boolean started;
+ private Thread closingThread;
+ private CompletionStage beforeEnd = CompletableFuture.completedFuture(null);
+
+ ClientSession(Twitch twitch, ChannelRepository channels) {
+ this.twitch = Objects.requireNonNull(twitch);
+ this.channels = Objects.requireNonNull(channels);
+ }
+
+ Twitch twitch() { return twitch; }
+ ChannelRepository channels() { return channels; }
+ CompletionStage completion() { return result; }
+
+ void requestLogout() {
+ requestLogout(CompletableFuture.completedFuture(null));
+ }
+
+ void requestLogout(CompletionStage detached) {
+ synchronized (lifecycleLock) {
+ if (started) throw new IllegalStateException("session is already ending");
+ logoutRequested = true;
+ beforeEnd = Objects.requireNonNull(detached);
+ twitch.freezeCredentials();
+ }
+ }
+
+ void requestClose(CompletionStage detached) {
+ synchronized (lifecycleLock) {
+ if (started) throw new IllegalStateException("session is already ending");
+ beforeEnd = Objects.requireNonNull(detached);
+ twitch.freezeCredentials();
+ }
+ }
+
+ @Override
+ public void close() {
+ final boolean owner;
+ final boolean logout;
+ final CompletionStage prerequisite;
+ synchronized (lifecycleLock) {
+ if (closingThread == Thread.currentThread()) return;
+ owner = !started;
+ if (owner) {
+ started = true;
+ closingThread = Thread.currentThread();
+ }
+ logout = logoutRequested;
+ prerequisite = beforeEnd;
+ }
+ if (!owner) {
+ try { completed.join(); }
+ catch (CompletionException failure) { rethrow(failure.getCause()); }
+ return;
+ }
+ try {
+ CloseActions.runAll(twitch::freezeCredentials, () -> {
+ try { prerequisite.toCompletableFuture().join(); }
+ catch (CompletionException failure) { rethrow(failure.getCause()); }
+ }, channels::clear, logout ? twitch::logout : twitch::close);
+ completed.complete(null);
+ } catch (RuntimeException | Error failure) {
+ completed.completeExceptionally(failure);
+ throw failure;
+ } finally {
+ synchronized (lifecycleLock) { closingThread = null; }
+ }
+ }
+
+ private static void rethrow(Throwable failure) {
+ if (failure instanceof RuntimeException exception) throw exception;
+ if (failure instanceof Error error) throw error;
+ throw new IllegalStateException(failure);
+ }
+}
diff --git a/src/main/java/com/github/k7t3/tcv/app/core/ClientSessions.java b/src/main/java/com/github/k7t3/tcv/app/core/ClientSessions.java
new file mode 100644
index 0000000..efecfcb
--- /dev/null
+++ b/src/main/java/com/github/k7t3/tcv/app/core/ClientSessions.java
@@ -0,0 +1,251 @@
+package com.github.k7t3.tcv.app.core;
+
+import com.github.k7t3.tcv.domain.Twitch;
+import com.github.k7t3.tcv.domain.channel.ChannelRepository;
+import com.github.k7t3.tcv.lifecycle.CloseActions;
+import javafx.beans.property.*;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.CompletionStage;
+import java.util.concurrent.Executor;
+import java.util.function.Function;
+
+/**
+ * アプリごとの現在・終了待ちのセッションと、資格情報の再採用制御を所有する。
+ * executorは借用し、停止しない。UIを切り離した後、実I/Oの回収後に背景でcloseする。
+ */
+public final class ClientSessions implements AutoCloseable {
+ private static final Logger LOGGER = LoggerFactory.getLogger(ClientSessions.class);
+ private final Object lifecycleLock = new Object();
+ private final Executor executor;
+ private final Executor ui;
+ private final Function channelFactory;
+ private final Runnable invalidated;
+ private final ReadOnlyStringWrapper userId = new ReadOnlyStringWrapper();
+ private final ReadOnlyStringWrapper userName = new ReadOnlyStringWrapper();
+ private final ReadOnlyBooleanWrapper authorized = new ReadOnlyBooleanWrapper();
+ private final ReadOnlyObjectWrapper twitch = new ReadOnlyObjectWrapper<>();
+ private final Set sessions = new HashSet<>();
+ private final Set revokedTokens = new HashSet<>();
+ private final Set revokingSessions = new HashSet<>();
+ private final List sessionFailures = new ArrayList<>();
+ private final CompletableFuture completed = new CompletableFuture<>();
+ private ClientSession activeSession;
+ private boolean stopping;
+ private boolean closed;
+ private Thread closingThread;
+
+ ClientSessions(Executor executor, Executor ui, Function channelFactory, Runnable invalidated) {
+ this.executor = Objects.requireNonNull(executor);
+ this.ui = Objects.requireNonNull(ui);
+ this.channelFactory = Objects.requireNonNull(channelFactory);
+ this.invalidated = Objects.requireNonNull(invalidated);
+ userId.bind(twitch.map(Twitch::getUserId));
+ userName.bind(twitch.map(Twitch::getUserName));
+ authorized.bind(twitch.isNotNull());
+ }
+
+ /** 現在のセッションのリポジトリを借用する。終了後・未ログインでは取得できない。 */
+ public ChannelRepository getChannelRepository() {
+ synchronized (lifecycleLock) {
+ checkOpen();
+ if (activeSession == null) throw new IllegalStateException("no active client session");
+ return activeSession.channels();
+ }
+ }
+
+ /** FXで画面を切り離した後に背景で解放する。観測の取消は実解放を取り消さない。 */
+ public CompletionStage logoutAsync(Runnable detachViews) {
+ return endSession(null, true, detachViews);
+ }
+
+ private CompletionStage endSession(ClientSession expected, boolean revoke, Runnable detachViews) {
+ final ClientSession session;
+ var detached = new CompletableFuture();
+ Throwable preparationFailure = null;
+ synchronized (lifecycleLock) {
+ if (expected != null && (closed || stopping || activeSession != expected)) return CompletableFuture.completedFuture(null);
+ checkOpen();
+ session = activeSession;
+ if (session != null) {
+ try {
+ CloseActions.runAll(() -> {
+ if (revoke) session.requestLogout(detached);
+ else session.requestClose(detached);
+ }, () -> {
+ revokingSessions.add(session);
+ revokedTokens.addAll(tokens(session.twitch()));
+ });
+ } catch (RuntimeException | Error failure) {
+ preparationFailure = failure;
+ }
+ }
+ activeSession = null;
+ }
+ Throwable detachFailure = null;
+ final var beforeDetach = preparationFailure;
+ try {
+ CloseActions.runAll(() -> { if (beforeDetach != null) rethrow(beforeDetach); },
+ () -> twitch.set(null), detachViews);
+ } catch (RuntimeException | Error failure) {
+ detachFailure = failure;
+ }
+ if (detachFailure == null) detached.complete(null);
+ else detached.completeExceptionally(detachFailure);
+ var result = new CompletableFuture();
+ final var previous = detachFailure;
+ var completion = session == null ? CompletableFuture.completedFuture(null) : session.completion();
+ completion.whenComplete((ignored, failure) -> {
+ var actual = unwrap(failure);
+ if (previous != null) {
+ if (actual != null && actual != previous) previous.addSuppressed(actual);
+ actual = previous;
+ }
+ if (actual == null) result.complete(null);
+ else result.completeExceptionally(actual);
+ });
+ if (session != null) releaseAsync(session);
+ return result.minimalCompletionStage();
+ }
+
+ private void sessionInvalidated(ClientSession session) {
+ ui.execute(() -> endSession(session, false, invalidated));
+ }
+
+ private static Set tokens(Twitch client) {
+ var result = new HashSet<>(client.credentialTokens());
+ var current = client.getAccessToken();
+ if (current != null) result.add(current);
+ return result;
+ }
+
+ private void releaseAsync(ClientSession session) {
+ Runnable release = () -> {
+ try { session.close(); }
+ catch (RuntimeException | Error failure) { LOGGER.error("client session release failed", failure); }
+ };
+ try {
+ executor.execute(release);
+ } catch (RuntimeException | Error rejected) {
+ // sessions が引き続き所有するため、アプリ停止もこの終了完了を回収する。
+ Thread.ofVirtual().name("TCV-Session-End").start(release);
+ }
+ }
+
+ ReadOnlyStringProperty userIdProperty() { return userId.getReadOnlyProperty(); }
+ String getUserId() { return userId.get(); }
+
+ public ReadOnlyStringProperty userNameProperty() { return userName.getReadOnlyProperty(); }
+ String getUserName() { return userName.get(); }
+
+ public ReadOnlyBooleanProperty authorizedProperty() { return authorized.getReadOnlyProperty(); }
+ boolean isAuthorized() { return authorized.get(); }
+
+ ReadOnlyObjectProperty twitchProperty() { return twitch.getReadOnlyProperty(); }
+ public Twitch getTwitch() { return twitch.get(); }
+ /** FX上でクライアントを採用する。終了・失効済みの資格情報は受け付けない。 */
+ public void adopt(Twitch client) {
+ final ClientSession previous;
+ synchronized (lifecycleLock) {
+ checkOpen();
+ if (activeSession != null && activeSession.twitch() == client) return;
+ if (client != null) {
+ var candidate = tokens(client);
+ if (client.isClosed() || client.isClosing() || client.hasInvalidCredentials()
+ || candidate.stream().anyMatch(revokedTokens::contains)
+ || revokingSessions.stream().anyMatch(session -> tokens(session.twitch()).stream().anyMatch(candidate::contains))) {
+ throw new IllegalStateException("client credential belongs to an ended session");
+ }
+ }
+ var next = client == null ? null : new ClientSession(client, channelFactory.apply(client));
+ previous = activeSession;
+ activeSession = next;
+ if (next != null) {
+ sessions.add(next);
+ next.completion().whenComplete((ignored, failure) -> {
+ synchronized (lifecycleLock) {
+ sessions.remove(next);
+ if (revokingSessions.remove(next)) revokedTokens.addAll(tokens(next.twitch()));
+ if (failure != null) sessionFailures.add(unwrap(failure));
+ }
+ });
+ client.onInvalidated(() -> sessionInvalidated(next));
+ }
+ }
+ CloseActions.runAll(() -> twitch.set(client), () -> { if (previous != null) releaseAsync(previous); });
+ }
+
+ /** 新しい採用を止める。状態確定中にクライアント側の処理は呼び出さない。 */
+ void stopAccepting() {
+ synchronized (lifecycleLock) {
+ stopping = true;
+ }
+ }
+
+ /** 停止済みの受付範囲にある全クライアントを試行し、最初の失敗を保持する。 */
+ void freezeCredentials() {
+ final List owned;
+ synchronized (lifecycleLock) { owned = List.copyOf(sessions); }
+ CloseActions.runAll(owned.stream().map(session -> (Runnable) session.twitch()::freezeCredentials).toArray(Runnable[]::new));
+ }
+
+ /** 所有するプロパティの参照をFX側の終了準備で外す。 */
+ void detachViews() { twitch.set(null); }
+
+ @Override
+ public void close() {
+ final List owned;
+ final List failures;
+ final boolean owner;
+ synchronized (lifecycleLock) {
+ if (closingThread == Thread.currentThread()) return;
+ owner = !closed;
+ if (owner) {
+ closed = true;
+ stopping = true;
+ closingThread = Thread.currentThread();
+ }
+ owned = List.copyOf(sessions);
+ failures = List.copyOf(sessionFailures);
+ }
+ if (!owner) {
+ try { completed.join(); }
+ catch (CompletionException failure) { rethrow(unwrap(failure)); }
+ return;
+ }
+ try {
+ CloseActions.runAll(
+ () -> CloseActions.runAll(owned.stream().map(session -> (Runnable) session::close).toArray(Runnable[]::new)),
+ () -> CloseActions.runAll(failures.stream().map(failure -> (Runnable) () -> rethrow(failure)).toArray(Runnable[]::new)));
+ completed.complete(null);
+ } catch (RuntimeException | Error failure) {
+ completed.completeExceptionally(failure);
+ throw failure;
+ } finally {
+ synchronized (lifecycleLock) { closingThread = null; }
+ }
+ }
+
+ private void checkOpen() {
+ if (closed || stopping) throw new IllegalStateException("application is closed");
+ }
+
+ private static Throwable unwrap(Throwable failure) {
+ while (failure instanceof CompletionException && failure.getCause() != null) failure = failure.getCause();
+ return failure;
+ }
+
+ private static void rethrow(Throwable failure) {
+ if (failure instanceof RuntimeException exception) throw exception;
+ if (failure instanceof Error error) throw error;
+ throw new IllegalStateException(failure);
+ }
+}
diff --git a/src/main/java/com/github/k7t3/tcv/app/core/DesktopUtils.java b/src/main/java/com/github/k7t3/tcv/app/core/DesktopUtils.java
index 4bb94ec..c4f2a0d 100644
--- a/src/main/java/com/github/k7t3/tcv/app/core/DesktopUtils.java
+++ b/src/main/java/com/github/k7t3/tcv/app/core/DesktopUtils.java
@@ -19,37 +19,13 @@
import javafx.scene.input.Clipboard;
import javafx.scene.input.DataFormat;
-import java.awt.*;
-import java.io.IOException;
-import java.net.URI;
-import java.net.URISyntaxException;
import java.util.Map;
public class DesktopUtils {
- public static void browse(String url) throws URISyntaxException, IOException {
- var uri = new URI(url);
- C.desktop.browse(uri);
- }
-
- public static void clipText(String text) {
- var cb = Clipboard.getSystemClipboard();
- cb.setContent(Map.of(DataFormat.PLAIN_TEXT, text));
- }
-
public static void clipURL(String url) {
var cb = Clipboard.getSystemClipboard();
cb.setContent(Map.of(DataFormat.URL, url, DataFormat.PLAIN_TEXT, url));
}
- private static class C {
- private static final Desktop desktop;
- static {
- desktop = Desktop.getDesktop();
- if (!desktop.isSupported(Desktop.Action.BROWSE)) {
- throw new RuntimeException("browse action not supported");
- }
- }
- }
-
}
diff --git a/src/main/java/com/github/k7t3/tcv/app/core/ExceptionHandler.java b/src/main/java/com/github/k7t3/tcv/app/core/ExceptionHandler.java
index bacb123..ea22ba0 100644
--- a/src/main/java/com/github/k7t3/tcv/app/core/ExceptionHandler.java
+++ b/src/main/java/com/github/k7t3/tcv/app/core/ExceptionHandler.java
@@ -20,6 +20,8 @@
import javafx.scene.control.Alert;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
+import javafx.stage.WindowEvent;
+import javafx.event.EventHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -34,27 +36,26 @@ public class ExceptionHandler {
private ExceptionHandler() {
}
- public static void handle(Throwable e) {
- handle(null, e);
- }
-
+ /**
+ * 指定された所有者へ表示する。認証失効では、所有関係の最上位Stageを終了する。
+ * 所有者がなければ、別アプリのウインドウを取得・終了しない。
+ */
public static void handle(Stage parent, Throwable e) {
LOGGER.error(e.getMessage(), e);
// 資格情報が無効になったとき
if (e instanceof InvalidCredentialException) {
- var helper = AppHelper.getInstance();
- var primaryStage = helper.getPrimaryStage();
-
+ var application = parent;
+ while (application != null && application.getOwner() instanceof Stage owner) application = owner;
var alert = new Alert(Alert.AlertType.ERROR);
- alert.initOwner(primaryStage);
+ if (application != null) alert.initOwner(application);
alert.setTitle("Twitch API Error");
alert.setHeaderText(Resources.getString("terminate.header"));
alert.setContentText(Resources.getString("terminate.content"));
- alert.showAndWait();
+ showOwned(application, alert);
- primaryStage.close();
+ if (application != null) application.close();
return;
@@ -80,7 +81,21 @@ public static void handle(Stage parent, Throwable e) {
pane.setContent(stacktrace);
pane.setExpanded(false);
- alert.showAndWait();
+ showOwned(parent, alert);
+ }
+
+ private static void showOwned(Stage owner, Alert alert) {
+ if (owner == null) {
+ alert.showAndWait();
+ return;
+ }
+ EventHandler closed = event -> alert.close();
+ owner.addEventHandler(WindowEvent.WINDOW_HIDDEN, closed);
+ try {
+ alert.showAndWait();
+ } finally {
+ owner.removeEventHandler(WindowEvent.WINDOW_HIDDEN, closed);
+ }
}
}
diff --git a/src/main/java/com/github/k7t3/tcv/app/core/LoggerInitializer.java b/src/main/java/com/github/k7t3/tcv/app/core/LoggerInitializer.java
index 8ae754a..fa25825 100644
--- a/src/main/java/com/github/k7t3/tcv/app/core/LoggerInitializer.java
+++ b/src/main/java/com/github/k7t3/tcv/app/core/LoggerInitializer.java
@@ -16,33 +16,151 @@
package com.github.k7t3.tcv.app.core;
+import com.github.k7t3.tcv.lifecycle.CloseActions;
+import java.io.IOException;
import java.io.InputStream;
-import java.util.concurrent.Callable;
-import java.util.logging.LogManager;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.io.UncheckedIOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+import java.util.Properties;
+import java.util.logging.ConsoleHandler;
+import java.util.logging.FileHandler;
+import java.util.logging.Formatter;
+import java.util.logging.Handler;
+import java.util.logging.Level;
+import java.util.logging.LogRecord;
+import java.util.logging.Logger;
public class LoggerInitializer {
private LoggerInitializer() {
}
- public static void initialize() {
- initialize(() -> LoggerInitializer.class.getResourceAsStream("/logging.properties"));
+ public static LoggingSession initialize() {
+ return initialize(OS.current().getApplicationDirectory(), Logger.getLogger(""),
+ LoggerInitializer.class.getResourceAsStream("/logging.properties"));
}
- private static void initialize(Callable callable) {
- try (var is = callable.call()) {
- LogManager.getLogManager().updateConfiguration(is, k -> ((o, n) -> {
- if (k.equals("java.util.logging.FileHandler.pattern")) {
- var appDir = OS.current().getApplicationDirectory();
- var logFile = appDir.resolve("log%g.log");
- return logFile.toString();
- } else {
- return n;
+ /** 設定ストリームを消費・解放し、指定した logger のハンドラーだけを管理する。 */
+ static LoggingSession initialize(Path directory, Logger target, InputStream source) {
+ var properties = new Properties();
+ try (var input = Objects.requireNonNull(source, "logging configuration is missing")) {
+ properties.load(input);
+ } catch (IOException failure) { throw new UncheckedIOException(failure); }
+ var level = Level.parse(properties.getProperty(".level", "INFO"));
+ var consoleLevel = Level.parse(properties.getProperty("java.util.logging.ConsoleHandler.level", "INFO"));
+ var fileLevel = Level.parse(properties.getProperty("java.util.logging.FileHandler.level", "ALL"));
+ var limit = Long.parseLong(properties.getProperty("java.util.logging.FileHandler.limit", "1073741824"));
+ var count = Integer.parseInt(properties.getProperty("java.util.logging.FileHandler.count", "10"));
+ if (limit < 0 || count < 1) throw new IllegalArgumentException("invalid log rotation settings");
+ var formatter = new TextLogFormatter(properties.getProperty("java.util.logging.SimpleFormatter.format",
+ "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS.%1$tL %4$s [%2$s] %5$s %6$s%n"));
+ var handlers = new ArrayList();
+ LoggingSession session = null;
+ try {
+ Files.createDirectories(directory);
+ var console = new ConsoleHandler();
+ handlers.add(console);
+ console.setEncoding("UTF-8");
+ console.setFormatter(formatter);
+ console.setLevel(consoleLevel);
+ // 明示的に生成し、FileHandler の開始エラーを起動失敗として呼出元へ返す。
+ var file = new FileHandler(directory.resolve("log%g.log").toString(), limit, count, false);
+ handlers.add(file);
+ file.setEncoding("UTF-8");
+ file.setFormatter(formatter);
+ file.setLevel(fileLevel);
+ synchronized (target) {
+ session = new LoggingSession(target, handlers, target.getHandlers(), target.getLevel());
+ for (var previous : session.borrowed) target.removeHandler(previous);
+ for (var handler : handlers) target.addHandler(handler);
+ target.setLevel(level);
+ }
+ return session;
+ } catch (IOException | RuntimeException | Error failure) {
+ var primary = failure instanceof IOException io ? new UncheckedIOException(io) : failure;
+ var installed = session;
+ CloseActions.runAll(() -> rethrow(primary), () -> {
+ if (installed != null) installed.close();
+ else CloseActions.runAll(handlers.stream().map(handler -> (Runnable) handler::close).toArray(Runnable[]::new));
+ });
+ throw new AssertionError("unreachable");
+ }
+ }
+
+ /** アプリが導入したハンドラーだけを閉じ、借用した設定を戻す。 */
+ public static final class LoggingSession implements AutoCloseable {
+ private final Logger target;
+ private final List owned;
+ private final Handler[] borrowed;
+ private final Level previousLevel;
+ private boolean closed;
+
+ private LoggingSession(Logger target, List owned, Handler[] borrowed, Level previousLevel) {
+ this.target = target;
+ this.owned = List.copyOf(owned);
+ this.borrowed = borrowed;
+ this.previousLevel = previousLevel;
+ }
+
+ @Override public void close() {
+ synchronized (target) {
+ if (closed) return;
+ closed = true;
+ var actions = new ArrayList();
+ for (var handler : owned) {
+ actions.add(() -> target.removeHandler(handler));
+ actions.add(handler::close);
}
- }));
- } catch (Exception e) {
- throw new RuntimeException(e);
+ for (var handler : borrowed) actions.add(() -> {
+ if (Arrays.stream(target.getHandlers()).noneMatch(current -> current == handler)) target.addHandler(handler);
+ });
+ actions.add(() -> target.setLevel(previousLevel));
+ CloseActions.runAll(actions.toArray(Runnable[]::new));
+ }
}
}
+ private static final class TextLogFormatter extends Formatter {
+ private final String pattern;
+
+ private TextLogFormatter(String pattern) {
+ this.pattern = pattern;
+ // リソースを作成する前に、6引数の書式が有効か確認する。
+ render(ZonedDateTime.now(), "source", "logger", "INFO", "message", "");
+ }
+
+ @Override public String format(LogRecord record) {
+ var source = record.getSourceClassName();
+ if (source == null) source = record.getLoggerName();
+ else if (record.getSourceMethodName() != null) source += " " + record.getSourceMethodName();
+ var trace = new StringWriter();
+ if (record.getThrown() != null) {
+ var writer = new PrintWriter(trace);
+ writer.println();
+ record.getThrown().printStackTrace(writer);
+ writer.flush();
+ }
+ return render(record.getInstant().atZone(ZoneId.systemDefault()), source, record.getLoggerName(),
+ record.getLevel().getLocalizedName(), formatMessage(record), trace.toString());
+ }
+
+ private String render(ZonedDateTime time, String source, String logger, String level, String message, String trace) {
+ return String.format(pattern, time, source, logger, level, message, trace);
+ }
+ }
+
+ private static void rethrow(Throwable failure) {
+ if (failure instanceof RuntimeException exception) throw exception;
+ if (failure instanceof Error error) throw error;
+ throw new RuntimeException(failure);
+ }
}
diff --git a/src/main/java/com/github/k7t3/tcv/app/core/Resources.java b/src/main/java/com/github/k7t3/tcv/app/core/Resources.java
index 3669d61..e5e1b26 100644
--- a/src/main/java/com/github/k7t3/tcv/app/core/Resources.java
+++ b/src/main/java/com/github/k7t3/tcv/app/core/Resources.java
@@ -28,11 +28,13 @@ public class Resources {
private static final ResourceBundle RESOURCE_BUNDLE;
- private static final TreeMap ICONS;
-
static {
RESOURCE_BUNDLE = ResourceBundle.getBundle("com.github.k7t3.tcv.tcv");
- ICONS = new TreeMap<>(
+ }
+
+ /** 文字列の参照では画像・描画基盤を初期化しない。 */
+ private static class IconsHolder {
+ private static final TreeMap ICONS = new TreeMap<>(
Map.of(
16, smallerIcon(16),
32, smallerIcon(32),
@@ -56,7 +58,7 @@ private static Image loadIcon(double size) {
}
public static List getIcons() {
- return ICONS.entrySet().stream()
+ return IconsHolder.ICONS.entrySet().stream()
.sorted(Comparator.comparingInt(Map.Entry::getKey))
.map(Map.Entry::getValue)
.toList();
diff --git a/src/main/java/com/github/k7t3/tcv/app/emoji/ChatEmojiStore.java b/src/main/java/com/github/k7t3/tcv/app/emoji/ChatEmojiStore.java
index bb8eb9f..ab3b25b 100644
--- a/src/main/java/com/github/k7t3/tcv/app/emoji/ChatEmojiStore.java
+++ b/src/main/java/com/github/k7t3/tcv/app/emoji/ChatEmojiStore.java
@@ -17,6 +17,7 @@
package com.github.k7t3.tcv.app.emoji;
import com.github.k7t3.tcv.app.image.LazyImage;
+import com.github.k7t3.tcv.app.image.ImageLoader;
import com.github.k7t3.tcv.app.service.CachedImageStore;
import org.jetbrains.annotations.Nullable;
@@ -25,16 +26,19 @@
public class ChatEmojiStore extends CachedImageStore {
private final Emoji emoji;
+ private final ImageLoader images;
- public ChatEmojiStore(Emoji emoji) {
+ /** アーカイブと画像サービスは借用し、このストアのキャッシュだけを所有する。 */
+ public ChatEmojiStore(Emoji emoji, ImageLoader images) {
super(64, Duration.ofHours(1));
- this.emoji = emoji;
+ this.emoji = java.util.Objects.requireNonNull(emoji);
+ this.images = java.util.Objects.requireNonNull(images);
}
@Override
protected @Nullable LazyImage loadImage(String key) {
// 対応する絵文字がないときはnull
if (!emoji.contains(key)) return null;
- return new LazyImage(() -> emoji.openImageStream(key), 32, 32);
+ return images.decode(() -> emoji.openImageStream(key), 32, 32);
}
}
diff --git a/src/main/java/com/github/k7t3/tcv/app/emoji/Emoji.java b/src/main/java/com/github/k7t3/tcv/app/emoji/Emoji.java
index 09fbce3..cb12902 100644
--- a/src/main/java/com/github/k7t3/tcv/app/emoji/Emoji.java
+++ b/src/main/java/com/github/k7t3/tcv/app/emoji/Emoji.java
@@ -16,75 +16,172 @@
package com.github.k7t3.tcv.app.emoji;
-import javafx.beans.property.ObjectProperty;
-import javafx.beans.property.ReadOnlyBooleanProperty;
-import javafx.beans.property.ReadOnlyBooleanWrapper;
-import javafx.beans.property.SimpleObjectProperty;
+import com.github.k7t3.tcv.lifecycle.CloseActions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
+import java.util.Collections;
import java.util.HashMap;
+import java.util.Locale;
import java.util.Map;
import java.util.Objects;
-import java.util.concurrent.atomic.AtomicReference;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
- * 絵文字イメージをロードするためのクラス。
+ * 絵文字アーカイブを所有し、画像の入力 stream を提供する。
+ * 検証・配置と終了は直列化する。呼び出し側は返された stream を閉じる。
*/
public class Emoji implements AutoCloseable {
private static final Logger LOGGER = LoggerFactory.getLogger(Emoji.class);
private static final String FILE_NAME = "openmoji-72x72-color.zip";
- private final Map hexAndName = new HashMap<>();
- private final ObjectProperty archivePath = new SimpleObjectProperty<>();
- private final ReadOnlyBooleanWrapper ready = new ReadOnlyBooleanWrapper(false);
- private final AtomicReference properties = new AtomicReference<>();
- private final AtomicReference zipFile = new AtomicReference<>();
+ private final Object archiveLock = new Object();
+ @FunctionalInterface interface ArchiveInput { InputStream open(Path path) throws IOException; }
+ @FunctionalInterface interface ArchiveOpener { ZipFile open(Path path) throws IOException; }
+ @FunctionalInterface interface ArchiveResource { InputStream open() throws IOException; }
+ @FunctionalInterface interface ArchiveMetadata { BasicFileAttributes read(Path path) throws IOException; }
+
+ private final Path archivePath;
+ private final ArchiveInput input;
+ private final ArchiveOpener opener;
+ private final ArchiveResource resource;
+ private final ArchiveMetadata metadata;
+ private EmojiProperties properties;
+ private OpenArchive archive;
+
+ private record OpenArchive(ZipFile zip, Map entries, FileVersion version, Path copy) {}
+
+ private record FileVersion(Object key, long size, FileTime modified, FileTime created) {
+ static FileVersion read(BasicFileAttributes attributes) {
+ return new FileVersion(attributes.fileKey(), attributes.size(),
+ attributes.lastModifiedTime(), attributes.creationTime());
+ }
+
+ }
+
+ /** 識別子がない保存先では、ハッシュを検証した同じbytesをZIPの所有期間中保持する。 */
+ private static final class ArchiveCopy implements AutoCloseable {
+ private final Path path;
+ private boolean adopted;
+
+ private ArchiveCopy(FileVersion version) throws IOException {
+ path = version.key() == null ? Files.createTempFile("tcv-emoji-verified-", ".zip") : null;
+ }
+
+ private String hash(InputStream input) throws IOException {
+ if (path == null) return computeHash(input);
+ try (var output = Files.newOutputStream(path)) { return computeHash(input, output); }
+ }
+
+ private Path adopt() { adopted = true; return path; }
+
+ @Override public void close() throws IOException {
+ if (!adopted && path != null) Files.deleteIfExists(path);
+ }
+ }
private boolean closed = false;
public Emoji(Path extractDir) {
- setArchivePath(extractDir.resolve(FILE_NAME));
+ this(extractDir, Files::newInputStream, path -> new ZipFile(path.toFile()));
+ }
+
+ Emoji(Path extractDir, ArchiveInput input, ArchiveOpener opener) {
+ this(extractDir, input, opener, Emoji::bundledArchive);
+ }
+
+ Emoji(Path extractDir, ArchiveInput input, ArchiveOpener opener, ArchiveResource resource) {
+ this(extractDir, input, opener, resource, path -> Files.readAttributes(path, BasicFileAttributes.class));
+ }
+
+ Emoji(Path extractDir, ArchiveInput input, ArchiveOpener opener, ArchiveResource resource, ArchiveMetadata metadata) {
+ this.archivePath = Objects.requireNonNull(extractDir).resolve(FILE_NAME);
+ this.input = Objects.requireNonNull(input);
+ this.opener = Objects.requireNonNull(opener);
+ this.resource = Objects.requireNonNull(resource);
+ this.metadata = Objects.requireNonNull(metadata);
+ }
+
+ private FileVersion readVersion(Path path) throws IOException { return FileVersion.read(metadata.read(path)); }
+
+ private static InputStream bundledArchive() throws IOException {
+ var input = Emoji.class.getResourceAsStream(FILE_NAME);
+ if (input == null) throw new IOException("missing bundled emoji archive");
+ return input;
}
public boolean contains(String hex) {
- checkReady();
- return hexAndName.containsKey(hex);
+ synchronized (archiveLock) {
+ checkReady();
+ return archive.entries().containsKey(hex);
+ }
}
/**
* キーにマッチする絵文字のイメージをロードする{@link InputStream}を返す。
* @param hex 絵文字のHexキー
- * @return 絵文字のイメージInputStream
- * @throws IOException キーにマッチするイメージがないときにスローされる
+ * @return 呼び出し側が閉じる入力 stream。アーカイブの置換・終了でも無効になる
+ * @throws IllegalArgumentException キーに対応する画像がない場合
+ * @throws IllegalStateException 検証前または終了済みの場合
+ * @throws IOException 画像の入力 stream を開けない場合
*/
public InputStream openImageStream(String hex) throws IOException {
- checkReady();
- var key = hexAndName.get(hex);
- if (key == null) throw new IllegalArgumentException();
+ synchronized (archiveLock) {
+ checkReady();
+ var key = archive.entries().get(hex);
+ if (key == null) throw new IllegalArgumentException();
- var zip = zipFile.get();
- var entry = zip.getEntry(key);
- return zip.getInputStream(entry);
+ var zip = archive.zip();
+ var entry = zip.getEntry(key);
+ return zip.getInputStream(entry);
+ }
}
/**
- * アーカイブを抽出する
+ * 配置先の親ディレクトリを作成し、同梱アーカイブを抽出する。
+ * @throws IllegalStateException 終了している場合
+ * @throws IOException アーカイブの配置に失敗した場合
*/
public void extractArchive() throws IOException {
- final var archivePath = getArchivePath();
- try (var input = Objects.requireNonNull(getClass().getResourceAsStream(FILE_NAME))) {
- Files.copy(input, archivePath, StandardCopyOption.REPLACE_EXISTING);
+ synchronized (archiveLock) {
+ checkOpen();
+ var target = archivePath.toAbsolutePath();
+ Files.createDirectories(target.getParent());
+ var temporary = Files.createTempFile(target.getParent(), ".tcv-emoji-", ".tmp");
+ Throwable primary = null;
+ try {
+ try (var input = resource.open()) {
+ Files.copy(input, temporary, StandardCopyOption.REPLACE_EXISTING);
+ }
+ try (var input = Files.newInputStream(temporary)) {
+ if (!properties().getHash().equals(computeHash(input)))
+ throw new IOException("invalid bundled emoji archive");
+ }
+ releaseArchive();
+ Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
+ } catch (IOException | RuntimeException | Error failure) {
+ primary = failure;
+ throw failure;
+ } finally {
+ try { Files.deleteIfExists(temporary); }
+ catch (IOException cleanup) {
+ if (primary == null) throw cleanup;
+ if (primary != cleanup) primary.addSuppressed(cleanup);
+ }
+ }
}
}
@@ -92,96 +189,143 @@ public void extractArchive() throws IOException {
* 絵文字アーカイブファイルが所定のパスに抽出されているかを判定する。
*
* @return 抽出されているファイルが適切なものである場合はtrueを返す。
+ * @throws IllegalStateException 終了している場合
+ * @throws IOException アーカイブを開けない場合
*/
public boolean validateArchive() throws IOException {
- var properties = this.properties.get();
- if (properties == null) {
- properties = new EmojiProperties();
- properties.loadEmojiProperties();
- LOGGER.info("emoji properties {}", properties);
- this.properties.set(properties);
- }
+ synchronized (archiveLock) {
+ checkOpen();
+ try {
+ var properties = properties();
- var path = getArchivePath();
- if (Files.exists(path)) {
- // 存在するファイルのハッシュ値を求める
- try (var input = Files.newInputStream(path)) {
- var hash = computeHash(input);
- if (properties.getHash().equals(hash)) {
- final var archivePath = getArchivePath();
-
- // コピーしたアーカイブをロード
- var zip = new ZipFile(archivePath.toFile());
- zip.stream().map(ZipEntry::getName).forEach(name -> {
- var hex = name.toLowerCase();
- var index = hex.indexOf(".");
- if (0 < index) {
- hex = hex.substring(0, index);
+ var path = getArchivePath();
+ if (Files.exists(path)) {
+ var version = readVersion(path);
+ try (var copy = new ArchiveCopy(version)) {
+ final String hash;
+ try (var input = this.input.open(path)) {
+ hash = copy.hash(input);
}
- hexAndName.put(hex, name);
- });
- zipFile.set(zip);
-
- ready.set(true);
- return true;
+ checkOpen();
+ if (properties.getHash().equals(hash)) {
+ if (!version.equals(readVersion(path)))
+ throw new IOException("emoji archive changed during validation");
+ // 識別子がない場合も、所有コピーは検証済み内容から変更されない。
+ if (archive != null && version.equals(archive.version())) return true;
+ releaseArchive();
+ checkOpen();
+ var zip = opener.open(copy.path == null ? path : copy.path);
+ try {
+ checkOpen();
+ if (!version.equals(readVersion(path)))
+ throw new IOException("emoji archive changed while opening");
+ var entries = new HashMap();
+ zip.stream().map(ZipEntry::getName).forEach(name -> {
+ var hex = name.toLowerCase(Locale.ROOT);
+ var index = hex.indexOf(".");
+ if (0 < index) {
+ hex = hex.substring(0, index);
+ }
+ entries.put(hex, name);
+ });
+ checkOpen();
+ archive = new OpenArchive(zip, Collections.unmodifiableMap(entries), version, copy.adopt());
+ return true;
+ } catch (IOException | RuntimeException | Error failure) {
+ try { closeZip(zip); }
+ catch (RuntimeException | Error cleanup) {
+ if (cleanup != failure) failure.addSuppressed(cleanup);
+ }
+ throw failure;
+ }
+ }
+ }
+ }
+ releaseArchive();
+ return false;
+ } catch (IOException | RuntimeException | Error failure) {
+ try { releaseArchive(); }
+ catch (RuntimeException | Error cleanup) {
+ if (cleanup != failure) failure.addSuppressed(cleanup);
}
+ throw failure;
}
}
- return false;
+ }
+
+ private EmojiProperties properties() {
+ if (properties == null) {
+ var loaded = new EmojiProperties();
+ loaded.loadEmojiProperties();
+ LOGGER.info("emoji properties {}", loaded);
+ properties = loaded;
+ }
+ return properties;
}
private void checkReady() {
- if (!isReady()) throw new IllegalStateException("not ready");
+ checkOpen();
+ if (archive == null) throw new IllegalStateException("not ready");
+ }
+
+ private void checkOpen() {
if (closed) throw new IllegalStateException("closed");
}
+ /** 進行中の検証・配置を待ち、アーカイブを一度だけ閉じる。返却済みの stream も無効になる。 */
@Override
public void close() {
- if (closed) return;
- closed = true;
- if (zipFile.get() != null) {
- try {
- zipFile.get().close();
- } catch (IOException e) {
- LOGGER.error("error occurred on closing", e);
- }
+ synchronized (archiveLock) {
+ if (closed) return;
+ closed = true;
+ releaseArchive();
}
}
- public static String computeHash(InputStream input) {
- MessageDigest digest;
- try {
- digest = MessageDigest.getInstance("sha-256");
- } catch (NoSuchAlgorithmException e) {
- throw new RuntimeException(e);
- }
-
- try {
- var bytes = new byte[1024];
- int length;
- while ((length = input.read(bytes)) != -1) {
- digest.update(bytes, 0, length);
+ private void releaseArchive() {
+ var previous = archive;
+ archive = null;
+ if (previous != null) CloseActions.runAll(() -> closeZip(previous.zip()), () -> {
+ if (previous.copy() != null) {
+ try { Files.deleteIfExists(previous.copy()); }
+ catch (IOException failure) { throw new UncheckedIOException("failed to delete owned emoji archive " + previous.copy(), failure); }
}
+ });
+ }
- var hashBytes = digest.digest();
- var builder = new StringBuilder();
- // 1文字目の0が消えてしまうのでInteger.toHexStringじゃなくformatで
- for (var b : hashBytes)
- builder.append("%02x".formatted(Byte.toUnsignedInt(b)));
- //builder.append(Integer.toHexString(Byte.toUnsignedInt(b)));
- return builder.toString();
+ private static void closeZip(ZipFile zip) {
+ try { zip.close(); }
+ catch (IOException failure) { throw new UncheckedIOException("failed to close emoji archive", failure); }
+ }
- } catch (IOException e) {
- throw new RuntimeException(e);
+ private static String computeHash(InputStream input) throws IOException {
+ return computeHash(input, OutputStream.nullOutputStream());
+ }
+
+ private static String computeHash(InputStream input, OutputStream output) throws IOException {
+ final MessageDigest digest;
+ try { digest = MessageDigest.getInstance("SHA-256"); }
+ catch (NoSuchAlgorithmException impossible) { throw new IllegalStateException("SHA-256 unavailable", impossible); }
+ var bytes = new byte[8192];
+ int length;
+ while ((length = input.read(bytes)) != -1) {
+ digest.update(bytes, 0, length);
+ output.write(bytes, 0, length);
}
+ return java.util.HexFormat.of().formatHex(digest.digest());
}
- public EmojiProperties getProperties() { return properties.get(); }
+ public EmojiProperties getProperties() {
+ synchronized (archiveLock) {
+ return properties;
+ }
+ }
- public ObjectProperty archivePathProperty() { return archivePath; }
- public Path getArchivePath() { return archivePath.get(); }
- public void setArchivePath(Path path) { archivePath.set(Objects.requireNonNull(path)); }
+ public final Path getArchivePath() { return archivePath; }
- public ReadOnlyBooleanProperty readyProperty() { return ready.getReadOnlyProperty(); }
- public boolean isReady() { return ready.get(); }
+ public boolean isReady() {
+ synchronized (archiveLock) {
+ return archive != null;
+ }
+ }
}
diff --git a/src/main/java/com/github/k7t3/tcv/app/event/ChatOpeningEvent.java b/src/main/java/com/github/k7t3/tcv/app/event/ChatOpeningEvent.java
index 43286de..9abb174 100644
--- a/src/main/java/com/github/k7t3/tcv/app/event/ChatOpeningEvent.java
+++ b/src/main/java/com/github/k7t3/tcv/app/event/ChatOpeningEvent.java
@@ -19,7 +19,6 @@
import com.github.k7t3.tcv.app.channel.MultipleChatOpenType;
import com.github.k7t3.tcv.app.channel.TwitchChannelViewModel;
-import java.util.Collections;
import java.util.List;
/**
@@ -40,7 +39,7 @@ public ChatOpeningEvent(
List channels
) {
this.chatOpenType = chatOpenType;
- this.channels = Collections.unmodifiableList(channels);
+ this.channels = List.copyOf(channels);
}
/**
diff --git a/src/main/java/com/github/k7t3/tcv/app/event/SessionInvalidatedEvent.java b/src/main/java/com/github/k7t3/tcv/app/event/SessionInvalidatedEvent.java
new file mode 100644
index 0000000..89cfc01
--- /dev/null
+++ b/src/main/java/com/github/k7t3/tcv/app/event/SessionInvalidatedEvent.java
@@ -0,0 +1,6 @@
+package com.github.k7t3.tcv.app.event;
+
+import com.github.k7t3.tcv.app.core.ClientSessions;
+
+/** 同じアプリが所有する失効済みセッションの画面を、FX スレッドで切り離す。 */
+public record SessionInvalidatedEvent(ClientSessions source) implements AppEvent {}
diff --git a/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroup.java b/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroup.java
index 170821f..1e4cbd6 100644
--- a/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroup.java
+++ b/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroup.java
@@ -51,9 +51,9 @@ public UUID getId() {
return id;
}
- public void generateId() {
- if (id != null) throw new IllegalStateException();
- id = UUID.randomUUID();
+ void assignPersistedId(UUID value) {
+ if (id != null && !id.equals(value)) throw new IllegalStateException("group id cannot change");
+ id = java.util.Objects.requireNonNull(value);
}
// ******************** PROPERTIES ********************
diff --git a/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroupListViewModel.java b/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroupListViewModel.java
index 8fc5813..3b7364e 100644
--- a/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroupListViewModel.java
+++ b/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroupListViewModel.java
@@ -18,13 +18,13 @@
import com.github.k7t3.tcv.app.channel.TwitchChannelViewModel;
import com.github.k7t3.tcv.app.model.AbstractViewModel;
-import com.github.k7t3.tcv.app.core.Resources;
import com.github.k7t3.tcv.app.service.FXTask;
-import com.github.k7t3.tcv.domain.event.EventSubscribers;
import javafx.beans.binding.Bindings;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.ObservableList;
+import javafx.collections.FXCollections;
+import javafx.beans.Observable;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
@@ -33,13 +33,18 @@
public class ChannelGroupListViewModel extends AbstractViewModel {
private final ChannelGroupRepository repository;
+ private final ObservableList source;
+ private final ObservableList items = FXCollections.observableArrayList(
+ group -> new Observable[] { group.pinnedProperty(), group.nameProperty(), group.updatedAtProperty() });
private final SortedList sorted;
private final FilteredList filtered;
private final StringProperty filter = new SimpleStringProperty();
public ChannelGroupListViewModel(ChannelGroupRepository repository) {
this.repository = repository;
- sorted = new SortedList<>(repository.getAll());
+ source = repository.getAll();
+ Bindings.bindContent(items, source);
+ sorted = new SortedList<>(items);
filtered = new FilteredList<>(sorted);
filtered.predicateProperty().bind(Bindings.createObjectBinding(() -> this::test, filter));
}
@@ -73,7 +78,9 @@ private boolean test(TwitchChannelViewModel channel, String filter) {
}
public void setComparator(Comparator comparator) {
- sorted.setComparator(ChannelGroupPinnedComparator.INSTANCE.thenComparing(comparator));
+ checkOpen();
+ sorted.setComparator(comparator == null ? ChannelGroupPinnedComparator.INSTANCE
+ : ChannelGroupPinnedComparator.INSTANCE.thenComparing(comparator));
}
public ObservableList getChannelGroups() {
@@ -81,16 +88,19 @@ public ObservableList getChannelGroups() {
}
public FXTask> create(String name) {
+ checkOpen();
var group = new ChannelGroup();
group.setName(name);
return repository.saveAsync(group);
}
public FXTask> update(ChannelGroup group) {
+ checkOpen();
return repository.saveAsync(group);
}
public FXTask> delete(ChannelGroup group) {
+ checkOpen();
return repository.removeAsync(group);
}
@@ -98,54 +108,13 @@ public FXTask> delete(ChannelGroup group) {
public String getFilter() { return filter.get(); }
public void setFilter(String filter) { this.filter.set(filter); }
- @Override
- public void subscribeEvents(EventSubscribers eventSubscribers) {
- // no-op
- }
-
- @Override
- public void onLogout() {
- // no-op
- }
-
- @Override
- public void close() {
- // no-op
- }
-
- public enum Comparators implements Comparator {
-
- UPDATED_AT("group.comparator.updated", Comparator.comparing(ChannelGroup::getUpdatedAt)),
-
- CREATED_AT("group.comparator.created", Comparator.comparing(ChannelGroup::getCreatedAt)),
-
- LIVE_COUNT("group.comparator.liver", Comparator.comparingLong(g -> g.getChannels()
- .stream()
- .filter(TwitchChannelViewModel::isLive)
- .count()
- )),
+ private void checkOpen() { if (isClosed()) throw new IllegalStateException("group editor is closed"); }
- /** 状態の規定値として名前を使用しているので変更しないようにするか別の形で定義したい・・・。*/
- NAME("group.comparator.name", Comparator.comparing(ChannelGroup::getName));
-
- private final String display;
-
- private final Comparator comparator;
-
- Comparators(String display, Comparator comparator) {
- this.display = Resources.getString(display);
- this.comparator = comparator;
- }
-
- @Override
- public String toString() {
- return display;
- }
-
- @Override
- public int compare(ChannelGroup o1, ChannelGroup o2) {
- return comparator.compare(o1, o2);
- }
+ @Override protected void onClose() {
+ Bindings.unbindContent(items, source);
+ filtered.predicateProperty().unbind();
+ filter.unbind();
+ items.clear();
}
}
diff --git a/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroupOrder.java b/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroupOrder.java
new file mode 100644
index 0000000..f51085a
--- /dev/null
+++ b/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroupOrder.java
@@ -0,0 +1,40 @@
+package com.github.k7t3.tcv.app.group;
+
+import com.github.k7t3.tcv.app.channel.TwitchChannelViewModel;
+import com.github.k7t3.tcv.app.core.Resources;
+import java.util.Comparator;
+
+public enum ChannelGroupOrder implements Comparator {
+
+ UPDATED_AT("group.comparator.updated", Comparator.comparing(ChannelGroup::getUpdatedAt)),
+
+ CREATED_AT("group.comparator.created", Comparator.comparing(ChannelGroup::getCreatedAt)),
+
+ LIVE_COUNT("group.comparator.liver", Comparator.comparingLong(g -> g.getChannels()
+ .stream()
+ .filter(TwitchChannelViewModel::isLive)
+ .count()
+ )),
+
+ /** 名前は既存の保存形式として維持する。 */
+ NAME("group.comparator.name", Comparator.comparing(ChannelGroup::getName));
+
+ private final String display;
+
+ private final Comparator comparator;
+
+ ChannelGroupOrder(String display, Comparator comparator) {
+ this.display = display;
+ this.comparator = comparator;
+ }
+
+ @Override
+ public String toString() {
+ return Resources.getString(display);
+ }
+
+ @Override
+ public int compare(ChannelGroup o1, ChannelGroup o2) {
+ return comparator.compare(o1, o2);
+ }
+}
diff --git a/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroupRepository.java b/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroupRepository.java
index 1604948..b1601a2 100644
--- a/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroupRepository.java
+++ b/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroupRepository.java
@@ -19,152 +19,288 @@
import com.github.k7t3.tcv.app.channel.TwitchChannelViewModel;
import com.github.k7t3.tcv.app.model.AbstractViewModel;
import com.github.k7t3.tcv.app.service.FXTask;
-import com.github.k7t3.tcv.domain.event.EventSubscribers;
+import com.github.k7t3.tcv.app.service.SerialIoQueue;
import com.github.k7t3.tcv.entity.ChannelGroupEntity;
import com.github.k7t3.tcv.entity.SaveType;
import com.github.k7t3.tcv.entity.service.ChannelGroupEntityService;
+import javafx.application.Platform;
import javafx.beans.Observable;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import java.time.LocalDateTime;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
+import java.util.*;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.CompletionStage;
+import java.util.concurrent.Executor;
+import java.util.function.Consumer;
import java.util.stream.Collectors;
+/** グループの表示と、受付済みの不変な保存要求を所有する。 */
public class ChannelGroupRepository extends AbstractViewModel {
-
+ private static final Logger LOGGER = LoggerFactory.getLogger(ChannelGroupRepository.class);
private final ChannelGroupEntityService service;
-
+ private final SerialIoQueue io;
+ private final Consumer> shutdownAwaiter;
+ private final Consumer reportFailure;
+ private final Map plans = new IdentityHashMap<>();
+ private final Map committed = new IdentityHashMap<>();
+ private final Map pendingRetention = new IdentityHashMap<>();
+ private long scope;
+ private long sequence;
private final ObservableList groups = FXCollections.observableArrayList(
- g -> new Observable[] { g.pinnedProperty(), g.nameProperty(), g.updatedAtProperty() }
- );
+ group -> new Observable[] {group.pinnedProperty(), group.nameProperty(), group.updatedAtProperty()});
- public ChannelGroupRepository(ChannelGroupEntityService service) {
- this.service = service;
- }
+ private record State(ChannelGroupEntity entity, Set channels) {}
- public List retrieveAllChannelIds() {
- return service.retrieveAll().stream()
- .flatMap(entity -> entity.channelIds().stream())
- .distinct()
- .toList();
+ private static final class Plan {
+ final ChannelGroup group;
+ final UUID id;
+ final LocalDateTime created;
+ boolean persisted; // I/O キュー内だけで更新する。
+ State durable; // I/O キュー内だけで更新し、各結果へ捕捉する。
+ Object latestRequest;
+ long publishedSequence;
+ boolean deleting;
+ Plan(ChannelGroup group, State baseline) {
+ this.group = group;
+ id = group.getId() == null ? UUID.randomUUID() : group.getId();
+ created = group.getCreatedAt() == null ? LocalDateTime.now() : group.getCreatedAt();
+ persisted = group.getId() != null;
+ durable = baseline;
+ }
}
- /**
- * チャンネルグループで使用しているチャンネルを与える
- *
- * {@link #retrieveAllChannelIds()}で事前に使用しているチャンネルを取得しておくこと
- *
- */
- public void injectChannels(Map channels) {
- var entities = service.retrieveAll();
+ private record Outcome(Throwable failure, State durable) {}
- var groups = new HashSet();
+ public ChannelGroupRepository(ChannelGroupEntityService service, Executor executor,
+ Consumer> shutdownAwaiter, Consumer reportFailure) {
+ this.service = Objects.requireNonNull(service);
+ io = new SerialIoQueue(executor);
+ this.shutdownAwaiter = Objects.requireNonNull(shutdownAwaiter);
+ this.reportFailure = Objects.requireNonNull(reportFailure);
+ }
+
+ /** 背景で、先に受付済みの書込を終えてから読む。UI モデルは参照しない。 */
+ public List loadSnapshot() {
+ checkOpen();
+ if (Platform.isFxApplicationThread()) throw new IllegalStateException("group loading must run outside FX");
+ return io.call(() -> service.retrieveAll().stream().map(entity -> new ChannelGroupEntity(
+ entity.id(), entity.name(), entity.comment(), entity.pinned(), entity.createdAt(),
+ entity.updatedAt(), Set.copyOf(entity.channelIds()))).toList());
+ }
+ /** FX 上で一括反映する。読取中に編集・作成・削除した同じ表示モデルを古い一覧で置換しない。 */
+ public void applySnapshot(List entities, Map channels) {
+ checkOpen();
+ var local = new HashMap();
+ plans.values().forEach(plan -> local.put(plan.id, plan));
+ var next = new ArrayList();
for (var entity : entities) {
+ if (local.containsKey(entity.id())) continue;
var group = new ChannelGroup(entity.id());
group.setName(entity.name());
group.setComment(entity.comment());
group.setPinned(entity.pinned());
group.setCreatedAt(entity.createdAt());
group.setUpdatedAt(entity.updatedAt());
- var groupChannels = entity.channelIds().stream().map(channels::get).toList();
- group.getChannels().addAll(groupChannels);
- groups.add(group);
+ group.getChannels().addAll(entity.channelIds().stream().map(channels::get)
+ .map(Objects::requireNonNull).toList());
+ committed.put(group, capture(group, entity.id(), entity.createdAt(), entity.updatedAt()));
+ next.add(group);
}
-
- this.groups.addAll(groups);
+ // 保存要求のモデルはこのセッション中の正本。未確定の新規作成は自身の成功時に公開する。
+ groups.stream().filter(plans::containsKey).forEach(next::add);
+ groups.setAll(next);
+ committed.keySet().removeIf(group -> !groups.contains(group) && !plans.containsKey(group));
}
- /**
- * リポジトリにロードされているすべてのグループを取得する
- * @return リポジトリにロードされているすべてのグループ
- */
- public ObservableList getAll() {
- return groups;
- }
+ public ObservableList getAll() { return groups; }
+
+ public FXTask> saveAsync(ChannelGroup group) { return submit(group, false); }
+ public FXTask> removeAsync(ChannelGroup group) { return submit(group, true); }
- /**
- * グループを保存する
- * @param group 保存するグループ
- */
- public FXTask> saveAsync(ChannelGroup group) {
+ private FXTask submit(ChannelGroup group, boolean remove) {
+ checkOpen();
if (group == null) throw new IllegalArgumentException("group is null");
+ if (!Platform.isFxApplicationThread()) throw new IllegalStateException("group edits must run on FX");
+ var plan = plans.computeIfAbsent(group, value -> new Plan(value, committed.get(value)));
+ if (plan.deleting) throw new IllegalStateException("group deletion is pending or complete");
+ var updated = group.getId() == null && plan.latestRequest == null ? plan.created : LocalDateTime.now();
+ var snapshot = capture(group, plan.id, plan.created, updated);
+ if (!remove && snapshot.channels().stream().anyMatch(TwitchChannelViewModel::isRetiring)) {
+ throw new IllegalStateException("cannot save a group with a released channel");
+ }
+ var request = new Object();
+ var previousRequest = plan.latestRequest;
+ plan.latestRequest = request;
+ if (remove) plan.deleting = true;
+ var requestScope = scope;
+ long requestSequence = ++sequence;
+ var actual = new CompletableFuture();
+ var failure = new java.util.concurrent.atomic.AtomicReference();
+ var result = FXTask.observation(() -> {
+ rethrow(failure.get());
+ return null;
+ });
+ result.onFailure(error -> {
+ if (!isClosed() && scope == requestScope) reportFailure.accept(error);
+ });
+ // 実行開始前から所有する。観測の取消・画面終了でも受付済み SQL は実行する。
+ try { shutdownAwaiter.accept(actual.minimalCompletionStage()); }
+ catch (RuntimeException | Error rejected) {
+ if (plan.latestRequest == request) {
+ plan.latestRequest = previousRequest;
+ plan.deleting = false;
+ }
+ failure.set(rejected);
+ actual.completeExceptionally(rejected);
+ result.run();
+ return result;
+ }
+ io.submit(() -> {
+ try {
+ if (remove) {
+ if (plan.persisted) service.remove(snapshot.entity());
+ plan.persisted = false;
+ plan.durable = null;
+ } else {
+ service.save(plan.persisted ? SaveType.UPDATE : SaveType.INSERT, snapshot.entity());
+ plan.persisted = true;
+ plan.durable = snapshot;
+ }
+ return new Outcome(null, plan.durable);
+ } catch (Throwable error) {
+ return new Outcome(error, plan.durable);
+ }
+ }).whenComplete((outcome, rejected) -> {
+ var completed = rejected == null ? outcome : new Outcome(unwrap(rejected), plan.durable);
+ var error = completed.failure();
+ failure.set(error);
+ try {
+ if (error != null) LOGGER.error("Failed to persist channel group", error);
+ Platform.runLater(() -> {
+ if (!isClosed() && scope == requestScope && plans.get(group) == plan) {
+ finishPublication(plan, request, requestSequence, snapshot, remove, completed, requestScope);
+ }
+ });
+ } finally {
+ try { result.run(); }
+ finally {
+ if (error == null) actual.complete(null);
+ else actual.completeExceptionally(error);
+ }
+ }
+ });
+ // 監視と実行受付を先に確定する。プロパティ通知から終了処理へ再入しても自己待機しない。
+ if (!remove) snapshot.channels().forEach(channel -> {
+ if (isCurrent(plan, requestScope)) {
+ pendingRetention.merge(channel, 1, Integer::sum);
+ reconcileRetention(channel);
+ }
+ });
+ return result;
+ }
+
+ private boolean isCurrent(Plan plan, long expectedScope) {
+ return !isClosed() && scope == expectedScope && plans.get(plan.group) == plan;
+ }
- SaveType saveType;
- var now = LocalDateTime.now();
- if (group.getId() == null) {
- saveType = SaveType.INSERT;
- group.generateId();
- group.setCreatedAt(now);
- group.setUpdatedAt(now);
- groups.add(group);
- } else {
- saveType = SaveType.UPDATE;
- group.setUpdatedAt(now);
+ private void finishPublication(Plan plan, Object request, long order, State snapshot, boolean remove,
+ Outcome outcome, long requestScope) {
+ var affected = new HashSet<>(snapshot.channels());
+ var previous = committed.get(plan.group);
+ if (previous != null) affected.addAll(previous.channels());
+ if (outcome.durable() != null) affected.addAll(outcome.durable().channels());
+ try { applyWrite(plan, request, order, snapshot, remove, outcome, requestScope); }
+ finally {
+ if (isCurrent(plan, requestScope)) {
+ if (!remove) snapshot.channels().forEach(channel ->
+ pendingRetention.computeIfPresent(channel, (key, count) -> count == 1 ? null : count - 1));
+ affected.forEach(channel -> {
+ if (isCurrent(plan, requestScope)) reconcileRetention(channel);
+ });
+ }
}
+ }
- var t = FXTask.task(() -> {
- var userIds = List.copyOf(group.getChannels()).stream()
- .map(c -> c.getBroadcaster().getUserId())
- .collect(Collectors.toSet());
-
- var entity = new ChannelGroupEntity(
- group.getId(),
- group.getName(),
- group.getComment(),
- group.isPinned(),
- group.getCreatedAt(),
- group.getUpdatedAt(),
- userIds
- );
- service.save(saveType, entity);
- });
- t.runAsync();
- return t;
+ private void reconcileRetention(TwitchChannelViewModel channel) {
+ boolean retained = channel.isFollowing() || pendingRetention.containsKey(channel)
+ || committed.values().stream().anyMatch(state -> state.channels().contains(channel));
+ channel.setPersistent(retained);
}
- /**
- * グループを削除する
- * @param group 削除するグループ
- */
- public FXTask> removeAsync(ChannelGroup group) {
- if (group == null) throw new IllegalArgumentException("group is null");
+ private void applyWrite(Plan plan, Object request, long order, State snapshot, boolean remove, Outcome outcome,
+ long requestScope) {
+ if (order <= plan.publishedSequence) return;
+ plan.publishedSequence = order;
+ var group = plan.group;
+ var durable = outcome.durable();
+ if (outcome.failure() != null) {
+ if (plan.latestRequest == request) {
+ plan.deleting = false;
+ if (durable != null) restoreUnchangedFields(group, snapshot, durable);
+ }
+ } else if (remove) {
+ groups.remove(group);
+ if (isCurrent(plan, requestScope)) committed.remove(group);
+ return;
+ }
+ if (!isCurrent(plan, requestScope)) return;
+ if (durable != null) {
+ group.assignPersistedId(durable.entity().id());
+ group.setCreatedAt(durable.entity().createdAt());
+ if (!isCurrent(plan, requestScope)) return;
+ group.setUpdatedAt(durable.entity().updatedAt());
+ if (!isCurrent(plan, requestScope)) return;
+ committed.put(group, durable);
+ if (!plan.deleting && !groups.contains(group)) groups.add(group);
+ }
+ }
- groups.remove(group);
-
- var t = FXTask.task(() -> {
- var entity = new ChannelGroupEntity(
- group.getId(),
- group.getName(),
- group.getComment(),
- group.isPinned(),
- group.getCreatedAt(),
- group.getUpdatedAt(),
- Set.of()
- );
- service.remove(entity);
- });
- t.runAsync();
- return t;
+ private static State capture(ChannelGroup group, UUID id, LocalDateTime created, LocalDateTime updated) {
+ var channels = Set.copyOf(group.getChannels());
+ var ids = channels.stream().map(channel -> channel.getBroadcaster().getUserId()).collect(Collectors.toUnmodifiableSet());
+ return new State(new ChannelGroupEntity(id, group.getName(), group.getComment(), group.isPinned(),
+ created, updated, ids), channels);
}
- @Override
- public void subscribeEvents(EventSubscribers eventSubscribers) {
- // no-op
+ private static void restoreUnchangedFields(ChannelGroup group, State requested, State baseline) {
+ var input = requested.entity();
+ var stored = baseline.entity();
+ if (Objects.equals(group.getName(), input.name())) group.setName(stored.name());
+ if (Objects.equals(group.getComment(), input.comment())) group.setComment(stored.comment());
+ if (group.isPinned() == input.pinned()) group.setPinned(stored.pinned());
+ if (Set.copyOf(group.getChannels()).equals(requested.channels())) {
+ group.getChannels().clear();
+ group.getChannels().addAll(baseline.channels());
+ }
}
- @Override
- public void onLogout() {
- groups.clear();
+ private static Throwable unwrap(Throwable failure) {
+ while (failure instanceof CompletionException && failure.getCause() != null) failure = failure.getCause();
+ return failure;
}
- @Override
- public void close() {
- groups.clear();
+ private static void rethrow(Throwable failure) throws Exception {
+ if (failure instanceof Exception exception) throw exception;
+ if (failure instanceof Error error) throw error;
+ if (failure != null) throw new IllegalStateException(failure);
}
+ private void checkOpen() { if (isClosed()) throw new IllegalStateException("group repository is closed"); }
+ private void endSession() {
+ scope++;
+ var pending = List.copyOf(pendingRetention.keySet());
+ pendingRetention.clear();
+ groups.clear();
+ plans.clear();
+ pending.forEach(this::reconcileRetention);
+ committed.clear();
+ }
+ @Override protected void onLoggedOut() { endSession(); }
+ @Override protected void onClose() { endSession(); }
}
diff --git a/src/main/java/com/github/k7t3/tcv/app/help/AboutViewModel.java b/src/main/java/com/github/k7t3/tcv/app/help/AboutViewModel.java
index 45f1f82..032c9d3 100644
--- a/src/main/java/com/github/k7t3/tcv/app/help/AboutViewModel.java
+++ b/src/main/java/com/github/k7t3/tcv/app/help/AboutViewModel.java
@@ -17,8 +17,7 @@
package com.github.k7t3.tcv.app.help;
import com.github.k7t3.tcv.app.model.AppViewModel;
-import com.github.k7t3.tcv.app.core.DesktopUtils;
-import com.github.k7t3.tcv.app.service.FXTask;
+import com.github.k7t3.tcv.app.service.BrowserActions;
import com.github.k7t3.tcv.domain.event.EventSubscribers;
public class AboutViewModel implements AppViewModel {
@@ -27,15 +26,11 @@ public class AboutViewModel implements AppViewModel {
private static final String LICENSE_LINK = "https://github.com/k7t3/TwitchChatViewer/blob/main/docs/license.md";
private static final String LIBRARIES_LINK = "https://github.com/k7t3/TwitchChatViewer/blob/main/docs/external-libraries.md";
- public AboutViewModel() {
- }
+ private final BrowserActions browsers;
- private void browse(String link) {
- FXTask.task(() -> {
- DesktopUtils.browse(link);
- return null;
- }).runAsync();
- }
+ public AboutViewModel(BrowserActions browsers) { this.browsers = browsers; }
+
+ private void browse(String link) { browsers.open(link); }
public void browseGitHubPage() {
browse(GITHUB_LINK);
@@ -55,12 +50,8 @@ public void subscribeEvents(EventSubscribers eventSubscribers) {
}
@Override
- public void onLogout() {
- // no-op
- }
+ public void onLogout() { browsers.cancelAll(); }
@Override
- public void close() {
- // no-op
- }
+ public void close() { browsers.close(); }
}
diff --git a/src/main/java/com/github/k7t3/tcv/app/image/ImageDownloader.java b/src/main/java/com/github/k7t3/tcv/app/image/ImageDownloader.java
new file mode 100644
index 0000000..cb61f4c
--- /dev/null
+++ b/src/main/java/com/github/k7t3/tcv/app/image/ImageDownloader.java
@@ -0,0 +1,132 @@
+package com.github.k7t3.tcv.app.image;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.net.http.HttpTimeoutException;
+import java.nio.ByteBuffer;
+import java.time.Duration;
+import java.util.List;
+import java.util.Objects;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionStage;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Flow;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+/** HTTP クライアントを所有し、画像のバイト列を取得する。画像のデコードと UI の反映は呼び出し側が行う。 */
+final class ImageDownloader implements AutoCloseable {
+ private final Object lifecycle = new Object();
+ private HttpClient client;
+ private boolean closed;
+ private final Duration timeout;
+ private final int maxBytes;
+
+ ImageDownloader(Duration timeout) {
+ this(timeout, 16 * 1024 * 1024);
+ }
+
+ ImageDownloader(Duration timeout, int maxBytes) {
+ this.timeout = Objects.requireNonNull(timeout);
+ if (timeout.isZero() || timeout.isNegative()) throw new IllegalArgumentException("timeout must be positive");
+ this.maxBytes = maxBytes;
+ }
+
+ private HttpClient client() throws IOException {
+ synchronized (lifecycle) {
+ if (closed) throw new IOException("image downloader is closed");
+ if (client == null) {
+ client = HttpClient.newBuilder().connectTimeout(timeout)
+ .followRedirects(HttpClient.Redirect.NORMAL).build();
+ }
+ return client;
+ }
+ }
+
+ byte[] download(URI uri) throws IOException, InterruptedException {
+ var request = HttpRequest.newBuilder(uri).timeout(timeout).GET().build();
+ var response = client().sendAsync(request, ignored -> new LimitedBodySubscriber(maxBytes));
+ try {
+ var received = response.get(timeout.toNanos(), TimeUnit.NANOSECONDS);
+ if (received.statusCode() < 200 || received.statusCode() >= 300) {
+ throw new IOException("image request failed: HTTP " + received.statusCode());
+ }
+ return received.body();
+ } catch (TimeoutException failure) {
+ var timeout = new HttpTimeoutException("image download timed out");
+ timeout.initCause(failure);
+ throw timeout;
+ } catch (ExecutionException failure) {
+ if (failure.getCause() instanceof IOException ioFailure) throw ioFailure;
+ throw new IOException("image download failed", failure.getCause());
+ } finally {
+ response.cancel(true);
+ }
+ }
+
+ @Override
+ public void close() {
+ final HttpClient owned;
+ synchronized (lifecycle) {
+ if (closed) return;
+ closed = true;
+ owned = client;
+ }
+ if (owned != null) {
+ owned.shutdownNow();
+ owned.close();
+ }
+ }
+
+ private static final class LimitedBodySubscriber implements HttpResponse.BodySubscriber {
+ private final int maxBytes;
+ private final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ private final CompletableFuture result = new CompletableFuture<>();
+ private Flow.Subscription subscription;
+
+ private LimitedBodySubscriber(int maxBytes) {
+ this.maxBytes = maxBytes;
+ }
+
+ @Override
+ public CompletionStage getBody() {
+ return result;
+ }
+
+ @Override
+ public void onSubscribe(Flow.Subscription subscription) {
+ this.subscription = subscription;
+ subscription.request(1);
+ }
+
+ @Override
+ public void onNext(List buffers) {
+ if (result.isDone()) return;
+ for (var buffer : buffers) {
+ if (buffer.remaining() > maxBytes - bytes.size()) {
+ subscription.cancel();
+ result.completeExceptionally(new IOException("image exceeds " + maxBytes + " bytes"));
+ return;
+ }
+ var chunk = new byte[buffer.remaining()];
+ buffer.get(chunk);
+ bytes.writeBytes(chunk);
+ }
+ subscription.request(1);
+ }
+
+ @Override
+ public void onError(Throwable failure) {
+ result.completeExceptionally(failure);
+ }
+
+ @Override
+ public void onComplete() {
+ if (!result.isDone()) result.complete(bytes.toByteArray());
+ }
+ }
+}
diff --git a/src/main/java/com/github/k7t3/tcv/app/image/ImageLoader.java b/src/main/java/com/github/k7t3/tcv/app/image/ImageLoader.java
new file mode 100644
index 0000000..bdd4b4e
--- /dev/null
+++ b/src/main/java/com/github/k7t3/tcv/app/image/ImageLoader.java
@@ -0,0 +1,81 @@
+package com.github.k7t3.tcv.app.image;
+
+import com.github.k7t3.tcv.lifecycle.CloseActions;
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.net.URI;
+import java.time.Duration;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Callable;
+import java.util.concurrent.Executor;
+
+/** URLと入力streamの画像を読み込み、未完了画像を所有する。executorは所有者から借用する。 */
+public final class ImageLoader implements AutoCloseable {
+ private final ImageDownloader downloader = new ImageDownloader(Duration.ofSeconds(15));
+ private final Executor executor;
+ private final Object lifecycle = new Object();
+ private final Set pending = ConcurrentHashMap.newKeySet();
+ private boolean closed;
+
+ /** @param executor FX スレッドとは別のスレッドで画像を処理する executor */
+ public ImageLoader(Executor executor) {
+ this.executor = Objects.requireNonNull(executor);
+ }
+
+ /**
+ * HTTP 画像の読み込みを開始する。FX スレッドから呼び出す。
+ * @param url 取得する HTTP または HTTPS の URL
+ * @param width 要求幅。0 の場合は元画像の幅
+ * @param height 要求高さ。0 の場合は元画像の高さ
+ * @return 読み込みの結果を観測する画像
+ * @throws IllegalStateException このサービスが終了している場合
+ */
+ public LazyImage load(String url, double width, double height) {
+ return decode(() -> new ByteArrayInputStream(downloader.download(URI.create(url))), width, height);
+ }
+
+ /**
+ * 借用executorで入力streamを開き、画像をデコードする。FXスレッドから呼び出す。
+ * @param input streamの提供元。取得したstreamは成功・失敗によらず閉じる
+ * @param width 要求幅。0の場合は元画像の幅
+ * @param height 要求高さ。0の場合は元画像の高さ
+ * @return FX上での反映と失敗・取消を観測する画像
+ * @throws IllegalStateException このサービスが終了している場合
+ */
+ public LazyImage decode(Callable input, double width, double height) {
+ synchronized (lifecycle) {
+ if (closed) throw new IllegalStateException("image loader is closed");
+ var image = new LazyImage(Objects.requireNonNull(input), width, height, executor);
+ if (closed) {
+ image.close();
+ return image;
+ }
+ pending.add(image);
+ image.completion().whenComplete((value, failure) -> pending.remove(image));
+ return image;
+ }
+ }
+
+ /**
+ * 未完了・UI反映待ちの画像を取り消し、HTTPクライアントを終了する。
+ * 借用executorは終了しない。入力streamの実処理の終了待ちはexecutorの所有者が行う。
+ */
+ @Override
+ public void close() {
+ final List owned;
+ synchronized (lifecycle) {
+ if (closed) return;
+ closed = true;
+ owned = List.copyOf(pending);
+ pending.clear();
+ }
+ CloseActions.runAll(
+ () -> CloseActions.runAll(owned.stream().map(image -> (Runnable) image::close).toArray(Runnable[]::new)),
+ downloader::close
+ );
+ }
+}
diff --git a/src/main/java/com/github/k7t3/tcv/app/image/LazyImage.java b/src/main/java/com/github/k7t3/tcv/app/image/LazyImage.java
index 8e14445..e0df58e 100644
--- a/src/main/java/com/github/k7t3/tcv/app/image/LazyImage.java
+++ b/src/main/java/com/github/k7t3/tcv/app/image/LazyImage.java
@@ -22,59 +22,104 @@
import javafx.scene.image.Image;
import java.io.InputStream;
+import java.util.Objects;
import java.util.concurrent.Callable;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionStage;
+import java.util.concurrent.Executor;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.atomic.AtomicBoolean;
/**
- * 非同期で遅延読み込みするイメージ
+ * 非同期で遅延読み込みするイメージ。構築とプロパティの参照は FX スレッドで行う。
+ * 所有者は不要になった時点で {@link #close()} を呼び、取消と遅延結果の破棄を要求する。
*/
-public class LazyImage {
+public class LazyImage implements AutoCloseable {
private final ReadOnlyObjectWrapper value = new ReadOnlyObjectWrapper<>();
+ private final AtomicBoolean closed = new AtomicBoolean();
+ private final CompletableFuture completion = new CompletableFuture<>();
+ private final LoadImageTask task;
+
+ /**
+ * 指定したバックグラウンド executor で読み込む。executor は借用し、このインスタンスでは終了しない。
+ * 提供元から受け取ったstreamは、デコードの成功・失敗によらず閉じる。
+ * @param callable 閉じる責任を移譲する stream の提供元
+ * @param requestWidth 要求幅。0 の場合は元画像の幅
+ * @param requestHeight 要求高さ。0 の場合は元画像の高さ
+ * @param executor FX スレッドとは別のスレッドで実行する executor
+ */
+ public LazyImage(Callable callable, double requestWidth, double requestHeight, Executor executor) {
+ this(new LoadImageTask(callable, requestWidth, requestHeight), executor);
+ }
+
+ private LazyImage(LoadImageTask task, Executor executor) {
+ this.task = task;
+ Objects.requireNonNull(executor);
+ task.onDone(image -> {
+ if (!closed.get()) {
+ value.set(image);
+ completion.complete(image);
+ }
+ });
+ task.setOnFailed(event -> {
+ if (!closed.get()) completion.completeExceptionally(task.getException());
+ });
+ task.setOnCancelled(event -> completion.cancel(false));
+ try {
+ executor.execute(task);
+ } catch (RejectedExecutionException failure) {
+ completion.completeExceptionally(failure);
+ task.cancel();
+ }
+ }
- public LazyImage(String url, double requestWidth, double requestHeight) {
- var task = new LoadImageTask(url, requestWidth, requestHeight);
- task.onDone(value::set).runAsync();
+ /**
+ * FX 上での反映後に成功し、取得の失敗または終了時の取消も通知する。
+ * 返す stage から読込を変更・取消することはできない。
+ * 取消の通知は close の呼び出しスレッドでも発生する。
+ * @return 画像の反映を観測する stage
+ */
+ public CompletionStage completion() {
+ return completion.minimalCompletionStage();
}
- public LazyImage(Callable callable, double requestWidth, double requestHeight) {
- var task = new LoadImageTask(callable, requestWidth, requestHeight);
- task.onDone(value::set).runAsync();
+ /** 任意のスレッドから読込の取消を要求する。繰り返し呼び出してもよく、表示済み画像は保持する。 */
+ @Override
+ public void close() {
+ if (closed.compareAndSet(false, true)) {
+ task.cancel();
+ completion.cancel(false);
+ }
}
public ReadOnlyObjectProperty valueProperty() { return value.getReadOnlyProperty(); }
public Image getValue() { return value.get(); }
- private static class LoadImageTask extends FXTask {
+ private static final class LoadImageTask extends FXTask {
- private final String url;
private final Callable inputCallable;
private final double requestWidth;
private final double requestHeight;
- public LoadImageTask(String url, double requestWidth, double requestHeight) {
- this(url, null, requestWidth, requestHeight);
- }
-
- public LoadImageTask(Callable callable, double requestWidth, double requestHeight) {
- this(null, callable, requestWidth, requestHeight);
- }
-
- private LoadImageTask(String url, Callable inputCallable, double requestWidth, double requestHeight) {
- this.url = url;
- this.inputCallable = inputCallable;
+ private LoadImageTask(Callable callable, double requestWidth, double requestHeight) {
+ this.inputCallable = callable;
this.requestWidth = requestWidth;
this.requestHeight = requestHeight;
}
@Override
protected Image call() throws Exception {
- if (url != null) {
- return new Image(url, requestWidth, requestHeight, true, true, false);
- } else {
- return new Image(inputCallable.call(), requestWidth, requestHeight, true, true);
+ try (var input = inputCallable.call()) {
+ return decoded(new Image(input, requestWidth, requestHeight, true, true));
}
}
+ private static Image decoded(Image image) throws Exception {
+ if (image.isError()) throw image.getException();
+ return image;
+ }
+
}
}
diff --git a/src/main/java/com/github/k7t3/tcv/app/main/MainViewModel.java b/src/main/java/com/github/k7t3/tcv/app/main/MainViewModel.java
index b10adae..38bafcf 100644
--- a/src/main/java/com/github/k7t3/tcv/app/main/MainViewModel.java
+++ b/src/main/java/com/github/k7t3/tcv/app/main/MainViewModel.java
@@ -17,24 +17,35 @@
package com.github.k7t3.tcv.app.main;
import com.github.k7t3.tcv.app.channel.ChannelViewModelRepository;
+import com.github.k7t3.tcv.app.auth.AuthenticatorViewModel;
import com.github.k7t3.tcv.app.channel.TwitchChannelListViewModel;
import com.github.k7t3.tcv.app.channel.TwitchChannelViewModel;
import com.github.k7t3.tcv.app.chat.ChatRoomContainerViewModel;
import com.github.k7t3.tcv.app.clip.PostedClipRepository;
import com.github.k7t3.tcv.app.model.AbstractViewModel;
-import com.github.k7t3.tcv.app.core.AppHelper;
+import com.github.k7t3.tcv.app.service.LiveStateNotificator;
+import com.github.k7t3.tcv.lifecycle.CloseActions;
import com.github.k7t3.tcv.app.event.ClientLoadedEvent;
import com.github.k7t3.tcv.app.event.LoginEvent;
import com.github.k7t3.tcv.app.event.LogoutEvent;
-import com.github.k7t3.tcv.app.group.ChannelGroupRepository;
-import com.github.k7t3.tcv.domain.channel.ChannelRepository;
-import com.github.k7t3.tcv.domain.event.EventSubscribers;
+import com.github.k7t3.tcv.app.event.SessionInvalidatedEvent;
+import com.github.k7t3.tcv.domain.auth.CredentialStore;
import javafx.beans.property.*;
import javafx.collections.ListChangeListener;
-
import java.util.stream.Collectors;
+import java.util.List;
+import java.util.Objects;
+import java.util.concurrent.CompletionException;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import com.github.k7t3.tcv.app.core.ClientSessions;
+import com.github.k7t3.tcv.domain.event.EventSubscribers;
+import javafx.application.Platform;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class MainViewModel extends AbstractViewModel {
+ private static final Logger LOGGER = LoggerFactory.getLogger(MainViewModel.class);
private static final int NORM_STREAM_TITLE_LENGTH = 20;
@@ -48,12 +59,39 @@ public class MainViewModel extends AbstractViewModel {
private final ChatRoomContainerViewModel chatContainer;
private final TwitchChannelListViewModel channelList;
private final PostedClipRepository clipRepository;
+ private AuthenticatorViewModel activeAuthenticator;
+ private final ClientSessions sessions;
+ private final EventSubscribers source;
+ private final Function authenticationFactory;
+ private final Consumer failures;
+ private final LiveStateNotificator liveNotificator;
+ private long sessionGeneration;
+ private long authenticationRequest;
+
+ /** 渡された子モデルを所有する。セッションと発行元は借用し、ここでは閉じない。 */
+ public MainViewModel(ClientSessions sessions, EventSubscribers source, ChannelViewModelRepository channelRepository,
+ ChatRoomContainerViewModel chatContainer, TwitchChannelListViewModel channelList,
+ PostedClipRepository clipRepository, LiveStateNotificator liveNotificator,
+ Function authenticationFactory, Consumer failures) {
+ this.sessions = Objects.requireNonNull(sessions);
+ this.source = Objects.requireNonNull(source);
+ this.authenticationFactory = Objects.requireNonNull(authenticationFactory);
+ this.failures = Objects.requireNonNull(failures);
+ this.channelRepository = Objects.requireNonNull(channelRepository);
+ this.chatContainer = Objects.requireNonNull(chatContainer);
+ this.channelList = Objects.requireNonNull(channelList);
+ this.clipRepository = Objects.requireNonNull(clipRepository);
+ this.liveNotificator = Objects.requireNonNull(liveNotificator);
+ try { initialize(); }
+ catch (RuntimeException | Error failure) { closeAfterConstructionFailure(failure); throw failure; }
+ }
- public MainViewModel(ChannelGroupRepository groupRepository) {
- channelRepository = new ChannelViewModelRepository(groupRepository);
- chatContainer = new ChatRoomContainerViewModel();
- channelList = new TwitchChannelListViewModel();
- clipRepository = new PostedClipRepository();
+ private void initialize() {
+ setEventSubscribers(source);
+ for (var child : List.of(channelRepository, chatContainer, channelList, clipRepository, liveNotificator)) {
+ child.setEventSubscribers(source);
+ child.delegateLifecycleToOwner();
+ }
// 選択しているチャンネルのライブ配信タイトルを正規化してフッターに表示するためのリスナ
channelList.getSelectedChannels().addListener(this::onChanged);
@@ -62,6 +100,9 @@ public MainViewModel(ChannelGroupRepository groupRepository) {
// ログイン時のイベント
subscribe(LoginEvent.class, this::onLogin);
+ subscribe(SessionInvalidatedEvent.class, event -> {
+ if (event.source() == sessions) detachSessionViews();
+ });
}
// 選択しているチャンネルの配信タイトルをフッターに表示するためのリスナ
@@ -90,38 +131,63 @@ private String normTitle(TwitchChannelViewModel channel) {
return title.substring(0, NORM_STREAM_TITLE_LENGTH);
}
- @Override
- public void subscribeEvents(EventSubscribers eventSubscribers) {
- // no-op
- }
-
private void onLogin(LoginEvent event) {
- var helper = AppHelper.getInstance();
- var twitch = helper.getTwitch();
- var publishers = helper.getPublishers();
-
- userName.bind(helper.userNameProperty());
- authorized.bind(helper.authorizedProperty());
-
- channelRepository.setRepository(new ChannelRepository(twitch, publishers));
+ var generation = ++sessionGeneration;
+ if (!isCurrentLogin(generation)) return;
+ userName.bind(sessions.userNameProperty());
+ if (!isCurrentLogin(generation)) return;
+ authorized.bind(sessions.authorizedProperty());
+ if (!isCurrentLogin(generation)) return;
+
+ channelRepository.setRepository(sessions.getChannelRepository());
+ if (!isCurrentLogin(generation)) return;
+ clipRepository.setSession(sessions.getTwitch());
+ if (!isCurrentLogin(generation)) return;
+ for (var child : List.of(channelRepository, chatContainer, channelList, clipRepository, liveNotificator)) {
+ if (!isCurrentLogin(generation)) return;
+ child.subscribeEvents(source);
+ }
channelRepository.loadAllAsync().onDone(() -> {
+ if (!isCurrentLogin(generation)) return;
var channels = channelRepository.getChannels();
// リポジトリがロードしたチャンネルをリストにバインド
channelList.bindChannels(channels);
// チャンネルがロードできたら完了イベントを発行
- publish(new ClientLoadedEvent());
+ if (isCurrentLogin(generation)) publish(new ClientLoadedEvent());
+ }).onFailure(failure -> {
+ if (isCurrentLogin(generation)) reportFailure(failure);
+ else LOGGER.debug("discarded initial-load failure from an ended session", failure);
});
// チャットに必要な部品をロード
- chatContainer.loadAsync();
+ if (isCurrentLogin(generation)) chatContainer.loadAsync();
}
+ private boolean isCurrentLogin(long generation) { return !isClosed() && sessionGeneration == generation; }
+
public void logout() {
- var helper = AppHelper.getInstance();
- helper.logoutAsync();
+ if (isClosed()) return;
+ sessions.logoutAsync(this::detachSessionViews).whenComplete((ignored, failure) -> {
+ if (failure == null) return;
+ var cause = failure instanceof CompletionException && failure.getCause() != null ? failure.getCause() : failure;
+ Platform.runLater(() -> {
+ if (isClosed()) LOGGER.error("logout failed during shutdown", cause);
+ else reportFailure(cause);
+ });
+ });
+ }
+
+ private void detachSessionViews() {
+ sessionGeneration++;
+ CloseActions.runAll(() -> CloseActions.runAll(
+ () -> { if (activeAuthenticator != null) activeAuthenticator.onLogout(); },
+ liveNotificator::onLogout, chatContainer::onLogout, channelList::onLogout, clipRepository::onLogout, channelRepository::onLogout),
+ () -> publish(new LogoutEvent()));
+ }
- publish(new LogoutEvent());
+ private void reportFailure(Throwable failure) {
+ failures.accept(failure);
}
public ChannelViewModelRepository getChannelRepository() {
@@ -140,14 +206,59 @@ public PostedClipRepository getClipRepository() {
return clipRepository;
}
+ public LiveStateNotificator getLiveNotificator() { return liveNotificator; }
+
+ private void closeAfterConstructionFailure(Throwable failure) {
+ try { close(); }
+ catch (RuntimeException | Error cleanupFailure) {
+ if (cleanupFailure != failure) failure.addSuppressed(cleanupFailure);
+ }
+ }
+
+ /** 既存の認証画面を閉じ、Main と寿命を共有する認証モデルを作成する。FX スレッドから呼び出す。 */
+ public AuthenticatorViewModel createAuthenticator(CredentialStore store) {
+ if (isClosed()) throw new IllegalStateException("main view model is closed");
+ var request = ++authenticationRequest;
+ var previous = activeAuthenticator;
+ activeAuthenticator = null;
+ if (previous != null) previous.close();
+ requireCurrentAuthentication(request, null);
+ var created = authenticationFactory.apply(store);
+ requireCurrentAuthentication(request, created);
+ activeAuthenticator = created;
+ return created;
+ }
+
+ private void requireCurrentAuthentication(long request, AuthenticatorViewModel created) {
+ if (isClosed() || request != authenticationRequest) {
+ var failure = new IllegalStateException(isClosed()
+ ? "main view model is closed" : "authentication request was superseded");
+ try { if (created != null) created.close(); }
+ catch (RuntimeException | Error cleanup) { if (cleanup != failure) failure.addSuppressed(cleanup); }
+ throw failure;
+ }
+ }
+
@Override
- public void onLogout() {
- // ログアウトはlogout()メソッド起点で行うためここでは何もしない
+ protected void onLoggedOut() {
+ // 終端済み Task の FX 成功・失敗イベントも、この時点で旧世代にする。
+ sessionGeneration++;
+ authenticationRequest++;
}
@Override
- public void close() {
- // no-op
+ protected void onClose() {
+ sessionGeneration++;
+ authenticationRequest++;
+ var authenticator = activeAuthenticator;
+ activeAuthenticator = null;
+ CloseActions.runAll(() -> {
+ if (authenticator != null) authenticator.close();
+ }, () -> { if (liveNotificator != null) liveNotificator.close(); },
+ () -> { if (chatContainer != null) chatContainer.close(); },
+ () -> { if (channelList != null) channelList.close(); },
+ () -> { if (clipRepository != null) clipRepository.close(); },
+ () -> { if (channelRepository != null) channelRepository.close(); });
}
// ******************** PROPERTIES ********************
diff --git a/src/main/java/com/github/k7t3/tcv/app/model/AbstractViewModel.java b/src/main/java/com/github/k7t3/tcv/app/model/AbstractViewModel.java
index b5b4fa3..52e7cfd 100644
--- a/src/main/java/com/github/k7t3/tcv/app/model/AbstractViewModel.java
+++ b/src/main/java/com/github/k7t3/tcv/app/model/AbstractViewModel.java
@@ -16,11 +16,19 @@
package com.github.k7t3.tcv.app.model;
-import com.github.k7t3.tcv.app.core.AppHelper;
+import com.github.k7t3.tcv.app.event.AppEvent;
import com.github.k7t3.tcv.app.event.LoginEvent;
import com.github.k7t3.tcv.app.event.LogoutEvent;
import com.github.k7t3.tcv.app.event.ShutdownEvent;
import com.github.k7t3.tcv.domain.event.EventSubscribers;
+import com.github.k7t3.tcv.lifecycle.CloseActions;
+import com.github.k7t3.tcv.reactive.FlowableSubscriber;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.function.Predicate;
/**
* ログイン時、ログアウト時、アプリケーションの終了時に処理が自動でトリガーするベースクラス
@@ -31,28 +39,241 @@
*/
public abstract class AbstractViewModel implements AppViewModel {
+ private final AtomicBoolean closed = new AtomicBoolean();
+ private final List registrations = new ArrayList<>();
+ private SessionSubscriptions session;
+ private EventSubscribers eventSubscribers;
+
+ private record Registration(Class extends AppEvent> type,
+ TypeSafeNotificationObserver> observer,
+ TypeSafeNotificationObserver> forwarding,
+ AtomicBoolean active,
+ SessionSubscriptions owner) {
+ }
+
protected final TypeSafeNotificationObserver onLogin = this::onLogin;
protected final TypeSafeNotificationObserver onLogout = this::onLogout;
protected final TypeSafeNotificationObserver onShutdown = this::onShutdown;
public AbstractViewModel() {
- subscribe(LoginEvent.class, onLogin);
- subscribe(LogoutEvent.class, onLogout);
- subscribe(ShutdownEvent.class, onShutdown);
+ try {
+ subscribe(LoginEvent.class, onLogin);
+ subscribe(LogoutEvent.class, onLogout);
+ subscribe(ShutdownEvent.class, onShutdown);
+ } catch (RuntimeException | Error failure) {
+ closed.set(true);
+ try {
+ // 子クラスは未構築なので、共通クラスが登録した通知だけを解放する。
+ removeRegistrations(registration -> true);
+ } catch (RuntimeException | Error cleanup) {
+ if (cleanup != failure) failure.addSuppressed(cleanup);
+ }
+ throw failure;
+ }
}
private void onLogin(LoginEvent loginEvent) {
- var helper = AppHelper.getInstance();
- var subscribers = helper.getSubscribers();
- subscribeEvents(subscribers);
+ if (eventSubscribers != null) subscribeEvents(eventSubscribers);
+ }
+
+ /**
+ * ログイン通知で Flow を開始するモデルへ、所有者の発行元を渡す。
+ * 未設定では Flow を開始しない。購読中の差し替えはログアウト後に行う。
+ */
+ public final void setEventSubscribers(EventSubscribers source) {
+ if (closed.get() || session != null) throw new IllegalStateException("cannot replace active event subscriptions");
+ eventSubscribers = Objects.requireNonNull(source);
+ }
+
+ /** 親が開始・ログアウト・終了を一度ずつ呼び出すモデルでは、既定の全体通知への接続を外す。 */
+ public final void delegateLifecycleToOwner() {
+ if (closed.get() || session != null) throw new IllegalStateException("cannot delegate an active lifecycle");
+ CloseActions.runAll(() -> unsubscribe(onLogin), () -> unsubscribe(onLogout), () -> unsubscribe(onShutdown));
+ }
+
+ @Override
+ public final void subscribeEvents(EventSubscribers eventSubscribers) {
+ final SessionSubscriptions opening;
+ synchronized (registrations) {
+ if (closed.get() || session != null) return;
+ opening = new SessionSubscriptions();
+ session = opening;
+ }
+ try {
+ onSubscribeEvents(eventSubscribers, opening);
+ } catch (RuntimeException | Error failure) {
+ try {
+ opening.close();
+ } catch (RuntimeException | Error cleanup) {
+ if (cleanup != failure) failure.addSuppressed(cleanup);
+ }
+ throw failure;
+ }
+ }
+
+ /**
+ * Flow とセッション中の通知を、渡された購読範囲へ登録する。
+ * 再入 logout / close 後も、この呼び出しには終了済みの同じ範囲が渡され続ける。
+ */
+ protected void onSubscribeEvents(EventSubscribers eventSubscribers, SessionSubscriptions subscriptions) {
}
private void onLogout(LogoutEvent logoutEvent) {
onLogout();
}
+ @Override
+ public final void onLogout() {
+ final SessionSubscriptions previous;
+ synchronized (registrations) {
+ if (closed.get()) return;
+ previous = session;
+ session = null;
+ }
+ CloseActions.runAll(() -> { if (previous != null) previous.close(); }, this::onLoggedOut);
+ }
+
+ /** セッションの購読を解除した後に実行するログアウト処理。 */
+ protected void onLoggedOut() {
+ }
+
private void onShutdown(ShutdownEvent shutdownEvent) {
close();
}
+ @Override
+ public final void subscribe(Class eventType, TypeSafeNotificationObserver observer) {
+ register(eventType, observer, null);
+ }
+
+ private void register(Class eventType, TypeSafeNotificationObserver observer,
+ SessionSubscriptions owner) {
+ Objects.requireNonNull(eventType);
+ Objects.requireNonNull(observer);
+ final Registration registration;
+ final TypeSafeNotificationObserver forwarding;
+ synchronized (registrations) {
+ if (owner != null && (closed.get() || owner.retired)) return;
+ if (closed.get()) throw new IllegalStateException("view model is closed");
+ var active = new AtomicBoolean(true);
+ forwarding = event -> {
+ if (!closed.get() && active.get()) observer.receivedNotification(event);
+ };
+ registration = new Registration(eventType, observer, forwarding, active, owner);
+ registrations.add(registration);
+ }
+ try {
+ AppViewModel.super.subscribe(eventType, forwarding);
+ // 登録先からの再入終了より後に戻った登録も、その場で解除する。
+ if (!registration.active().get()) AppViewModel.super.unsubscribe(forwarding);
+ } catch (RuntimeException | Error failure) {
+ synchronized (registrations) {
+ registration.active().set(false);
+ registrations.remove(registration);
+ }
+ try {
+ AppViewModel.super.unsubscribe(forwarding);
+ } catch (RuntimeException | Error cleanup) {
+ if (cleanup != failure) failure.addSuppressed(cleanup);
+ }
+ throw failure;
+ }
+ }
+
+ @Override
+ public final void unsubscribe(TypeSafeNotificationObserver observer) {
+ removeRegistrations(registration -> registration.observer() == observer);
+ }
+
+ @Override
+ public final void unsubscribe(Class eventType, TypeSafeNotificationObserver observer) {
+ removeRegistrations(registration -> registration.type() == eventType && registration.observer() == observer);
+ }
+
+ private void removeRegistrations(Predicate