diff --git a/AllServerForMac/App/Models/NavigationSelection.swift b/AllServerForMac/App/Models/NavigationSelection.swift index 7ec82f9..0314016 100644 --- a/AllServerForMac/App/Models/NavigationSelection.swift +++ b/AllServerForMac/App/Models/NavigationSelection.swift @@ -4,9 +4,14 @@ import Foundation enum NavigationSelection: Hashable { case home case favorites + /// 途中でやめた動画だけを、最後に再生した順に並べる画面。 + /// ブラウザ UI の「続きを見る」タブと同じ中身(保管庫が `/sync` で共有されているため)。 + case continueWatching case history case trash case sceneExtraction + /// 動画・画像のアルバムを表紙つきで一覧するページ。 + case albums case album(UUID) /// アルバム名の "/" 区切りで表現されるフォルダ。実体を持たないためIDではなく /// パス文字列で指す。動画ツリーと画像ツリーは別建てで同名フォルダが両立しうるので、 diff --git a/AllServerForMac/App/Views/ContentView.swift b/AllServerForMac/App/Views/ContentView.swift index 543cdbf..b5c4300 100644 --- a/AllServerForMac/App/Views/ContentView.swift +++ b/AllServerForMac/App/Views/ContentView.swift @@ -7,9 +7,9 @@ struct ContentView: View { @ObservedObject private var dataManager: LibraryViewModel @ObservedObject private var playbackCoordinator: PlaybackCoordinator @ObservedObject private var appSettings: AppSettings - private let sidebarMinWidth: CGFloat = 300 - private let sidebarIdealWidth: CGFloat = 320 - private let sidebarMaxWidth: CGFloat = 360 + /// サイドバーの幅。行の幅(253)に左右の余白(10×2)とスクロールバーの分(15)を足した値で、行は固定幅で組んである。 + private let sidebarWidth: CGFloat = 288 + @State private var isSidebarVisible = true init() { let viewModel = AppViewModel() @@ -38,8 +38,14 @@ struct ContentView: View { // ライブラリ画面を外した瞬間に素の(=黒い)ウィンドウ背景が覗かないよう、 // 常駐する下地を1枚敷いておく。上端の黒帯対策の要はこの下地とウィンドウ設定であって、 // ライブラリ画面を出しっぱなしにすることではない。 - NeomorphicTheme.background + if shouldShowLibraryView { + // デスクトップが透けるガラス地はやめ、単色の下地にする(色の濁りと環境による見た目の差をなくす)。 + NeomorphicTheme.canvas + .id(appSettings.neomorphicDarkBase) .ignoresSafeArea() + } else { + Color.black.ignoresSafeArea() + } if let error = dataManager.storageInitializationError { LibraryStorageInitializationErrorView(error: error) @@ -66,7 +72,8 @@ struct ContentView: View { // ウィンドウのクロム設定はライブラリ画面の有無に関わらず効かせる必要があるため、 // ライブラリ画面ではなくこの常駐の階層に付ける。 .toolbar(isToolbarHidden ? .hidden : .automatic, for: .windowToolbar) - .toolbarBackground(NeomorphicTheme.background, for: .windowToolbar) + // タイトルバーの帯はサイドバーと同じ色にし、窓の上端でサイドバーと一続きに見せる。 + .toolbarBackground(NeomorphicTheme.sidebar, for: .windowToolbar) .toolbarBackground( isToolbarHidden ? .hidden : .visible, for: .windowToolbar @@ -157,13 +164,12 @@ struct ContentView: View { : .normal, onClose: playbackCoordinator.closeVariantFinder ) - .background(.regularMaterial) + .appSheet() .clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous)) .overlay( RoundedRectangle(cornerRadius: 14, style: .continuous) - .strokeBorder(.white.opacity(0.14), lineWidth: 1) + .strokeBorder(NeomorphicTheme.cardBorder, lineWidth: 0.5) ) - .shadow(color: .black.opacity(0.42), radius: 28, y: 12) .id("\(albumID.uuidString)-\(String(describing: playbackCoordinator.variantFinderAlignmentMode))") } } @@ -190,9 +196,13 @@ struct ContentView: View { currentVideo: current, dataManager: dataManager, watchState: viewModel.watchState, - settings: viewModel.playbackSettings + settings: viewModel.playbackSettings, + initialStartTime: playbackCoordinator.singleStartTime ) .id(current.id) + case .tour(let session): + PlaybackTourView(session: session, dataManager: dataManager) + .id(session.id) case .multi(let videos): MultiVideoPlayerView(videos: videos, dataManager: dataManager) .ignoresSafeArea() @@ -227,20 +237,46 @@ struct ContentView: View { // ツールバーの背後まで同じ背景を広げ,フルスクリーン時の色の段差をなくす。 CommandDeckBackground() - NavigationSplitView { - MainSidebarView( + // 標準の NavigationSplitView は macOS 26 でサイドバーが「浮いた角丸のガラス」になり、 + // 窓の端や上下に余白ができて平らにできない。そこで左カラムを自前で組み、窓の端から端まで + // 単色で伸ばす(タイトルバーの帯もサイドバーと同じ色にして、一続きに見せる)。 + HStack(spacing: 0) { + // 左端のアイコンのレール。サイドバーを隠しても残り、主要な行き先と設定へいつでも移れる。 + SidebarRailView( dataManager: dataManager, - webServerManager: viewModel.webServerManager, + watchState: viewModel.watchState, selection: $viewModel.selection, - isShowingPreferences: $viewModel.isShowingPreferences, - isShowingStorageManager: $viewModel.isShowingStorageManager + allVideosAlbumID: dataManager.albums.first { $0.name == LibraryViewModel.allVideosAlbumName }?.id, + allPhotosAlbumID: dataManager.albums.first { $0.name == LibraryViewModel.allPhotosAlbumName }?.id, + onShowStorage: { viewModel.isShowingStorageManager = true }, + onShowPreferences: { viewModel.isShowingPreferences = true } ) - .navigationSplitViewColumnWidth( - min: sidebarMinWidth, - ideal: sidebarIdealWidth, - max: sidebarMaxWidth + .background(NeomorphicTheme.rail.ignoresSafeArea()) + .overlay(alignment: .trailing) { + Rectangle() + .fill(NeomorphicTheme.separator) + .frame(width: 0.5) + .ignoresSafeArea() + } + + if isSidebarVisible { + MainSidebarView( + dataManager: dataManager, + webServerManager: viewModel.webServerManager, + selection: $viewModel.selection ) - } detail: { + .frame(width: sidebarWidth) + .frame(maxHeight: .infinity) + .background(NeomorphicTheme.sidebar.ignoresSafeArea()) + .overlay(alignment: .trailing) { + Rectangle() + .fill(NeomorphicTheme.separator) + .frame(width: 0.5) + .ignoresSafeArea() + } + .transition(.move(edge: .leading)) + } + NavigationStack { switch viewModel.selection { case .home: @@ -256,6 +292,13 @@ struct ContentView: View { onAnalyzeScenes: viewModel.openSceneExtraction ) .navigationTitle("お気に入り") + case .continueWatching: + LibraryCategoryView( + kind: .continueWatching, + dataManager: dataManager, + onAnalyzeScenes: viewModel.openSceneExtraction + ) + .navigationTitle("続きを見る") case .history: LibraryCategoryView( kind: .history, @@ -275,6 +318,12 @@ struct ContentView: View { viewModel: viewModel.sceneExtraction, onClose: viewModel.closeSceneExtraction ) + case .albums: + AlbumOverviewView( + dataManager: dataManager, + selection: $viewModel.selection + ) + .navigationTitle("アルバム一覧") case .album(let albumID): if let album = dataManager.albums.first( where: { $0.id == albumID } @@ -284,7 +333,7 @@ struct ContentView: View { dataManager: dataManager, onAnalyzeScenes: viewModel.openSceneExtraction ) - .navigationTitle(album.name) + .navigationTitle(album.displayTitle) } else { ContentUnavailableView("アルバムが見つかりません", systemImage: "questionmark.folder") } @@ -301,6 +350,30 @@ struct ContentView: View { ContentUnavailableView("サイドバーから項目を選択してください", systemImage: "sidebar.left") } } + // ツールバーのメニューだけがアクセントの青になり、ボタンの中立色とちぐはぐに見えるので、 + // 内容側(ツールバー含む)の色味は文字色にそろえる。ホームは自分でアクセントを指定している。 + .tint(NeomorphicTheme.ink) + // ページ見出しと同じ文字がタイトルバーにも出て重複するので、ツールバーのタイトルは外す + // (ウィンドウ自体のタイトルは残るので、Mission Control などでは識別できる)。 + .toolbar(removing: .title) + // タイトルを外すと、右寄せだった各画面のボタンが左へ詰まるので、中央に伸びる空きを置いて右側に戻す。 + .toolbar { principalSpacer } + // 標準の分割表示が確保していたツールバーの下の余白を、自前の構成でも同じだけ空ける。 + .safeAreaInset(edge: .top, spacing: 0) { + Color.clear.frame(height: 44) + } + } + .toolbar { + ToolbarItemGroup(placement: .navigation) { + Button { + withAnimation(.easeInOut(duration: 0.2)) { isSidebarVisible.toggle() } + } label: { + Label("サイドバー", systemImage: "sidebar.leading") + } + .keyboardShortcut("s", modifiers: [.command, .control]) + .help(isSidebarVisible ? "サイドバーを隠す(⌃⌘S)" : "サイドバーを表示(⌃⌘S)") + + } } } // tint / preferredColorScheme / toolbarBackground / WindowChromeConfigurator は @@ -312,6 +385,21 @@ struct ContentView: View { .id(appSettings.neomorphicDarkBase) } + /// ツールバーの中央に伸びる透明な空き。macOS 26 では部品ごとに丸い背景が付くので、その背景は消す。 + @ToolbarContentBuilder + private var principalSpacer: some ToolbarContent { + if #available(macOS 26.0, *) { + ToolbarItem(placement: .principal) { + Color.clear.frame(minWidth: 40, maxWidth: .infinity, minHeight: 1) + } + .sharedBackgroundVisibility(.hidden) + } else { + ToolbarItem(placement: .principal) { + Color.clear.frame(minWidth: 40, maxWidth: .infinity, minHeight: 1) + } + } + } + private var appMenuContext: AppMenuContext { AppMenuContext( isLibraryLoaded: dataManager.isLibraryLoaded, @@ -394,7 +482,7 @@ private struct LibraryStorageInitializationErrorView: View { VStack(spacing: 8) { Text("ライブラリ保存先を準備できませんでした") - .font(.title2.bold()) + .font(.appTitle.bold()) Text("データを保護するため,ライブラリの読み込みとサーバー起動を停止しています.") .foregroundStyle(.secondary) .multilineTextAlignment(.center) @@ -408,7 +496,7 @@ private struct LibraryStorageInitializationErrorView: View { } .padding(20) .frame(maxWidth: 680, alignment: .leading) - .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 16)) + .background(NeomorphicTheme.card, in: RoundedRectangle(cornerRadius: 16, style: .continuous)) HStack(spacing: 12) { Button { @@ -434,7 +522,7 @@ private struct LibraryStorageInitializationErrorView: View { private func errorRow(title: String, value: String) -> some View { VStack(alignment: .leading, spacing: 4) { Text(title) - .font(.caption.weight(.semibold)) + .font(.appCaption.weight(.semibold)) .foregroundStyle(.secondary) Text(value) .textSelection(.enabled) diff --git a/AllServerForMac/App/Views/WindowChromeConfigurator.swift b/AllServerForMac/App/Views/WindowChromeConfigurator.swift index 18006e7..4a35bd9 100644 --- a/AllServerForMac/App/Views/WindowChromeConfigurator.swift +++ b/AllServerForMac/App/Views/WindowChromeConfigurator.swift @@ -34,9 +34,9 @@ final class WindowChromeView: NSView { window.appearance = NSAppearance( named: NeomorphicTheme.isDarkBase ? .darkAqua : .aqua ) - window.backgroundColor = NeomorphicTheme.isDarkBase - ? NSColor(red: 0.08, green: 0.085, blue: 0.09, alpha: 1.0) - : NSColor(red: 0.89, green: 0.92, blue: 0.93, alpha: 1.0) + // 下地は単色なので、透過ウィンドウにはしない(角の表示も安定する)。 + window.isOpaque = true + window.backgroundColor = NSColor(NeomorphicTheme.canvas) window.toolbarStyle = .unifiedCompact window.toolbar?.isVisible = !isToolbarHidden } diff --git a/AllServerForMac/Common/DesignSystem/DesignSystem.swift b/AllServerForMac/Common/DesignSystem/DesignSystem.swift index 6eba1a8..435cc7c 100644 --- a/AllServerForMac/Common/DesignSystem/DesignSystem.swift +++ b/AllServerForMac/Common/DesignSystem/DesignSystem.swift @@ -1,71 +1,165 @@ import AppKit import SwiftUI +// MARK: - 文字サイズの階層 + +/// アプリ全体の文字サイズの段階。システム標準の `.caption`(macOS では 10pt)は小さすぎて読みにくいので使わず、 +/// 画面ごとにばらついていた指定を、次の 6 段階にそろえる。強弱は太さ(.weight)で足す。 +/// +/// | 名前 | pt | 用途 | +/// |---------------|----|----------------------------------------| +/// | appMicro | 11 | バッジ・単位・時刻などの補足 | +/// | appCaption | 12 | 説明文・2 行目・ラベル | +/// | appBody | 13 | 本文・行・ボタン | +/// | appHeadline | 15 | カードの見出し | +/// | appTitle | 17 | シート・パネルの見出し | +/// | appLargeTitle | 26 | ページの見出し(LibraryPageHeader) | +extension Font { + static let appMicro = Font.system(size: 11) + static let appCaption = Font.system(size: 12) + static let appBody = Font.system(size: 13) + static let appHeadline = Font.system(size: 15, weight: .semibold) + static let appTitle = Font.system(size: 17, weight: .semibold) + static let appLargeTitle = Font.system(size: 26, weight: .bold) +} + // MARK: - デザイントークン enum DS { - static let cardCornerRadius: CGFloat = 8 - static let cardPadding: CGFloat = 18 - static let cardSpacing: CGFloat = 18 - static let cyan = Color(red: 0.18, green: 0.86, blue: 1.0) - static let violet = Color(red: 0.52, green: 0.42, blue: 1.0) - static let lime = Color(red: 0.42, green: 1.0, blue: 0.63) - static let signalRed = Color(red: 1.0, green: 0.19, blue: 0.18) - static let signalAmber = Color(red: 1.0, green: 0.65, blue: 0.16) - static let tallyGreen = Color(red: 0.49, green: 0.9, blue: 0.13) - static let surface = Color.black - static let surfaceRaised = Color(white: 0.028) + static let cardCornerRadius: CGFloat = 16 + static let cardPadding: CGFloat = 20 + static let cardSpacing: CGFloat = 20 } -/// ネオモーフィズムのベースカラー。設定「外観」のトグルで白ベース⇄黒ベースを切り替える。 -/// 色の値だけを差し替え、レイアウトやシャドウの構造は白ベースと完全に共通のまま保つ。 -/// 単一の真実の source として UserDefaults を直接読むことで、AppSettings を経由できない -/// 静的な色参照(CommandDeckBackground など)や AppKit 側(NSColor)からも常に同じ値を得る。 -/// トグル時の一貫した再描画は ContentView 側の `.id()` による作り直しで保証している。 +/// ガラス風テーマの色です.既存の外観設定キーを引き継ぎます. +/// 静的な色参照とAppKitのウィンドウ外観を同じ設定に揃えます. enum NeomorphicTheme { static let darkBaseDefaultsKey = "appearance.neomorphicDarkBase" + /// 未設定のときは黒基調。動画・画像が主役のアプリなので、作品の色が映える暗い下地を既定にする。 static var isDarkBase: Bool { - UserDefaults.standard.bool(forKey: darkBaseDefaultsKey) + UserDefaults.standard.object(forKey: darkBaseDefaultsKey) as? Bool ?? true } - static var background: Color { - isDarkBase ? Color(red: 0.08, green: 0.085, blue: 0.09) : Color(red: 0.89, green: 0.92, blue: 0.93) + // 配色の考え方:色味のない中立のグレーだけで面を作り、強弱は面の明るさと文字の濃淡でつける。 + // 色(アクセント)は、主要ボタン・スイッチ・選択中の枠のような「操作の目印」にだけ使う。 + + /// 内容側の下地。 + static var canvas: Color { + isDarkBase ? Color(white: 0.105) : Color(white: 0.965) + } + /// サイドバー・カードの面。下地よりわずかに明るい(黒基調)/白(明るい側)。 + static var sidebar: Color { + isDarkBase ? Color(white: 0.150) : Color(white: 0.925) + } + /// サイドバーの左に並ぶアイコンのレール。サイドバーより一段暗くして、2列を重ねて見せる。 + static var rail: Color { + isDarkBase ? Color(white: 0.125) : Color(white: 0.895) + } + static var card: Color { + isDarkBase ? Color(white: 0.150) : Color.white + } + /// 入力欄・検索欄・セグメントのような、面の上に置く操作部品の地。 + static var control: Color { + isDarkBase ? Color.white.opacity(0.085) : Color.black.opacity(0.055) + } + /// セグメントの選ばれている側。地(control)より一段はっきりさせる。 + static var controlSelected: Color { + isDarkBase ? Color.white.opacity(0.17) : Color.white + } + static var cardBorder: Color { + isDarkBase ? Color.white.opacity(0.06) : Color.black.opacity(0.07) } + static var background: Color { canvas } static var surface: Color { - isDarkBase ? Color(red: 0.14, green: 0.15, blue: 0.16) : Color(red: 0.91, green: 0.93, blue: 0.93) + isDarkBase ? Color.white.opacity(0.06) : Color.black.opacity(0.04) } static var ink: Color { - isDarkBase ? Color(red: 0.90, green: 0.92, blue: 0.93) : Color(red: 0.16, green: 0.18, blue: 0.19) + isDarkBase ? Color(white: 0.93) : Color(white: 0.10) } static var muted: Color { - isDarkBase ? Color(red: 0.60, green: 0.64, blue: 0.66) : Color(red: 0.48, green: 0.52, blue: 0.54) + isDarkBase ? Color(white: 0.62) : Color(white: 0.42) } static var accent: Color { - Color(red: 0.14, green: 0.59, blue: 0.66) + isDarkBase ? Color(red: 0.33, green: 0.60, blue: 1.0) : Color(red: 0.0, green: 0.40, blue: 0.92) + } + static var separator: Color { + isDarkBase ? Color.white.opacity(0.08) : Color.black.opacity(0.08) + } + /// 選択中の行・セグメント。色を付けず、面を一段明るく(暗く)するだけにする。 + static var selection: Color { + isDarkBase ? Color.white.opacity(0.11) : Color.black.opacity(0.08) + } + static var hover: Color { + isDarkBase ? Color.white.opacity(0.06) : Color.black.opacity(0.045) } static var shadow: Color { - isDarkBase ? Color(red: 0.0, green: 0.0, blue: 0.0) : Color(red: 0.62, green: 0.67, blue: 0.69) + Color.black.opacity(isDarkBase ? 0.5 : 0.12) + } + /// 稼働中・許可の目印(状態ドットと同じ落ち着いた緑) + static let online = Color(red: 0.30, green: 0.78, blue: 0.45) + /// 拒否・削除・エラーの目印(ハートや破壊的な操作と同じ赤) + static let negative = Color(red: 1.0, green: 0.27, blue: 0.23) + /// 「どちらとも言えない」「注意」の目印(強い黄・橙ではなく、落ち着いた琥珀) + static let caution = Color(red: 0.96, green: 0.68, blue: 0.22) +} + +// MARK: - 見出しつきのカード + +/// 標準の GroupBox の代わりに使う、平らなカード。見出しは控えめな文字だけで、枠や色は付けない。 +struct SectionCard: View { + let title: String + @ViewBuilder var content: Content + + var body: some View { + VStack(alignment: .leading, spacing: 10) { + Text(title) + .font(.system(size: 13, weight: .semibold)) + .foregroundStyle(NeomorphicTheme.muted) + content + } + .padding(14) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + .background(GlassCardSurface()) + } +} + +// MARK: - シート共通 + +extension View { + /// シートの下地を、アプリ本体と同じ中立の単色にそろえる。 + /// 何も指定しないと OS 標準の半透明になり、デスクトップの色で青や緑に濁る。 + func appSheet() -> some View { + self + .foregroundStyle(NeomorphicTheme.ink) + .background(NeomorphicTheme.canvas) + .tint(NeomorphicTheme.accent) } } -struct NeomorphicWavePattern: Shape { - func path(in rect: CGRect) -> Path { - var path = Path() - let lineCount = 22 - for index in 0..: View { + let options: [Option] + let title: (Option) -> String + @Binding var selection: Option + let width: CGFloat + var body: some View { - ZStack { - NeomorphicTheme.background - - NeomorphicWavePattern() - .stroke(Color.white.opacity(0.48), lineWidth: 1) - .frame(width: 540, height: 260) - .offset(x: -300, y: -240) - - NeomorphicWavePattern() - .stroke(Color(red: 0.72, green: 0.79, blue: 0.83).opacity(0.38), lineWidth: 1) - .frame(width: 700, height: 340) - .rotationEffect(.degrees(8)) - .offset(x: 330, y: 270) + let inner = width - 4 + let segment = inner / CGFloat(max(options.count, 1)) + HStack(spacing: 0) { + ForEach(options, id: \.self) { option in + let isSelected = option == selection + Button { + selection = option + } label: { + Text(title(option)) + .font(.system(size: 12, weight: .medium)) + .foregroundStyle(isSelected ? NeomorphicTheme.ink : NeomorphicTheme.muted) + .frame(width: segment, height: 24) + .background( + RoundedRectangle(cornerRadius: 6, style: .continuous) + .fill(isSelected ? NeomorphicTheme.controlSelected : Color.clear) + ) + .contentShape(RoundedRectangle(cornerRadius: 6, style: .continuous)) + } + .buttonStyle(.plain) + } } - .ignoresSafeArea() - .allowsHitTesting(false) + .padding(2) + .frame(width: width) + .background(RoundedRectangle(cornerRadius: 8, style: .continuous).fill(NeomorphicTheme.control)) } } @@ -103,16 +270,7 @@ struct CardBackground: ViewModifier { func body(content: Content) -> some View { content .padding(DS.cardPadding) - .background( - RoundedRectangle(cornerRadius: DS.cardCornerRadius, style: .continuous) - .fill(NeomorphicTheme.surface) - .shadow(color: .white.opacity(0.9), radius: isHovering ? 10 : 7, x: -6, y: -6) - .shadow(color: NeomorphicTheme.shadow.opacity(isHovering ? 0.36 : 0.28), radius: isHovering ? 16 : 11, x: 8, y: 8) - ) - .overlay( - RoundedRectangle(cornerRadius: DS.cardCornerRadius, style: .continuous) - .strokeBorder(.white.opacity(isHovering ? 0.76 : 0.58), lineWidth: 1) - ) + .background(GlassCardSurface(isHovering: isHovering)) .animation(.easeOut(duration: 0.18), value: isHovering) .onHover { isHovering = $0 } } @@ -134,14 +292,18 @@ struct CardHeader: View { var body: some View { HStack(spacing: 10) { - IconTile(icon: icon, tint: tint) + // 角丸のタイルで囲まず、アイコンだけを置く(カードごとに青いタイルが並ぶとテンプレート然として見えるため)。 + Image(systemName: icon) + .font(.system(size: 16, weight: .regular)) + .foregroundStyle(NeomorphicTheme.muted) + .frame(width: 24, height: 24) VStack(alignment: .leading, spacing: 1) { Text(title) - .font(.system(size: 13, weight: .bold, design: .rounded)) + .font(.system(size: 15, weight: .semibold)) .foregroundStyle(NeomorphicTheme.ink) if let subtitle { Text(subtitle) - .font(.system(size: 10, weight: .medium, design: .rounded)) + .font(.system(size: 12)) .foregroundStyle(NeomorphicTheme.muted) } } @@ -156,19 +318,17 @@ struct IconTile: View { var size: CGFloat = 26 var body: some View { - RoundedRectangle(cornerRadius: 3, style: .continuous) - .fill(NeomorphicTheme.surface) + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(tint.opacity(0.10)) .frame(width: size, height: size) - .shadow(color: .white.opacity(0.9), radius: 3, x: -2, y: -2) - .shadow(color: NeomorphicTheme.shadow.opacity(0.24), radius: 5, x: 3, y: 3) .overlay( safeSystemImage(named: icon) .font(.system(size: size * 0.5, weight: .semibold)) .foregroundStyle(tint) ) .overlay( - RoundedRectangle(cornerRadius: 3, style: .continuous) - .strokeBorder(.white.opacity(0.64), lineWidth: 1) + RoundedRectangle(cornerRadius: 8, style: .continuous) + .strokeBorder(tint.opacity(0.12), lineWidth: 1) ) } @@ -193,16 +353,15 @@ struct StatusDot: View { ZStack { if active { Circle() - .fill(Color.green.opacity(0.35)) + .fill(Color(red: 0.30, green: 0.78, blue: 0.45).opacity(0.35)) .frame(width: 16, height: 16) .scaleEffect(pulse ? 1.6 : 0.8) .opacity(pulse ? 0 : 0.8) .animation(.easeOut(duration: 1.4).repeatForever(autoreverses: false), value: pulse) } Circle() - .fill(active ? Color.green : Color.secondary.opacity(0.5)) + .fill(active ? Color(red: 0.30, green: 0.78, blue: 0.45) : Color.secondary.opacity(0.5)) .frame(width: 9, height: 9) - .shadow(color: active ? .green.opacity(0.6) : .clear, radius: 3) } .frame(width: 18, height: 18) .onAppear { pulse = active } @@ -219,13 +378,33 @@ struct SettingRow: View { var body: some View { HStack { Text(label) - .font(.system(size: 12)) + .font(.system(size: 13)) Spacer() content } } } +/// ラベルを左、スイッチを右端に置く設定行(macOS のシステム設定と同じ並び)。 +/// スイッチをラベルのすぐ隣に置くと、行ごとに位置がばらついて見える。 +struct SettingToggleRow: View { + let title: String + @Binding var isOn: Bool + + var body: some View { + HStack { + Text(title) + .font(.system(size: 13)) + Spacer(minLength: 12) + Toggle("", isOn: $isOn) + .labelsHidden() + .toggleStyle(.switch) + .controlSize(.small) + } + .contentShape(Rectangle()) + } +} + // MARK: - コピー可能なテキスト(クリックでコピー、フィードバック付き) struct CopyableText: View { @@ -269,7 +448,7 @@ struct ProminentActionButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { configuration.label - .font(.system(size: 13, weight: .bold, design: .rounded)) + .font(.system(size: 15, weight: .semibold)) .foregroundStyle(.white) .padding(.horizontal, 22) .padding(.vertical, 9) @@ -305,7 +484,7 @@ struct StatPill: View { .foregroundStyle(.secondary) VStack(alignment: .leading, spacing: 0) { Text(label) - .font(.system(size: 9)) + .font(.system(size: 11)) .foregroundStyle(.secondary) Text(value) .font(.system(size: 12, weight: .semibold)) @@ -316,7 +495,24 @@ struct StatPill: View { .padding(.horizontal, 10) .padding(.vertical, 6) .background( - Capsule().fill(DS.cyan.opacity(0.1)) + Capsule().fill(NeomorphicTheme.accent.opacity(0.1)) ) } } + +// MARK: - 入力欄の自動選択を外す + +/// 置かれたウィンドウの最初の入力欄の自動選択を,表示直後に一度だけ外す。 +struct InitialFirstResponderClearer: NSViewRepresentable { + func makeNSView(context: Context) -> ClearerView { ClearerView() } + func updateNSView(_ nsView: ClearerView, context: Context) {} + + final class ClearerView: NSView { + override func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + guard let window else { return } + // AppKit が初期の first responder を決めるのはウィンドウが key になった後なので,次のループで外す。 + DispatchQueue.main.async { window.makeFirstResponder(nil) } + } + } +} diff --git a/AllServerForMac/Common/Utilities/ImageAnalysisUtilities.swift b/AllServerForMac/Common/Utilities/ImageAnalysisUtilities.swift index b47086b..575c816 100644 --- a/AllServerForMac/Common/Utilities/ImageAnalysisUtilities.swift +++ b/AllServerForMac/Common/Utilities/ImageAnalysisUtilities.swift @@ -1,4 +1,7 @@ +import AVFoundation import CoreGraphics +import CoreVideo +import Foundation // MARK: - Shared Utilities @@ -22,3 +25,172 @@ nonisolated func isImagePredominantlyBlack(image: CGImage, threshold: CGFloat = } return Double(darkPixelCount) / Double(size * size) > 0.8 } + +nonisolated enum LoopBlackFrameAnalysisError: LocalizedError { + case invalidDuration + case cannotReadFrames(String) + case unsupportedPixelBuffer + + var errorDescription: String? { + switch self { + case .invalidDuration: + return "動画の長さを取得できませんでした." + case .cannotReadFrames(let reason): + return "黒画面の解析用フレームを読み取れませんでした.\(reason)" + case .unsupportedPixelBuffer: + return "黒画面の解析に必要な画素形式を取得できませんでした." + } + } +} + +/// 端から連続する黒フレームだけを調べ,中間の暗転を含む再生範囲を返します. +nonisolated struct LoopBlackFrameAnalyzer: Sendable { + private let tailWindowSeconds: TimeInterval = 2 + private let fallbackFramesPerSecond: Float = 30 + private static let sampleWidth = 160 + private static let sampleHeight = 90 + private static let maximumBlackComponent: UInt8 = 8 + private static let minimumBlackPixelRatio = 0.995 + + func analyze(asset: AVAsset) async throws -> CMTimeRange? { + try Task.checkCancellation() + guard let track = try await asset.loadTracks(withMediaType: .video).first else { + return nil + } + let duration = try await asset.load(.duration) + guard duration.seconds.isFinite, duration.seconds > 0 else { + throw LoopBlackFrameAnalysisError.invalidDuration + } + let frameRate = try await track.load(.nominalFrameRate) + let fallbackFrameDuration = CMTime( + seconds: 1 / Double(frameRate.isFinite && frameRate > 0 ? frameRate : fallbackFramesPerSecond), + preferredTimescale: 60_000 + ) + let head = try scan( + asset: asset, track: track, + range: CMTimeRange(start: .zero, duration: duration), + fallbackFrameDuration: fallbackFrameDuration, + stopsAtFirstVisibleFrame: true + ) + // 全編が黒い動画は,有効な再生区間を作れないため省略しません. + guard let start = head.firstVisibleTime else { return nil } + + let window = CMTime(seconds: tailWindowSeconds, preferredTimescale: 60_000) + var windowEnd = duration + while CMTimeCompare(windowEnd, start) > 0 { + try Task.checkCancellation() + let windowStart = CMTimeMaximum(start, CMTimeSubtract(windowEnd, window)) + let tail = try scan( + asset: asset, track: track, + range: CMTimeRange(start: windowStart, end: windowEnd), + fallbackFrameDuration: fallbackFrameDuration, + stopsAtFirstVisibleFrame: false + ) + if let lastVisibleEnd = tail.lastVisibleEnd { + let end = CMTimeMinimum(lastVisibleEnd, duration) + guard CMTimeCompare(end, start) > 0 else { return nil } + return CMTimeRange(start: start, end: end) + } + windowEnd = windowStart + } + return nil + } + + private struct EdgeFrames { + var firstVisibleTime: CMTime? + var lastVisibleEnd: CMTime? + } + + /// 末尾は短い区間を後ろから順に読み,長い本編の全フレーム解析を避けます. + private func scan( + asset: AVAsset, + track: AVAssetTrack, + range: CMTimeRange, + fallbackFrameDuration: CMTime, + stopsAtFirstVisibleFrame: Bool + ) throws -> EdgeFrames { + try Task.checkCancellation() + let reader = try AVAssetReader(asset: asset) + reader.timeRange = range + let output = AVAssetReaderTrackOutput(track: track, outputSettings: [ + kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA + ]) + output.alwaysCopiesSampleData = false + guard reader.canAdd(output) else { + throw LoopBlackFrameAnalysisError.cannotReadFrames("映像出力を追加できませんでした.") + } + reader.add(output) + guard reader.startReading() else { + throw LoopBlackFrameAnalysisError.cannotReadFrames( + reader.error?.localizedDescription ?? "読み取りを開始できませんでした." + ) + } + defer { reader.cancelReading() } + + var frames = EdgeFrames() + var previousFrameWasVisible = false + while let sample = output.copyNextSampleBuffer() { + try Task.checkCancellation() + let time = CMSampleBufferGetPresentationTimeStamp(sample) + guard time.seconds.isFinite else { + throw LoopBlackFrameAnalysisError.cannotReadFrames("フレームの時刻が不正です.") + } + // 次のフレームの実時刻を使い,可変フレームレートでも境界を合わせます. + if previousFrameWasVisible { frames.lastVisibleEnd = time } + guard let pixels = CMSampleBufferGetImageBuffer(sample) else { + throw LoopBlackFrameAnalysisError.unsupportedPixelBuffer + } + let black = try Self.isBlackFrame(pixels) + previousFrameWasVisible = !black + if !black { + if frames.firstVisibleTime == nil { frames.firstVisibleTime = time } + let sampleDuration = CMSampleBufferGetDuration(sample) + let frameDuration = sampleDuration.seconds.isFinite && sampleDuration.seconds > 0 + ? sampleDuration : fallbackFrameDuration + frames.lastVisibleEnd = CMTimeAdd(time, frameDuration) + if stopsAtFirstVisibleFrame { return frames } + } + } + try Task.checkCancellation() + guard reader.status == .completed else { + throw LoopBlackFrameAnalysisError.cannotReadFrames( + reader.error?.localizedDescription ?? "フレームの読み取りが中断されました." + ) + } + return frames + } + + /// 暗い場面や黒帯を除外し,画面のほぼ全域が黒い場合だけ判定します. + static func isBlackFrame(_ pixels: CVPixelBuffer) throws -> Bool { + guard CVPixelBufferGetPixelFormatType(pixels) == kCVPixelFormatType_32BGRA, + CVPixelBufferLockBaseAddress(pixels, .readOnly) == kCVReturnSuccess else { + throw LoopBlackFrameAnalysisError.unsupportedPixelBuffer + } + defer { CVPixelBufferUnlockBaseAddress(pixels, .readOnly) } + guard let address = CVPixelBufferGetBaseAddress(pixels) else { + throw LoopBlackFrameAnalysisError.unsupportedPixelBuffer + } + let width = CVPixelBufferGetWidth(pixels) + let height = CVPixelBufferGetHeight(pixels) + let rowBytes = CVPixelBufferGetBytesPerRow(pixels) + let sampledWidth = min(width, sampleWidth) + let sampledHeight = min(height, sampleHeight) + guard sampledWidth > 0, sampledHeight > 0 else { + throw LoopBlackFrameAnalysisError.unsupportedPixelBuffer + } + let bytes = address.assumingMemoryBound(to: UInt8.self) + var blackPixels = 0 + for y in 0..= minimumBlackPixelRatio + } +} diff --git a/AllServerForMac/Common/Views/MacVideoThumbnailView.swift b/AllServerForMac/Common/Views/MacVideoThumbnailView.swift index bdc937a..842ccbc 100644 --- a/AllServerForMac/Common/Views/MacVideoThumbnailView.swift +++ b/AllServerForMac/Common/Views/MacVideoThumbnailView.swift @@ -67,6 +67,9 @@ nonisolated struct DecodedThumbnail: @unchecked Sendable { struct MacVideoThumbnailView: View { let videoItem: VideoItem let dataManager: LibraryViewModel + /// 動画の中央に再生ボタンを常時出すか。一覧のように大量に並ぶ場所では、全部に出るとうるさいので + /// false にして、呼び出し側でホバー時だけ出す。 + var showsPlayGlyph: Bool = true @EnvironmentObject private var appSettings: AppSettings @State private var thumbnail: NSImage? @@ -113,7 +116,7 @@ struct MacVideoThumbnailView: View { } } .overlay { - if videoItem.mediaType == .video && thumbnail != nil { + if showsPlayGlyph && videoItem.mediaType == .video && thumbnail != nil { Image(systemName: "play.fill") .font(.system(size: 14, weight: .bold)) .foregroundStyle(.white) @@ -122,7 +125,7 @@ struct MacVideoThumbnailView: View { .overlay(Circle().strokeBorder(.white.opacity(0.55), lineWidth: 1)) } } - .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) + .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous)) // 影とフェードインアニメーションはセルごとにオフスクリーン描画・アニメーショントランザクションを発生させ、 // 大量枚数のグリッドではスクロールのカクつきに直結するため外している。 .task { await generateThumbnail(forceRegenerate: false) } diff --git a/AllServerForMac/Features/Dashboard/Views/DashboardMetricViews.swift b/AllServerForMac/Features/Dashboard/Views/DashboardMetricViews.swift index f06a633..7274754 100644 --- a/AllServerForMac/Features/Dashboard/Views/DashboardMetricViews.swift +++ b/AllServerForMac/Features/Dashboard/Views/DashboardMetricViews.swift @@ -6,23 +6,23 @@ import SwiftUI struct DuplicateCheckCountBadge: View { let title: String let count: Int - let tint: Color var body: some View { + // 緑・橙の強い色の面はやめ、中立の面に濃い文字で数字だけを見せる。 VStack(alignment: .leading, spacing: 4) { Text(title) - .font(.system(size: 10, weight: .medium)) - .foregroundStyle(.secondary) - Text("\(count)") - .font(.system(size: 20, weight: .bold, design: .rounded)) + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) + Text(count.formatted()) + .font(.system(size: 22, weight: .semibold)) .monospacedDigit() - .foregroundStyle(tint) + .foregroundStyle(NeomorphicTheme.ink) } - .padding(10) + .padding(12) .frame(maxWidth: .infinity, alignment: .leading) .background( - RoundedRectangle(cornerRadius: 8, style: .continuous) - .fill(tint.opacity(0.12)) + RoundedRectangle(cornerRadius: 10, style: .continuous) + .fill(NeomorphicTheme.control) ) } } @@ -38,8 +38,8 @@ struct ResourceGauge: View { Gauge(value: min(max(value, 0), 100), in: 0...100) { Text(label) } currentValueLabel: { - Text("\(Int(value))") - .font(.system(size: 13, weight: .bold)) + Text("\(Int(value))%") + .font(.system(size: 11, weight: .bold)) .monospacedDigit() } .gaugeStyle(.accessoryCircularCapacity) @@ -48,7 +48,7 @@ struct ResourceGauge: View { .frame(width: 52, height: 52) Text(label) - .font(.system(size: 10, weight: .medium)) + .font(.system(size: 11, weight: .medium)) .foregroundStyle(.secondary) } } diff --git a/AllServerForMac/Features/Dashboard/Views/DashboardSurfaceViews.swift b/AllServerForMac/Features/Dashboard/Views/DashboardSurfaceViews.swift index baaf6e1..38a861e 100644 --- a/AllServerForMac/Features/Dashboard/Views/DashboardSurfaceViews.swift +++ b/AllServerForMac/Features/Dashboard/Views/DashboardSurfaceViews.swift @@ -22,15 +22,6 @@ struct NeomorphicTile: View { var body: some View { content .padding(padding) - .background( - RoundedRectangle(cornerRadius: 8, style: .continuous) - .fill(NeomorphicTheme.surface) - .shadow(color: .white.opacity(0.92), radius: 8, x: -7, y: -7) - .shadow(color: NeomorphicTheme.shadow.opacity(0.32), radius: 16, x: 9, y: 9) - ) - .overlay( - RoundedRectangle(cornerRadius: 8, style: .continuous) - .strokeBorder(.white.opacity(0.65), lineWidth: 1) - ) + .background(GlassCardSurface()) } } diff --git a/AllServerForMac/Features/Dashboard/Views/HomeView.swift b/AllServerForMac/Features/Dashboard/Views/HomeView.swift index b8d1aa5..d520d91 100644 --- a/AllServerForMac/Features/Dashboard/Views/HomeView.swift +++ b/AllServerForMac/Features/Dashboard/Views/HomeView.swift @@ -14,6 +14,8 @@ struct HomeView: View { @State private var isShowingAccessLog = false @State private var isShowingStorageManager = false @State private var logFilter: Int = 0 // 0: 全て, 1: 動画本体, 2: サムネ, 3: その他 + /// ページ見出しの2行目に出す、ライブラリの規模(「動画 1,038本 · 画像 26,529枚 · アルバム 513」)。 + @State private var librarySummary = "" init(dataManager: LibraryViewModel, webServerManager: ServerViewModel) { self.dataManager = dataManager @@ -27,12 +29,16 @@ struct HomeView: View { NeomorphicHomeBackground() ScrollView { VStack(spacing: DS.cardSpacing) { - ServerHeroCard(webServerManager: webServerManager) + LibraryPageHeader(title: "ホーム", subtitle: librarySummary) + .padding(.horizontal, -24) // カードごとの高さが異なるため,行の高さを強制するLazyVGridは使わない。 // 左右のカラムを独立して積むことで,縦長カードの横に空白が残らない。 + // 接続に必要な「サーバーの状態」と「PIN認証」を各カラムの先頭に置く + // (以前の「設定の概要」は,すぐ下の設定カードと同じ項目の繰り返しだったので廃止)。 HStack(alignment: .top, spacing: DS.cardSpacing) { VStack(spacing: DS.cardSpacing) { + ServerHeroCard(webServerManager: webServerManager) connectionCard scheduleCard duplicateCheckCard @@ -58,42 +64,65 @@ struct HomeView: View { .frame(maxWidth: .infinity) } } + // ウィンドウを開いた直後に最初の入力欄(ポート番号)が自動で選択されないようにする。 + .background(InitialFirstResponderClearer()) .tint(NeomorphicTheme.accent) .foregroundStyle(NeomorphicTheme.ink) .preferredColorScheme(appSettings.neomorphicDarkBase ? .dark : .light) .sheet(isPresented: $isShowingAccessLog) { AccessLogView(webServerManager: webServerManager) } + // 重複チェックの件数キャッシュは自動チェックのループ(起動から90秒後に開始,オフなら初回のみ)でしか + // 作られないため,それまでホームが 0/0 のままになり「今すぐすべてチェック」も押せない. + // ホームを開いたとき・ライブラリの読み込みが終わったときに一度作っておく. + .onAppear(perform: refreshDuplicateCheckCountsIfNeeded) + .onAppear(perform: refreshLibrarySummary) + .onChange(of: dataManager.isLibraryLoaded) { refreshDuplicateCheckCountsIfNeeded() } + .onChange(of: dataManager.videos) { refreshLibrarySummary() } + .onChange(of: dataManager.albums) { refreshLibrarySummary() } .sheet(isPresented: $isShowingStorageManager) { StorageManagerView(dataManager: dataManager) } } + /// 1回の走査で本数・枚数を数える(ホームは1秒ごとに再描画されるので、body の中では数えない)。 + private func refreshLibrarySummary() { + var videoCount = 0 + var photoCount = 0 + for item in dataManager.videos where !item.isInTrash { + if item.mediaType == .video { videoCount += 1 } else { photoCount += 1 } + } + let albumCount = [false, true].reduce(0) { + $0 + SidebarViewModel.treeAlbums(from: dataManager.albums, isPhoto: $1).count + } + librarySummary = "動画 \(videoCount.formatted())本 · 画像 \(photoCount.formatted())枚 · アルバム \(albumCount.formatted())" + } + // MARK: 重複チェックカード + private func refreshDuplicateCheckCountsIfNeeded() { + guard dataManager.isLibraryLoaded, !dataManager.isDuplicateCheckRunning else { return } + dataManager.refreshDuplicateCheckAlbumCaches() + } + private var duplicateCheckCard: some View { let checkedAlbums = duplicateCheckStatus.checkedAlbums let uncheckedAlbums = duplicateCheckStatus.uncheckedAlbums let totalCount = checkedAlbums.count + uncheckedAlbums.count return VStack(alignment: .leading, spacing: 12) { - CardHeader(icon: "checkmark.seal.fill", tint: .mint, title: "素材検品", subtitle: "DUPLICATE INSPECTION") + CardHeader(icon: "checkmark.seal.fill", tint: NeomorphicTheme.accent, title: "重複メディアの確認", subtitle: "同じファイルがないかアルバムごとに確認") - Toggle(isOn: $dataManager.isAutoDuplicateCheckEnabled) { - Text("バックグラウンドで自動チェック") - .font(.system(size: 12)) - } - .toggleStyle(.switch) - .controlSize(.small) - .help("オフにすると、インポート後などにバックグラウンドで自動実行される重複チェックを停止します。アルバム内の「重複チェック」ボタンによる手動実行には影響しません。") + SettingToggleRow(title: "バックグラウンドで自動チェック", isOn: $dataManager.isAutoDuplicateCheckEnabled) + .help("オフにすると,インポート後などにバックグラウンドで自動実行される重複チェックを停止します.アルバム内の「重複チェック」ボタンによる手動実行には影響しません.") HStack(spacing: 10) { - DuplicateCheckCountBadge(title: "チェック済み", count: checkedAlbums.count, tint: .green) - DuplicateCheckCountBadge(title: "未チェック", count: uncheckedAlbums.count, tint: .orange) + DuplicateCheckCountBadge(title: "チェック済み", count: checkedAlbums.count) + DuplicateCheckCountBadge(title: "未チェック", count: uncheckedAlbums.count) } if totalCount == 0 { - Text("対象アルバムはありません。") - .font(.system(size: 12)) + Text("対象アルバムはありません.") + .font(.appCaption) .foregroundStyle(.secondary) .frame(maxWidth: .infinity, alignment: .center) .padding(.vertical, 12) @@ -101,15 +130,15 @@ struct HomeView: View { VStack(alignment: .leading, spacing: 8) { ProgressView(value: duplicateCheckStatus.progress, total: 1.0) .progressViewStyle(.linear) - .tint(.mint) + .tint(NeomorphicTheme.accent) Text(duplicateCheckStatus.statusMessage) - .font(.system(size: 11)) + .font(.appMicro) .foregroundStyle(.secondary) .lineLimit(2) } } else { Text(duplicateCheckStatus.statusMessage) - .font(.system(size: 11)) + .font(.appMicro) .foregroundStyle(.secondary) } @@ -119,15 +148,16 @@ struct HomeView: View { Label("今すぐすべてチェック", systemImage: "checkmark.seal.fill") .frame(maxWidth: .infinity) } - .buttonStyle(.borderedProminent) - .tint(.mint) + // 補助の操作は塗りつぶさない(青い全幅ボタンが並ぶと、本当の主役である「開始」が埋もれる)。 + .buttonStyle(.bordered) + .tint(NeomorphicTheme.ink) .disabled(duplicateCheckStatus.isAutoChecking || dataManager.isDuplicateCheckRunning || totalCount == 0) - .help("自動チェックのオン/オフに関わらず、対象アルバムの重複をまとめて今すぐチェックします。") + .help("自動チェックのオン/オフに関わらず,対象アルバムの重複をまとめて今すぐチェックします.") Divider() - duplicateAlbumList(title: "未チェック", albums: uncheckedAlbums, emptyMessage: "未チェックのアルバムはありません。") - duplicateAlbumList(title: "チェック済み", albums: checkedAlbums, emptyMessage: "チェック済みのアルバムはありません。") + duplicateAlbumList(title: "未チェック", albums: uncheckedAlbums, emptyMessage: "未チェックのアルバムはありません.") + duplicateAlbumList(title: "チェック済み", albums: checkedAlbums, emptyMessage: "チェック済みのアルバムはありません.") } .dashboardCard() } @@ -137,10 +167,10 @@ struct HomeView: View { let count = dataManager.linkedFolderCount let status = linkedFolderScanStatus return VStack(alignment: .leading, spacing: 12) { - CardHeader(icon: "folder.badge.gearshape", tint: .cyan, title: "素材搬入", subtitle: "INGEST FOLDERS") + CardHeader(icon: "folder.badge.gearshape", tint: NeomorphicTheme.accent, title: "リンクフォルダ", subtitle: "元フォルダの変更をライブラリへ反映") SettingRow(label: "リンク中のフォルダ") { - Text("\(count)") + Text("\(count)フォルダ") .font(.system(size: 13, weight: .semibold)) .monospacedDigit() } @@ -148,18 +178,18 @@ struct HomeView: View { if status.isScanning { linkedFolderScanProgress(status) } else { - Text("紐づけたフォルダに追加・削除したメディアは、下のボタンを押したときに取り込まれます。") - .font(.system(size: 10)) + Text("紐づけたフォルダに追加・削除したメディアは,下のボタンを押したときに取り込まれます.") + .font(.appMicro) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) if count > 0 && !status.statusMessage.isEmpty { HStack(alignment: .top, spacing: 6) { Image(systemName: "checkmark.circle.fill") - .font(.system(size: 11)) + .font(.appMicro) .foregroundStyle(.green) Text(status.statusMessage) - .font(.system(size: 11)) + .font(.appMicro) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) } @@ -174,13 +204,14 @@ struct HomeView: View { Label(status.isScanning ? "更新中…" : "リンクフォルダを更新", systemImage: "arrow.triangle.2.circlepath") .frame(maxWidth: .infinity) } - .buttonStyle(.borderedProminent) - .tint(.cyan) + // 補助の操作は塗りつぶさない(青い全幅ボタンが並ぶと、本当の主役である「開始」が埋もれる)。 + .buttonStyle(.bordered) + .tint(NeomorphicTheme.ink) .disabled(status.isScanning || count == 0) if count == 0 { - Text("フォルダを紐づけるには、アルバムを開いてツールバーの「フォルダ紐づけ」を使ってください。") - .font(.system(size: 10)) + Text("フォルダを紐づけるには,アルバムを開いてツールバーの「フォルダ紐づけ」を使ってください.") + .font(.appMicro) .foregroundStyle(.tertiary) .fixedSize(horizontal: false, vertical: true) } @@ -207,22 +238,22 @@ struct HomeView: View { ProgressView(value: Double(status.processedCount), total: Double(max(status.totalCount, 1))) .progressViewStyle(.linear) - .tint(.cyan) + .tint(NeomorphicTheme.accent) if let name = status.currentFolderName { HStack(spacing: 6) { Image(systemName: "folder.fill") - .font(.system(size: 10)) + .font(.appMicro) .foregroundStyle(.cyan) Text(name) - .font(.system(size: 11)) + .font(.appMicro) .foregroundStyle(.secondary) .lineLimit(1) .truncationMode(.middle) Spacer() if status.processedItemsInCurrentFolder > 0 { Text("\(status.processedItemsInCurrentFolder)件取り込み") - .font(.system(size: 10, design: .monospaced)) + .font(.system(size: 11, design: .monospaced)) .foregroundStyle(.secondary) } } @@ -251,7 +282,7 @@ struct HomeView: View { HStack(spacing: 8) { Image(systemName: "rectangle.stack.fill") .foregroundStyle(.yellow) - .font(.system(size: 12)) + .font(.appCaption) Text(conflict.albumName) .font(.system(size: 12, weight: .semibold)) .lineLimit(1) @@ -263,13 +294,13 @@ struct HomeView: View { HStack(spacing: 8) { VStack(alignment: .leading, spacing: 2) { Text(candidate.folderPath) - .font(.system(size: 11)) + .font(.appMicro) .foregroundStyle(.primary) .lineLimit(1) .truncationMode(.middle) .help(candidate.folderPath) Text("\(candidate.matchCount)件一致") - .font(.system(size: 10)) + .font(.appMicro) .foregroundStyle(.secondary) } @@ -281,6 +312,7 @@ struct HomeView: View { Label("選択", systemImage: "checkmark.circle") } .buttonStyle(.bordered) + .tint(NeomorphicTheme.ink) .controlSize(.small) } .padding(8) @@ -310,13 +342,13 @@ struct HomeView: View { if albums.isEmpty { Text(emptyMessage) - .font(.system(size: 11)) + .font(.appMicro) .foregroundStyle(.tertiary) } else { ForEach(albums.prefix(5)) { album in HStack(spacing: 8) { Text(album.name) - .font(.system(size: 12)) + .font(.appCaption) .lineLimit(1) .truncationMode(.middle) Spacer() @@ -328,7 +360,7 @@ struct HomeView: View { if albums.count > 5 { Text("ほか\(albums.count - 5)件") - .font(.system(size: 10)) + .font(.appMicro) .foregroundStyle(.tertiary) } } @@ -338,7 +370,7 @@ struct HomeView: View { // MARK: 接続設定カード private var connectionCard: some View { VStack(alignment: .leading, spacing: 12) { - CardHeader(icon: "network", tint: .blue, title: "送出設定", subtitle: "PORT / AUTO STOP") + CardHeader(icon: "network", tint: .blue, title: "接続・自動停止の設定", subtitle: "ポート番号とアプリを終了するまでの時間") SettingRow(label: "ポート番号") { HStack(spacing: 6) { @@ -357,18 +389,19 @@ struct HomeView: View { } } + if webServerManager.isRunning { + Text("接続・自動停止の設定は,サーバーを停止すると変更できます.") + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) + } + Divider() - Toggle(isOn: $webServerManager.autoStopEnabled) { - Text("自動停止タイマー") - .font(.system(size: 12)) - } - .toggleStyle(.switch) - .controlSize(.small) + SettingToggleRow(title: "自動停止タイマー", isOn: $webServerManager.autoStopEnabled) .disabled(webServerManager.isRunning) if webServerManager.autoStopEnabled { - SettingRow(label: "停止までの時間") { + SettingRow(label: "サーバー開始から終了まで") { HStack(spacing: 5) { TextField("分", value: $webServerManager.autoStopIntervalMinutes, format: .number) .textFieldStyle(.roundedBorder) @@ -376,7 +409,7 @@ struct HomeView: View { .multilineTextAlignment(.trailing) .disabled(webServerManager.isRunning) Text("分") - .font(.system(size: 12)) + .font(.appCaption) .foregroundStyle(.secondary) } } @@ -389,38 +422,33 @@ struct HomeView: View { // MARK: スケジュールカード private var scheduleCard: some View { VStack(alignment: .leading, spacing: 12) { - CardHeader(icon: "calendar.badge.clock", tint: .purple, title: "放送予定", subtitle: "DAILY SCHEDULE") + CardHeader(icon: "calendar.badge.clock", tint: NeomorphicTheme.accent, title: "起動・停止スケジュール", subtitle: "毎日決まった時刻に自動で起動・終了") - Toggle(isOn: $webServerManager.scheduleEnabled) { - Text("毎日決まった時間に起動/停止") - .font(.system(size: 12)) - } - .toggleStyle(.switch) - .controlSize(.small) + SettingToggleRow(title: "毎日決まった時間に起動/停止", isOn: $webServerManager.scheduleEnabled) if webServerManager.scheduleEnabled { Divider() DatePicker("起動時刻", selection: $webServerManager.scheduleStartTime, displayedComponents: .hourAndMinute) - .font(.system(size: 12)) + .font(.appCaption) DatePicker("停止時刻", selection: $webServerManager.scheduleStopTime, displayedComponents: .hourAndMinute) - .font(.system(size: 12)) + .font(.appCaption) Button(action: { webServerManager.applySchedule() }) { Label("このスケジュールを適用", systemImage: "checkmark.circle") .frame(maxWidth: .infinity) } - .buttonStyle(.borderedProminent) - .tint(.purple) + .buttonStyle(.bordered) + .tint(NeomorphicTheme.ink) - Text("適用時に管理者パスワードの入力を求められます(スリープからの自動起床設定のため)。停止時刻になるとアプリは完全終了します。") - .font(.system(size: 10)) + Text("適用時に管理者パスワードの入力を求められます(スリープからの自動起床設定のため).停止時刻になるとアプリは完全終了します.") + .font(.appMicro) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) if !webServerManager.scheduleStatusMessage.isEmpty { Text(webServerManager.scheduleStatusMessage) - .font(.system(size: 11)) + .font(.appMicro) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) } @@ -433,23 +461,18 @@ struct HomeView: View { // MARK: セキュリティカード private var securityCard: some View { VStack(alignment: .leading, spacing: 12) { - CardHeader(icon: "lock.shield.fill", tint: .green, title: "アクセス制御", subtitle: "PIN / ACCESS LOG") + CardHeader(icon: "lock.shield.fill", tint: NeomorphicTheme.accent, title: "PIN認証", subtitle: "接続する端末に入力する6桁の番号") - Toggle(isOn: $webServerManager.authEnabled) { - Text("PIN認証を必須にする") - .font(.system(size: 12)) - } - .toggleStyle(.switch) - .controlSize(.small) - .help("オンにすると、Web・iOSアプリからのアクセスにPINが必要になります。") + SettingToggleRow(title: "PIN認証を必須にする", isOn: $webServerManager.authEnabled) + .help("オンにすると,Web・iOSアプリからのアクセスにPINが必要になります.") if webServerManager.authEnabled { SettingRow(label: "接続PIN") { HStack(spacing: 8) { CopyableText( text: webServerManager.authPIN, - font: .system(size: 17, weight: .bold, design: .monospaced), - tint: .green + font: .system(size: 20, weight: .semibold, design: .monospaced), + tint: NeomorphicTheme.ink ) Button(action: { webServerManager.regeneratePIN() }) { Image(systemName: "arrow.triangle.2.circlepath") @@ -458,15 +481,15 @@ struct HomeView: View { .help("PINを再生成する") } } - Text("このPINをiPhoneアプリ・ブラウザで入力してください。") - .font(.system(size: 10)) + Text("このPINをiPhoneアプリ・ブラウザで入力してください.") + .font(.appMicro) .foregroundStyle(.secondary) } else { HStack(spacing: 8) { Image(systemName: "exclamationmark.triangle.fill") .foregroundStyle(.orange) - Text("認証が無効です。同じWi-Fi内の誰でもアクセスできます。") - .font(.system(size: 11)) + Text("認証が無効です.同じWi-Fi内の誰でもアクセスできます.") + .font(.appMicro) .foregroundStyle(.orange) .fixedSize(horizontal: false, vertical: true) } @@ -474,27 +497,9 @@ struct HomeView: View { .frame(maxWidth: .infinity, alignment: .leading) .background( RoundedRectangle(cornerRadius: 8, style: .continuous) - .fill(Color.orange.opacity(0.12)) + .fill(NeomorphicTheme.accent.opacity(0.12)) ) } - - Divider() - - Button(action: { isShowingAccessLog = true }) { - HStack { - Label("アクセスログ", systemImage: "list.bullet.rectangle") - .font(.system(size: 12)) - Spacer() - Text("\(webServerManager.accessLogs.count)件") - .font(.system(size: 11)) - .foregroundStyle(.secondary) - Image(systemName: "chevron.right") - .font(.system(size: 10, weight: .semibold)) - .foregroundStyle(.tertiary) - } - .contentShape(Rectangle()) - } - .buttonStyle(.plain) } .animation(.easeInOut(duration: 0.18), value: webServerManager.authEnabled) .dashboardCard() @@ -503,11 +508,11 @@ struct HomeView: View { // MARK: システムリソースカード private var resourcesCard: some View { VStack(alignment: .leading, spacing: 12) { - CardHeader(icon: "gauge.with.dots.needle.50percent", tint: .orange, title: "送出機器", subtitle: "CPU / MEMORY LEVEL") + CardHeader(icon: "gauge.with.dots.needle.50percent", tint: .orange, title: "Macの使用状況", subtitle: "Mac全体のCPU・メモリ使用率") HStack(spacing: 24) { - ResourceGauge(label: "CPU", value: systemMonitor.cpuUsage, tint: .orange) - ResourceGauge(label: "メモリ", value: systemMonitor.memoryUsage, tint: .blue) + ResourceGauge(label: "CPU", value: systemMonitor.cpuUsage, tint: NeomorphicTheme.ink) + ResourceGauge(label: "メモリ", value: systemMonitor.memoryUsage, tint: NeomorphicTheme.ink) Spacer() } @@ -518,7 +523,7 @@ struct HomeView: View { y: .value("CPU(%)", point.value) ) .interpolationMethod(.catmullRom) - .foregroundStyle(Color.orange) + .foregroundStyle(NeomorphicTheme.accent) .lineStyle(StrokeStyle(lineWidth: 1.5)) AreaMark( @@ -528,7 +533,7 @@ struct HomeView: View { .interpolationMethod(.catmullRom) .foregroundStyle( LinearGradient( - gradient: Gradient(colors: [Color.orange.opacity(0.35), Color.orange.opacity(0.0)]), + gradient: Gradient(colors: [NeomorphicTheme.accent.opacity(0.35), NeomorphicTheme.accent.opacity(0.0)]), startPoint: .top, endPoint: .bottom ) @@ -545,6 +550,10 @@ struct HomeView: View { } } .frame(height: 90) + + Text("CPU使用率の推移(0〜100%)") + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) } .dashboardCard() } @@ -552,10 +561,10 @@ struct HomeView: View { // MARK: ストレージカード private var storageCard: some View { VStack(alignment: .leading, spacing: 12) { - CardHeader(icon: "internaldrive.fill", tint: .indigo, title: "素材庫", subtitle: "MEDIA INVENTORY") + CardHeader(icon: "internaldrive.fill", tint: NeomorphicTheme.accent, title: "ライブラリの容量", subtitle: "登録済みメディアの件数と合計サイズ") SettingRow(label: "総アイテム数") { - Text("\(dataManager.videos.count)") + Text("\(dataManager.videos.count)件") .font(.system(size: 13, weight: .semibold)) .monospacedDigit() } @@ -572,6 +581,7 @@ struct HomeView: View { .frame(maxWidth: .infinity) } .buttonStyle(.bordered) + .tint(NeomorphicTheme.ink) } .dashboardCard() } @@ -580,22 +590,20 @@ struct HomeView: View { private var logsCard: some View { VStack(alignment: .leading, spacing: 12) { HStack { - CardHeader(icon: "network.badge.shield.half.filled", tint: .teal, title: "回線ログ", subtitle: "LIVE ACCESS LOG") + CardHeader(icon: "network.badge.shield.half.filled", tint: NeomorphicTheme.accent, title: "最近のアクセス", subtitle: "端末からの通信履歴(接続台数ではありません)") Spacer() Button("すべて見る") { isShowingAccessLog = true } .font(.system(size: 11, weight: .semibold)) .buttonStyle(.plain) - .foregroundStyle(.blue) + .foregroundStyle(NeomorphicTheme.muted) } - Picker("", selection: $logFilter) { - Text("すべて").tag(0) - Text("動画本体").tag(1) - Text("サムネ").tag(2) - Text("その他").tag(3) - } - .pickerStyle(.segmented) - .labelsHidden() + FlatSegmentedControl( + options: [0, 1, 2, 3], + title: { ["すべて", "動画本体", "サムネ", "その他"][$0] }, + selection: $logFilter, + width: 320 + ) .padding(.bottom, 4) let filteredLogs = webServerManager.accessLogs.filter { entry in @@ -609,7 +617,7 @@ struct HomeView: View { if filteredLogs.isEmpty { Text("まだアクセスがありません") - .font(.system(size: 12)) + .font(.appCaption) .foregroundStyle(.secondary) .frame(maxWidth: .infinity, alignment: .center) .padding(.vertical, 20) @@ -618,21 +626,21 @@ struct HomeView: View { ForEach(filteredLogs.prefix(15)) { entry in HStack(spacing: 8) { Text(entry.date.formatted(.dateTime.hour().minute().second())) - .font(.system(size: 10, design: .monospaced)) + .font(.system(size: 11, design: .monospaced)) .foregroundStyle(.secondary) .frame(width: 58, alignment: .leading) Image(systemName: entry.authorized ? "checkmark.circle.fill" : "xmark.octagon.fill") .foregroundStyle(entry.authorized ? .green : .red) - .font(.system(size: 10)) + .font(.appMicro) Text(entry.method) - .font(.system(size: 10, weight: .bold, design: .monospaced)) + .font(.system(size: 11, weight: .bold, design: .monospaced)) .foregroundStyle(entry.method == "GET" ? .blue : .purple) .frame(width: 36, alignment: .leading) Text(entry.path) - .font(.system(size: 10)) + .font(.appMicro) .lineLimit(1) .truncationMode(.middle) .help(entry.path) @@ -640,7 +648,7 @@ struct HomeView: View { Spacer(minLength: 5) Text(entry.ip) - .font(.system(size: 10, design: .monospaced)) + .font(.system(size: 11, design: .monospaced)) .foregroundStyle(.tertiary) } .padding(.vertical, 4) diff --git a/AllServerForMac/Features/Dashboard/Views/QRCodeView.swift b/AllServerForMac/Features/Dashboard/Views/QRCodeView.swift new file mode 100644 index 0000000..31802cc --- /dev/null +++ b/AllServerForMac/Features/Dashboard/Views/QRCodeView.swift @@ -0,0 +1,60 @@ +import AppKit +import CoreImage +import CoreImage.CIFilterBuiltins +import SwiftUI + +// MARK: - QR コード + +/// 文字列から QR コードの画像を作る。 +/// 1モジュールを整数ピクセルに拡大して最近傍で描くので、縁がにじまず、カメラに読み取られやすい。 +enum QRCode { + private static let cache = NSCache() + private static let context = CIContext(options: [.useSoftwareRenderer: false]) + + static func image(for text: String, moduleSize: Int = 12) -> NSImage? { + let key = "\(moduleSize)|\(text)" as NSString + if let cached = cache.object(forKey: key) { return cached } + + let filter = CIFilter.qrCodeGenerator() + filter.message = Data(text.utf8) + // 誤り訂正は M(約15%まで欠けても読める)。画面表示なら十分で、モジュールが大きく保てる。 + filter.correctionLevel = "M" + guard let output = filter.outputImage else { return nil } + + let scaled = output + .samplingNearest() + .transformed(by: CGAffineTransform(scaleX: CGFloat(moduleSize), y: CGFloat(moduleSize))) + guard let cgImage = context.createCGImage(scaled, from: scaled.extent) else { return nil } + + let image = NSImage(cgImage: cgImage, size: NSSize(width: cgImage.width, height: cgImage.height)) + cache.setObject(image, forKey: key) + return image + } +} + +/// 白地に黒の QR コード。 +/// 読み取りの精度のため、黒基調の外観でも反転させず、常に白地・黒モジュール・周囲の余白つきで描く。 +struct QRCodeView: View { + let text: String + var size: CGFloat = 96 + + var body: some View { + Group { + if let image = QRCode.image(for: text) { + Image(nsImage: image) + .interpolation(.none) + .resizable() + .frame(width: size, height: size) + } else { + Image(systemName: "qrcode") + .font(.system(size: size * 0.5)) + .foregroundStyle(.black.opacity(0.3)) + .frame(width: size, height: size) + } + } + // QR コードの規格が求める「周囲の余白(クワイエットゾーン)」を白で確保する。 + .padding(8) + .background(Color.white, in: RoundedRectangle(cornerRadius: 10, style: .continuous)) + .accessibilityLabel("接続先のQRコード") + } +} diff --git a/AllServerForMac/Features/Dashboard/Views/ServerHeroCard.swift b/AllServerForMac/Features/Dashboard/Views/ServerHeroCard.swift index 135d153..880a943 100644 --- a/AllServerForMac/Features/Dashboard/Views/ServerHeroCard.swift +++ b/AllServerForMac/Features/Dashboard/Views/ServerHeroCard.swift @@ -1,416 +1,183 @@ import AppKit -import Charts import SwiftUI -// MARK: - サーバー状態ヒーローカード +// MARK: - サーバーの状態と接続案内 +/// ホームの先頭に置く、開始/停止と接続のしかたをまとめたカード。 +/// 停止中は「どう接続するか」の手順を、稼働中は「いまの接続先」をそのまま使える形で見せる。 struct ServerHeroCard: View { - @ObservedObject var webServerManager: ServerViewModel - - var body: some View { - ViewThatFits(in: .horizontal) { - HStack(alignment: .top, spacing: 22) { - leftColumn - .frame(width: 470) - rightColumn - .frame(maxWidth: .infinity) - } - - VStack(spacing: 18) { - leftColumn - rightColumn - } - } - .animation(.easeInOut(duration: 0.25), value: webServerManager.isRunning) - } - - private var leftColumn: some View { - VStack(spacing: 18) { - serverControlTile - - HStack(spacing: 18) { - NeomorphicSceneTile( - icon: "timer", - title: "Auto Stop", - value: webServerManager.autoStopEnabled ? "\(webServerManager.autoStopIntervalMinutes) min" : "Off", - tint: .orange - ) - NeomorphicSceneTile( - icon: "lock.shield", - title: "PIN Scene", - value: webServerManager.authEnabled ? "Protected" : "Open LAN", - tint: .green - ) - } - } - } - - private var rightColumn: some View { - VStack(spacing: 18) { - welcomePill - analyticsTile - } - } - - private var serverControlTile: some View { - NeomorphicTile(padding: 24) { - VStack(alignment: .leading, spacing: 18) { - HStack(alignment: .top) { - Label { - VStack(alignment: .leading, spacing: 3) { - Text("Mac Media Server") - .font(.system(size: 22, weight: .bold, design: .rounded)) - .foregroundStyle(NeomorphicTheme.ink) - Text(webServerManager.isRunning ? "Local Streaming" : "Standby Cooling") - .font(.system(size: 13, weight: .medium, design: .rounded)) - .foregroundStyle(NeomorphicTheme.muted) - } - } icon: { - Image(systemName: "snowflake") - .font(.system(size: 25, weight: .semibold)) - .foregroundStyle(NeomorphicTheme.ink) - } - - Spacer() - - Button(action: toggleServer) { - HStack(spacing: 8) { - Text(webServerManager.isRunning ? "On." : "Off.") - .font(.system(size: 13, weight: .bold, design: .rounded)) - Image(systemName: "power") - .font(.system(size: 13, weight: .bold)) - } - .foregroundStyle(webServerManager.isRunning ? .white : NeomorphicTheme.muted) - .padding(.horizontal, 15) - .padding(.vertical, 8) - .background( - Capsule() - .fill(webServerManager.isRunning ? NeomorphicTheme.accent : NeomorphicTheme.surface) - .shadow(color: .white.opacity(0.9), radius: 4, x: -3, y: -3) - .shadow(color: NeomorphicTheme.shadow.opacity(0.28), radius: 6, x: 4, y: 4) - ) - } - .buttonStyle(.plain) - .help(webServerManager.isRunning ? "サーバーを停止" : "サーバーを開始") - .accessibilityLabel(webServerManager.isRunning ? "サーバーを停止" : "サーバーを開始") - } - - HStack(spacing: 8) { - Image(systemName: "clock") - Text(webServerManager.isRunning ? webServerManager.uptimeString : "LAN内の視聴を待機") - } - .font(.system(size: 12, weight: .medium, design: .rounded)) - .foregroundStyle(NeomorphicTheme.muted) - .padding(.horizontal, 10) - .padding(.vertical, 6) - .background( - Capsule() - .fill(NeomorphicTheme.surface) - .shadow(color: .white.opacity(0.9), radius: 3, x: -2, y: -2) - .shadow(color: NeomorphicTheme.shadow.opacity(0.22), radius: 5, x: 3, y: 3) - ) - - ServerArcGauge(isRunning: webServerManager.isRunning) - .frame(maxWidth: .infinity) - - statusDetail - } + @ObservedObject var webServerManager: ServerViewModel + + var body: some View { + NeomorphicTile(padding: DS.cardPadding) { + VStack(alignment: .leading, spacing: 18) { + CardHeader(icon: "network", tint: NeomorphicTheme.accent, title: "サーバーの状態") + statusRow + + Text(webServerManager.isRunning + ? "同じWi-Fi内の端末から,動画・画像を閲覧できます." + : "「開始」を押すと,iPhoneやブラウザから接続できます.") + .font(.appBody) + .foregroundStyle(NeomorphicTheme.muted) + .fixedSize(horizontal: false, vertical: true) + + if !webServerManager.statusMessage.isEmpty, + webServerManager.statusMessage.contains("❌") || webServerManager.statusMessage.contains("⚠️") { + Label(webServerManager.statusMessage, systemImage: "exclamationmark.triangle.fill") + .font(.appBody) + .foregroundStyle(.orange) + .fixedSize(horizontal: false, vertical: true) } - } - - @ViewBuilder - private var statusDetail: some View { - if webServerManager.isRunning, let url = webServerManager.serverURL { - CopyableText(text: url, font: .system(size: 12, design: .monospaced), tint: NeomorphicTheme.accent) - .frame(maxWidth: .infinity, alignment: .center) - } else if webServerManager.statusMessage.contains("❌") { - Text(webServerManager.statusMessage.replacingOccurrences(of: "❌ ", with: "")) - .font(.system(size: 12, weight: .medium, design: .rounded)) - .foregroundStyle(.red) - .fixedSize(horizontal: false, vertical: true) - .frame(maxWidth: .infinity, alignment: .center) - } else { - Text("「開始」を押すと、同じWi-Fi内のiPhoneやブラウザから視聴できます") - .font(.system(size: 12, weight: .medium, design: .rounded)) - .foregroundStyle(NeomorphicTheme.muted) - .multilineTextAlignment(.center) - .frame(maxWidth: .infinity, alignment: .center) - } - } - - private var welcomePill: some View { - NeomorphicTile(padding: 15) { - HStack(spacing: 14) { - Circle() - .fill(NeomorphicTheme.accent) - .frame(width: 46, height: 46) - .overlay( - Image(systemName: "play.rectangle.stack.fill") - .font(.system(size: 18, weight: .bold)) - .foregroundStyle(.white) - ) - .shadow(color: .white.opacity(0.9), radius: 4, x: -3, y: -3) - .shadow(color: NeomorphicTheme.shadow.opacity(0.28), radius: 6, x: 4, y: 4) - VStack(alignment: .leading, spacing: 2) { - Text("Hi, Local Server") - .font(.system(size: 15, weight: .bold, design: .rounded)) - .foregroundStyle(NeomorphicTheme.ink) - Text(webServerManager.isRunning ? "1 server active" : "Server ready") - .font(.system(size: 12, weight: .medium, design: .rounded)) - .foregroundStyle(NeomorphicTheme.muted) - } - - Spacer() - - Image(systemName: "ellipsis") - .font(.system(size: 17, weight: .bold)) - .foregroundStyle(NeomorphicTheme.muted) - } - } - } + Rectangle().fill(NeomorphicTheme.separator).frame(height: 0.5) - private var analyticsTile: some View { - NeomorphicTile(padding: 22) { - VStack(alignment: .leading, spacing: 17) { - HStack(spacing: 10) { - Image(systemName: "bolt.fill") - .font(.system(size: 24, weight: .bold)) - .foregroundStyle(NeomorphicTheme.ink) - VStack(alignment: .leading, spacing: 2) { - Text("AI Power Analytics") - .font(.system(size: 20, weight: .bold, design: .rounded)) - .foregroundStyle(NeomorphicTheme.ink) - Text("Daily Usage") - .font(.system(size: 12, weight: .medium, design: .rounded)) - .foregroundStyle(NeomorphicTheme.muted) - } - Spacer() - Image(systemName: "arrow.up.right") - .font(.system(size: 13, weight: .bold)) - .foregroundStyle(NeomorphicTheme.muted) - .padding(9) - .background( - Circle() - .fill(NeomorphicTheme.surface) - .shadow(color: .white.opacity(0.95), radius: 3, x: -2, y: -2) - .shadow(color: NeomorphicTheme.shadow.opacity(0.24), radius: 5, x: 3, y: 3) - ) - } - - VStack(spacing: 12) { - NeomorphicAnalyticsRow(icon: "antenna.radiowaves.left.and.right", title: "Local Relay", value: webServerManager.isRunning ? "Running | \(webServerManager.targetPort)" : "Idle | \(webServerManager.targetPort)") - NeomorphicAnalyticsRow(icon: "lock.shield", title: "PIN Security", value: webServerManager.authEnabled ? "Protected" : "Open LAN") - NeomorphicAnalyticsRow(icon: "list.bullet.rectangle", title: "Access Log", value: "\(webServerManager.accessLogs.count) entries") - NeomorphicAnalyticsRow(icon: "timer", title: "Auto Stop", value: webServerManager.autoStopEnabled ? "\(webServerManager.autoStopIntervalMinutes) minutes" : "Disabled") - } - } - } - } - - private var remainingTimeString: String { - let remaining = max(0, (webServerManager.autoStopIntervalMinutes * 60) - Int(Date().timeIntervalSince(webServerManager.serverStartTime ?? Date()))) - return String(format: "%d分 %02d秒", remaining / 60, remaining % 60) - } - private func toggleServer() { if webServerManager.isRunning { - webServerManager.stopServer() + runningDetails } else { - webServerManager.startServer() + connectionSteps } - } -} - -private struct ServerArcGauge: View { - let isRunning: Bool - - private let tickCount = 42 - private let startAngle = -112.0 - private let endAngle = 112.0 - - var body: some View { - ZStack { - ForEach(0.. 0.74 ? 28 : 22) - .offset(y: -82) - .rotationEffect(.degrees(startAngle + (endAngle - startAngle) * ratio)) - } - - VStack(spacing: 2) { - Text(isRunning ? "Streaming" : "Standby") - .font(.system(size: 22, weight: .bold, design: .rounded)) - .foregroundStyle(NeomorphicTheme.ink) - } - .offset(y: 28) + } + .frame(maxWidth: .infinity, alignment: .topLeading) + } + } + + // MARK: 状態と開始/停止 + + private var statusRow: some View { + HStack(spacing: 12) { + StatusDot(active: webServerManager.isRunning) + Text(webServerManager.isRunning ? "配信中" : "停止中") + .font(.system(size: 30, weight: .bold, design: .default)) + if webServerManager.isRunning { + // 稼働時間は補足なので、状態の文字より小さく控えめに添える。 + Text("稼働 \(webServerManager.uptimeString)") + .font(.system(size: 13).monospacedDigit()) + .foregroundStyle(NeomorphicTheme.muted) + .padding(.top, 8) + } + Spacer() + if webServerManager.isRunning { + // 停止は主役の操作ではない(誤って押したくもない)ので、塗りつぶさない。 + Button(action: toggleServer) { + Label("停止", systemImage: "stop.fill") + .font(.system(size: 13, weight: .medium)) + .padding(.horizontal, 6) + .padding(.vertical, 3) } - .frame(height: 190) - .accessibilityElement(children: .ignore) - .accessibilityLabel(isRunning ? "サーバー稼働中" : "サーバー待機中") - } - - private func tickColor(for ratio: Double) -> Color { - let activeLimit = isRunning ? 0.82 : 0.28 - if ratio > activeLimit { - return NeomorphicTheme.shadow.opacity(0.18) + .buttonStyle(.bordered) + .tint(NeomorphicTheme.ink) + .accessibilityLabel("サーバーを停止") + } else { + Button(action: toggleServer) { + Label("開始", systemImage: "power") + .font(.system(size: 13, weight: .semibold)) + .padding(.horizontal, 8) + .padding(.vertical, 4) } - return ratio > 0.72 ? NeomorphicTheme.accent : NeomorphicTheme.ink.opacity(0.84) - } -} - -private struct NeomorphicSceneTile: View { - let icon: String - let title: String - let value: String - let tint: Color - - var body: some View { - NeomorphicTile(padding: 16) { - VStack(alignment: .leading, spacing: 36) { - HStack { - Image(systemName: icon) - .font(.system(size: 15, weight: .semibold)) - .foregroundStyle(tint) - .padding(9) - .background( - Circle() - .fill(NeomorphicTheme.surface) - .shadow(color: .white.opacity(0.9), radius: 3, x: -2, y: -2) - .shadow(color: NeomorphicTheme.shadow.opacity(0.24), radius: 5, x: 3, y: 3) - ) - Spacer() - Image(systemName: "ellipsis") - .font(.system(size: 15, weight: .bold)) - .foregroundStyle(NeomorphicTheme.muted) - } - - VStack(alignment: .leading, spacing: 3) { - Text(title) - .font(.system(size: 15, weight: .bold, design: .rounded)) - .foregroundStyle(NeomorphicTheme.ink) - .lineLimit(1) - Text(value) - .font(.system(size: 12, weight: .medium, design: .rounded)) - .foregroundStyle(NeomorphicTheme.muted) - .lineLimit(1) - } - } - .frame(maxWidth: .infinity, minHeight: 120, alignment: .leading) - } - } -} - -private struct NeomorphicAnalyticsRow: View { - let icon: String - let title: String - let value: String - - var body: some View { - HStack(spacing: 14) { - Image(systemName: icon) - .font(.system(size: 14, weight: .semibold)) - .foregroundStyle(NeomorphicTheme.muted) - .frame(width: 36, height: 36) - .background( - Circle() - .fill(NeomorphicTheme.surface) - .shadow(color: .white.opacity(0.92), radius: 3, x: -2, y: -2) - .shadow(color: NeomorphicTheme.shadow.opacity(0.24), radius: 5, x: 3, y: 3) - ) - - VStack(alignment: .leading, spacing: 2) { - Text(title) - .font(.system(size: 14, weight: .bold, design: .rounded)) - .foregroundStyle(NeomorphicTheme.ink) - .lineLimit(1) - Text(value) - .font(.system(size: 12, weight: .medium, design: .rounded)) - .foregroundStyle(NeomorphicTheme.muted) - .lineLimit(1) - } - + .buttonStyle(.borderedProminent) + .accessibilityLabel("サーバーを開始") + } + } + } + + // MARK: 稼働中:いまの接続先 + + private var runningDetails: some View { + VStack(alignment: .leading, spacing: 14) { + VStack(alignment: .leading, spacing: 8) { + Text("ブラウザの接続先") + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) + + if let url = webServerManager.serverURL { + HStack(spacing: 12) { + // 読み取り・入力しやすいよう大きめの等幅にして、クリックでコピーできるようにする。 + CopyableText( + text: url, + font: .system(size: 17, weight: .medium, design: .monospaced), + tint: NeomorphicTheme.ink + ) Spacer(minLength: 8) - - Image(systemName: "chevron.right") - .font(.system(size: 15, weight: .bold)) - .foregroundStyle(NeomorphicTheme.muted) - } - .padding(14) - .background( - RoundedRectangle(cornerRadius: 8, style: .continuous) - .fill(NeomorphicTheme.surface) - .shadow(color: .white.opacity(0.92), radius: 5, x: -4, y: -4) - .shadow(color: NeomorphicTheme.shadow.opacity(0.25), radius: 8, x: 5, y: 5) - ) - .overlay( - RoundedRectangle(cornerRadius: 8, style: .continuous) - .strokeBorder(.white.opacity(0.58), lineWidth: 1) - ) - } -} - -/// ライブ配信機器のレベルメーターを模した表示。ネットワークの稼働状態だけを表すため, -/// 実測値のように見せるランダムなアニメーションは使いません。 -private struct BroadcastLevelMeter: View { - let isRunning: Bool - let port: Int - - var body: some View { - VStack(alignment: .leading, spacing: 8) { - HStack { - Text("NETWORK LEVEL") - .font(.system(size: 10, weight: .bold, design: .monospaced)) - .foregroundStyle(.secondary) - Spacer() - Text("TX / RX") - .font(.system(size: 9, weight: .medium, design: .monospaced)) - .foregroundStyle(.secondary) - } - - levelRow(label: "TX", activeCount: isRunning ? 13 : 0) - levelRow(label: "RX", activeCount: isRunning ? 10 : 0) - - HStack(spacing: 12) { - BroadcastStatusLabel(label: "LAN", value: isRunning ? "LINK" : "IDLE", active: isRunning) - BroadcastStatusLabel(label: "PORT", value: "\(port)", active: true) - BroadcastStatusLabel(label: "PIN", value: "READY", active: true) - } - } - } - - private func levelRow(label: String, activeCount: Int) -> some View { - HStack(spacing: 4) { - Text(label) - .font(.system(size: 10, weight: .bold, design: .monospaced)) - .foregroundStyle(.secondary) - .frame(width: 20, alignment: .leading) - ForEach(0..<16, id: \.self) { index in - Rectangle() - .fill(index < activeCount ? meterColor(for: index) : Color.white.opacity(0.1)) - .frame(width: 7, height: index.isMultiple(of: 4) ? 13 : 9) + Button { + if let target = URL(string: url) { NSWorkspace.shared.open(target) } + } label: { + Label("開く", systemImage: "arrow.up.forward.app") + .font(.system(size: 13, weight: .medium)) } + .buttonStyle(.bordered) + .tint(NeomorphicTheme.ink) + .help("このMacのブラウザで接続先を開く") + } + .padding(.horizontal, 14) + .padding(.vertical, 12) + .background(NeomorphicTheme.control, in: RoundedRectangle(cornerRadius: 10, style: .continuous)) + } else { + Text("接続先を取得しています…") + .font(.appBody) + .foregroundStyle(NeomorphicTheme.muted) } - } - - private func meterColor(for index: Int) -> Color { - index >= 12 ? DS.signalAmber : DS.tallyGreen - } -} - -private struct BroadcastStatusLabel: View { - let label: String - let value: String - let active: Bool - - var body: some View { - HStack(spacing: 5) { - Circle() - .fill(active ? DS.tallyGreen : Color.secondary) - .frame(width: 5, height: 5) - Text("\(label) \(value)") - .font(.system(size: 9, weight: .semibold, design: .monospaced)) - .foregroundStyle(.secondary) + } + + // スマホのカメラで読み取るための QR コード。URL を打ち込まずに接続できる。 + // QR に入れるのは接続先の URL だけで、PIN は含めない(画面を見られても PIN が漏れないようにする)。 + if let url = webServerManager.serverURL { + HStack(alignment: .center, spacing: 16) { + QRCodeView(text: url, size: 96) + VStack(alignment: .leading, spacing: 6) { + Text("スマホで読み取る") + .font(.system(size: 13, weight: .semibold)) + Text(webServerManager.authEnabled + ? "カメラで読み取ると,ブラウザで接続先が開きます.開いたら「PIN認証」の6桁のPINを入力します." + : "カメラで読み取ると,ブラウザで接続先が開きます.(PIN認証は無効です)") + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) + .fixedSize(horizontal: false, vertical: true) + Text("iPhoneアプリは,このMacを自動で見つけます.") + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) + .fixedSize(horizontal: false, vertical: true) + } } - } + } + } + } + + // MARK: 停止中:接続の手順 + + private var connectionSteps: some View { + VStack(alignment: .leading, spacing: 12) { + Text("接続方法") + .font(.system(size: 13, weight: .semibold)) + step(1, "端末をMacと同じWi-Fiに接続します.") + step(2, "iPhoneアプリでこのMacを選ぶか,ブラウザで接続先を開きます.") + step(3, webServerManager.authEnabled + ? "「PIN認証」に表示される6桁のPINを入力します." + : "PIN認証は無効です.同じWi-Fi内の端末はPINなしで接続できます.") + Text("接続先のURLは,サーバー開始後にここへ表示されます.") + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) + .padding(.top, 2) + } + } + + /// 番号を小さな丸に入れた手順1行分。 + private func step(_ number: Int, _ text: String) -> some View { + HStack(alignment: .firstTextBaseline, spacing: 10) { + Text("\(number)") + .font(.system(size: 11, weight: .semibold).monospacedDigit()) + .foregroundStyle(NeomorphicTheme.muted) + .frame(width: 20, height: 20) + .background(Circle().fill(NeomorphicTheme.control)) + Text(text) + .font(.appBody) + .fixedSize(horizontal: false, vertical: true) + } + } + + private func toggleServer() { + if webServerManager.isRunning { + webServerManager.stopServer() + } else { + webServerManager.startServer() + } + } } diff --git a/AllServerForMac/Features/Library/Models/AlbumSummary.swift b/AllServerForMac/Features/Library/Models/AlbumSummary.swift new file mode 100644 index 0000000..5543710 --- /dev/null +++ b/AllServerForMac/Features/Library/Models/AlbumSummary.swift @@ -0,0 +1,127 @@ +import Foundation + +/// アルバム/フォルダ1件分の中身の要約。 +/// サイドバーの行・アルバム一覧ページ・フォルダ画面のタイルが、同じ数字を同じ書き方で出すために +/// 集計と文言をここ1箇所にまとめている(ゴミ箱のメディアは数えない)。 +struct AlbumSummary { + var videoCount = 0 + var photoCount = 0 + /// 動画の合計再生時間(秒)。画像は含まない。 + var totalDuration: TimeInterval = 0 + /// 配下の、中身のある実アルバムの数。フォルダの「3アルバム」表示に使う + /// (空のアルバムを数えると、見える中身より多く見えてしまう)。 + var albumCount = 0 + var latestImportDate: Date? + /// 表紙に使う代表メディア(最大4件)。自分のアルバムを先に、足りなければ子孫を順に辿る + /// (サーバー・iOSクライアントの coverVideoID と同じ「先頭から」の考え方)。 + var coverItems: [VideoItem] = [] + + static let coverLimit = 4 + + var mediaCount: Int { videoCount + photoCount } + + mutating func merge(_ other: AlbumSummary) { + videoCount += other.videoCount + photoCount += other.photoCount + totalDuration += other.totalDuration + albumCount += other.albumCount + if let date = other.latestImportDate { + latestImportDate = max(latestImportDate ?? date, date) + } + let room = Self.coverLimit - coverItems.count + if room > 0 { + coverItems.append(contentsOf: other.coverItems.prefix(room)) + } + } + + // MARK: - 集計 + + /// ゴミ箱を除いたメディアの索引。呼び出し側で1回だけ作って、全アルバムの集計に使い回す。 + static func itemIndex(_ videos: [VideoItem]) -> [UUID: VideoItem] { + var index: [UUID: VideoItem] = [:] + index.reserveCapacity(videos.count) + for video in videos where !video.isInTrash { + index[video.id] = video + } + return index + } + + /// 実アルバム1件ぶん(そのアルバム自身のメディアだけ)。 + static func of(album: Album, itemByID: [UUID: VideoItem]) -> AlbumSummary { + var summary = AlbumSummary() + for id in album.videoIDs { + guard let item = itemByID[id] else { continue } + if item.mediaType == .video { + summary.videoCount += 1 + summary.totalDuration += item.duration + } else { + summary.photoCount += 1 + } + summary.latestImportDate = max(summary.latestImportDate ?? item.importDate, item.importDate) + if summary.coverItems.count < coverLimit { + summary.coverItems.append(item) + } + } + summary.albumCount = summary.mediaCount > 0 ? 1 : 0 + return summary + } + + /// 画面に出ているメディアの並び(検索で絞った結果など)から作る要約。ページ見出しの2行目に使う。 + static func of(items: [VideoItem]) -> AlbumSummary { + var summary = AlbumSummary() + for item in items { + if item.mediaType == .video { + summary.videoCount += 1 + summary.totalDuration += item.duration + } else { + summary.photoCount += 1 + } + } + return summary + } + + /// フォルダ/アルバムのノード1件ぶん(配下をすべて含む)。 + static func of(node: SidebarAlbumNode, itemByID: [UUID: VideoItem]) -> AlbumSummary { + var summary = AlbumSummary() + if let album = node.album { + summary.merge(of(album: album, itemByID: itemByID)) + } + for child in node.children { + summary.merge(of(node: child, itemByID: itemByID)) + } + return summary + } + + // MARK: - 文言 + + /// 「動画 12本 · 38分」「画像 120枚」「5アルバム · 動画 80本 · 4時間12分」のような1行の説明。 + func detailText(isFolder: Bool) -> String { + var parts: [String] = [] + if isFolder, albumCount > 0 { + parts.append("\(albumCount.formatted())アルバム") + } + if videoCount > 0 { + parts.append("動画 \(videoCount.formatted())本") + if totalDuration >= 1 { + parts.append(Self.durationText(totalDuration)) + } + } + if photoCount > 0 { + parts.append("画像 \(photoCount.formatted())枚") + } + if mediaCount == 0 { + parts.append("空のアルバム") + } + return parts.joined(separator: " · ") + } + + static func durationText(_ seconds: TimeInterval) -> String { + let total = Int(seconds.rounded()) + if total < 60 { return "\(total)秒" } + let minutes = total / 60 + if minutes < 60 { return "\(minutes)分" } + let hours = minutes / 60 + let rest = minutes % 60 + return rest == 0 ? "\(hours)時間" : "\(hours)時間\(rest)分" + } +} diff --git a/AllServerForMac/Features/Library/ViewModels/LibraryViewModel+DuplicateChecking.swift b/AllServerForMac/Features/Library/ViewModels/LibraryViewModel+DuplicateChecking.swift index 518c0f4..ba3b83e 100644 --- a/AllServerForMac/Features/Library/ViewModels/LibraryViewModel+DuplicateChecking.swift +++ b/AllServerForMac/Features/Library/ViewModels/LibraryViewModel+DuplicateChecking.swift @@ -111,6 +111,9 @@ extension LibraryViewModel { // オフにしても30秒ごとにライブラリ全件走査が走り、UIが定期的に引っかかっていた。 // 状態表示は初回に一度だけ更新すれば足りるので、既にオフ表示なら何もしない。 if self.duplicateCheckStatus.statusMessage != "自動チェックはオフです" { + // ただしアルバム一覧のキャッシュは一度作っておく。空のままだとホームの件数が 0/0 になり、 + // 自動チェックと独立して使えるはずの「今すぐすべてチェック」まで押せなくなる。 + self.refreshDuplicateCheckAlbumCaches() self.duplicateCheckStatus.isAutoChecking = false self.duplicateCheckStatus.currentAlbumName = nil self.duplicateCheckStatus.progress = 0 diff --git a/AllServerForMac/Features/Library/ViewModels/LibraryViewModel+Import.swift b/AllServerForMac/Features/Library/ViewModels/LibraryViewModel+Import.swift index a33bc5a..a091162 100644 --- a/AllServerForMac/Features/Library/ViewModels/LibraryViewModel+Import.swift +++ b/AllServerForMac/Features/Library/ViewModels/LibraryViewModel+Import.swift @@ -221,7 +221,7 @@ extension LibraryViewModel { saveData() if failedCount > 0 { - print("⚠️ [IMPORT] \(failedCount)件のメディアをインポートできませんでした。") + print("⚠️ [IMPORT] \(failedCount)件のメディアをインポートできませんでした.") } } diff --git a/AllServerForMac/Features/Library/ViewModels/LibraryViewModel+LinkedFolders.swift b/AllServerForMac/Features/Library/ViewModels/LibraryViewModel+LinkedFolders.swift index f93217a..0fe081e 100644 --- a/AllServerForMac/Features/Library/ViewModels/LibraryViewModel+LinkedFolders.swift +++ b/AllServerForMac/Features/Library/ViewModels/LibraryViewModel+LinkedFolders.swift @@ -554,7 +554,7 @@ extension LibraryViewModel { guard !linkedFolderScanStatus.isScanning else { return } let linkedAlbums = albums.filter { $0.linkedFolderPath != nil || $0.linkedFolderBookmarkData != nil } guard !linkedAlbums.isEmpty else { - linkedFolderScanStatus.statusMessage = "リンクされたフォルダはありません。" + linkedFolderScanStatus.statusMessage = "リンクされたフォルダはありません." return } @@ -596,11 +596,11 @@ extension LibraryViewModel { linkedFolderScanStatus.currentFolderName = nil linkedFolderScanStatus.processedItemsInCurrentFolder = 0 if wasCancelled { - linkedFolderScanStatus.statusMessage = "リンクフォルダの更新を中止しました。" + linkedFolderScanStatus.statusMessage = "リンクフォルダの更新を中止しました." } else { linkedFolderScanStatus.statusMessage = imported > 0 - ? "\(linkedAlbums.count)件のフォルダを更新し、\(imported)件の新しいメディアを取り込みました。" - : "\(linkedAlbums.count)件のフォルダを更新しました(新規メディアはありません)。" + ? "\(linkedAlbums.count)件のフォルダを更新し,\(imported)件の新しいメディアを取り込みました." + : "\(linkedAlbums.count)件のフォルダを更新しました(新規メディアはありません)." } } diff --git a/AllServerForMac/Features/Library/ViewModels/LibraryViewModel+MediaFiles.swift b/AllServerForMac/Features/Library/ViewModels/LibraryViewModel+MediaFiles.swift index 9d9cf26..66a8b07 100644 --- a/AllServerForMac/Features/Library/ViewModels/LibraryViewModel+MediaFiles.swift +++ b/AllServerForMac/Features/Library/ViewModels/LibraryViewModel+MediaFiles.swift @@ -316,7 +316,7 @@ extension LibraryViewModel { guard let exportSession = AVAssetExportSession(asset: asset, presetName: preset) else { await MainActor.run { self.proxyProgressMap[key] = nil - self.proxyFailureMap[key] = "このファイルはmacOSの変換機能で読み込めません。" + self.proxyFailureMap[key] = "このファイルはmacOSの変換機能で読み込めません." } return } diff --git a/AllServerForMac/Features/Library/ViewModels/LibraryViewModel+Persistence.swift b/AllServerForMac/Features/Library/ViewModels/LibraryViewModel+Persistence.swift index f155de2..057819c 100644 --- a/AllServerForMac/Features/Library/ViewModels/LibraryViewModel+Persistence.swift +++ b/AllServerForMac/Features/Library/ViewModels/LibraryViewModel+Persistence.swift @@ -89,7 +89,7 @@ extension LibraryViewModel { if let container = try? JSONDecoder().decode(DataContainer.self, from: data) { let isNewerSchema = (container.schemaVersion ?? 0) > librarySchemaVersion if isNewerSchema { - print("⚠️ [LOAD] library.json はこのバージョンより新しい形式(v\(container.schemaVersion ?? 0))です。バックアップの更新をスキップします。") + print("⚠️ [LOAD] library.json はこのバージョンより新しい形式(v\(container.schemaVersion ?? 0))です.バックアップの更新をスキップします.") } let shouldSkipBackup = isNewerSchema diff --git a/AllServerForMac/Features/Library/ViewModels/LibraryViewModel.swift b/AllServerForMac/Features/Library/ViewModels/LibraryViewModel.swift index 9ebbb2d..fa36888 100644 --- a/AllServerForMac/Features/Library/ViewModels/LibraryViewModel.swift +++ b/AllServerForMac/Features/Library/ViewModels/LibraryViewModel.swift @@ -354,7 +354,7 @@ class LibraryViewModel: ObservableObject { DispatchQueue.main.async { let alert = NSAlert() alert.messageText = "AllServerForMac は既に起動しています" - alert.informativeText = "別のインスタンス(例: Xcodeからの実行と通常起動)が同じライブラリを開いています。データの二重書き込みによる消失を防ぐため、このインスタンスは終了します。" + alert.informativeText = "別のインスタンス(例: Xcodeからの実行と通常起動)が同じライブラリを開いています.データの二重書き込みによる消失を防ぐため,このインスタンスは終了します." alert.alertStyle = .warning alert.runModal() NSApplication.shared.terminate(nil) diff --git a/AllServerForMac/Features/Library/Views/AlbumDetailView.swift b/AllServerForMac/Features/Library/Views/AlbumDetailView.swift index ee71e13..7b0caf7 100644 --- a/AllServerForMac/Features/Library/Views/AlbumDetailView.swift +++ b/AllServerForMac/Features/Library/Views/AlbumDetailView.swift @@ -63,13 +63,22 @@ struct AlbumDetailView: View { /// 実際に並べる列数。グリッドの組み立てと矢印キーの上下移動が必ず同じ値を見るように、 /// ここだけで決める(ズレると下キーが斜めに飛ぶ)。 private var columnCount: Int { - max(2, Int(appSettings.columnCount)) + MediaGridLayout.columnCount(requested: appSettings.columnCount, availableWidth: gridWidth) } + /// グリッドを置く領域の幅。狭いウィンドウで列を自動的に減らすために測る。 + @State private var gridWidth: CGFloat = 0 + private var gridColumns: [GridItem] { Array(repeating: GridItem(.flexible(), spacing: MediaGridLayout.spacing), count: columnCount) } + /// ツールバーの「整理」メニューに出せる項目が1つでもあるか。 + private var hasOrganizeTools: Bool { + canRemoveItemsFromCurrentAlbum || displayedItems.count >= 2 + || displayedItems.contains(where: { $0.mediaType == .photo }) + } + private var currentAlbum: Album { dataManager.albums.first(where: { $0.id == album.id }) ?? album } @@ -102,6 +111,16 @@ struct AlbumDetailView: View { displayedItems.filter { selectedVideoIDs.contains($0.id) } } + private func headerSubtitle(for items: [VideoItem]) -> String { + var parts: [String] = [] + let folders = album.name.components(separatedBy: "/").dropLast() + if canRemoveItemsFromCurrentAlbum, !folders.isEmpty { + parts.append(folders.joined(separator: " › ")) + } + parts.append(AlbumSummary.of(items: items).detailText(isFolder: false)) + return parts.joined(separator: " · ") + } + private var canRemoveItemsFromCurrentAlbum: Bool { album.name != LibraryViewModel.allVideosAlbumName && album.name != LibraryViewModel.allPhotosAlbumName } @@ -114,6 +133,12 @@ struct AlbumDetailView: View { let selectedItems = items.filter { selectedVideoIDs.contains($0.id) && $0.mediaType == .video } return VStack(spacing: 0) { + LibraryPageHeader( + title: album.displayTitle, + // 2行目は「動画 12本 · 38分」のような中身の要約にする(以前は見出しと同じ名前の繰り返しだった)。 + // 階層のあるアルバムは、場所が分かるよう親フォルダのパスを頭に付ける。 + subtitle: headerSubtitle(for: items) + ) ZStack { // 背景タップで選択解除(カードタップ時は内側のジェスチャーが優先される) Color.clear @@ -143,11 +168,12 @@ struct AlbumDetailView: View { .foregroundColor(.white) Text("\(duplicateCheckCurrent) / \(duplicateCheckTotal) (\(Int(duplicateCheckProgress * 100))%)") .foregroundColor(.white) - .font(.subheadline) + .font(.appBody) } - .padding() - .background(.thickMaterial) - .cornerRadius(12) + .padding(20) + .background(NeomorphicTheme.card, in: RoundedRectangle(cornerRadius: 14, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(NeomorphicTheme.cardBorder, lineWidth: 0.5)) + .environment(\.colorScheme, NeomorphicTheme.isDarkBase ? .dark : .light) } // フォルダの中身が多いと動画の尺・撮影日時の読み込みに時間がかかるため、 @@ -160,11 +186,12 @@ struct AlbumDetailView: View { .tint(.accentColor) Text("インポート中...(\(importedCount)件処理済み)") .foregroundColor(.white) - .font(.subheadline) + .font(.appBody) } - .padding() - .background(.thickMaterial) - .cornerRadius(12) + .padding(20) + .background(NeomorphicTheme.card, in: RoundedRectangle(cornerRadius: 14, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(NeomorphicTheme.cardBorder, lineWidth: 0.5)) + .environment(\.colorScheme, NeomorphicTheme.isDarkBase ? .dark : .light) } if isExporting { @@ -177,11 +204,12 @@ struct AlbumDetailView: View { .foregroundColor(.white) Text("\(exportCurrent) / \(exportTotal)") .foregroundColor(.white) - .font(.subheadline) + .font(.appBody) } - .padding() - .background(.thickMaterial) - .cornerRadius(12) + .padding(20) + .background(NeomorphicTheme.card, in: RoundedRectangle(cornerRadius: 14, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(NeomorphicTheme.cardBorder, lineWidth: 0.5)) + .environment(\.colorScheme, NeomorphicTheme.isDarkBase ? .dark : .light) } } @@ -191,6 +219,9 @@ struct AlbumDetailView: View { .background(CommandDeckBackground()) .searchable(text: $searchText, placement: .toolbar, prompt: "タイトルを検索") .toolbar { + ToolbarItem(placement: .primaryAction) { + LibraryTourMenu(videos: videoItems, dataManager: dataManager, beforePlay: { rememberGridState() }) + } ToolbarItem(placement: .primaryAction) { Button(action: importFilesViaDialog) { Label("インポート", systemImage: "plus.circle") @@ -208,63 +239,63 @@ struct AlbumDetailView: View { } } - // 重複チェックはアルバム単位でのみ意味を持つ(すべての動画/画像には全アルバムのメディアが - // 集まっているため、ここで実行すると別アルバム同士のメディアまで重複扱いになってしまう)。 - if canRemoveItemsFromCurrentAlbum { - ToolbarItem(placement: .primaryAction) { - Button(action: runDuplicateCheck) { - Label("重複チェック", systemImage: "checkmark.seal") - } - .help("このアルバム内の重複メディアを検出してゴミ箱へ移動") - .disabled(isCheckingDuplicates || dataManager.isDuplicateCheckRunning || items.isEmpty) - } - } - - // ラフ画・線画の抽出(画像がある場合のみ) + // 重複チェック・似ているもの・差分動画などの整理系ツールは,アイコンだけを5つ並べると + // 見分けがつかないため,名前付きの1つのメニューにまとめる。 ToolbarItem(placement: .primaryAction) { - if items.contains(where: { $0.mediaType == .photo }) { - Button { - showSketchCleanup = true - } label: { - Label("ラフ画・線画", systemImage: "scribble.variable") - } - .help("このアルバムの画像からラフ画・線画を自動で拾い出して、確認してから削除します") - } - } + if hasOrganizeTools { + Menu { + // 重複チェックはアルバム単位でのみ意味を持つ(すべての動画/画像には全アルバムのメディアが + // 集まっているため、ここで実行すると別アルバム同士のメディアまで重複扱いになってしまう)。 + if canRemoveItemsFromCurrentAlbum { + Button(action: runDuplicateCheck) { + Label("重複チェック", systemImage: "checkmark.seal") + } + .help("このアルバム内の重複メディアを検出してゴミ箱へ移動") + .disabled(isCheckingDuplicates || dataManager.isDuplicateCheckRunning || items.isEmpty) + } - // 似ているメディアの整理(重複チェックと違い、完全一致でなくても拾う) - ToolbarItem(placement: .primaryAction) { - if items.count >= 2 { - Button { - showSimilarMedia = true - } label: { - Label("似ているものを探す", systemImage: "square.on.square.dashed") - } - .help("見た目が似ているメディアをまとめて表示し、残す1件を選んで残りを削除します") - } - } + // 似ているメディアの整理(重複チェックと違い、完全一致でなくても拾う) + if items.count >= 2 { + Button { + showSimilarMedia = true + } label: { + Label("似ているものを探す", systemImage: "square.on.square.dashed") + } + .help("見た目が似ているメディアをまとめて表示し,残す1件を選んで残りを削除します") + } - // 差分動画(同じ尺・同じ動きで絵だけ違う書き出し)を探して切り替え再生へ渡す - ToolbarItem(placement: .primaryAction) { - if videoItems.count >= 2 { - Button { - openVariantFinder(alignmentMode: .sameTime) - } label: { - Label("差分動画を探す", systemImage: "rectangle.on.rectangle.angled") - } - .help("尺が揃っていて絵だけが違う動画を束にして、選んだぶんを切り替えながら再生します") - } - } + // ラフ画・線画の抽出(画像がある場合のみ) + if items.contains(where: { $0.mediaType == .photo }) { + Button { + showSketchCleanup = true + } label: { + Label("ラフ画・線画を探す", systemImage: "scribble.variable") + } + .help("このアルバムの画像からラフ画・線画を自動で拾い出して,確認してから削除します") + } - // 尺が違っても,動画内の一部に同じ場面が続く強制差分候補を探す - ToolbarItem(placement: .primaryAction) { - if videoItems.count >= 2 { - Button { - openVariantFinder(alignmentMode: .content) + if videoItems.count >= 2 { + Divider() + // 差分動画(同じ尺・同じ動きで絵だけ違う書き出し)を探して切り替え再生へ渡す + Button { + openVariantFinder(alignmentMode: .sameTime) + } label: { + Label("差分動画を探す", systemImage: "rectangle.on.rectangle.angled") + } + .help("尺が揃っていて絵だけが違う動画を束にして,選んだぶんを切り替えながら再生します") + + // 尺が違っても,動画内の一部に同じ場面が続く強制差分候補を探す + Button { + openVariantFinder(alignmentMode: .content) + } label: { + Label("強制差分候補を探す", systemImage: "link.badge.plus") + } + .help("尺が大きく違っても,一部に同じ場面が続く動画を探します") + } } label: { - Label("強制差分候補を探す", systemImage: "link.badge.plus") + Label("整理", systemImage: "wand.and.stars") } - .help("尺が大きく違っても,一部に同じ場面が続く動画を探します") + .help("重複チェック・似ているもの・差分動画など,アルバムを整理する機能") } } @@ -280,7 +311,7 @@ struct AlbumDetailView: View { } label: { Label("ランダム同時再生", systemImage: "square.grid.2x2") } - .help("このアルバムの動画から、選んだ本数だけ無作為に選んで同時再生します") + .help("このアルバムの動画から,選んだ本数だけ無作為に選んで同時再生します") } } @@ -299,7 +330,7 @@ struct AlbumDetailView: View { if !selectedVideoIDs.isEmpty { ToolbarItem(placement: .primaryAction) { Text("\(selectedVideoIDs.count)項目を選択中") - .font(.system(size: 11)) + .font(.appMicro) .foregroundStyle(.secondary) } if selectedItems.count == 1, let video = selectedItems.first { @@ -312,44 +343,38 @@ struct AlbumDetailView: View { .help("選択した動画から候補シーンを抽出します") } } + // 複数選択時の再生方法は4種類あり,アイコンだけを並べると見分けにくいので1つのメニューにまとめる。 ToolbarItem(placement: .primaryAction) { if selectedItems.count >= 2 { - Button { - startMultiPlayback(selectedItems) - } label: { - Label("同時再生", systemImage: "square.grid.2x2.fill") - } - .help("選択した動画を同期再生(最大9本)") - } - } - ToolbarItem(placement: .primaryAction) { - if selectedItems.count >= 2 { - Button { - startVariantSwitchPlayback(selectedItems) - } label: { - Label("差分切り替え再生", systemImage: "rectangle.on.rectangle.angled") - } - .help("選択した動画を同期再生し、一定間隔/キー操作で見せる1本を切り替える(最大9本)") - } - } - ToolbarItem(placement: .primaryAction) { - if selectedItems.count >= 2 { - Button { - startContentAlignedVariantPlayback(selectedItems) - } label: { - Label("類似点で合わせる", systemImage: "link") - } - .help("動画内の類似場面を探し,最初に共通位置へ一度だけ合わせて再生する(最大9本)") - } - } - ToolbarItem(placement: .primaryAction) { - if selectedItems.count >= 2 { - Button { - startSlideshowPlayback(selectedItems) + Menu { + Button { + startMultiPlayback(selectedItems) + } label: { + Label("同時再生", systemImage: "square.grid.2x2.fill") + } + .help("選択した動画を同期再生(最大9本)") + Button { + startVariantSwitchPlayback(selectedItems) + } label: { + Label("差分切り替え再生", systemImage: "rectangle.on.rectangle.angled") + } + .help("選択した動画を同期再生し,一定間隔/キー操作で見せる1本を切り替える(最大9本)") + Button { + startContentAlignedVariantPlayback(selectedItems) + } label: { + Label("類似点で合わせる", systemImage: "link") + } + .help("動画内の類似場面を探し,最初に共通位置へ一度だけ合わせて再生する(最大9本)") + Button { + startSlideshowPlayback(selectedItems) + } label: { + Label("スライドショー", systemImage: "play.square.stack") + } + .help("選択した動画をスライドショー再生") } label: { - Label("スライドショー", systemImage: "play.square.stack") + Label("選択を再生", systemImage: "play.rectangle.on.rectangle") } - .help("選択した動画をスライドショー再生") + .help("選択した動画を同時再生・差分切り替え・スライドショーなどで再生") } } ToolbarItem(placement: .primaryAction) { @@ -425,7 +450,7 @@ struct AlbumDetailView: View { } Button("キャンセル", role: .cancel) { pendingFolderURL = nil } } message: { - Text("\(mixedContentInfo)\n指定したタイプ (\(album.type.displayName)) 以外のファイルは無視されます。") + Text("\(mixedContentInfo)\n指定したタイプ (\(album.type.displayName)) 以外のファイルは無視されます.") } .alert("重複チェック完了", isPresented: $showDuplicateCheckResultAlert) { Button("OK", role: .cancel) { } @@ -450,22 +475,22 @@ struct AlbumDetailView: View { } Button("キャンセル", role: .cancel) { pendingMoveVideoIDs = [] } } message: { - Text("移動先の新しいアルバム名を入力してください。") + Text("移動先の新しいアルバム名を入力してください.") } .sheet(isPresented: $showSplitSheet) { VStack(spacing: 20) { Text("分割再生") - .font(.headline) + .font(.system(size: 17, weight: .semibold)) if let video = splitTargetVideo { Text(video.originalFilename) - .font(.subheadline) + .font(.appBody) .foregroundStyle(.secondary) .lineLimit(1) } Stepper("分割数: \(splitCount)", value: $splitCount, in: 2...9) .frame(width: 200) Text("動画を\(splitCount)等分して\(splitCount)画面で同時再生します") - .font(.caption) + .font(.appCaption) .foregroundStyle(.secondary) HStack(spacing: 16) { Button("キャンセル") { showSplitSheet = false } @@ -482,6 +507,7 @@ struct AlbumDetailView: View { } .padding(30) .frame(minWidth: 320) + .appSheet() } // 他のアルバムに移動したら、このアルバムのデコード済みサムネイルはメモリから解放する。 // ディスクキャッシュは消さないので、戻ってきたときの再表示は速いまま。 @@ -560,6 +586,7 @@ struct AlbumDetailView: View { .padding(MediaGridLayout.contentInset) } .scrollPosition(id: $scrollTargetMediaID, anchor: .top) + .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { gridWidth = $0 } // フォーカスはグリッド全体で1つだけ持つ。セルごとに .focusable() を付けると、 // SwiftUI 標準の矢印キーによるフォーカス送りが自前の「index ± 列数」移動と同時に走り、 // 1回の入力で二重に動いたり斜めに飛んだりする(列数によって挙動が変わって見える原因)。 @@ -752,12 +779,15 @@ struct AlbumDetailView: View { } private var noResultsState: some View { - ContentUnavailableView( - "該当する項目がありません", - systemImage: "magnifyingglass", - description: Text("「\(searchText)」に一致するタイトルは見つかりませんでした") - ) - .frame(maxWidth: .infinity, maxHeight: .infinity) + ContentUnavailableView { + Label("該当する項目がありません", systemImage: "magnifyingglass") + } description: { + Text("「\(searchText)」に一致するタイトルは見つかりませんでした.") + } actions: { + Button("検索を解除") { searchText = "" } + .buttonStyle(.borderedProminent) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) } private var emptyState: some View { @@ -766,9 +796,9 @@ struct AlbumDetailView: View { .font(.system(size: 42, weight: .light)) .foregroundStyle(.secondary) Text("メディアがありません") - .font(.title3.weight(.semibold)) + .font(.appTitle.weight(.semibold)) Text("ファイルやフォルダをここにドロップして追加") - .font(.callout) + .font(.appBody) .foregroundStyle(.secondary) } .padding(48) @@ -783,13 +813,13 @@ struct AlbumDetailView: View { private var dropOverlay: some View { ZStack { Rectangle() - .fill(.ultraThinMaterial) + .fill(NeomorphicTheme.canvas.opacity(0.88)) VStack(spacing: 10) { Image(systemName: "arrow.down.circle.fill") .font(.system(size: 44)) .foregroundStyle(Color.accentColor) Text("ドロップして追加") - .font(.title3.weight(.semibold)) + .font(.appTitle.weight(.semibold)) } } .overlay( @@ -872,7 +902,7 @@ struct AlbumDetailView: View { func loadNextProvider(at index: Int) { guard index < providers.count else { if loadedURLs.count != providers.count { - print("⚠️ [DROP] \(providers.count)件中\(loadedURLs.count)件のURLを取得しました。") + print("⚠️ [DROP] \(providers.count)件中\(loadedURLs.count)件のURLを取得しました.") } completion(loadedURLs) return @@ -956,8 +986,8 @@ struct AlbumDetailView: View { } isExporting = false exportResultMessage = result.failedCount > 0 - ? "\(result.successCount)件を書き出しました。\(result.failedCount)件は失敗しました。" - : "\(result.successCount)件を書き出しました。" + ? "\(result.successCount)件を書き出しました.\(result.failedCount)件は失敗しました." + : "\(result.successCount)件を書き出しました." showExportResultAlert = true } } @@ -988,9 +1018,9 @@ struct AlbumDetailView: View { private func duplicateCheckMessage(for result: DuplicateCheckResult) -> String { var lines: [String] if result.duplicateCount > 0 { - lines = ["\(result.duplicateCount)件の重複メディアをゴミ箱へ移動しました。"] + lines = ["\(result.duplicateCount)件の重複メディアをゴミ箱へ移動しました."] } else { - lines = ["重複メディアは見つかりませんでした。"] + lines = ["重複メディアは見つかりませんでした."] } lines.append("確認した項目: \(result.checkedCount)件") @@ -1221,3 +1251,15 @@ struct AlbumDetailView: View { coordinator.playSplit(video: video, splitCount: splitCount) } } + +extension Album { + /// 画面に出すアルバム名。システムアルバムの内部名(ALL VIDEOS など)は日本語にし, + /// 階層付きの名前は末尾だけにする。ページ見出しとウィンドウタイトルで同じ表記を使う。 + @MainActor var displayTitle: String { + switch name { + case LibraryViewModel.allVideosAlbumName: return "すべての動画" + case LibraryViewModel.allPhotosAlbumName: return "すべての画像" + default: return name.components(separatedBy: "/").last ?? name + } + } +} diff --git a/AllServerForMac/Features/Library/Views/AlbumOverviewView.swift b/AllServerForMac/Features/Library/Views/AlbumOverviewView.swift new file mode 100644 index 0000000..c9da5f9 --- /dev/null +++ b/AllServerForMac/Features/Library/Views/AlbumOverviewView.swift @@ -0,0 +1,299 @@ +import SwiftUI + +// MARK: - アルバム一覧ページ(動画・画像のアルバムを表紙つきで並べる) + +/// サイドバーの「アルバム一覧」で右ペインに出す画面。 +/// サイドバーは名前と件数しか見えず、アルバムが多いと中身の見当がつかないので、 +/// 表紙・本数・合計時間を一度に見渡せるカードで並べる。フォルダは階層のまま、または全アルバムを平らに並べられる。 +struct AlbumOverviewView: View { + @ObservedObject var dataManager: LibraryViewModel + @Binding var selection: NavigationSelection? + + @EnvironmentObject private var appSettings: AppSettings + + enum Kind: String, CaseIterable, Identifiable { + case all = "すべて" + case video = "動画" + case photo = "画像" + var id: String { rawValue } + } + + enum Order: String, CaseIterable, Identifiable { + case name = "名前" + case count = "件数の多い順" + case recent = "最近追加した順" + case duration = "再生時間の長い順" + var id: String { rawValue } + } + + /// 動画ツリー/画像ツリーそれぞれのカード一式。 + private struct OverviewSection: Identifiable { + let isPhoto: Bool + let entries: [FolderEntry] + var id: Bool { isPhoto } + var title: String { isPhoto ? "画像アルバム" : "動画アルバム" } + } + + @AppStorage("albumOverview.kind") private var kind: Kind = .all + @AppStorage("albumOverview.order") private var order: Order = .name + /// フォルダの中のアルバムも最上位に並べる(false なら、フォルダはフォルダとして1枚のカードにまとめる)。 + @AppStorage("albumOverview.flat") private var showsAllAlbums = false + /// 中身のないアルバム(紐づけ元のフォルダが空になったものなど)を出さない。 + @AppStorage("albumOverview.hideEmpty") private var hidesEmpty = false + + @State private var searchText = "" + @State private var sections: [OverviewSection] = [] + /// 絞り込み前の,実アルバムの総数(サイドバーの「アルバム一覧」の件数と同じ数え方)。 + @State private var totalAlbumCount = 0 + + private var trimmedQuery: String { + searchText.trimmingCharacters(in: .whitespacesAndNewlines) + } + + /// 検索中は、フォルダの中も含めて名前に一致するアルバムをすべて出す(サイドバーの検索と同じ考え方)。 + private var isFlat: Bool { + showsAllAlbums || !trimmedQuery.isEmpty + } + + private var totalCount: Int { + sections.reduce(0) { $0 + $1.entries.count } + } + + var body: some View { + VStack(spacing: 0) { + LibraryPageHeader( + title: "アルバム", + subtitle: isFlat + ? "フォルダの中も含めて,アルバムを1枚ずつ並べています.(全\(totalAlbumCount.formatted())アルバム)" + : "全\(totalAlbumCount.formatted())アルバム.フォルダのカードを開くと,中のアルバムが見られます.", + count: totalCount + ) + + controls + + Divider() + + if totalCount == 0 { + emptyState + } else { + ScrollView { + VStack(alignment: .leading, spacing: 24) { + ForEach(sections) { section in + if !section.entries.isEmpty { + sectionTitle(section.title, count: section.entries.count) + LazyVGrid( + columns: [GridItem(.adaptive(minimum: 150, maximum: 230), spacing: 14)], + alignment: .leading, + spacing: 14 + ) { + ForEach(section.entries) { entry in + FolderEntryTile( + entry: entry, + dataManager: dataManager, + onOpen: { open(entry, isPhoto: section.isPhoto) } + ) + } + } + } + } + } + .padding(MediaGridLayout.contentInset) + .padding(.bottom, 12) + } + } + } + .background(CommandDeckBackground()) + .searchable(text: $searchText, placement: .toolbar, prompt: "アルバム名を検索") + .onAppear(perform: rebuild) + .onChange(of: dataManager.albums) { rebuild() } + .onChange(of: dataManager.videos) { rebuild() } + .onChange(of: kind) { rebuild() } + .onChange(of: order) { rebuild() } + .onChange(of: showsAllAlbums) { rebuild() } + .onChange(of: hidesEmpty) { rebuild() } + .onChange(of: searchText) { rebuild() } + .onDisappear { + // 表紙のためにデコードした画像を持ち越さない(ディスクキャッシュは残るので戻れば即表示される)。 + MacVideoThumbnailView.evictFromMemoryCache( + videoIDs: sections.flatMap { $0.entries.flatMap { $0.coverItems.map(\.id) } } + ) + } + } + + // MARK: - 操作バー + + /// 幅が足りないとチェックボックスの文言が折り返して崩れるので、そのときは2段に組み替える。 + private var controls: some View { + ViewThatFits(in: .horizontal) { + HStack(spacing: 16) { + kindPicker + flatToggle + hideEmptyToggle + orderMenu + } + VStack(alignment: .leading, spacing: 8) { + HStack(spacing: 16) { + kindPicker + orderMenu + } + HStack(spacing: 16) { + flatToggle + hideEmptyToggle + } + } + } + .font(.appCaption) + .padding(.horizontal, 24) + .padding(.vertical, 10) + .frame(maxWidth: .infinity, alignment: .leading) + } + + private var kindPicker: some View { + FlatSegmentedControl( + options: Kind.allCases, + title: { $0.rawValue }, + selection: $kind, + width: 190 + ) + .accessibilityLabel("種類") + } + + private var flatToggle: some View { + Toggle("フォルダの中も並べる", isOn: $showsAllAlbums) + .toggleStyle(.checkbox) + .lineLimit(1) + .fixedSize() + .disabled(!trimmedQuery.isEmpty) + .help(trimmedQuery.isEmpty + ? "オンにすると,フォルダの中のアルバムも最上位に並べます." + : "検索中は,フォルダの中も含めて探します.") + } + + private var hideEmptyToggle: some View { + Toggle("空のアルバムを隠す", isOn: $hidesEmpty) + .toggleStyle(.checkbox) + .lineLimit(1) + .fixedSize() + .help("中身が0件のアルバムを一覧から外します.オフでも,空のアルバムは各区画の末尾にまとまります.") + } + + private var orderMenu: some View { + Menu { + ForEach(Order.allCases) { option in + Toggle(option.rawValue, isOn: Binding( + get: { order == option }, + set: { isOn in if isOn { order = option } } + )) + } + } label: { + Label("並び順:\(order.rawValue)", systemImage: "arrow.up.arrow.down") + } + .fixedSize() + } + + private func sectionTitle(_ title: String, count: Int) -> some View { + HStack(spacing: 8) { + Text(title) + .font(.system(size: 12, weight: .bold, design: .default)) + .foregroundStyle(.secondary) + Text("\(count.formatted())") + .font(.system(size: 11, weight: .semibold, design: .monospaced)) + .foregroundStyle(.tertiary) + } + .padding(.leading, 4) + } + + @ViewBuilder + private var emptyState: some View { + if trimmedQuery.isEmpty { + ContentUnavailableView( + "アルバムがありません", + systemImage: "rectangle.stack", + description: Text("サイドバーの+でアルバムを作るか,フォルダをサイドバーへドラッグして取り込んでください.") + ) + } else { + ContentUnavailableView( + "一致するアルバムはありません", + systemImage: "magnifyingglass", + description: Text("「\(trimmedQuery)」を名前に含むアルバムは見つかりませんでした.") + ) + } + } + + // MARK: - 組み立て + + /// 表示内容は videos / albums / 絞り込み条件が変わったときだけ組み立て直す + /// (body のたびに全メディアを集計し直さないため)。 + private func rebuild() { + let itemByID = AlbumSummary.itemIndex(dataManager.videos) + let terms = trimmedQuery.split(whereSeparator: \.isWhitespace).map(String.init) + + let built: [OverviewSection] = [false, true].compactMap { isPhoto in + guard kind == .all || (kind == .photo) == isPhoto else { return nil } + let albums = SidebarViewModel.treeAlbums(from: dataManager.albums, isPhoto: isPhoto) + + var entries: [FolderEntry] + if isFlat { + entries = albums + .filter { album in terms.allSatisfy { album.name.localizedStandardContains($0) } } + .map { album in + FolderEntry( + id: album.id.uuidString, + title: album.name, + isFolder: false, + kind: .album(album.id), + summary: AlbumSummary.of(album: album, itemByID: itemByID) + ) + } + } else { + let roots = SidebarAlbumNode.buildTree(from: albums) + // 作ったばかりの空のアルバムも出す(出ないと「作ったのに無い」ように見える)。 + entries = FolderContent.entries(for: roots, itemByID: itemByID, includeEmpty: true) + } + + if hidesEmpty { + entries.removeAll { $0.count == 0 } + } + entries.sort(by: ordering) + return OverviewSection(isPhoto: isPhoto, entries: entries) + } + sections = built + totalAlbumCount = [false, true] + .filter { kind == .all || (kind == .photo) == $0 } + .reduce(0) { $0 + SidebarViewModel.treeAlbums(from: dataManager.albums, isPhoto: $1).count } + } + + private func ordering(_ lhs: FolderEntry, _ rhs: FolderEntry) -> Bool { + // 中身のないアルバムは、どの並び順でも末尾にまとめる(先頭に並ぶと本命が見えなくなる)。 + if (lhs.count == 0) != (rhs.count == 0) { return lhs.count != 0 } + let byName = lhs.title.localizedStandardCompare(rhs.title) == .orderedAscending + switch order { + case .name: + return byName + case .count: + if lhs.count != rhs.count { return lhs.count > rhs.count } + return byName + case .recent: + switch (lhs.summary.latestImportDate, rhs.summary.latestImportDate) { + case let (l?, r?) where l != r: return l > r + case (_?, nil): return true + case (nil, _?): return false + default: return byName + } + case .duration: + if lhs.summary.totalDuration != rhs.summary.totalDuration { + return lhs.summary.totalDuration > rhs.summary.totalDuration + } + return byName + } + } + + private func open(_ entry: FolderEntry, isPhoto: Bool) { + switch entry.kind { + case .folder(let path): + selection = .folder(path: path, isPhoto: isPhoto) + case .album(let albumID): + selection = .album(albumID) + } + } +} diff --git a/AllServerForMac/Features/Library/Views/FolderDetailView.swift b/AllServerForMac/Features/Library/Views/FolderDetailView.swift index 0590130..7ee9077 100644 --- a/AllServerForMac/Features/Library/Views/FolderDetailView.swift +++ b/AllServerForMac/Features/Library/Views/FolderDetailView.swift @@ -26,9 +26,12 @@ struct FolderDetailView: View { @State private var pendingMoveVideoIDs: [UUID] = [] private var columnCount: Int { - max(2, Int(appSettings.columnCount)) + MediaGridLayout.columnCount(requested: appSettings.columnCount, availableWidth: gridWidth) } + /// グリッドを置く領域の幅。狭いウィンドウで列を自動的に減らすために測る。 + @State private var gridWidth: CGFloat = 0 + private var gridColumns: [GridItem] { Array(repeating: GridItem(.flexible(), spacing: MediaGridLayout.spacing), count: columnCount) } @@ -56,17 +59,23 @@ struct FolderDetailView: View { ) return VStack(spacing: 0) { + LibraryPageHeader( + title: path.components(separatedBy: "/").last ?? path, + // 件数は、子フォルダ・子アルバムのカードと、このフォルダ直下のメディアの合計にする + // (カードだけを数えると、メディアだけのフォルダが「0件」に見える)。 + subtitle: "フォルダ · \(path)", count: context.entries.count + context.directMedia.count + ) if node == nil { ContentUnavailableView( "フォルダが見つかりません", systemImage: "questionmark.folder", - description: Text("「\(path)」は移動または名前変更された可能性があります。") + description: Text("「\(path)」は移動または名前変更された可能性があります.") ) } else if context.entries.isEmpty && context.directMedia.isEmpty { ContentUnavailableView( "このフォルダは空です", systemImage: "folder", - description: Text("アルバムをこのフォルダへドラッグすると、ここに表紙が並びます。") + description: Text("アルバムをこのフォルダへドラッグすると,ここに表紙が並びます.") ) } else { content(context) @@ -101,7 +110,7 @@ struct FolderDetailView: View { newAlbumNameForMove = "" } } message: { - Text("\(pendingMoveVideoIDs.count)件を新しく作るアルバムへ移動します。") + Text("\(pendingMoveVideoIDs.count)件を新しく作るアルバムへ移動します.") } .onDisappear { // 表紙のためにデコードした画像を持ち越さない(ディスクキャッシュは残るので戻れば即表示される)。 @@ -142,6 +151,7 @@ struct FolderDetailView: View { .padding(MediaGridLayout.contentInset) .padding(.bottom, 12) } + .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { gridWidth = $0 } .background( // 背景クリックで選択解除 Color.clear @@ -153,7 +163,7 @@ struct FolderDetailView: View { private func sectionTitle(_ title: String, count: Int) -> some View { HStack(spacing: 8) { Text(title) - .font(.system(size: 12, weight: .bold, design: .rounded)) + .font(.system(size: 12, weight: .bold, design: .default)) .foregroundStyle(.secondary) Text("\(count)") .font(.system(size: 11, weight: .semibold, design: .monospaced)) @@ -167,9 +177,23 @@ struct FolderDetailView: View { private var breadcrumb: some View { let parts = path.components(separatedBy: "/").filter { !$0.isEmpty } return HStack(spacing: 4) { - Image(systemName: isPhoto ? "photo.stack" : "film.stack") - .font(.system(size: 11, weight: .semibold)) + // 一番左は「アルバム一覧」へ戻る入口。フォルダを掘ったあとに最上位へ一気に戻れる。 + Button { + selection = .albums + } label: { + HStack(spacing: 4) { + Image(systemName: isPhoto ? "photo.stack" : "film.stack") + .font(.system(size: 11, weight: .semibold)) + Text("アルバム") + .font(.system(size: 12, weight: .medium, design: .default)) + } .foregroundStyle(.secondary) + } + .buttonStyle(.plain) + .help("アルバム一覧へ戻る") + Image(systemName: "chevron.right") + .font(.system(size: 9, weight: .bold)) + .foregroundStyle(.tertiary) ForEach(Array(parts.enumerated()), id: \.offset) { index, part in if index > 0 { @@ -186,7 +210,7 @@ struct FolderDetailView: View { ) } label: { Text(part) - .font(.system(size: 12, weight: isLast ? .bold : .medium, design: .rounded)) + .font(.system(size: 12, weight: isLast ? .bold : .medium, design: .default)) .foregroundStyle(isLast ? Color.primary : Color.secondary) } .buttonStyle(.plain) @@ -195,7 +219,7 @@ struct FolderDetailView: View { } .padding(.horizontal, 12) .padding(.vertical, 8) - .background(.ultraThinMaterial) + .background(NeomorphicTheme.canvas) } private func mediaCell(_ video: VideoItem, in items: [VideoItem]) -> some View { @@ -321,11 +345,14 @@ struct FolderEntry: Identifiable { let id: String let title: String - let count: Int - /// 表紙モザイクに使う代表メディア(最大4件)。 - let coverItems: [VideoItem] let isFolder: Bool let kind: Kind + /// 本数・合計時間・表紙など。サイドバーやアルバム一覧ページと同じ集計を使う。 + let summary: AlbumSummary + + var count: Int { summary.mediaCount } + /// 表紙モザイクに使う代表メディア(最大4件)。 + var coverItems: [VideoItem] { summary.coverItems } } /// 1回の描画で必要なものをまとめて1度だけ計算する(body の中で何度も再計算しないため)。 @@ -333,7 +360,7 @@ struct FolderContent { let entries: [FolderEntry] let directMedia: [VideoItem] - static let coverLimit = 4 + static let coverLimit = AlbumSummary.coverLimit init( node: SidebarAlbumNode?, @@ -349,66 +376,42 @@ struct FolderContent { return } - var itemByID: [UUID: VideoItem] = [:] - itemByID.reserveCapacity(videos.count) - for video in videos where !video.isInTrash { - itemByID[video.id] = video - } + let itemByID = AlbumSummary.itemIndex(videos) + entries = Self.entries(for: node.children, itemByID: itemByID, includeEmpty: false) - entries = node.children.compactMap { child in - let count = Self.mediaCount(of: child, itemByID: itemByID) - guard count > 0 else { return nil } + directMedia = (node.album?.videoIDs ?? []) + .compactMap { itemByID[$0] } + .sorted(by: sortOrder, reversed: sortReversed, lastPlayed: lastPlayed, metadata: metadata) + } + + /// 子ノードをタイル1件ずつにする。アルバム一覧ページ(最上位)とフォルダ画面で同じ組み立てを使う。 + /// includeEmpty が false だと、中身のないアルバム/フォルダは出さない。 + static func entries( + for nodes: [SidebarAlbumNode], + itemByID: [UUID: VideoItem], + includeEmpty: Bool + ) -> [FolderEntry] { + nodes.compactMap { child in + let summary = AlbumSummary.of(node: child, itemByID: itemByID) + guard includeEmpty || summary.mediaCount > 0 else { return nil } - let covers = Self.coverItems(of: child, itemByID: itemByID) if child.children.isEmpty, let album = child.album { return FolderEntry( id: child.id, title: child.name, - count: count, - coverItems: covers, isFolder: false, - kind: .album(album.id) + kind: .album(album.id), + summary: summary ) } return FolderEntry( id: child.id, title: child.name, - count: count, - coverItems: covers, isFolder: true, - kind: .folder(path: child.id) + kind: .folder(path: child.id), + summary: summary ) } - - directMedia = (node.album?.videoIDs ?? []) - .compactMap { itemByID[$0] } - .sorted(by: sortOrder, reversed: sortReversed, lastPlayed: lastPlayed, metadata: metadata) - } - - /// ゴミ箱を除いた、そのノード配下の総メディア数。 - private static func mediaCount(of node: SidebarAlbumNode, itemByID: [UUID: VideoItem]) -> Int { - let own = (node.album?.videoIDs ?? []).reduce(0) { $0 + (itemByID[$1] == nil ? 0 : 1) } - return node.children.reduce(own) { $0 + mediaCount(of: $1, itemByID: itemByID) } - } - - /// 表紙用の代表メディア。自分のアルバムを先に、足りなければ子孫を順に辿る - /// (サーバー・iOSクライアントの coverVideoID と同じ「先頭から」の考え方)。 - private static func coverItems(of node: SidebarAlbumNode, itemByID: [UUID: VideoItem]) -> [VideoItem] { - var result: [VideoItem] = [] - - func collect(_ node: SidebarAlbumNode) { - for id in node.album?.videoIDs ?? [] { - guard result.count < coverLimit else { return } - if let item = itemByID[id] { result.append(item) } - } - for child in node.children { - guard result.count < coverLimit else { return } - collect(child) - } - } - - collect(node) - return result } } @@ -419,6 +422,8 @@ struct FolderEntryTile: View { let entry: FolderEntry let dataManager: LibraryViewModel var showTitle: Bool = true + /// 名前の下に「動画 12本 · 38分」のような要約を出すか。 + var showDetail: Bool = true let onOpen: () -> Void @State private var isHovering = false @@ -426,6 +431,11 @@ struct FolderEntryTile: View { var body: some View { VStack(alignment: .leading, spacing: 6) { AlbumCoverMosaicView(items: entry.coverItems, dataManager: dataManager, isFolder: entry.isFolder) + // 縁線は常時ごく細く、カーソルを乗せると少し濃く太くして「押せる」ことを示す(塗りではなく線で示す)。 + .overlay( + RoundedRectangle(cornerRadius: 10, style: .continuous) + .strokeBorder(Color.primary.opacity(isHovering ? 0.30 : 0.10), lineWidth: isHovering ? 1.5 : 0.5) + ) .overlay(alignment: .topLeading) { if entry.isFolder { badge(systemImage: "folder.fill") @@ -434,7 +444,7 @@ struct FolderEntryTile: View { } .overlay(alignment: .topTrailing) { Text("\(entry.count)") - .font(.caption2.weight(.semibold)) + .font(.appMicro.weight(.semibold)) .monospacedDigit() .foregroundStyle(.white) .padding(.horizontal, 6) @@ -444,22 +454,30 @@ struct FolderEntryTile: View { } if showTitle { - Text(entry.title) - .font(.caption) - .lineLimit(1) - .truncationMode(.middle) - .padding(.horizontal, 4) + VStack(alignment: .leading, spacing: 1) { + Text(entry.title) + .font(.system(size: 12, weight: .medium)) + .lineLimit(1) + .truncationMode(.middle) + if showDetail { + Text(entry.summary.detailText(isFolder: entry.isFolder)) + .font(.appMicro) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.tail) + } + } + .padding(.horizontal, 4) } } .padding(MediaGridLayout.itemInset) - .background( - RoundedRectangle(cornerRadius: 14, style: .continuous) - .fill(isHovering ? Color.primary.opacity(0.06) : Color.clear) - ) .contentShape(RoundedRectangle(cornerRadius: 14, style: .continuous)) .onHover { isHovering = $0 } .onTapGesture { onOpen() } - .help(entry.isFolder ? "フォルダ「\(entry.title)」を開く" : "アルバム「\(entry.title)」を開く") + .help( + (entry.isFolder ? "フォルダ「\(entry.title)」を開く" : "アルバム「\(entry.title)」を開く") + + "\n" + entry.summary.detailText(isFolder: entry.isFolder) + ) } private func badge(systemImage: String) -> some View { @@ -483,7 +501,7 @@ struct AlbumCoverMosaicView: View { Color.clear .aspectRatio(1, contentMode: .fit) .overlay { mosaic } - .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) + .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous)) } @ViewBuilder @@ -540,7 +558,7 @@ struct AlbumCoverMosaicView: View { /// モザイクの1マス。グリッドのセルと同じキャッシュから画像を取るので、 /// 一度表示したメディアの表紙は生成し直しにならない。 -private struct CoverThumbnail: View { +struct CoverThumbnail: View { let item: VideoItem let dataManager: LibraryViewModel diff --git a/AllServerForMac/Features/Library/Views/LibraryCategoryView.swift b/AllServerForMac/Features/Library/Views/LibraryCategoryView.swift index baf9127..32be7ce 100644 --- a/AllServerForMac/Features/Library/Views/LibraryCategoryView.swift +++ b/AllServerForMac/Features/Library/Views/LibraryCategoryView.swift @@ -6,6 +6,9 @@ import UniformTypeIdentifiers struct LibraryCategoryView: View { enum Kind: Hashable { case favorites + /// 途中でやめた動画だけを並べる。中身は視聴位置の保管庫なので、 + /// ブラウザ・iPhone で途中まで観たものもここに出る。 + case continueWatching case history case trash } @@ -48,6 +51,7 @@ struct LibraryCategoryView: View { private var isTrash: Bool { kind == .trash } private var isHistory: Bool { kind == .history } + private var isContinueWatching: Bool { kind == .continueWatching } @State private var showClearHistoryAlert = false @@ -55,6 +59,8 @@ struct LibraryCategoryView: View { switch kind { case .favorites: return dataManager.favoriteVideos + case .continueWatching: + return continueWatchingItems case .history: return historyItems case .trash: @@ -72,11 +78,33 @@ struct LibraryCategoryView: View { return watchState.historyOrder.compactMap { itemByID[$0] } } + /// 途中でやめた動画を、最後に再生した順(新しい順)に並べたもの。 + /// 並びに `historyOrder` を使うのは、視聴位置そのものには前後関係が無いため。 + /// 履歴から外した動画は並びから消えるので、視聴位置だけが残っているものを末尾に足す。 + private var continueWatchingItems: [VideoItem] { + let itemByID = Dictionary( + dataManager.videos.lazy.filter { !$0.isInTrash && $0.mediaType == .video }.map { ($0.id, $0) }, + uniquingKeysWith: { current, _ in current } + ) + var seen = Set() + var result: [VideoItem] = [] + for id in watchState.historyOrder { + guard let item = itemByID[id], + watchState.resumableSeconds(for: id, duration: item.duration) != nil else { continue } + seen.insert(id) + result.append(item) + } + // 履歴を消しても視聴位置は残る(仕様)。その分は順序を決めようがないので後ろへ回す。 + let orphans = itemByID.values + .filter { !seen.contains($0.id) && watchState.resumableSeconds(for: $0.id, duration: $0.duration) != nil } + .sorted { $0.originalFilename.localizedStandardCompare($1.originalFilename) == .orderedAscending } + return result + orphans + } + private var displayedItems: [VideoItem] { let filtered = sourceItems.filtered(bySearch: searchText) - // 履歴は「再生した順」そのものが中身なので並べ替えない - // (名前順に並べ替えた履歴には意味がない)。 - guard !isHistory else { return filtered } + // 履歴と「続きを見る」は、並び(最後に再生した順)そのものが中身なので並べ替えない。 + guard !isHistory, !isContinueWatching else { return filtered } return filtered.sorted(by: appSettings.sortOrder, reversed: appSettings.sortReversed, lastPlayed: watchState.lastPlayed) { dataManager.fileMetadata(for: $0) } } private var selectedVideoItems: [VideoItem] { @@ -91,13 +119,34 @@ struct LibraryCategoryView: View { /// 実際に並べる列数。グリッドの組み立てと矢印キーの上下移動が必ず同じ値を見るように、 /// ここだけで決める(ズレると下キーが斜めに飛ぶ)。 private var columnCount: Int { - max(2, Int(appSettings.columnCount)) + MediaGridLayout.columnCount(requested: appSettings.columnCount, availableWidth: gridWidth) } + /// グリッドを置く領域の幅。狭いウィンドウで列を自動的に減らすために測る。 + @State private var gridWidth: CGFloat = 0 + private var gridColumns: [GridItem] { Array(repeating: GridItem(.flexible(), spacing: MediaGridLayout.spacing), count: columnCount) } + private var pageTitle: String { + switch kind { + case .favorites: return "お気に入り" + case .continueWatching: return "続きを見る" + case .history: return "再生履歴" + case .trash: return "ゴミ箱" + } + } + + private var pageSubtitle: String { + switch kind { + case .favorites: return "もう一度楽しみたいメディアを,ひとつの場所に." + case .continueWatching: return "前回の続きから,再生できます." + case .history: return "最近再生した順に並んでいます." + case .trash: return "削除したメディアを確認・復元できます." + } + } + var body: some View { // displayedItems(フィルタ+ソート)は1回の描画につき1回だけ計算し、toolbar/sheetも含めて使い回す。 let items = displayedItems @@ -105,6 +154,7 @@ struct LibraryCategoryView: View { let selectedItems = items.filter { selectedVideoIDs.contains($0.id) && $0.mediaType == .video } return VStack(spacing: 0) { + LibraryPageHeader(title: pageTitle, subtitle: pageSubtitle, count: items.count) ZStack { Color.clear .contentShape(Rectangle()) @@ -126,18 +176,24 @@ struct LibraryCategoryView: View { .foregroundColor(.white) Text("\(exportCurrent) / \(exportTotal)") .foregroundColor(.white) - .font(.subheadline) + .font(.appBody) } - .padding() - .background(.thickMaterial) - .cornerRadius(12) + .padding(20) + .background(NeomorphicTheme.card, in: RoundedRectangle(cornerRadius: 14, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(NeomorphicTheme.cardBorder, lineWidth: 0.5)) + .environment(\.colorScheme, NeomorphicTheme.isDarkBase ? .dark : .light) } } Divider() - MediaGridControlBar(dataManager: dataManager, showsSortControls: !isHistory) + MediaGridControlBar(dataManager: dataManager, showsSortControls: !isHistory && !isContinueWatching) } .searchable(text: $searchText, placement: .toolbar, prompt: "タイトルを検索") .toolbar { + if !isTrash { + ToolbarItem(placement: .primaryAction) { + LibraryTourMenu(videos: videoItems, dataManager: dataManager, beforePlay: { rememberGridState() }) + } + } if isTrash { ToolbarItem(placement: .primaryAction) { if !dataManager.trashedVideos.isEmpty { @@ -172,7 +228,7 @@ struct LibraryCategoryView: View { if !selectedVideoIDs.isEmpty { ToolbarItem(placement: .primaryAction) { Text("\(selectedVideoIDs.count)項目を選択中") - .font(.system(size: 11)) + .font(.appMicro) .foregroundStyle(.secondary) } } @@ -186,28 +242,38 @@ struct LibraryCategoryView: View { .help("選択した動画から候補シーンを抽出します") } } - if selectedItems.count >= 2 { - ToolbarItem(placement: .primaryAction) { - Button { startMultiPlayback(selectedItems) } label: { - Label("同時再生", systemImage: "square.grid.2x2.fill") - } - } - ToolbarItem(placement: .primaryAction) { - Button { startVariantSwitchPlayback(selectedItems) } label: { - Label("差分切り替え再生", systemImage: "rectangle.on.rectangle.angled") - } - .help("選択した動画を同期再生し、一定間隔/キー操作で見せる1本を切り替える(最大9本)") - } - ToolbarItem(placement: .primaryAction) { - Button { startContentAlignedVariantPlayback(selectedItems) } label: { - Label("類似点で合わせる", systemImage: "link") - } - .help("動画内の類似場面を探し,最初に共通位置へ一度だけ合わせて再生する(最大9本)") - } - ToolbarItem(placement: .primaryAction) { - Button { startSlideshowPlayback(selectedItems) } label: { - Label("スライドショー", systemImage: "play.square.stack") + // 複数選択時の再生方法は4種類あり,アイコンだけを並べると見分けにくいので1つのメニューにまとめる。 + ToolbarItem(placement: .primaryAction) { + if selectedItems.count >= 2 { + Menu { + Button { + startMultiPlayback(selectedItems) + } label: { + Label("同時再生", systemImage: "square.grid.2x2.fill") + } + .help("選択した動画を同期再生(最大9本)") + Button { + startVariantSwitchPlayback(selectedItems) + } label: { + Label("差分切り替え再生", systemImage: "rectangle.on.rectangle.angled") + } + .help("選択した動画を同期再生し,一定間隔/キー操作で見せる1本を切り替える(最大9本)") + Button { + startContentAlignedVariantPlayback(selectedItems) + } label: { + Label("類似点で合わせる", systemImage: "link") + } + .help("動画内の類似場面を探し,最初に共通位置へ一度だけ合わせて再生する(最大9本)") + Button { + startSlideshowPlayback(selectedItems) + } label: { + Label("スライドショー", systemImage: "play.square.stack") + } + .help("選択した動画をスライドショー再生") + } label: { + Label("選択を再生", systemImage: "play.rectangle.on.rectangle") } + .help("選択した動画を同時再生・差分切り替え・スライドショーなどで再生") } } if selectedItems.count == 1, let video = selectedItems.first { @@ -260,7 +326,7 @@ struct LibraryCategoryView: View { } Button("キャンセル", role: .cancel) {} } message: { - Text("動画そのものと「続きから」の視聴位置は消えません。ブラウザや iPhone の履歴からも消えます。") + Text("動画そのものと「続きから」の視聴位置は消えません.ブラウザや iPhone の履歴からも消えます.") } .alert("エクスポート完了", isPresented: $showExportResultAlert) { Button("OK", role: .cancel) { } @@ -299,22 +365,22 @@ struct LibraryCategoryView: View { } Button("キャンセル", role: .cancel) { pendingMoveVideoIDs = [] } } message: { - Text("作成する新しいアルバム名を入力してください。") + Text("作成する新しいアルバム名を入力してください.") } .sheet(isPresented: $showSplitSheet) { VStack(spacing: 20) { Text("分割再生") - .font(.headline) + .font(.system(size: 17, weight: .semibold)) if let video = splitTargetVideo { Text(video.originalFilename) - .font(.subheadline) + .font(.appBody) .foregroundStyle(.secondary) .lineLimit(1) } Stepper("分割数: \(splitCount)", value: $splitCount, in: 2...9) .frame(width: 200) Text("動画を\(splitCount)等分して\(splitCount)画面で同時再生します") - .font(.caption) + .font(.appCaption) .foregroundStyle(.secondary) HStack(spacing: 16) { Button("キャンセル") { showSplitSheet = false } @@ -331,6 +397,7 @@ struct LibraryCategoryView: View { } .padding(30) .frame(minWidth: 320) + .appSheet() } // 他の画面に移動したら、ここで表示していたサムネイルはメモリから解放する。 .onDisappear { @@ -386,10 +453,7 @@ struct LibraryCategoryView: View { onAnalyzeScenes(video) } : nil, affectedItems: menuTargets(for: video, in: items), - onRemoveFromHistory: isHistory ? { - watchState.removeHistory(videoIDs: targetIDs(for: video)) - selectedVideoIDs.removeAll() - } : nil + onRemoveFromList: listRemoval(for: video) ) .id(video.id) } @@ -398,6 +462,7 @@ struct LibraryCategoryView: View { .padding(MediaGridLayout.contentInset) } .scrollPosition(id: $scrollTargetMediaID, anchor: .top) + .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { gridWidth = $0 } // フォーカスはグリッド全体で1つだけ持つ。セルごとに .focusable() を付けると、 // SwiftUI 標準の矢印キーによるフォーカス送りが自前の「index ± 列数」移動と同時に走り、 // 1回の入力で二重に動いたり斜めに飛んだりする(列数によって挙動が変わって見える原因)。 @@ -745,32 +810,67 @@ struct LibraryCategoryView: View { } isExporting = false exportResultMessage = result.failedCount > 0 - ? "\(result.successCount)件を書き出しました。\(result.failedCount)件は失敗しました。" - : "\(result.successCount)件を書き出しました。" + ? "\(result.successCount)件を書き出しました.\(result.failedCount)件は失敗しました." + : "\(result.successCount)件を書き出しました." showExportResultAlert = true } } + /// 「再生履歴」「続きを見る」から外す右クリック項目。どちらでもない画面では出さない。 + private func listRemoval(for video: VideoItem) -> (label: String, action: () -> Void)? { + if isHistory { + return ("履歴から削除", { + watchState.removeHistory(videoIDs: targetIDs(for: video)) + selectedVideoIDs.removeAll() + }) + } + if isContinueWatching { + // 捨てるのは視聴位置だけ。履歴にも動画そのものにも触らない + // (「もう続きは要らない」と「観た記録を消したい」は別の意思表示)。 + return ("続きを見るから外す", { + for id in targetIDs(for: video) { watchState.markFinished(videoID: id) } + watchState.publishPendingChanges() + selectedVideoIDs.removeAll() + }) + } + return nil + } + private var categoryScope: PlaybackCoordinator.LibraryScope { switch kind { case .favorites: return .favorites + case .continueWatching: return .continueWatching case .history: return .history case .trash: return .trash } } + @ViewBuilder private var emptyState: some View { + if !searchText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + ContentUnavailableView { + Label("該当する項目がありません", systemImage: "magnifyingglass") + } description: { + Text("「\(searchText)」に一致するタイトルは見つかりませんでした.") + } actions: { + Button("検索を解除") { searchText = "" } + .buttonStyle(.borderedProminent) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else { ContentUnavailableView( - emptyStateTitle, - systemImage: emptyStateSymbol, - description: Text(emptyStateDescription) + emptyStateTitle, + systemImage: emptyStateSymbol, + description: Text(emptyStateDescription) ) .frame(maxWidth: .infinity, maxHeight: .infinity) + } } private var emptyStateTitle: String { switch kind { case .favorites: return "お気に入りはありません" + case .continueWatching: return "途中の動画はありません" case .history: return "再生履歴はありません" case .trash: return "ゴミ箱は空です" } @@ -779,6 +879,7 @@ struct LibraryCategoryView: View { private var emptyStateSymbol: String { switch kind { case .favorites: return "heart" + case .continueWatching: return "play.circle" case .history: return "clock.arrow.circlepath" case .trash: return "trash" } @@ -787,6 +888,7 @@ struct LibraryCategoryView: View { private var emptyStateDescription: String { switch kind { case .favorites: return "グリッドの右クリックメニューからお気に入りに追加できます" + case .continueWatching: return "最後まで観ずにやめた動画がここに並びます(ブラウザや iPhone で観た分も含みます)" case .history: return "再生した動画がここに新しい順で並びます(ブラウザや iPhone での再生も含みます)" case .trash: return "削除した項目はここに移動します" } diff --git a/AllServerForMac/Features/Library/Views/MediaGallerySupport.swift b/AllServerForMac/Features/Library/Views/MediaGallerySupport.swift index 027d273..99a2b4b 100644 --- a/AllServerForMac/Features/Library/Views/MediaGallerySupport.swift +++ b/AllServerForMac/Features/Library/Views/MediaGallerySupport.swift @@ -4,9 +4,21 @@ import UniformTypeIdentifiers /// サムネイル一覧の余白。密度を高めつつ,選択枠とホバー状態を見分けられる最小限の間隔を保つ。 enum MediaGridLayout { - static let spacing: CGFloat = 3 - static let itemInset: CGFloat = 1 - static let contentInset: CGFloat = 5 + static let spacing: CGFloat = 10 + static let itemInset: CGFloat = 4 + static let contentInset: CGFloat = 16 + /// これより細いタイルは名前も再生時間も読めないので、列を減らして幅を確保する。 + static let minTileWidth: CGFloat = 120 + + /// 実際に並べる列数。設定の列数を上限に、ウィンドウが狭いときは入る分だけに減らす。 + /// 幅がまだ測れていない(0)ときは設定値をそのまま使う。 + static func columnCount(requested: Double, availableWidth: CGFloat) -> Int { + let requested = max(2, Int(requested)) + let usable = availableWidth - contentInset * 2 + guard usable > 0 else { return requested } + let fitting = Int((usable + spacing) / (minTileWidth + spacing)) + return max(2, min(requested, fitting)) + } } /// 一覧グリッドの矢印キー移動。アルバム詳細とお気に入り/ゴミ箱の両方、 @@ -72,16 +84,16 @@ struct MediaDeletionConfirmationSheet: View { VStack(alignment: .leading, spacing: 16) { HStack(spacing: 10) { Label("削除方法を選んでください", systemImage: "trash") - .font(.title3.weight(.semibold)) + .font(.system(size: 17, weight: .semibold)) Spacer() - Text("\(items.count)件を選択中") - .font(.subheadline.monospacedDigit()) - .foregroundStyle(.secondary) + Text("\(items.count.formatted())件を選択中") + .font(.system(size: 13).monospacedDigit()) + .foregroundStyle(NeomorphicTheme.muted) } Text("下のサムネイルが削除対象です.アプリ内のゴミ箱は復元できます.Macのゴミ箱へ移動すると,リンク元を含む実ファイルも移動します.") - .font(.subheadline) - .foregroundStyle(.secondary) + .font(.appBody) + .foregroundStyle(NeomorphicTheme.muted) Divider() @@ -91,7 +103,8 @@ struct MediaDeletionConfirmationSheet: View { VStack(alignment: .leading, spacing: 6) { MacVideoThumbnailView( videoItem: item, - dataManager: dataManager + dataManager: dataManager, + showsPlayGlyph: false ) .overlay(alignment: .topTrailing) { Image(systemName: "checkmark.circle.fill") @@ -102,7 +115,7 @@ struct MediaDeletionConfirmationSheet: View { } Text(item.originalFilename) - .font(.caption) + .font(.appCaption) .lineLimit(2) .truncationMode(.middle) .frame(maxWidth: .infinity, alignment: .leading) @@ -136,14 +149,17 @@ struct MediaDeletionConfirmationSheet: View { Button("完全に削除", role: .destructive) { perform(onDeleteCompletely) } + .tint(Color(red: 1.0, green: 0.27, blue: 0.23)) Button("実ファイルをMacのゴミ箱へ移動", role: .destructive) { perform(onMoveToSystemTrash) } + .tint(Color(red: 1.0, green: 0.27, blue: 0.23)) } } .padding(20) .frame(width: Self.sheetWidth) + .appSheet() } private func perform(_ action: () -> Void) { diff --git a/AllServerForMac/Features/Library/Views/MediaGridControlBar.swift b/AllServerForMac/Features/Library/Views/MediaGridControlBar.swift index d15ed9f..51ccc22 100644 --- a/AllServerForMac/Features/Library/Views/MediaGridControlBar.swift +++ b/AllServerForMac/Features/Library/Views/MediaGridControlBar.swift @@ -20,71 +20,121 @@ struct MediaGridControlBar: View { return f }() + private static let minimumColumnCount = 2.0 + private static let maximumColumnCount = 12.0 + private static let columnSliderWidth: CGFloat = 110 + var body: some View { + ViewThatFits(in: .horizontal) { HStack(spacing: 14) { - if showsSortControls { - Menu { - ForEach(SortOrder.allCases) { order in - Button(order.rawValue) { - // ファイル属性で並べる順を選び直したときは実ファイルを読み直して最新化する。 - if order.needsFileMetadata { dataManager.refreshFileMetadataCache() } - appSettings.sortOrder = order - } - } - } label: { - Label(appSettings.sortOrder.rawValue, systemImage: "arrow.up.arrow.down") - } - .fixedSize() - - // 並び順の上下をワンクリックで反転する(既に並んだ結果を反転するだけなので再読み込み不要)。 - Button { - appSettings.sortReversed.toggle() - } label: { - Image(systemName: appSettings.sortReversed ? "arrow.up" : "arrow.down") - } - .help(appSettings.sortReversed ? "並び順を元に戻す(逆順中)" : "並び順を上下逆にする") - } - - Menu { - ForEach(ThumbnailOption.allCases) { option in - Button(option.rawValue) { appSettings.thumbnailOption = option } - } - } label: { - Label("サムネ: \(appSettings.thumbnailOption.rawValue)", systemImage: "photo.on.rectangle.angled") - } - .fixedSize() + sortingControls + thumbnailControls + Spacer(minLength: 12) + displayControls + columnControls + } + VStack(spacing: 10) { + HStack(spacing: 12) { + sortingControls + Spacer(minLength: 8) + thumbnailControls + } + HStack(spacing: 12) { + displayControls + Spacer(minLength: 8) + columnControls + } + } + } + .font(.appCaption) + .tint(NeomorphicTheme.ink) + .padding(.horizontal, 20) + .padding(.vertical, 10) + // 下地と同じ不透明色にして、区切りは細い線だけにする(帯が浮くと画面が散らかって見える)。 + .background(NeomorphicTheme.canvas) + .overlay(alignment: .top) { + Rectangle().fill(NeomorphicTheme.separator).frame(height: 0.5) + } + // メニューのグレーの枠は付けず、文字とアイコンだけの軽い見た目にする。 + .menuStyle(.borderlessButton) + } - if appSettings.thumbnailOption == .custom { - HStack(spacing: 4) { - Stepper("", value: $appSettings.customThumbnailTime, in: 0...3600, step: 1) - .labelsHidden() - TextField("秒", value: $appSettings.customThumbnailTime, formatter: MediaGridControlBar.secondsFormatter) - .frame(width: 46) - .multilineTextAlignment(.trailing) - Text("秒").font(.caption) - } - } + @ViewBuilder + private var sortingControls: some View { + if showsSortControls { + // 「短い順」の横に ↓ / ↑ だけのボタンを並べると,矢印が何を指すのか分からない. + // 逆順はメニューの中のチェック項目にし,効いているときはラベルに「(逆順)」と出す. + Menu { + ForEach(SortOrder.allCases) { order in + Toggle(order.rawValue, isOn: Binding( + get: { appSettings.sortOrder == order }, + set: { isOn in + guard isOn else { return } + // ファイル属性を使う並べ替えは,最新の属性を読み直します. + if order.needsFileMetadata { dataManager.refreshFileMetadataCache() } + appSettings.sortOrder = order + } + )) + } + Divider() + Toggle("逆順にする", isOn: $appSettings.sortReversed) + } label: { + Label( + "並び順:\(appSettings.sortOrder.rawValue)\(appSettings.sortReversed ? "(逆順)" : "")", + systemImage: "arrow.up.arrow.down" + ) + } + .fixedSize() + .help("並び順と,逆順にするかを選びます.") + } + } - Spacer() + private var thumbnailControls: some View { + HStack(spacing: 6) { + Menu { + ForEach(ThumbnailOption.allCases) { option in + Button(option.rawValue) { appSettings.thumbnailOption = option } + } + } label: { + Label("サムネ:\(appSettings.thumbnailOption.rawValue)", systemImage: "photo.on.rectangle.angled") + } + .fixedSize() + if appSettings.thumbnailOption == .custom { + HStack(spacing: 4) { + Stepper("サムネイルの秒数", value: $appSettings.customThumbnailTime, in: 0...3600, step: 1) + .labelsHidden() + TextField("秒", value: $appSettings.customThumbnailTime, formatter: Self.secondsFormatter) + .frame(width: 46) + .multilineTextAlignment(.trailing) + .accessibilityLabel("サムネイルの秒数") + Text("秒") + } + } + } + } - Menu { - Toggle("タイトルを表示", isOn: $appSettings.showTitles) - Toggle("インポート日を表示", isOn: $appSettings.showImportDates) - } label: { - Image(systemName: appSettings.showTitles || appSettings.showImportDates ? "text.below.photo.fill" : "text.below.photo") - } - .help("サムネイル下の表示項目を設定") + private var displayControls: some View { + Menu { + Toggle("タイトルを表示", isOn: $appSettings.showTitles) + Toggle("インポート日を表示", isOn: $appSettings.showImportDates) + } label: { + Label("表示項目", systemImage: "text.below.photo") + } + .fixedSize() + .help("サムネイルの下に表示するタイトル・日付を変更します.") + } - HStack(spacing: 6) { - Image(systemName: "square.grid.2x2") - Slider(value: $appSettings.columnCount, in: 2...12, step: 1) - .frame(width: 140) - Image(systemName: "square.grid.4x3.fill") - } - .help("表示列数: \(Int(appSettings.columnCount))列") - } - .padding(.horizontal, 14) - .padding(.vertical, 8) - .background(.regularMaterial) + private var columnControls: some View { + HStack(spacing: 8) { + Text("\(Int(appSettings.columnCount))列") + .monospacedDigit() + .fixedSize() + Slider(value: $appSettings.columnCount, + in: Self.minimumColumnCount...Self.maximumColumnCount, step: 1) + .frame(width: Self.columnSliderWidth) + .accessibilityLabel("表示列数") + .accessibilityValue("\(Int(appSettings.columnCount))列") + } + .help("列を減らすとサムネイルが大きくなります.") } } diff --git a/AllServerForMac/Features/Library/Views/MediaGridItem.swift b/AllServerForMac/Features/Library/Views/MediaGridItem.swift index 9217fa7..9b22c7c 100644 --- a/AllServerForMac/Features/Library/Views/MediaGridItem.swift +++ b/AllServerForMac/Features/Library/Views/MediaGridItem.swift @@ -30,11 +30,15 @@ struct MediaGridItem: View { /// 複数選択中に右クリックすると選択全体が対象になるため、 /// 確認文が「このセル1件」の話に見えないよう、対象の実態をここで受け取る。 var affectedItems: [VideoItem] = [] - /// 「再生履歴」アルバムでのみ渡す。nil なら右クリックメニューに項目を出さない。 - var onRemoveFromHistory: (() -> Void)? + /// 「再生履歴」「続きを見る」でだけ渡す、その一覧から外すための項目。 + /// nil なら右クリックメニューに出さない。 + var onRemoveFromList: (label: String, action: () -> Void)? @EnvironmentObject private var watchState: WatchStateStore + /// サムネイルの角丸。フォルダ/アルバムの表紙(FolderEntryTile)と同じ値にそろえる。 + static let thumbnailRadius: CGFloat = 10 + @State private var isHovering = false @State private var showDeleteConfirmation = false @@ -63,7 +67,7 @@ struct MediaGridItem: View { var body: some View { VStack(alignment: .leading, spacing: 6) { - MacVideoThumbnailView(videoItem: video, dataManager: dataManager) + MacVideoThumbnailView(videoItem: video, dataManager: dataManager, showsPlayGlyph: false) // YouTube と同じ、サムネイル下端の視聴済みバー。 // サムネイル側が角丸で切り抜いているので、こちらでも同じ形で切り抜いて下端に沿わせる。 .overlay(alignment: .bottom) { @@ -81,11 +85,27 @@ struct MediaGridItem: View { .accessibilityLabel("視聴済み \(Int(watchedFraction * 100))パーセント") } } - .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) + .clipShape(RoundedRectangle(cornerRadius: Self.thumbnailRadius, style: .continuous)) + // 明るい/暗い画像のどちらでも輪郭が立つよう、ごく細い縁線を引く。選択中はアクセント色の枠にする。 + .overlay( + RoundedRectangle(cornerRadius: Self.thumbnailRadius, style: .continuous) + .strokeBorder(Color.primary.opacity(0.10), lineWidth: 0.5) + ) .overlay( - RoundedRectangle(cornerRadius: 12, style: .continuous) + RoundedRectangle(cornerRadius: Self.thumbnailRadius, style: .continuous) .strokeBorder(isSelected ? Color.accentColor : Color.clear, lineWidth: 2.5) ) + // 再生ボタンは常時ではなく、カーソルを乗せたときだけ出す(全サムネイルに付くと画面がうるさい)。 + .overlay { + if isHovering && video.mediaType == .video { + Image(systemName: "play.fill") + .font(.system(size: 15, weight: .semibold)) + .foregroundStyle(.white) + .frame(width: 44, height: 44) + .background(Color.black.opacity(0.55), in: Circle()) + .allowsHitTesting(false) + } + } .overlay(alignment: .topTrailing) { if isSelected { Image(systemName: "checkmark.circle.fill") @@ -98,13 +118,13 @@ struct MediaGridItem: View { .overlay(alignment: .bottomTrailing) { if video.mediaType == .video, video.duration > 0 { Text(formatDuration(video.duration)) - .font(.caption2.weight(.semibold)) + .font(.system(size: 11, weight: .medium)) .monospacedDigit() .foregroundStyle(.white) - .padding(.horizontal, 5) + .padding(.horizontal, 6) .padding(.vertical, 2) - .background(Capsule().fill(.black.opacity(0.65))) - .padding(7) + .background(RoundedRectangle(cornerRadius: 5, style: .continuous).fill(.black.opacity(0.62))) + .padding(6) } } .overlay(alignment: .topLeading) { @@ -113,7 +133,7 @@ struct MediaGridItem: View { if isHovering && !isTrashView { Button(action: onToggleFavorite) { Image(systemName: video.isFavorite ? "heart.fill" : "heart") - .font(.system(size: 13)) + .font(.appBody) .foregroundStyle(.red) .padding(7) .contentShape(Rectangle()) @@ -122,7 +142,7 @@ struct MediaGridItem: View { .help(video.isFavorite ? "お気に入りから外す" : "お気に入りに追加") } else if video.isFavorite { Image(systemName: "heart.fill") - .font(.system(size: 13)) + .font(.appBody) .foregroundStyle(.red) .padding(7) } @@ -132,14 +152,15 @@ struct MediaGridItem: View { VStack(alignment: .leading, spacing: 2) { if showTitle { Text(video.originalFilename) - .font(.caption) + .font(.system(size: 12, weight: .medium)) + .foregroundStyle(NeomorphicTheme.ink) .lineLimit(1) .truncationMode(.middle) } if showImportDate { Text(MediaGridItem.itemFormatter.string(from: video.importDate)) - .font(.caption2) + .font(.appMicro) .foregroundStyle(.secondary) } } @@ -147,12 +168,7 @@ struct MediaGridItem: View { } } .padding(MediaGridLayout.itemInset) - .background( - RoundedRectangle(cornerRadius: 14, style: .continuous) - .fill(isSelected - ? Color.accentColor.opacity(0.12) - : (isHovering ? Color.primary.opacity(0.06) : Color.clear)) - ) + // 選択はサムネイルのアクセント枠で示すので、セル全体の塗りは付けない(枠と塗りの二重で重く見えるため)。 .contentShape(RoundedRectangle(cornerRadius: 14, style: .continuous)) .onHover { hovering in // アニメーション付きだとセルの出入りのたびにトランザクションが発生し、 @@ -187,6 +203,9 @@ struct MediaGridItem: View { if showRemoveFromAlbum { Button("アルバムから外す") { onRemoveFromAlbum() } } + if let onRemoveFromList { + Button(onRemoveFromList.label) { onRemoveFromList.action() } + } Divider() Button("削除…", role: .destructive) { showDeleteConfirmation = true } } diff --git a/AllServerForMac/Features/MediaAnalysis/Views/SimilarMediaView.swift b/AllServerForMac/Features/MediaAnalysis/Views/SimilarMediaView.swift index d994a1d..9692726 100644 --- a/AllServerForMac/Features/MediaAnalysis/Views/SimilarMediaView.swift +++ b/AllServerForMac/Features/MediaAnalysis/Views/SimilarMediaView.swift @@ -26,6 +26,7 @@ struct SimilarMediaView: View { footer } .frame(minWidth: 820, idealWidth: 1020, minHeight: 540, idealHeight: 700) + .appSheet() .onAppear { model.configure { dataManager.fileMetadata(for: $0).size } model.scan(items: items, dataManager: dataManager) @@ -51,7 +52,7 @@ struct SimilarMediaView: View { private var header: some View { HStack(spacing: 12) { Label("似ているメディアの整理", systemImage: "square.on.square.dashed") - .font(.headline) + .font(.appHeadline) Spacer() Button("閉じる") { dismiss() } .keyboardShortcut(.cancelAction) @@ -68,7 +69,7 @@ struct SimilarMediaView: View { .progressViewStyle(.linear) .frame(width: 260) Text("\(model.scanStage.title)… \(model.scannedCount) / \(model.totalCount)") - .font(.subheadline) + .font(.appBody) .foregroundStyle(.secondary) Button("中止") { model.cancelScan() } } @@ -77,7 +78,7 @@ struct SimilarMediaView: View { ContentUnavailableView( "似ているメディアはありません", systemImage: "checkmark.circle", - description: Text("「似ている度合い」をゆるめると候補が増えます。") + description: Text("「似ている度合い」をゆるめると候補が増えます.") ) .frame(maxWidth: .infinity, maxHeight: .infinity) } else { @@ -96,11 +97,11 @@ struct SimilarMediaView: View { VStack(alignment: .leading, spacing: 6) { HStack(spacing: 8) { Text("\(group.items.count)件が似ています") - .font(.caption) + .font(.appCaption) .foregroundStyle(.secondary) if group.hasAudioDifferences { Label("音声が異なる版を含みます", systemImage: "waveform.badge.exclamationmark") - .font(.caption2.weight(.semibold)) + .font(.appMicro.weight(.semibold)) .foregroundStyle(.orange) } } @@ -122,7 +123,7 @@ struct SimilarMediaView: View { let isKept = group.keepIDs.contains(item.id) let isSelected = model.selectedIDs.contains(item.id) return VStack(spacing: 4) { - MacVideoThumbnailView(videoItem: item, dataManager: dataManager) + MacVideoThumbnailView(videoItem: item, dataManager: dataManager, showsPlayGlyph: false) .frame(width: thumbnailSide, height: thumbnailSide) .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous)) .overlay( @@ -134,7 +135,7 @@ struct SimilarMediaView: View { ) .overlay(alignment: .bottomLeading) { Text(isKept ? "残す候補" : (isSelected ? "削除" : "対象外")) - .font(.system(size: 10, weight: .bold)) + .font(.appMicro.weight(.bold)) .foregroundStyle(.white) .padding(.horizontal, 6) .padding(.vertical, 3) @@ -147,13 +148,13 @@ struct SimilarMediaView: View { Button(item.mediaType == .photo ? "これを残す" : "この音声版を残す") { model.setKeep(item.id, inGroupAt: groupIndex) } - .font(.system(size: 10)) + .font(.appMicro) .buttonStyle(.plain) - .foregroundStyle(isKept ? Color.secondary : Color.accentColor) + .foregroundStyle(isKept ? NeomorphicTheme.muted : NeomorphicTheme.ink) .disabled(isKept) Text(item.originalFilename) - .font(.system(size: 9)) + .font(.appMicro) .lineLimit(1) .truncationMode(.middle) .frame(width: thumbnailSide) @@ -173,7 +174,7 @@ struct SimilarMediaView: View { Text(String(format: "映像 %.1f Mbps", details.videoBitrate / 1_000_000)) } } - .font(.system(size: 9).monospacedDigit()) + .font(.system(size: 11).monospacedDigit()) .foregroundStyle(.secondary) .frame(width: thumbnailSide) } @@ -203,7 +204,7 @@ struct SimilarMediaView: View { private func metadataBadge(_ title: String, systemImage: String, color: Color) -> some View { Label(title, systemImage: systemImage) - .font(.system(size: 9, weight: .medium)) + .font(.system(size: 11, weight: .medium)) .foregroundStyle(color) .padding(.horizontal, 6) .padding(.vertical, 3) @@ -215,24 +216,24 @@ struct SimilarMediaView: View { VStack(spacing: 10) { HStack(spacing: 10) { Text("似ている度合い") - .font(.caption) + .font(.appCaption) Slider(value: $model.maxDistance, in: 0...16, step: 1) .frame(width: 200) Text("±\(Int(model.maxDistance))") - .font(.caption.monospacedDigit()) + .font(.appCaption.monospacedDigit()) .frame(width: 38, alignment: .leading) Text("小さいほど「ほぼ同じ」だけに絞られます.音声・尺・画質が一致する動画は再圧縮差も補完します") - .font(.caption) + .font(.appCaption) .foregroundStyle(.secondary) Spacer() } HStack(spacing: 10) { Text("\(model.groups.count)グループ / \(model.selectedIDs.count)件を削除対象") - .font(.subheadline) + .font(.appBody) if model.unreadableCount > 0 { Text("照合できなかった項目: \(model.unreadableCount)件") - .font(.caption) + .font(.appCaption) .foregroundStyle(.secondary) } Spacer() diff --git a/AllServerForMac/Features/MediaAnalysis/Views/SketchCleanupView.swift b/AllServerForMac/Features/MediaAnalysis/Views/SketchCleanupView.swift index 09e856b..36a6983 100644 --- a/AllServerForMac/Features/MediaAnalysis/Views/SketchCleanupView.swift +++ b/AllServerForMac/Features/MediaAnalysis/Views/SketchCleanupView.swift @@ -27,6 +27,7 @@ struct SketchCleanupView: View { footer } .frame(minWidth: 780, idealWidth: 980, minHeight: 520, idealHeight: 680) + .appSheet() .onAppear { model.scan(items: items, dataManager: dataManager) } .onDisappear { model.cancelScan() } .sheet(isPresented: $showDeleteConfirmation) { @@ -49,7 +50,7 @@ struct SketchCleanupView: View { private var header: some View { HStack(spacing: 12) { Label("ラフ画・線画の抽出", systemImage: "scribble.variable") - .font(.headline) + .font(.appHeadline) Spacer() Button("閉じる") { dismiss() } .keyboardShortcut(.cancelAction) @@ -66,7 +67,7 @@ struct SketchCleanupView: View { .progressViewStyle(.linear) .frame(width: 260) Text("判定中… \(model.scannedCount) / \(model.totalCount)") - .font(.subheadline) + .font(.appBody) .foregroundStyle(.secondary) Button("中止") { model.cancelScan() } } @@ -76,8 +77,8 @@ struct SketchCleanupView: View { "該当する画像はありません", systemImage: "checkmark.circle", description: Text(model.candidates.isEmpty - ? "このアルバムには判定できる画像がありませんでした。" - : "「きびしさ」を下げると候補が増えます。") + ? "このアルバムには判定できる画像がありませんでした." + : "「きびしさ」を下げると候補が増えます.") ) .frame(maxWidth: .infinity, maxHeight: .infinity) } else { @@ -98,7 +99,7 @@ struct SketchCleanupView: View { private func candidateCell(_ candidate: SketchCleanupViewModel.Candidate) -> some View { let isSelected = model.selectedIDs.contains(candidate.id) return VStack(spacing: 5) { - MacVideoThumbnailView(videoItem: candidate.item, dataManager: dataManager) + MacVideoThumbnailView(videoItem: candidate.item, dataManager: dataManager, showsPlayGlyph: false) .frame(width: thumbnailSide, height: thumbnailSide) .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous)) .overlay( @@ -115,7 +116,7 @@ struct SketchCleanupView: View { } .overlay(alignment: .bottomTrailing) { Text("\(candidate.judgement.kind.displayName) \(Int(candidate.judgement.score * 100))%") - .font(.system(size: 10, weight: .semibold)) + .font(.appMicro.weight(.semibold)) .foregroundStyle(.white) .padding(.horizontal, 6) .padding(.vertical, 3) @@ -125,7 +126,7 @@ struct SketchCleanupView: View { .opacity(isSelected ? 1 : 0.55) Text(candidate.item.originalFilename) - .font(.system(size: 10)) + .font(.appMicro) .lineLimit(1) .truncationMode(.middle) .frame(width: thumbnailSide) @@ -140,29 +141,27 @@ struct SketchCleanupView: View { VStack(spacing: 10) { HStack(spacing: 10) { Text("きびしさ") - .font(.caption) + .font(.appCaption) Slider(value: $model.threshold, in: 0.3...0.95) .frame(width: 200) Text("\(Int(model.threshold * 100))%") - .font(.caption.monospacedDigit()) + .font(.appCaption.monospacedDigit()) .frame(width: 38, alignment: .leading) - Picker("", selection: $model.kindFilter) { - ForEach(SketchCleanupViewModel.KindFilter.allCases) { filter in - Text(filter.displayName).tag(filter) - } - } - .pickerStyle(.segmented) - .labelsHidden() - .frame(width: 240) + FlatSegmentedControl( + options: Array(SketchCleanupViewModel.KindFilter.allCases), + title: { $0.displayName }, + selection: $model.kindFilter, + width: 240 + ) Spacer() } HStack(spacing: 10) { Text("\(model.visibleCandidates.count)件が該当 / \(model.selectedIDs.count)件を選択中") - .font(.subheadline) + .font(.appBody) if model.unreadableCount > 0 { Text("読み取れなかった画像: \(model.unreadableCount)件") - .font(.caption) + .font(.appCaption) .foregroundStyle(.secondary) } Spacer() diff --git a/AllServerForMac/Features/MediaAnalysis/Views/VariantVideoView.swift b/AllServerForMac/Features/MediaAnalysis/Views/VariantVideoView.swift index 855cbf1..a2bc19c 100644 --- a/AllServerForMac/Features/MediaAnalysis/Views/VariantVideoView.swift +++ b/AllServerForMac/Features/MediaAnalysis/Views/VariantVideoView.swift @@ -86,11 +86,11 @@ struct VariantVideoView: View { ? "rectangle.on.rectangle.angled" : "link.badge.plus" ) - .font(.headline) + .font(.appHeadline) Text(model.searchMode == .normal ? "尺が揃っていて,絵だけが違うものを束にします" : "尺を問わず,一部に同じ場面が続く動画を探します") - .font(.caption) + .font(.appCaption) .foregroundStyle(.secondary) Spacer() Picker( @@ -104,6 +104,7 @@ struct VariantVideoView: View { Text("一部一致").tag(VariantVideoViewModel.SearchMode.partial) } .pickerStyle(.segmented) + .tint(NeomorphicTheme.ink) .frame(width: 190) Button { model.rescan() @@ -111,7 +112,7 @@ struct VariantVideoView: View { Label("探し直す", systemImage: "arrow.clockwise") } .disabled(model.isScanning) - .help("取り込み直したファイルを拾わせたいときに、フレームの照合をやり直します") + .help("取り込み直したファイルを拾わせたいときに,フレームの照合をやり直します") Button("閉じる") { onClose() } // 背後の View に付いたショートカットもプレイヤー越しに反応するため、 // 再生中は外して Esc が探索画面まで閉じないようにする。 @@ -130,10 +131,10 @@ struct VariantVideoView: View { .progressViewStyle(.linear) .frame(width: 260) Text(progressDescription) - .font(.subheadline) + .font(.appBody) .foregroundStyle(.secondary) Text(progressDetailDescription) - .font(.caption) + .font(.appCaption) .foregroundStyle(.secondary) Button("中止") { model.cancelScan() } } @@ -156,11 +157,11 @@ struct VariantVideoView: View { HStack(spacing: 10) { ProgressView().controlSize(.small) Text(compactProgressDescription) - .font(.caption) + .font(.appCaption) .foregroundStyle(.secondary) Spacer() Button("中止") { model.cancelScan() } - .font(.caption) + .font(.appCaption) } .padding(.horizontal, 14) .padding(.vertical, 8) @@ -185,26 +186,26 @@ struct VariantVideoView: View { return VStack(alignment: .leading, spacing: 8) { HStack(spacing: 8) { Text(groupTitle(group)) - .font(.caption) + .font(.appCaption) .foregroundStyle(.secondary) Spacer(minLength: 4) Button("すべて選ぶ") { model.selectAll(inGroupAt: index) } - .font(.caption) + .font(.appCaption) .buttonStyle(.plain) - .foregroundStyle(Color.accentColor) + .foregroundStyle(NeomorphicTheme.ink) .disabled(selectedCount == group.items.count) } if let stats = group.stats { Text(evidenceText(stats)) - .font(.caption2.monospacedDigit()) + .font(.appMicro.monospacedDigit()) .foregroundStyle(.tertiary) .lineLimit(1) .minimumScaleFactor(0.8) - .help("絵の差はフレームどうしのハミング距離(小さいほど似ている)、名前の近さは 0〜1。名前の近さはしきい値を上下させる補助に使っています") + .help("絵の差はフレームどうしのハミング距離(小さいほど似ている),名前の近さは 0〜1.名前の近さはしきい値を上下させる補助に使っています") } else if let score = group.partialMatchScore { Text(String(format: "一部一致の絵の差 %.1f ・ 小さいほど近い", score)) - .font(.caption2.monospacedDigit()) + .font(.appMicro.monospacedDigit()) .foregroundStyle(.tertiary) } @@ -241,7 +242,7 @@ struct VariantVideoView: View { private func candidateCell(_ item: VideoItem, group: VariantVideoViewModel.Group, groupIndex: Int) -> some View { let isSelected = group.selectedIDs.contains(item.id) return VStack(spacing: 5) { - MacVideoThumbnailView(videoItem: item, dataManager: dataManager) + MacVideoThumbnailView(videoItem: item, dataManager: dataManager, showsPlayGlyph: false) .frame(maxWidth: .infinity) .aspectRatio(1, contentMode: .fit) .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous)) @@ -263,7 +264,7 @@ struct VariantVideoView: View { .onTapGesture { model.toggle(item.id, inGroupAt: groupIndex) } Text(item.originalFilename) - .font(.system(size: 10)) + .font(.appMicro) .lineLimit(2) .multilineTextAlignment(.center) .truncationMode(.middle) @@ -280,19 +281,19 @@ struct VariantVideoView: View { } else { HStack(spacing: 10) { Text("最小尺差") - .font(.caption) + .font(.appCaption) Stepper( value: $model.minimumPartialDurationDifference, in: 1...120, step: 1 ) { Text("\(Int(model.minimumPartialDurationDifference))秒以上") - .font(.caption.monospacedDigit()) + .font(.appCaption.monospacedDigit()) .frame(width: 66, alignment: .leading) } .disabled(model.isScanning) Text("通常差分と重ならず,この尺差以上ある動画ペアだけを表示します") - .font(.caption) + .font(.appCaption) .foregroundStyle(.secondary) Spacer() } @@ -300,20 +301,20 @@ struct VariantVideoView: View { HStack(spacing: 10) { Text("サムネイル") - .font(.caption) + .font(.appCaption) Slider(value: $thumbnailSide, in: 110...320, step: 2) .frame(width: 150) Text("\(Int(thumbnailSide))px") - .font(.caption.monospacedDigit()) + .font(.appCaption.monospacedDigit()) .frame(width: 46, alignment: .leading) Text(model.searchMode == .normal ? "\(model.groups.count)グループ / \(model.totalGroupedCount)本" : "\(model.groups.count)組の強制差分候補") - .font(.subheadline) + .font(.appBody) if model.unreadableCount > 0 { Text("フレームを読めなかった項目: \(model.unreadableCount)件") - .font(.caption) + .font(.appCaption) .foregroundStyle(.secondary) } Spacer() @@ -327,33 +328,33 @@ struct VariantVideoView: View { VStack(spacing: 10) { HStack(spacing: 10) { Text("尺の許容差") - .font(.caption) + .font(.appCaption) Slider(value: $model.durationTolerance, in: 0...2, step: 0.05) .frame(width: 150) Text(String(format: "±%.2f秒", model.durationTolerance)) - .font(.caption.monospacedDigit()) + .font(.appCaption.monospacedDigit()) .frame(width: 62, alignment: .leading) Text("似ている度合い") - .font(.caption) + .font(.appCaption) Slider(value: $model.maxAverageDistance, in: 2...20, step: 1) .frame(width: 150) Text("±\(Int(model.maxAverageDistance))") - .font(.caption.monospacedDigit()) + .font(.appCaption.monospacedDigit()) .frame(width: 34, alignment: .leading) Spacer() } HStack(spacing: 10) { Text("タイトルの効き") - .font(.caption) + .font(.appCaption) Slider(value: $model.titleInfluence, in: 0...8, step: 1) .frame(width: 150) Text("±\(Int(model.titleInfluence))") - .font(.caption.monospacedDigit()) + .font(.appCaption.monospacedDigit()) .frame(width: 34, alignment: .leading) Text(titleInfluenceHint) - .font(.caption) + .font(.appCaption) .foregroundStyle(.secondary) Spacer() } @@ -363,13 +364,13 @@ struct VariantVideoView: View { /// 名前が近いほど「似ている度合い」を何点ぶん甘く見るか、を実際の数字で見せる。 private var titleInfluenceHint: String { guard model.titleInfluence > 0 else { - return "0 ならファイル名を見ず、絵だけで判定します" + return "0 ならファイル名を見ず,絵だけで判定します" } let loose = VariantVideoDetector.effectiveThreshold( base: model.maxAverageDistance, titleSimilarity: 1, influence: model.titleInfluence) let tight = VariantVideoDetector.effectiveThreshold( base: model.maxAverageDistance, titleSimilarity: 0, influence: model.titleInfluence) - return String(format: "名前がそっくりなら %.0f まで、まるで違えば %.0f までに絞ります", loose, tight) + return String(format: "名前がそっくりなら %.0f まで,まるで違えば %.0f までに絞ります", loose, tight) } private func evidenceText(_ stats: VariantVideoDetector.GroupStats) -> String { diff --git a/AllServerForMac/Features/Navigation/ViewModels/SidebarViewModel.swift b/AllServerForMac/Features/Navigation/ViewModels/SidebarViewModel.swift index a9bcfd6..ad15714 100644 --- a/AllServerForMac/Features/Navigation/ViewModels/SidebarViewModel.swift +++ b/AllServerForMac/Features/Navigation/ViewModels/SidebarViewModel.swift @@ -7,6 +7,19 @@ final class SidebarViewModel: ObservableObject { @Published private(set) var trashedMediaIDs: Set = [] @Published private(set) var videoAlbumNodes: [SidebarAlbumNode] = [] @Published private(set) var photoAlbumNodes: [SidebarAlbumNode] = [] + /// 行ごとの要約(本数・合計時間・表紙)。アルバム行は album.id、フォルダ行は folderKey で引く。 + /// 描画のたびに全件を数え直さないよう、videos / albums が変わったときだけここで作る。 + @Published private(set) var albumSummaries: [UUID: AlbumSummary] = [:] + @Published private(set) var folderSummaries: [String: AlbumSummary] = [:] + + /// 動画ツリーと画像ツリーで同名フォルダが両立しうるので、ツリーごとにキーを分ける + /// (サイドバーのドロップ先・展開状態のキーと同じ書き方)。 + static func folderKey(path: String, isPhoto: Bool) -> String { + (isPhoto ? "photo:" : "video:") + path + } + + /// 一覧に出る実アルバムの数(システムアルバムを除く)。 + var albumCount: Int { albumSummaries.count } /// サイドバーのツリーに載せるアルバム(システムアルバムを除き、動画/画像で棲み分ける)。 /// フォルダ一覧画面も同じ絞り込みを使うので static にしている。 @@ -27,6 +40,35 @@ final class SidebarViewModel: ObservableObject { photoAlbumNodes = SidebarAlbumNode.buildTree( from: Self.treeAlbums(from: albums, isPhoto: true) ) + refreshSummaries(videos: videos) + } + + private func refreshSummaries(videos: [VideoItem]) { + let itemByID = AlbumSummary.itemIndex(videos) + var albumResult: [UUID: AlbumSummary] = [:] + var folderResult: [String: AlbumSummary] = [:] + + /// 配下をまとめて1回で集計する(ノードごとに配下を辿り直さない)。 + func walk(_ node: SidebarAlbumNode, isPhoto: Bool) -> AlbumSummary { + var total = AlbumSummary() + if let album = node.album { + let own = AlbumSummary.of(album: album, itemByID: itemByID) + albumResult[album.id] = own + total.merge(own) + } + for child in node.children { + total.merge(walk(child, isPhoto: isPhoto)) + } + if !node.children.isEmpty { + folderResult[Self.folderKey(path: node.id, isPhoto: isPhoto)] = total + } + return total + } + + for node in videoAlbumNodes { _ = walk(node, isPhoto: false) } + for node in photoAlbumNodes { _ = walk(node, isPhoto: true) } + albumSummaries = albumResult + folderSummaries = folderResult } func albumIDs(in node: SidebarAlbumNode) -> [UUID] { diff --git a/AllServerForMac/Features/Navigation/Views/MainSidebarView.swift b/AllServerForMac/Features/Navigation/Views/MainSidebarView.swift index f39073a..9b9abed 100644 --- a/AllServerForMac/Features/Navigation/Views/MainSidebarView.swift +++ b/AllServerForMac/Features/Navigation/Views/MainSidebarView.swift @@ -8,8 +8,10 @@ struct MainSidebarView: View { @EnvironmentObject var appSettings: AppSettings @EnvironmentObject private var watchState: WatchStateStore @Binding var selection: NavigationSelection? - @Binding var isShowingPreferences: Bool - @Binding var isShowingStorageManager: Bool + + @State private var albumSearchText = "" + @State private var albumFilter = "すべて" + @FocusState private var isAlbumSearchFocused: Bool @State private var isShowingAddAlbumSheet = false @State private var newAlbumName = "" @@ -45,8 +47,12 @@ struct MainSidebarView: View { // キャッシュなしだと「アルバムをクリックするたびにライブラリ全件を再集計する」状態になっていた。 // dataManager.videos / .albums が実際に変化したときだけ refreshSidebarCaches() で更新する。 private let sidebarContentPadding: CGFloat = 10 - private let sidebarTopPadding: CGFloat = 42 - private let sidebarRowHeight: CGFloat = 28 + private let sidebarTopPadding: CGFloat = 12 + private let sidebarToolbarInset: CGFloat = 54 + private let sidebarRowHeight: CGFloat = 32 + /// 表紙と2行目(要約)つきの行の高さ。 + private let sidebarDetailRowHeight: CGFloat = 46 + private let sidebarCoverSize: CGFloat = 34 private let sidebarRowCornerRadius: CGFloat = 7 private let sidebarIconWidth: CGFloat = 16 // 行の左余白。アイコンが左端ギリギリに見えないよう、右側の余白より少し広めにとる。 @@ -57,9 +63,11 @@ struct MainSidebarView: View { // `.overlay(alignment:)`、GeometryReader での実測、DisclosureGroup など、 // 「利用可能な幅いっぱいに広げる」系のAPIを使うと、このビルド環境ではなぜか // 行の中身(アイコン・文字)が描画位置ごと画面外に飛んでしまう現象があった。 - // そのため、ContentView 側で決めているサイドバー列の幅(300〜360pt、標準320pt)に + // そのため、ContentView 側で決めているサイドバー列の幅(288pt)に // 合わせた固定値を `.frame(width:)` に渡すことで回避している。 - private let sidebarRowWidth: CGFloat = 300 + // 行の幅は、列の幅から左右の余白(10)とスクロールバーの分(15)を引いた値にしてある。 + private let sidebarColumnWidth: CGFloat = 288 + private let sidebarRowWidth: CGFloat = 253 /// 展開中のフォルダ(動画/画像ツリーで独立させるため dropKey と同じキーを使う)。 /// DisclosureGroup 標準の「>」は当たり判定が小さいため、タイトルをクリックしても @@ -68,8 +76,12 @@ struct MainSidebarView: View { var body: some View { ZStack { - CommandDeckBackground() - sidebarList + NeomorphicTheme.sidebar.ignoresSafeArea() + VStack(spacing: 0) { + albumSearchControls + Divider().padding(.horizontal, sidebarContentPadding) + sidebarList + } if isSidebarTargeted { RoundedRectangle(cornerRadius: 12, style: .continuous) .fill(NeomorphicTheme.accent.opacity(0.08)) @@ -88,7 +100,7 @@ struct MainSidebarView: View { .tint(NeomorphicTheme.accent) Text("エクスポート中... \(sidebarExportCurrent) / \(sidebarExportTotal)") .foregroundColor(NeomorphicTheme.ink) - .font(.caption) + .font(.appCaption) } .padding() .background( @@ -104,20 +116,6 @@ struct MainSidebarView: View { } message: { Text(sidebarExportResultMessage) } - .toolbar { - ToolbarItem(placement: .automatic) { - Button(action: { isShowingStorageManager = true }) { - Label("ストレージ管理", systemImage: "internaldrive") - } - .help("ストレージの内訳とクリーンアップ") - } - ToolbarItem(placement: .automatic) { - Button(action: { isShowingPreferences = true }) { - Label("詳細設定", systemImage: "gearshape") - } - .help("データの安全性・サーバー保護・パフォーマンスの設定") - } - } .onDrop(of: [.fileURL], isTargeted: $isSidebarTargeted) { providers in handleDropOnSidebar(providers: providers) } @@ -134,7 +132,7 @@ struct MainSidebarView: View { } Button("キャンセル", role: .cancel) { pendingSidebarFolderURL = nil } } message: { - Text("\(sidebarMixedContentInfo)\nどちらのタイプのアルバムとして作成しますか?指定したタイプ以外のファイルは無視されます。") + Text("\(sidebarMixedContentInfo)\nどちらのタイプのアルバムとして作成しますか?指定したタイプ以外のファイルは無視されます.") } } @@ -144,7 +142,7 @@ struct MainSidebarView: View { let buttonsWidth: CGFloat = isAlbumSelectionMode ? 116 : 60 return HStack(spacing: 0) { Text("アルバム") - .font(.system(size: 11, weight: .bold, design: .rounded)) + .font(.system(size: 11, weight: .bold, design: .default)) .foregroundStyle(NeomorphicTheme.muted) .padding(.leading, 10) .frame(width: sidebarRowWidth - buttonsWidth, alignment: .leading) @@ -204,42 +202,148 @@ struct MainSidebarView: View { } } - private var sidebarList: some View { - ScrollView(.vertical, showsIndicators: true) { - VStack(alignment: .leading, spacing: 10) { - sidebarNavigationButton(.home, title: "ホーム", systemImage: "house.fill") + /// スクロールしても検索の入口が隠れないように固定します. + private var albumSearchControls: some View { + VStack(spacing: 10) { + HStack(spacing: 8) { + Image(systemName: "magnifyingglass") + .foregroundStyle(NeomorphicTheme.muted) + TextField("アルバム・フォルダを検索", text: $albumSearchText) + .textFieldStyle(.plain) + .focused($isAlbumSearchFocused) + .onSubmit { openFirstAlbumSearchResult() } + .onExitCommand { + albumSearchText = "" + isAlbumSearchFocused = false + } + .help("名前やフォルダ名で検索します.Enterで先頭の結果を開き,Escで検索を解除します.") + .accessibilityLabel("アルバム・フォルダを検索") + if !albumSearchText.isEmpty { + Button { + albumSearchText = "" + isAlbumSearchFocused = true + } label: { + Image(systemName: "xmark.circle.fill") + } + .buttonStyle(.plain) + .help("アルバム検索を解除") + .accessibilityLabel("アルバム検索を解除") + } + } + .padding(10) + .background(NeomorphicTheme.control, in: RoundedRectangle(cornerRadius: 10, style: .continuous)) + FlatSegmentedControl( + options: ["すべて", "動画", "画像"], + title: { $0 }, + selection: $albumFilter, + width: sidebarRowWidth + ) + .accessibilityLabel("アルバムの種類") + } + .frame(width: sidebarRowWidth) + .padding(.horizontal, sidebarContentPadding) + .frame(width: sidebarColumnWidth, alignment: .leading) + // タイトルバーの下から検索欄を始めます. + .padding(.top, sidebarToolbarInset) + .padding(.bottom, 12) + } - VStack(alignment: .leading, spacing: 5) { - sidebarSectionTitle("ライブラリ") + private func openFirstAlbumSearchResult() { + guard !isAlbumSelectionMode, !normalizedAlbumQuery.isEmpty, + let album = matchingAlbums.first else { return } + selection = .album(album.id) + isAlbumSearchFocused = false + } - if let allVideos = dataManager.albums.first(where: { $0.name == LibraryViewModel.allVideosAlbumName }) { - sidebarNavigationButton(.album(allVideos.id), title: "すべての動画", systemImage: "film.stack", count: nonTrashedCount(in: allVideos)) - } - if let allPhotos = dataManager.albums.first(where: { $0.name == LibraryViewModel.allPhotosAlbumName }) { - sidebarNavigationButton(.album(allPhotos.id), title: "すべての画像", systemImage: "photo.stack", count: nonTrashedCount(in: allPhotos)) - } - sidebarNavigationButton(.favorites, title: "お気に入り", systemImage: "heart.fill", count: dataManager.favoriteVideos.count) - sidebarNavigationButton(.history, title: "再生履歴", systemImage: "clock.arrow.circlepath", count: historyCount) - sidebarNavigationButton(.trash, title: "ゴミ箱", systemImage: "trash.fill", count: dataManager.trashedVideos.count) - } + private var normalizedAlbumQuery: String { + albumSearchText.trimmingCharacters(in: .whitespacesAndNewlines) + } - VStack(alignment: .leading, spacing: 5) { - albumSectionHeader + /// フルパスを検索するため,閉じたフォルダの中も検索対象になります. + private var matchingAlbums: [Album] { + let terms = normalizedAlbumQuery.split(whereSeparator: { $0.isWhitespace }).map(String.init) + return dataManager.albums.filter { album in + guard album.name != LibraryViewModel.allVideosAlbumName, + album.name != LibraryViewModel.allPhotosAlbumName else { return false } + guard albumFilter == "すべて" || (albumFilter == "画像" ? album.type == .photo : album.type != .photo) else { + return false + } + return terms.allSatisfy { album.name.localizedStandardContains($0) } + } + .sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending } + } - // 動画アルバムと画像アルバムは別々のツリーとして棲み分ける - // (フォルダはアルバム名の "/" 区切りだけで表現されるため、混在すると - // 同名フォルダで動画と画像が同じ階層に混ざって見えてしまう)。 - // ツリー自体は viewModel.videoAlbumNodes / viewModel.photoAlbumNodes (refreshSidebarCaches() で更新)を使う。 - ForEach(viewModel.videoAlbumNodes) { node in - sidebarAlbumNodeRow(node, isPhotoTree: false) - } + private var sidebarList: some View { + ScrollView(.vertical, showsIndicators: true) { + VStack(alignment: .leading, spacing: 10) { + // 表紙つきの行は数百件になりうるので、画面に入った行だけ作る(表紙の読み込みも遅延される)。 + // 幅は他の行と同じ固定値にそろえる(貪欲な幅のままだと、行が左に寄って検索欄とずれる)。 + LazyVStack(alignment: .leading, spacing: 5) { + albumSectionHeader - ForEach(viewModel.photoAlbumNodes) { node in - sidebarAlbumNodeRow(node, isPhotoTree: true) + if !normalizedAlbumQuery.isEmpty { + Text("\(matchingAlbums.count)件のアルバム · Enterで先頭を開く") + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) + .padding(.leading, sidebarRowLeadingPadding) + if matchingAlbums.isEmpty { + VStack(alignment: .leading, spacing: 8) { + Text("一致するアルバムはありません") + .font(.appBody.weight(.semibold)) + Text("名前やフォルダ名を変えて検索してください.") + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) + Button("検索と絞り込みを解除") { + albumSearchText = "" + albumFilter = "すべて" + } + } + .padding(16) + .frame(width: sidebarRowWidth, alignment: .leading) + } + ForEach(matchingAlbums) { album in + VStack(alignment: .leading, spacing: 0) { + sidebarAlbumRow( + album: album, + title: album.name.components(separatedBy: "/").last ?? album.name, + systemImage: iconForAlbum(album) + ) + // 表紙つきの行は2行目に要約を出すので、フォルダの階層があるときだけ場所を補足する + // (最上位のアルバムでは名前の繰り返しになる)。 + if !appSettings.sidebarShowsAlbumDetails || album.name.contains("/") { + Text(album.name) + .font(.appMicro) + .foregroundStyle(NeomorphicTheme.muted) + .lineLimit(1) + .truncationMode(.middle) + .padding(.leading, appSettings.sidebarShowsAlbumDetails + ? sidebarRowLeadingPadding - 4 + sidebarCoverSize + 10 + : sidebarRowLeadingPadding + sidebarIconWidth + 8) + .frame(width: sidebarRowWidth, alignment: .leading) + } + } + .help(album.name) + } + } else { + if albumFilter != "画像" { + sidebarSectionTitle("動画アルバム") + ForEach(viewModel.videoAlbumNodes) { node in + sidebarAlbumNodeRow(node, isPhotoTree: false) + } + } + if albumFilter != "動画" { + sidebarSectionTitle("画像アルバム") + ForEach(viewModel.photoAlbumNodes) { node in + sidebarAlbumNodeRow(node, isPhotoTree: true) + } + } } } + .frame(width: sidebarRowWidth, alignment: .leading) } .padding(.horizontal, sidebarContentPadding) + // スクロールバーの有無で領域の幅が変わっても、行が中央寄せではみ出さず左端にそろうようにする。 + .frame(maxWidth: .infinity, alignment: .leading) .padding(.top, sidebarTopPadding) .padding(.bottom, 14) } @@ -291,42 +395,26 @@ struct MainSidebarView: View { Button("作成", action: createFolderFromSelection) Button("キャンセル", role: .cancel) { newFolderNameForSelection = "" } } message: { - Text("選択した\(selectedAlbumIDs.count)件のアルバムをこのフォルダの中に移動します。") + Text("選択した\(selectedAlbumIDs.count)件のアルバムをこのフォルダの中に移動します.") } .alert("新規アルバムに取り込む", isPresented: $isShowingSidebarFileImportAlbumNameAlert) { TextField("アルバム名", text: $newAlbumNameForSidebarFileImport) Button("作成して取り込む", action: importSidebarDroppedFiles) Button("キャンセル", role: .cancel) { pendingSidebarFileURLs = []; newAlbumNameForSidebarFileImport = "" } } message: { - Text("ドロップした\(pendingSidebarFileURLs.count)件のファイルを、新しく作るアルバムに取り込みます。") + Text("ドロップした\(pendingSidebarFileURLs.count)件のファイルを,新しく作るアルバムに取り込みます.") } } - /// 再生履歴の件数。履歴には削除済み・ゴミ箱行きの ID も残るので、 - /// 実際に一覧へ出るものだけを数える(お気に入り・ゴミ箱のバッジと同じ数え方に合わせる)。 - private var historyCount: Int { - guard !watchState.historyOrder.isEmpty else { return 0 } - let available = Set(dataManager.videos.lazy.filter { !$0.isInTrash }.map(\.id)) - return watchState.historyOrder.reduce(0) { $0 + (available.contains($1) ? 1 : 0) } - } - - private func sidebarNavigationButton(_ target: NavigationSelection, title: String, systemImage: String, count: Int? = nil) -> some View { - Button { - selection = target - } label: { - sidebarRowLabel(title, systemImage: systemImage, count: count, isActive: selection == target) - } - .buttonStyle(.plain) - } - private func sidebarRowLabel(_ title: String, systemImage: String, count: Int? = nil, isActive: Bool = false, isExpanded: Bool? = nil) -> some View { HStack(spacing: 8) { + // アイコンは線の細い無彩色にして、選ばれている行だけ濃くする(全部が濃いと名前が目立たない)。 Image(systemName: systemImage) - .font(.system(size: 12, weight: .semibold)) - .foregroundStyle(NeomorphicTheme.ink) + .font(.system(size: 13, weight: .regular)) + .foregroundStyle(isActive ? NeomorphicTheme.ink : NeomorphicTheme.muted) .frame(width: sidebarIconWidth) Text(title) - .font(.system(size: 12, weight: .medium, design: .rounded)) + .font(.system(size: 13, weight: .regular, design: .default)) .foregroundStyle(NeomorphicTheme.ink) .lineLimit(1) .truncationMode(.tail) @@ -346,19 +434,93 @@ struct MainSidebarView: View { .contentShape(RoundedRectangle(cornerRadius: sidebarRowCornerRadius, style: .continuous)) .background( RoundedRectangle(cornerRadius: sidebarRowCornerRadius, style: .continuous) - .fill(isActive ? NeomorphicTheme.accent.opacity(0.16) : Color.clear) + .fill(isActive ? NeomorphicTheme.selection : Color.clear) ) } + /// 表紙と2行目(「動画 12本 · 38分」など)つきの行。名前だけでは中身が分からないアルバムを + /// 見分けやすくするための表示で、設定でオフにすると従来の `sidebarRowLabel` に戻る。 + /// 幅は他の行と同じく固定値で指定する(上の sidebarRowWidth のコメント参照)。 + private func sidebarDetailRowLabel( + _ title: String, + summary: AlbumSummary?, + isFolder: Bool, + isActive: Bool, + isExpanded: Bool? = nil, + selected: Bool? = nil + ) -> some View { + HStack(spacing: 10) { + if let selected { + Image(systemName: selected ? "checkmark.circle.fill" : "circle") + .foregroundStyle(selected ? NeomorphicTheme.accent : NeomorphicTheme.muted) + } + sidebarCover(summary, isFolder: isFolder) + VStack(alignment: .leading, spacing: 2) { + Text(title) + .font(.system(size: 13, weight: .regular, design: .default)) + .foregroundStyle(NeomorphicTheme.ink) + .lineLimit(1) + .truncationMode(.tail) + Text(summary?.detailText(isFolder: isFolder) ?? " ") + .font(.appMicro) + .foregroundStyle(NeomorphicTheme.muted) + .lineLimit(1) + .truncationMode(.tail) + } + if let isExpanded { + Image(systemName: isExpanded ? "chevron.down" : "chevron.right") + .font(.system(size: 9, weight: .bold)) + .foregroundStyle(NeomorphicTheme.muted) + .frame(width: 12) + } + } + .padding(.leading, sidebarRowLeadingPadding - 4) + .padding(.trailing, sidebarRowTrailingPadding) + .frame(width: sidebarRowWidth, height: sidebarDetailRowHeight, alignment: .leading) + .contentShape(RoundedRectangle(cornerRadius: sidebarRowCornerRadius, style: .continuous)) + .background( + RoundedRectangle(cornerRadius: sidebarRowCornerRadius, style: .continuous) + .fill(isActive ? NeomorphicTheme.selection : Color.clear) + ) + .help(summary.map { "\(title)\n\($0.detailText(isFolder: isFolder))" } ?? title) + } + + /// 行の左の表紙。中身がなければフォルダ/アルバムのアイコンを出す。 + /// フォルダは右下に小さなフォルダ印を重ねて、アルバムと見分けられるようにする。 + private func sidebarCover(_ summary: AlbumSummary?, isFolder: Bool) -> some View { + ZStack { + Color.primary.opacity(0.08) + if let item = summary?.coverItems.first { + CoverThumbnail(item: item, dataManager: dataManager) + } else { + Image(systemName: isFolder ? "folder.fill" : "rectangle.stack") + .font(.system(size: 13, weight: .semibold)) + .foregroundStyle(NeomorphicTheme.muted) + } + } + .frame(width: sidebarCoverSize, height: sidebarCoverSize) + .clipShape(RoundedRectangle(cornerRadius: 7, style: .continuous)) + .overlay(alignment: .bottomTrailing) { + if isFolder { + Image(systemName: "folder.fill") + .font(.system(size: 8, weight: .bold)) + .foregroundStyle(.white) + .padding(3) + .background(Circle().fill(.black.opacity(0.6))) + .offset(x: 3, y: 3) + } + } + } + private func sidebarPlainLabel(_ title: String, systemImage: String) -> some View { Label(title, systemImage: systemImage) - .font(.system(size: 12, weight: .semibold, design: .rounded)) + .font(.system(size: 12, weight: .semibold, design: .default)) .foregroundStyle(NeomorphicTheme.ink) } private func sidebarSectionTitle(_ title: String) -> some View { Text(title) - .font(.system(size: 11, weight: .bold, design: .rounded)) + .font(.system(size: 12, weight: .medium, design: .default)) .foregroundStyle(NeomorphicTheme.muted) .padding(.leading, sidebarRowLeadingPadding) .padding(.trailing, sidebarRowTrailingPadding) @@ -368,13 +530,13 @@ struct MainSidebarView: View { private func sidebarSelectableRowLabel(_ title: String, systemImage: String, count: Int, isSelected: Bool) -> some View { HStack(spacing: 8) { Image(systemName: isSelected ? "checkmark.circle.fill" : "circle") - .foregroundStyle(isSelected ? NeomorphicTheme.accent : NeomorphicTheme.muted) + .foregroundStyle(isSelected ? NeomorphicTheme.ink : NeomorphicTheme.muted) Image(systemName: systemImage) - .font(.system(size: 12, weight: .semibold)) - .foregroundStyle(NeomorphicTheme.ink) + .font(.system(size: 13, weight: .regular)) + .foregroundStyle(NeomorphicTheme.muted) .frame(width: sidebarIconWidth) Text(title) - .font(.system(size: 12, weight: .medium, design: .rounded)) + .font(.system(size: 13, weight: .regular, design: .default)) .foregroundStyle(NeomorphicTheme.ink) .lineLimit(1) .truncationMode(.tail) @@ -387,34 +549,50 @@ struct MainSidebarView: View { } private func sidebarCountBadge(_ count: Int, tint: Color) -> some View { - Text("\(count)") - .font(.system(size: 10, weight: .semibold, design: .monospaced)) + // 件数は補足情報なので、色付きのカプセルにせず、控えめな数字だけにする + // (全行に青い太字のバッジが並ぶと、行の名前より数字が目立ってしまう)。 + Text("\(count.formatted())") + .font(.system(size: 11, weight: .regular)) .monospacedDigit() - .foregroundStyle(tint) - .padding(.horizontal, 6) - .padding(.vertical, 2) - .background( - Capsule() - .fill(NeomorphicTheme.surface) - .shadow(color: .white.opacity(0.8), radius: 2, x: -1, y: -1) - .shadow(color: NeomorphicTheme.shadow.opacity(0.18), radius: 3, x: 2, y: 2) - ) + .foregroundStyle(NeomorphicTheme.muted) } private func sidebarAlbumRow(album: Album, title: String, systemImage: String) -> AnyView { + let showsDetails = appSettings.sidebarShowsAlbumDetails + if isAlbumSelectionMode { return AnyView(Button { toggleAlbumSelection(album.id) } label: { - sidebarSelectableRowLabel(title, systemImage: systemImage, count: nonTrashedCount(in: album), isSelected: selectedAlbumIDs.contains(album.id)) + if showsDetails { + sidebarDetailRowLabel( + title, + summary: viewModel.albumSummaries[album.id], + isFolder: false, + isActive: false, + selected: selectedAlbumIDs.contains(album.id) + ) + } else { + sidebarSelectableRowLabel(title, systemImage: systemImage, count: nonTrashedCount(in: album), isSelected: selectedAlbumIDs.contains(album.id)) + } } .buttonStyle(.plain)) } return AnyView(Button { selection = .album(album.id) + isAlbumSearchFocused = false } label: { - sidebarRowLabel(title, systemImage: systemImage, count: nonTrashedCount(in: album), isActive: selection == .album(album.id)) + if showsDetails { + sidebarDetailRowLabel( + title, + summary: viewModel.albumSummaries[album.id], + isFolder: false, + isActive: selection == .album(album.id) + ) + } else { + sidebarRowLabel(title, systemImage: systemImage, count: nonTrashedCount(in: album), isActive: selection == .album(album.id)) + } } .buttonStyle(.plain) .draggable(AlbumDragPayload(albumIDs: [album.id], sourceFolderPath: nil)) @@ -447,7 +625,6 @@ struct MainSidebarView: View { /// ドラッグ&ドロップやフォルダの識別(ハイライト用キー)を型ごとに分離するために使う。 private func sidebarAlbumNodeRow(_ node: SidebarAlbumNode, isPhotoTree: Bool) -> AnyView { if node.children.isEmpty, let album = node.album { - guard nonTrashedCount(in: album) > 0 else { return AnyView(EmptyView()) } return sidebarAlbumRow(album: album, title: node.name, systemImage: iconForAlbum(album)) } else { let key = dropKey(forPath: node.id, isPhotoTree: isPhotoTree) @@ -551,34 +728,54 @@ struct MainSidebarView: View { } isExportingFromSidebar = false sidebarExportResultMessage = result.failedCount > 0 - ? "\(result.successCount)件を書き出しました。\(result.failedCount)件は失敗しました。" - : "\(result.successCount)件を書き出しました。" + ? "\(result.successCount)件を書き出しました.\(result.failedCount)件は失敗しました." + : "\(result.successCount)件を書き出しました." showSidebarExportResultAlert = true } } private func dropKey(forPath path: String, isPhotoTree: Bool) -> String { - (isPhotoTree ? "photo:" : "video:") + path + SidebarViewModel.folderKey(path: path, isPhoto: isPhotoTree) } @ViewBuilder private func folderRowLabel(_ node: SidebarAlbumNode, isPhotoTree: Bool) -> some View { let key = dropKey(forPath: node.id, isPhotoTree: isPhotoTree) + let showsDetails = appSettings.sidebarShowsAlbumDetails + let summary = viewModel.folderSummaries[key] Group { if isAlbumSelectionMode { - sidebarSelectableRowLabel(node.name, systemImage: "folder.fill", count: nonTrashedCount(in: node), isSelected: isAlbumNodeSelected(node)) + Group { + if showsDetails { + sidebarDetailRowLabel(node.name, summary: summary, isFolder: true, isActive: false, selected: isAlbumNodeSelected(node)) + } else { + sidebarSelectableRowLabel(node.name, systemImage: "folder.fill", count: nonTrashedCount(in: node), isSelected: isAlbumNodeSelected(node)) + } + } .contentShape(Rectangle()) .onTapGesture { toggleAlbumNodeSelection(node) } } else { - sidebarRowLabel( - node.name, - systemImage: "folder.fill", - count: nonTrashedCount(in: node), - isActive: selection == .folder(path: node.id, isPhoto: isPhotoTree), - isExpanded: expandedFolderIDs.contains(key) - ) + Group { + if showsDetails { + sidebarDetailRowLabel( + node.name, + summary: summary, + isFolder: true, + isActive: selection == .folder(path: node.id, isPhoto: isPhotoTree), + isExpanded: expandedFolderIDs.contains(key) + ) + } else { + sidebarRowLabel( + node.name, + systemImage: "folder.fill", + count: nonTrashedCount(in: node), + isActive: selection == .folder(path: node.id, isPhoto: isPhotoTree), + isExpanded: expandedFolderIDs.contains(key) + ) + } + } .contentShape(Rectangle()) // 標準の「>」だけだと当たり判定が小さいため、タイトル行全体のクリックでも開閉できるようにする。 // 併せて右ペインにこのフォルダの中身(子フォルダ・子アルバムの表紙)を出す。 @@ -788,26 +985,29 @@ struct MainSidebarView: View { private var addAlbumSheet: some View { VStack(spacing: 18) { - IconTile(icon: "rectangle.stack.badge.plus", tint: .accentColor, size: 44) + Image(systemName: "rectangle.stack.badge.plus") + .font(.system(size: 30, weight: .light)) + .foregroundStyle(NeomorphicTheme.muted) .padding(.top, 6) VStack(spacing: 4) { Text("新規アルバム") - .font(.headline) + .font(.system(size: 17, weight: .semibold)) Text("名前とタイプを選んで作成します") - .font(.caption) - .foregroundStyle(.secondary) + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) } TextField("アルバム名", text: $newAlbumName) .textFieldStyle(.roundedBorder) - Picker("タイプ", selection: $newAlbumType) { - Label("動画", systemImage: "film").tag(AlbumType.video) - Label("画像", systemImage: "photo").tag(AlbumType.photo) - } - .pickerStyle(.segmented) - .labelsHidden() + FlatSegmentedControl( + options: [AlbumType.video, AlbumType.photo], + title: { $0 == .video ? "動画" : "画像" }, + selection: $newAlbumType, + width: 272 + ) + .accessibilityLabel("タイプ") HStack { Button("キャンセル") { @@ -838,10 +1038,11 @@ struct MainSidebarView: View { .frame(maxWidth: .infinity) } .buttonStyle(.bordered) - .help("フォルダを選ぶと、そのフォルダ名でアルバムを作成し中身を一括インポートします") + .help("フォルダを選ぶと,そのフォルダ名でアルバムを作成し中身を一括インポートします") } .padding(24) .frame(width: 320) + .appSheet() } /// フォルダを選んで、そのフォルダ名のアルバムを作成しつつ中身を一括インポートする。 @@ -862,7 +1063,7 @@ struct MainSidebarView: View { panel.message = "アルバムとしてインポートするフォルダを選択してください" guard panel.runModal() == .OK, let folderURL = panel.url else { - print("⚠️ [IMPORT-BTN] パネルがキャンセルされたか、フォルダURLが取得できませんでした") + print("⚠️ [IMPORT-BTN] パネルがキャンセルされたか,フォルダURLが取得できませんでした") return } print("📥 [IMPORT-BTN] フォルダ選択: \(folderURL.path)") @@ -963,7 +1164,7 @@ struct MainSidebarView: View { func loadNextProvider(at index: Int) { guard index < providers.count else { if loadedURLs.count != providers.count { - print("⚠️ [DROP] \(providers.count)件中\(loadedURLs.count)件のURLを取得しました。") + print("⚠️ [DROP] \(providers.count)件中\(loadedURLs.count)件のURLを取得しました.") } completion(loadedURLs) return diff --git a/AllServerForMac/Features/Navigation/Views/SidebarRailView.swift b/AllServerForMac/Features/Navigation/Views/SidebarRailView.swift new file mode 100644 index 0000000..1d0a105 --- /dev/null +++ b/AllServerForMac/Features/Navigation/Views/SidebarRailView.swift @@ -0,0 +1,246 @@ +import Combine +import SwiftUI + +// MARK: - 件数 + +/// レールのバッジに出す件数。ライブラリの全件を数えるので、描画のたびには数えず、 +/// データが変わったあと少し待って(まとめて)数え直す。 +@MainActor +final class RailCountsModel: ObservableObject { + struct Counts: Equatable { + var videos = 0 + var photos = 0 + var albums = 0 + var favorites = 0 + var continueWatching = 0 + var history = 0 + var trash = 0 + } + + @Published private(set) var counts = Counts() + + private let dataManager: LibraryViewModel + private let watchState: WatchStateStore + private var cancellable: AnyCancellable? + + init(dataManager: LibraryViewModel, watchState: WatchStateStore) { + self.dataManager = dataManager + self.watchState = watchState + // 取り込みや視聴位置の更新は連続で起きるので、落ち着いてから1回だけ数える。 + cancellable = Publishers.Merge3( + dataManager.$videos.map { _ in () }, + dataManager.$albums.map { _ in () }, + watchState.objectWillChange.map { _ in () } + ) + .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) + .sink { [weak self] in self?.refresh() } + refresh() + } + + func refresh() { + var trashedIDs = Set() + var availableIDs = Set() + var favorites = 0 + var continueWatching = 0 + let hasProgress = !watchState.progress.isEmpty + let needsAvailable = !watchState.historyOrder.isEmpty + + for item in dataManager.videos { + if item.isInTrash { + trashedIDs.insert(item.id) + continue + } + if needsAvailable { availableIDs.insert(item.id) } + if item.isFavorite { favorites += 1 } + if hasProgress, item.mediaType == .video, + watchState.resumableSeconds(for: item.id, duration: item.duration) != nil { + continueWatching += 1 + } + } + + let history = watchState.historyOrder.reduce(0) { $0 + (availableIDs.contains($1) ? 1 : 0) } + let albums = dataManager.albums + func visibleCount(named name: String) -> Int { + albums.first { $0.name == name } + .map { album in album.videoIDs.reduce(0) { $0 + (trashedIDs.contains($1) ? 0 : 1) } } ?? 0 + } + let albumCount = [false, true].reduce(0) { + $0 + SidebarViewModel.treeAlbums(from: albums, isPhoto: $1).count + } + + let next = Counts( + videos: visibleCount(named: LibraryViewModel.allVideosAlbumName), + photos: visibleCount(named: LibraryViewModel.allPhotosAlbumName), + albums: albumCount, + favorites: favorites, + continueWatching: continueWatching, + history: history, + trash: trashedIDs.count + ) + if next != counts { counts = next } + } +} + +// MARK: - アイコンのレール(サイドバーの左に並ぶ細い縦の列) + +/// 主要な行き先と、ストレージ・設定のボタンを、アイコンだけでまとめた細い列。 +/// 以前はサイドバーの上半分を「ライブラリ」の行が占め、アルバムの一覧が下に押されていた。 +/// 行き先をここへ移すことで、サイドバーはアルバムの一覧に専念でき、サイドバーを隠してもレールは残る。 +struct SidebarRailView: View { + @StateObject private var countsModel: RailCountsModel + @Binding var selection: NavigationSelection? + /// 「すべての動画」「すべての画像」は、システムアルバムの ID で指す。ライブラリの読み込み前は nil。 + let allVideosAlbumID: UUID? + let allPhotosAlbumID: UUID? + let onShowStorage: () -> Void + let onShowPreferences: () -> Void + + static let width: CGFloat = 56 + + init( + dataManager: LibraryViewModel, + watchState: WatchStateStore, + selection: Binding, + allVideosAlbumID: UUID?, + allPhotosAlbumID: UUID?, + onShowStorage: @escaping () -> Void, + onShowPreferences: @escaping () -> Void + ) { + _countsModel = StateObject(wrappedValue: RailCountsModel(dataManager: dataManager, watchState: watchState)) + _selection = selection + self.allVideosAlbumID = allVideosAlbumID + self.allPhotosAlbumID = allPhotosAlbumID + self.onShowStorage = onShowStorage + self.onShowPreferences = onShowPreferences + } + + private struct Destination: Identifiable { + let id: String + let title: String + let symbol: String + let target: NavigationSelection? + var count: Int? = nil + } + + /// 区切り線で分ける3つのまとまり:ホーム/ライブラリ全体/自分用の入口。 + private var groups: [[Destination]] { + let c = countsModel.counts + return [ + [ + Destination(id: "home", title: "ホーム", symbol: "house", target: .home), + ], + [ + Destination(id: "videos", title: "すべての動画", symbol: "film.stack", target: allVideosAlbumID.map { .album($0) }, count: c.videos), + Destination(id: "photos", title: "すべての画像", symbol: "photo.stack", target: allPhotosAlbumID.map { .album($0) }, count: c.photos), + Destination(id: "albums", title: "アルバム一覧", symbol: "square.grid.2x2", target: .albums, count: c.albums), + ], + [ + Destination(id: "favorites", title: "お気に入り", symbol: "heart", target: .favorites, count: c.favorites), + Destination(id: "continue", title: "続きを見る", symbol: "play.circle", target: .continueWatching, count: c.continueWatching), + Destination(id: "history", title: "再生履歴", symbol: "clock.arrow.circlepath", target: .history, count: c.history), + Destination(id: "trash", title: "ゴミ箱", symbol: "trash", target: .trash, count: c.trash), + ], + ] + } + + var body: some View { + VStack(spacing: 0) { + // 信号機ボタンとツールバーの帯の下から始める。 + Spacer().frame(height: 54) + + VStack(spacing: 6) { + ForEach(Array(groups.enumerated()), id: \.offset) { index, group in + if index > 0 { + Rectangle() + .fill(NeomorphicTheme.separator) + .frame(width: 24, height: 0.5) + .padding(.vertical, 6) + } + ForEach(group) { item in + RailButton( + title: item.title, + symbol: item.symbol, + count: item.count, + isActive: item.target != nil && selection == item.target + ) { + if let target = item.target { selection = target } + } + .disabled(item.target == nil) + } + } + } + + Spacer(minLength: 12) + + VStack(spacing: 6) { + RailButton(title: "ストレージ管理", symbol: "internaldrive", count: nil, isActive: false, action: onShowStorage) + RailButton(title: "詳細設定", symbol: "gearshape", count: nil, isActive: false, action: onShowPreferences) + } + .padding(.bottom, 14) + } + .frame(width: Self.width) + .frame(maxHeight: .infinity) + } +} + +/// レールの1ボタン。選んでいるものは面を一段明るくし、色は付けない(サイドバーの選択表示と同じ)。 +private struct RailButton: View { + let title: String + let symbol: String + /// 件数バッジ。nil か 0 のときは出さない(0 件のバッジが並ぶと、何もないのに目立つため)。 + let count: Int? + let isActive: Bool + let action: () -> Void + + @Environment(\.isEnabled) private var isEnabled + @State private var isHovering = false + + var body: some View { + Button(action: action) { + Image(systemName: symbol) + .font(.system(size: 16, weight: .regular)) + .foregroundStyle(isActive ? NeomorphicTheme.ink : NeomorphicTheme.muted) + .frame(width: 38, height: 38) + .background( + RoundedRectangle(cornerRadius: 10, style: .continuous) + .fill(isActive ? NeomorphicTheme.selection : (isHovering ? NeomorphicTheme.hover : Color.clear)) + ) + .contentShape(RoundedRectangle(cornerRadius: 10, style: .continuous)) + } + .buttonStyle(.plain) + // 件数はアイコンの右上に小さく重ねる。幅の限られたレールに収まるよう、1,000 以上は「1.0K」の形にする。 + .overlay(alignment: .topTrailing) { + if let count, count > 0 { + Text(Self.compact(count)) + .font(.appMicro.weight(.semibold).monospacedDigit()) + .foregroundStyle(isActive ? NeomorphicTheme.ink : NeomorphicTheme.muted) + .padding(.horizontal, 4.5) + .frame(minWidth: 16, minHeight: 15) + .background(Capsule().fill(NeomorphicTheme.rail)) + .overlay(Capsule().strokeBorder(NeomorphicTheme.separator, lineWidth: 0.5)) + .offset(x: 7, y: -3) + .allowsHitTesting(false) + } + } + .opacity(isEnabled ? 1 : 0.35) + .onHover { isHovering = $0 } + .help(helpText) + .accessibilityLabel(helpText) + .accessibilityAddTraits(isActive ? .isSelected : []) + } + + private var helpText: String { + guard let count else { return title } + return "\(title)(\(count.formatted()))" + } + + /// 999 まではそのまま、1,000 以上は「1.0K」「26K」の形(2文字ぶんの幅に収める)。 + private static func compact(_ n: Int) -> String { + switch n { + case ..<1_000: return "\(n)" + case ..<10_000: return String(format: "%.1fK", Double(n) / 1_000) + case ..<1_000_000: return "\(n / 1_000)K" + default: return String(format: "%.1fM", Double(n) / 1_000_000) + } + } +} diff --git a/AllServerForMac/Features/Playback/Components/PlayerComponents.swift b/AllServerForMac/Features/Playback/Components/PlayerComponents.swift index e510742..9037b36 100644 --- a/AllServerForMac/Features/Playback/Components/PlayerComponents.swift +++ b/AllServerForMac/Features/Playback/Components/PlayerComponents.swift @@ -29,9 +29,122 @@ struct PlayerContainerView: NSViewRepresentable { } } +// MARK: - プレイヤー共通の見た目 + +/// 動画の上に重ねる操作部品の配色。アプリ本体と同じ「無彩色・平ら・影なし」にそろえる。 +/// 動画の明暗や、アプリの明るい/暗い外観に左右されないよう、常に暗い面に白い文字で組む。 +/// アクセントの青は使わず、「いま入っている」状態は面を一段明るくして示す。 +enum PlayerChrome { + /// 操作部品の面。動画が透けて見える程度の暗い半透明(ぼかしは使わず、平らに塗る)。 + static let panel = Color.black.opacity(0.74) + static let panelBorder = Color.white.opacity(0.09) + /// 「入っている」状態・押している間の面。 + static let chip = Color.white.opacity(0.18) + static let hover = Color.white.opacity(0.09) + static let icon = Color.white.opacity(0.88) + static let iconMuted = Color.white.opacity(0.58) + static let radius: CGFloat = 12 +} + +extension View { + /// 暗い平らな面(細い縁線つき)。操作バーやパネルの下地。 + func playerPanel(cornerRadius: CGFloat = PlayerChrome.radius) -> some View { + background( + RoundedRectangle(cornerRadius: cornerRadius, style: .continuous) + .fill(PlayerChrome.panel) + ) + .overlay( + RoundedRectangle(cornerRadius: cornerRadius, style: .continuous) + .strokeBorder(PlayerChrome.panelBorder, lineWidth: 0.5) + ) + } +} + +/// 操作バーの中に並べる、線の細いアイコンボタン。 +/// 「入っている」状態(シャッフル・リピート・お気に入りなど)は、色ではなく面の明るさで示す。 +struct PlayerIconButton: View { + let systemImage: String + var isActive = false + let help: String + var accessibilityLabel: String? + let action: () -> Void + + @Environment(\.isEnabled) private var isEnabled + @State private var isHovering = false + + var body: some View { + Button(action: action) { + Image(systemName: systemImage) + .font(.system(size: 14, weight: .regular)) + .foregroundStyle(isActive ? Color.white : PlayerChrome.icon) + .frame(width: 30, height: 30) + .background( + RoundedRectangle(cornerRadius: 7, style: .continuous) + .fill(isActive ? PlayerChrome.chip : (isHovering ? PlayerChrome.hover : Color.clear)) + ) + .contentShape(RoundedRectangle(cornerRadius: 7, style: .continuous)) + } + .buttonStyle(.plain) + .opacity(isEnabled ? 1 : 0.35) + .onHover { isHovering = $0 } + .help(help) + .accessibilityLabel(accessibilityLabel ?? help) + } +} + +/// 再生/一時停止だけは主役のボタンとして、白い丸に黒いアイコンで目立たせる(色は付けない)。 +struct PlayerPlayButton: View { + let isPlaying: Bool + let help: String + let action: () -> Void + + var body: some View { + Button(action: action) { + Image(systemName: isPlaying ? "pause.fill" : "play.fill") + .font(.system(size: 15, weight: .semibold)) + .foregroundStyle(Color.black.opacity(0.88)) + // 再生の三角は重心が左に寄って見えるので、わずかに右へ寄せて丸の中央に見せる。 + .offset(x: isPlaying ? 0 : 1) + .frame(width: 36, height: 36) + .background(Circle().fill(Color.white.opacity(0.94))) + .contentShape(Circle()) + } + .buttonStyle(.plain) + .help(help) + .accessibilityLabel(isPlaying ? "一時停止" : "再生") + } +} + +/// 画面隅に置く丸いボタン(ヘルプ・閉じる)。 +struct PlayerRoundButton: View { + let systemImage: String + let help: String + var accessibilityLabel: String? + let action: () -> Void + + @State private var isHovering = false + + var body: some View { + Button(action: action) { + Image(systemName: systemImage) + .font(.system(size: 13, weight: .medium)) + .foregroundStyle(PlayerChrome.icon) + .frame(width: 32, height: 32) + .background(Circle().fill(PlayerChrome.panel)) + .overlay(Circle().fill(isHovering ? PlayerChrome.hover : Color.clear)) + .overlay(Circle().strokeBorder(PlayerChrome.panelBorder, lineWidth: 0.5)) + .contentShape(Circle()) + } + .buttonStyle(.plain) + .onHover { isHovering = $0 } + .help(help) + .accessibilityLabel(accessibilityLabel ?? help) + } +} + // MARK: - プレイヤー共通UI(閉じる・ショートカットヘルプ) -/// プレイヤー画面の隅に重ねる「ヘルプ」「閉じる」ボタンの組。 +/// プレイヤー画面の隅に重ねる「音量」「ヘルプ」「閉じる」の組。 /// 全プレイヤーで見た目と操作感を揃える。 struct PlayerCornerControls: View { @Binding var showShortcutHelp: Bool @@ -42,36 +155,34 @@ struct PlayerCornerControls: View { let onClose: () -> Void var body: some View { - HStack(spacing: 10) { + HStack(spacing: 8) { if let volume, let isMuted { volumeControl(volume: volume, isMuted: isMuted) } - Button { + PlayerRoundButton( + systemImage: "questionmark", + help: "キーボードショートカット一覧(?キー)", + accessibilityLabel: "キーボードショートカット一覧" + ) { showShortcutHelp.toggle() - } label: { - Image(systemName: "questionmark.circle.fill") - .font(.largeTitle) - .symbolRenderingMode(.hierarchical) - .foregroundStyle(.white.opacity(0.7)) } - .buttonStyle(.plain) - .help("キーボードショートカット一覧(?キー)") - .accessibilityLabel("キーボードショートカット一覧") - - Button(action: onClose) { - Image(systemName: "xmark.circle.fill") - .font(.largeTitle) - .symbolRenderingMode(.hierarchical) - .foregroundStyle(.white.opacity(0.7)) - } - .buttonStyle(.plain) - .help("閉じる(Esc)") - .accessibilityLabel("プレイヤーを閉じる") + + PlayerRoundButton( + systemImage: "xmark", + help: "閉じる(Esc)", + accessibilityLabel: "プレイヤーを閉じる", + action: onClose + ) } .padding() + .padding(.top, Self.titlebarClearance) } + /// プレイヤーはタイトルバーの下まで広げて描くが,透明なタイトルバーはその帯のクリックを横取りする。 + /// ボタンを上端に置くと上半分が押せず「× を押しても閉じない」ので,その帯の下まで下げる。 + static let titlebarClearance: CGFloat = 24 + /// スピーカーボタン(クリックでミュート切替)と音量スライダー。 /// 全画面再生中はメニューバーもウィンドウのツールバーも出ないため、 /// 音量を変えられる場所がここしかない。 @@ -81,36 +192,46 @@ struct PlayerCornerControls: View { isMuted.wrappedValue.toggle() } label: { Image(systemName: Self.speakerSymbol(volume: volume.wrappedValue, isMuted: isMuted.wrappedValue)) - .font(.system(size: 15, weight: .semibold)) + .font(.system(size: 14, weight: .regular)) // 記号ごとに幅が違うのでスライダーが左右に揺れないよう固定幅にする。 .frame(width: 20, alignment: .center) - .foregroundStyle(.white.opacity(0.85)) + .foregroundStyle(PlayerChrome.icon) .contentShape(Rectangle()) } .buttonStyle(.plain) .help(isMuted.wrappedValue ? "ミュート解除" : "ミュート") .accessibilityLabel(isMuted.wrappedValue ? "ミュート解除" : "ミュート") - Slider(value: volume, in: 0...1) + // ミュート中も動かせるようにし,動かしたらミュートを解除する(無効化して薄くすると壊れて見える)。 + Slider( + value: Binding( + get: { volume.wrappedValue }, + set: { newValue in + volume.wrappedValue = newValue + if isMuted.wrappedValue { isMuted.wrappedValue = false } + } + ), + in: 0...1 + ) .controlSize(.small) .frame(width: 96) - .tint(.white.opacity(0.85)) - .disabled(isMuted.wrappedValue) - .opacity(isMuted.wrappedValue ? 0.35 : 1) + .tint(.white.opacity(0.9)) + .opacity(isMuted.wrappedValue ? 0.5 : 1) .help("音量") .accessibilityLabel("音量") } .padding(.horizontal, 12) - .padding(.vertical, 6) - .background(Capsule().fill(.black.opacity(0.35))) - .overlay(Capsule().strokeBorder(.white.opacity(0.18), lineWidth: 1)) + .frame(height: 32) + .playerPanel(cornerRadius: 16) + // 動画の上に重ねる暗い面なので,スライダーのトラックも暗い背景向けの色で描かせる。 + .environment(\.colorScheme, .dark) } private static func speakerSymbol(volume: Float, isMuted: Bool) -> String { - if isMuted || volume <= 0.001 { return "speaker.slash.fill" } - if volume < 0.34 { return "speaker.fill" } - if volume < 0.67 { return "speaker.wave.1.fill" } - return "speaker.wave.2.fill" + if isMuted || volume <= 0.001 { return "speaker.slash" } + if volume < 0.34 { return "speaker" } + if volume < 0.67 { return "speaker.wave.1" } + return "speaker.wave.2" } } @@ -123,46 +244,44 @@ struct ShortcutHelpPanel: View { var body: some View { ZStack { - Color.black.opacity(0.45) + Color.black.opacity(0.5) .contentShape(Rectangle()) .onTapGesture { onDismiss() } VStack(alignment: .leading, spacing: 14) { HStack { Label(title, systemImage: "keyboard") - .font(.headline) + .font(.system(size: 14, weight: .semibold)) Spacer() - Button(action: onDismiss) { - Image(systemName: "xmark.circle.fill") - .symbolRenderingMode(.hierarchical) - .font(.title3) - } - .buttonStyle(.plain) - .help("ヘルプを閉じる") + PlayerRoundButton(systemImage: "xmark", help: "ヘルプを閉じる", action: onDismiss) } - Divider() + Rectangle().fill(PlayerChrome.panelBorder).frame(height: 0.5) Grid(alignment: .leading, horizontalSpacing: 18, verticalSpacing: 8) { ForEach(Array(shortcuts.enumerated()), id: \.offset) { _, item in GridRow { Text(item.key) - .font(.system(.body, design: .monospaced).weight(.semibold)) + .font(.system(size: 12, weight: .medium, design: .monospaced)) .padding(.horizontal, 8) .padding(.vertical, 3) - .background(Color.primary.opacity(0.1)) + .background(PlayerChrome.hover) .clipShape(RoundedRectangle(cornerRadius: 5, style: .continuous)) .gridColumnAlignment(.trailing) Text(item.action) - .font(.body) + .font(.appBody) + .foregroundStyle(PlayerChrome.icon) } } } } + .foregroundStyle(PlayerChrome.icon) .padding(24) .frame(maxWidth: 420) - .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 14, style: .continuous)) - .shadow(radius: 24) + // 暗い平らな面。ぼかしや影は付けない(アプリ本体のカードと同じ質感にそろえる)。 + .background(RoundedRectangle(cornerRadius: 14, style: .continuous).fill(Color(white: 0.13))) + .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(PlayerChrome.panelBorder, lineWidth: 0.5)) + .environment(\.colorScheme, .dark) } .transition(.opacity) } diff --git a/AllServerForMac/Features/Playback/Components/PlayerLayerView.swift b/AllServerForMac/Features/Playback/Components/PlayerLayerView.swift index bbf4953..9196bc1 100644 --- a/AllServerForMac/Features/Playback/Components/PlayerLayerView.swift +++ b/AllServerForMac/Features/Playback/Components/PlayerLayerView.swift @@ -41,12 +41,17 @@ final class PlayerLayerHostView: NSView { struct PlayerLayerContainerView: NSViewRepresentable { let player: AVPlayer? + /// 映像の収め方。既定は全体が収まる表示。 + /// レイヤーを作り直さずにここだけ差し替える(作り直すと再生が途切れるうえ、 + /// `PictureInPictureCoordinator` が掴んでいる `AVPlayerLayer` が別物になってしまう)。 + var videoGravity: AVLayerVideoGravity = .resizeAspect /// レイヤーが出来たときに一度だけ呼ばれる。PiP コントローラーの作成に使う。 var onLayerReady: ((AVPlayerLayer) -> Void)? func makeNSView(context: Context) -> PlayerLayerHostView { let view = PlayerLayerHostView() view.playerLayer.player = player + view.playerLayer.videoGravity = videoGravity if let onLayerReady { // View 生成の最中に呼ぶと SwiftUI の状態更新と重なるため、次のループへ回す。 let layer = view.playerLayer @@ -59,5 +64,12 @@ struct PlayerLayerContainerView: NSViewRepresentable { if nsView.playerLayer.player !== player { nsView.playerLayer.player = player } + if nsView.playerLayer.videoGravity != videoGravity { + // 収め方の変更に暗黙アニメーションが乗ると、切り替えの瞬間に映像が伸び縮みして見える。 + CATransaction.begin() + CATransaction.setDisableActions(true) + nsView.playerLayer.videoGravity = videoGravity + CATransaction.commit() + } } } diff --git a/AllServerForMac/Features/Playback/Models/MediaShortcutModels.swift b/AllServerForMac/Features/Playback/Models/MediaShortcutModels.swift index 5c8da89..615eee3 100644 --- a/AllServerForMac/Features/Playback/Models/MediaShortcutModels.swift +++ b/AllServerForMac/Features/Playback/Models/MediaShortcutModels.swift @@ -121,6 +121,13 @@ enum MediaShortcutAction: String, CaseIterable, Identifiable { case videoRateDown case videoRateUp case videoTogglePictureInPicture + case videoVolumeUp + case videoVolumeDown + case videoToggleMute + case videoToggleFavorite + case videoStepBackward + case videoStepForward + case videoToggleFillScreen case variantNext case variantPrevious case variantRandom @@ -181,6 +188,13 @@ enum MediaShortcutAction: String, CaseIterable, Identifiable { case .videoRateDown: return "動画: 再生速度を下げる" case .videoRateUp: return "動画: 再生速度を上げる" case .videoTogglePictureInPicture: return "動画: ピクチャインピクチャ" + case .videoVolumeUp: return "動画: 音量を上げる" + case .videoVolumeDown: return "動画: 音量を下げる" + case .videoToggleMute: return "動画: ミュート切替" + case .videoToggleFavorite: return "動画: お気に入り切替" + case .videoStepBackward: return "動画: 1コマ戻る" + case .videoStepForward: return "動画: 1コマ進む" + case .videoToggleFillScreen: return "動画: 画面いっぱい切替" case .variantNext: return "差分: 次のバージョンへ" case .variantPrevious: return "差分: 前のバージョンへ" case .variantRandom: return "差分: ランダムなバージョンへ" @@ -237,6 +251,13 @@ enum MediaShortcutAction: String, CaseIterable, Identifiable { case .videoRateDown: return "再生速度を1段下げる" case .videoRateUp: return "再生速度を1段上げる" case .videoTogglePictureInPicture: return "他アプリの上に浮かぶ小窓で再生する/戻す" + case .videoVolumeUp: return "音量を上げる" + case .videoVolumeDown: return "音量を下げる" + case .videoToggleMute: return "ミュートを切り替え" + case .videoToggleFavorite: return "観ている動画のお気に入りを切り替え" + case .videoStepBackward: return "一時停止して1コマ戻る" + case .videoStepForward: return "一時停止して1コマ進む" + case .videoToggleFillScreen: return "黒帯を切り落として画面いっぱいに広げる/元に戻す" case .variantNext: return "次の差分バージョンへ切り替え" case .variantPrevious: return "前の差分バージョンへ切り替え" case .variantRandom: return "ランダムな差分バージョンへ切り替え" @@ -297,6 +318,22 @@ enum MediaShortcutAction: String, CaseIterable, Identifiable { case .videoRateDown: return [MediaShortcutKey(rawValue: ",")] case .videoRateUp: return [MediaShortcutKey(rawValue: ".")] case .videoTogglePictureInPicture: return [MediaShortcutKey(rawValue: "p")] + // 通常再生で空いていたのは ↑↓ と Z・C だけだったので、使用頻度の高い音量を矢印に置く。 + case .videoVolumeUp: return [.upArrow] + case .videoVolumeDown: return [.downArrow] + // ミュートは M が通用する。同時再生も M を音声ミキサーに直接割り当てているが、 + // あちらは `.videoToggleMute` を配っていない別画面なので、押し合いにはならない。 + case .videoToggleMute: return [.m] + // お気に入り(Okiniiri)の O。一覧側は V だが、V は差分切り替え再生が使っていて、 + // 環境設定の重複チェックは動画と差分をまとめて見るため、既定のまま警告が出てしまう。 + // 差分切り替え再生は Q〜O を「何本目を出すか」に直接割り当てているので O とも重なるが、 + // あちらは専用のキー処理を持つ別画面で、E・R・T・I も同じように重なっている。 + case .videoToggleFavorite: return [MediaShortcutKey(rawValue: "o")] + // Z と C は X(差分の削除マーク)を挟んで左右に並ぶ。左が戻る、右が進む。 + case .videoStepBackward: return [MediaShortcutKey(rawValue: "z")] + case .videoStepForward: return [MediaShortcutKey(rawValue: "c")] + // W(wide)。これも差分切り替え再生の直接選択と重なるが、事情は O と同じ。 + case .videoToggleFillScreen: return [MediaShortcutKey(rawValue: "w")] case .variantNext: return [MediaShortcutKey(rawValue: "n")] case .variantPrevious: return [MediaShortcutKey(rawValue: "b")] case .variantRandom: return [MediaShortcutKey(rawValue: "v")] @@ -351,7 +388,14 @@ enum MediaShortcutAction: String, CaseIterable, Identifiable { .videoCycleRepeat, .videoRateDown, .videoRateUp, - .videoTogglePictureInPicture + .videoTogglePictureInPicture, + .videoVolumeUp, + .videoVolumeDown, + .videoToggleMute, + .videoToggleFavorite, + .videoStepBackward, + .videoStepForward, + .videoToggleFillScreen ] /// 差分切り替え再生だけで使うもの。再生・シーク・閉じるは `videoActions` と共通なので重ねない。 diff --git a/AllServerForMac/Features/Playback/ViewModels/PlaybackCoordinator.swift b/AllServerForMac/Features/Playback/ViewModels/PlaybackCoordinator.swift index d620b5e..009900c 100644 --- a/AllServerForMac/Features/Playback/ViewModels/PlaybackCoordinator.swift +++ b/AllServerForMac/Features/Playback/ViewModels/PlaybackCoordinator.swift @@ -15,6 +15,7 @@ final class PlaybackCoordinator: ObservableObject { enum LibraryScope: Equatable { case album(UUID) case favorites + case continueWatching case history case trash } @@ -30,6 +31,7 @@ final class PlaybackCoordinator: ObservableObject { enum Mode: Equatable { case single(playlist: [VideoItem], current: VideoItem) + case tour(PlaybackTourSession) case multi([VideoItem]) case variantSwitch([VideoItem], alignment: VariantPlaybackAlignmentMode) case slideshow([VideoItem]) @@ -44,6 +46,7 @@ final class PlaybackCoordinator: ObservableObject { refreshSleepBlocker() } } + private(set) var singleStartTime: Double? @Published private(set) var libraryReturnState: LibraryReturnState? /// 通常再生をIキーで右下に小さくたたみ、アルバム一覧を裏に表示している間 true。 @Published var isMiniPlayerActive = false @@ -73,7 +76,7 @@ final class PlaybackCoordinator: ObservableObject { private static func blocksSleep(_ mode: Mode?) -> Bool { switch mode { case .none, .photos: return false - case .single, .multi, .variantSwitch, .slideshow, .splitPlay: return true + case .single, .tour, .multi, .variantSwitch, .slideshow, .splitPlay: return true } } @@ -115,7 +118,8 @@ final class PlaybackCoordinator: ObservableObject { } /// 通常再生(再生リスト+開始位置を指定) - func playSingle(playlist: [VideoItem], current: VideoItem) { + func playSingle(playlist: [VideoItem], current: VideoItem, startAt: Double? = nil) { + singleStartTime = startAt let videos = playlist.filter { $0.mediaType == .video } let start = (videos.contains(current) ? current : videos.first) ?? current isMiniPlayerActive = false @@ -127,12 +131,19 @@ final class PlaybackCoordinator: ObservableObject { // 差分一覧はライブラリ上のオーバーレイなので,背後に残ったRキーや // ツールバーの操作で通常プレイヤーを重ねない. guard variantFinderAlbumID == nil else { return } + singleStartTime = nil let shuffled = videos.filter { $0.mediaType == .video }.shuffled() guard let first = shuffled.first else { return } isMiniPlayerActive = false mode = .single(playlist: shuffled, current: first) } + func startTour(_ session: PlaybackTourSession) { + guard !session.entries.isEmpty, variantFinderAlbumID == nil else { return } + isMiniPlayerActive = false + mode = .tour(session) + } + /// 同時同期再生(2〜9本、9本超は先頭9本) func playMulti(_ videos: [VideoItem]) { let items = videos.filter { $0.mediaType == .video } @@ -208,3 +219,184 @@ final class PlaybackCoordinator: ObservableObject { libraryReturnState = nil } } + +// MARK: - 区間を一巡する再生リスト + +struct PlaybackTourEntry: Identifiable, Equatable { + let id: UUID + let video: VideoItem + let start: Double + let end: Double +} + +struct PlaybackTourSession: Identifiable, Equatable { + enum Kind: Equatable { + case preview + case scenes + case channels + case mix(Mood) + case timed + case highlights + } + enum Mood: String, CaseIterable { + case short = "短く楽しむ" + case unseen = "未視聴を発掘" + case favorites = "お気に入り中心" + } + struct Channel: Identifiable, Equatable { + let id: UUID + let name: String + let videos: [VideoItem] + } + let id = UUID() + let kind: Kind + let entries: [PlaybackTourEntry] + + let channels: [Channel] + let requestedSeconds: Double? + + var title: String { + switch kind { + case .preview: return "プレビュー巡回" + case .scenes: return "シーンシャッフル" + case .channels: return "マイチャンネル" + case .mix(let mood): return mood.rawValue + case .timed: return "時間ぴったり再生" + case .highlights: return "ストックした場面" + } + } + + init(kind: Kind, entries: [PlaybackTourEntry], channels: [Channel] = [], requestedSeconds: Double? = nil) { + self.kind = kind + self.entries = entries + self.channels = channels + self.requestedSeconds = requestedSeconds + } + + static func preview(videos: [VideoItem], seconds: Double) throws -> PlaybackTourSession { + guard seconds.isFinite, seconds > 0 else { throw PlaybackTourError.invalidRange } + let entries = eligibleVideos(videos).shuffled().map { video in + let length = min(seconds, video.duration) + let start = Double.random(in: 0...max(0, video.duration - length)) + return PlaybackTourEntry(id: UUID(), video: video, start: start, end: start + length) + } + guard !entries.isEmpty else { throw PlaybackTourError.noVideos } + return PlaybackTourSession(kind: .preview, entries: entries) + } + + static func scenes(videos: [VideoItem], urlForVideo: (VideoItem) -> URL?, + defaults: UserDefaults = .standard) throws -> PlaybackTourSession { + let saved = try AcceptedSceneStore.load(defaults: defaults) + let entries = eligibleVideos(videos).flatMap { video -> [PlaybackTourEntry] in + guard let url = urlForVideo(video) else { return [] } + return (saved[AcceptedSceneStore.sourceKey(url)] ?? []).compactMap { candidate in + guard candidate.userLabel == .accepted, + candidate.startTime.isFinite, candidate.endTime.isFinite else { return nil } + let start = max(0, candidate.startTime) + let end = min(video.duration, candidate.endTime) + guard end > start else { return nil } + return PlaybackTourEntry(id: UUID(), video: video, start: start, end: end) + } + }.shuffled() + guard !entries.isEmpty else { throw PlaybackTourError.noScenes } + return PlaybackTourSession(kind: .scenes, entries: entries) + } + + static func channelSession(albums: [Album], videos: [VideoItem]) throws -> PlaybackTourSession { + let byID = Dictionary(eligibleVideos(videos).map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }) + let channels = albums.filter { + $0.name != LibraryViewModel.allVideosAlbumName && $0.name != LibraryViewModel.allPhotosAlbumName + }.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }.compactMap { album -> Channel? in + let items = album.videoIDs.compactMap { byID[$0] } + return items.isEmpty ? nil : Channel(id: album.id, name: album.name, videos: items) + } + let entries = channels.compactMap { channel -> PlaybackTourEntry? in + guard let video = channel.videos.randomElement() else { return nil } + let start = Double.random(in: 0...max(0, video.duration - min(15, video.duration))) + return PlaybackTourEntry(id: UUID(), video: video, start: start, end: video.duration) + } + guard !entries.isEmpty else { throw PlaybackTourError.noChannels } + return PlaybackTourSession(kind: .channels, entries: entries, channels: channels) + } + + static func mix(videos: [VideoItem], mood: Mood, seenIDs: Set) throws -> PlaybackTourSession { + let available = eligibleVideos(videos) + let items: [VideoItem] + switch mood { + case .short: items = available.filter { $0.duration <= 180 } + case .unseen: items = available.filter { !seenIDs.contains($0.id) } + case .favorites: items = available.filter(\.isFavorite) + } + guard !items.isEmpty else { throw PlaybackTourError.noMoodMatches } + let preview = try preview(videos: items, seconds: mood == .short ? 30 : 60) + return PlaybackTourSession(kind: .mix(mood), entries: preview.entries) + } + + /// 同じ動画を一巡したら再利用し,最後の区間だけを短くして合計時間を合わせます. + static func timed(videos: [VideoItem], seconds: Double) throws -> PlaybackTourSession { + let minimumDuration = 0.5 + let maximumSeconds = 3600.0 + let items = eligibleVideos(videos).filter { $0.duration >= minimumDuration }.shuffled() + guard !items.isEmpty else { throw PlaybackTourError.noVideos } + guard seconds.isFinite, seconds > 0, seconds <= maximumSeconds else { throw PlaybackTourError.invalidRange } + var entries: [PlaybackTourEntry] = [] + var remaining = seconds + var cursor = 0 + while remaining > 0.000001 { + let video = items[cursor % items.count] + let length = min(video.duration, remaining) + entries.append(PlaybackTourEntry(id: UUID(), video: video, start: 0, end: length)) + remaining -= length + cursor += 1 + } + return PlaybackTourSession(kind: .timed, entries: entries, requestedSeconds: seconds) + } + + static func highlights(videos: [VideoItem], urlForVideo: (VideoItem) -> URL?, + defaults: UserDefaults = .standard) throws -> PlaybackTourSession { + let stored = try AcceptedSceneStore.load(defaults: defaults, key: HighlightStore.defaultsKey) + let entries = eligibleVideos(videos).flatMap { video -> [PlaybackTourEntry] in + guard let url = urlForVideo(video) else { return [] } + return (stored[AcceptedSceneStore.sourceKey(url)] ?? []).compactMap { scene in + let start = max(0, scene.startTime) + let end = min(video.duration, scene.endTime) + guard start.isFinite, end.isFinite, end > start else { return nil } + return PlaybackTourEntry(id: UUID(), video: video, start: start, end: end) + } + }.shuffled() + guard !entries.isEmpty else { throw PlaybackTourError.noHighlights } + return PlaybackTourSession(kind: .highlights, entries: entries) + } + + private static func eligibleVideos(_ videos: [VideoItem]) -> [VideoItem] { + var seen = Set() + return videos.filter { + $0.mediaType == .video && !$0.isInTrash && $0.duration.isFinite && $0.duration > 0 + && seen.insert($0.id).inserted + } + } +} + +enum PlaybackTourError: LocalizedError { + case noVideos + case noChannels + case noMoodMatches + case noHighlights + case noScenes + case invalidRange + case missingFile + case unplayable + + var errorDescription: String? { + switch self { + case .noChannels: return "動画を含むアルバムがありません.アルバムに動画を追加してください." + case .noMoodMatches: return "この気分に合う動画がありません.3分以内の動画・未視聴・お気に入りの条件や,表示中の一覧を確認してください." + case .noHighlights: return "ストックした場面がありません.再生中に「場面を保存」を押してください." + case .noVideos: return "再生時間が分かる動画がありません.動画を含む一覧から開始してください." + case .noScenes: return "採用済みのシーンがありません.動画の「シーン抽出」で区間を採用してから,もう一度開始してください." + case .invalidRange: return "有効な再生区間がありません.シーンの開始・終了位置を確認してください." + case .missingFile: return "元の動画が見つかりません.保存先を接続するか,次の項目へ進んでください." + case .unplayable: return "この動画を再生できません.ファイル形式を確認するか,次の項目へ進んでください." + } + } +} diff --git a/AllServerForMac/Features/Playback/ViewModels/VideoPlayerViewModel.swift b/AllServerForMac/Features/Playback/ViewModels/VideoPlayerViewModel.swift index 72f2eb8..bdcc2c1 100644 --- a/AllServerForMac/Features/Playback/ViewModels/VideoPlayerViewModel.swift +++ b/AllServerForMac/Features/Playback/ViewModels/VideoPlayerViewModel.swift @@ -12,9 +12,12 @@ final class VideoPlayerViewModel: ObservableObject { @Published var currentTime: Double = 0 @Published var duration: Double = 1.0 @Published var isPlaybackPlaying = false + @Published private(set) var loopAnalysisNotice: String? + @Published private(set) var isAnalyzingLoopEdges = false /// 前後移動の対象となる動画リスト(動画のみ) let allVideos: [VideoItem] + private var pendingInitialStartTime: Double? private let dataManager: LibraryViewModel /// 視聴位置と再生履歴の保管庫(ブラウザ・iPhone と共有)。 private let watchState: WatchStateStore @@ -22,6 +25,10 @@ final class VideoPlayerViewModel: ObservableObject { let settings: PlaybackSettings /// 「◯:◯◯ から再開しました」の一時表示。nil のときは出さない。 @Published var resumeNotice: String? + /// いま観ている動画がお気に入りか。 + /// ビューは `dataManager` を監視していない(巨大な配列の更新で再描画が走らないよう + /// ただの let で持っている)ので、表示に要る分だけここへ写しておく。 + @Published private(set) var isCurrentVideoFavorite = false /// この動画が持つ音声トラック(2本以上あるときだけ選択 UI を出す)。 @Published private(set) var audioTracks: [MediaTrackChoice] = [] /// この動画が持つ字幕トラック。先頭は必ず「オフ」。空なら字幕なし。 @@ -31,6 +38,15 @@ final class VideoPlayerViewModel: ObservableObject { private var chapterGenerationTask: Task? private var playerTimeObserver: Any? private weak var observedPlayer: AVPlayer? + private var monitoredItem: AVPlayerItem? + private var queuedLoopVideoID: UUID? + private let loopQueueItemCount = 3 + private let loopForwardBufferDuration: TimeInterval = 3 + private var loopAnalysisTask: Task? + private var loopAnalysisVideoID: UUID? + private var loopAnalysisGeneration = 0 + private var analyzedLoopVideoIDs = Set() + private var loopPlaybackRanges: [UUID: CMTimeRange] = [:] private var cancellables = Set() private var preloadTasks: [UUID: Task] = [:] private var assetCache: [UUID: AVURLAsset] = [:] @@ -46,9 +62,33 @@ final class VideoPlayerViewModel: ObservableObject { private var isRestoringPosition = false /// ループ先頭へシークしている間,末尾側の時刻通知で表示位置を戻さないためのフラグ. private var isRestartingLoop = false + /// シャッフル再生の「袋」。まだ流していない動画を混ぜて入れておき、端から取り出す。 + /// 毎回その場で randomElement() を引くと、数本前に観たものがすぐ再来するうえ、 + /// 「全部観たら終わり」を表現できない(袋が空になったかどうかが一巡の合図になる)。 + /// セッション限りの状態なので、UserDefaults へ保存する `PlaybackSettings` には置かない。 + private var shuffleBag: [UUID] = [] + /// 袋を一度でも作ったか。「まだ作っていない」と「使い切った」を区別しないと、 + /// 再生の途中でシャッフルを入れたときに空の袋を「もう全部観た」と誤解して即座に止まる。 + private var isShuffleBagPrepared = false + /// 実際に再生した順(古い順)。シャッフル中の「前へ」は、リストの並びではなくこちらを遡る。 + private var playedStack: [UUID] = [] + /// プレイヤーを開いている間ずっと張っておく購読。 + /// プレイヤー側の購読(`cancellables`)は動画を切り替えるたびに張り直すので、 + /// 寿命が違うこちらは別に持つ。 + private var sessionObservers = Set() private let adjacentPreloadRadius = 4 + /// 遡れる履歴の上限。これより古いところまで戻ることは実際には無い。 + private let maxPlayedStackCount = 100 + /// 切り替えた直後の「準備が整うまで待ってから再生する」処理。 + private var pendingStartTask: Task? + /// 連打で追い越された準備が、もう映していない動画の再生を始めてしまわないための世代番号。 + private var playbackStartGeneration = 0 private let chapterGenerationDelayNanoseconds: UInt64 = 280_000_000 private let playerTimeObserverInterval: TimeInterval = 0.25 + /// 差し替えた直後にデコードの準備を待つ上限。壊れたファイルを掴んでも + /// 「次へ送ったのに始まらない」にならないよう、ここを過ぎたら暖めを諦めてそのまま再生する。 + private let playbackStartReadyTimeoutSeconds: TimeInterval = 1.5 + private let playbackStartPollNanoseconds: UInt64 = 20_000_000 private let defaultDuration: Double = 1.0 /// 音量とミュート。動画を切り替えても、次にプレイヤーを開いたときも引き継ぐ。 @@ -65,16 +105,29 @@ final class VideoPlayerViewModel: ObservableObject { } } + /// 映像を画面いっぱいに広げる(上下左右は切り落とす)。 + /// レターボックスごと焼き込まれている素材を観るための切り替え。 + @Published var fillsScreen: Bool { + didSet { UserDefaults.standard.set(fillsScreen, forKey: Self.fillsScreenDefaultsKey) } + } + + /// 映像面へ渡す収め方。`fillsScreen` の言い換えだが、 + /// レイヤー側が AVFoundation の型しか受け取らないのでここで変換する。 + var videoGravity: AVLayerVideoGravity { fillsScreen ? .resizeAspectFill : .resizeAspect } + static let volumeDefaultsKey = "player.volume" static let mutedDefaultsKey = "player.muted" + static let fillsScreenDefaultsKey = "player.fillsScreen" init( videos: [VideoItem], currentVideo: VideoItem, dataManager: LibraryViewModel, watchState: WatchStateStore, - settings: PlaybackSettings + settings: PlaybackSettings, + initialStartTime: Double? = nil ) { + self.pendingInitialStartTime = initialStartTime self.allVideos = videos self.currentVideo = currentVideo self.dataManager = dataManager @@ -84,6 +137,8 @@ final class VideoPlayerViewModel: ObservableObject { let storedVolume = UserDefaults.standard.object(forKey: Self.volumeDefaultsKey) as? Double self.volume = Float(storedVolume ?? 1.0) self.isMuted = UserDefaults.standard.bool(forKey: Self.mutedDefaultsKey) + // 未設定なら従来どおり全体が収まる表示。 + self.fillsScreen = UserDefaults.standard.bool(forKey: Self.fillsScreenDefaultsKey) } func setupPlayer() { @@ -94,7 +149,7 @@ final class VideoPlayerViewModel: ObservableObject { } // View 更新中に @Published を変更しないよう次のループで実行する Task { @MainActor in - let newPlayer = AVPlayer(playerItem: item) + let newPlayer = AVQueuePlayer(items: [item]) newPlayer.automaticallyWaitsToMinimizeStalling = false // 終端で映像面を消さず,先頭フレームの準備中も最後のフレームを保持する. newPlayer.actionAtItemEnd = .none @@ -105,9 +160,11 @@ final class VideoPlayerViewModel: ObservableObject { newPlayer.defaultRate = Float(self.settings.rate) self.player = newPlayer self.configurePlaybackMonitoring(for: newPlayer) + self.observeSessionState() self.startWatching(self.currentVideo, on: newPlayer) self.activateNowPlaying() - newPlayer.play() + // 1本目も同じ順序で始める。開いた直後の頭が引っかかるのは切り替え時と同じ理由。 + self.startPlaybackWhenReady(on: newPlayer, item: item) self.preloadNearbyAssets(around: self.currentVideo) self.generateChapterPoints() } @@ -154,17 +211,27 @@ final class VideoPlayerViewModel: ObservableObject { resumeNoticeTask?.cancel() resumeNotice = nil chapterGenerationTask?.cancel() + cancelLoopBlackFrameAnalysis() + analyzedLoopVideoIDs.removeAll() + loopPlaybackRanges.removeAll() + cancelPendingPlaybackStart() if let observer = playerTimeObserver, let observedPlayer { observedPlayer.removeTimeObserver(observer) } playerTimeObserver = nil observedPlayer = nil cancellables.removeAll() + sessionObservers.removeAll() + shuffleBag.removeAll() + isShuffleBagPrepared = false + playedStack.removeAll() preloadTasks.values.forEach { $0.cancel() } preloadTasks.removeAll() assetCache.removeAll() player?.pause() + clearLoopQueue() player = nil + monitoredItem = nil currentTime = 0 duration = defaultDuration isPlaybackPlaying = false @@ -195,6 +262,8 @@ final class VideoPlayerViewModel: ObservableObject { isPlaybackPlaying = true refreshNowPlaying() } else { + // 準備待ちの直後に Space を2回叩かれた場合でも、止めたまま保つ。 + cancelPendingPlaybackStart() isRestartingLoop = false player.pause() isPlaybackPlaying = false @@ -210,6 +279,9 @@ final class VideoPlayerViewModel: ObservableObject { } func pause() { + // 準備待ちの最中は rate が 0 なので guard に弾かれる。その前に待ちを畳まないと、 + // リモート操作やメディアキーで止めたのに暖め終わった瞬間に走り出す。 + cancelPendingPlaybackStart() guard let player, player.rate != 0 else { return } isRestartingLoop = false player.pause() @@ -231,20 +303,109 @@ final class VideoPlayerViewModel: ObservableObject { seek(toSeconds: currentTime) } - private func changeVideo(to newVideo: VideoItem) { - guard let newItem = playerItem(for: newVideo) else { return } + /// 再生する動画を差し替える。 + /// `recordsPlayedStack` は「前へ」で戻ってきた時だけ false にする + /// (戻った先をもう一度履歴に積むと、← を押し続けても同じ2本を往復してしまう)。 + /// 差し替えられたら true。読めないファイル(外付けを抜いた、名前を変えた等)では false を返す。 + /// 袋や履歴を先に動かしてから失敗すると辻褄が合わなくなるので、呼び出し側が戻せるようにしてある。 + @discardableResult + private func changeVideo(to newVideo: VideoItem, recordsPlayedStack: Bool = true) -> Bool { + guard let newItem = playerItem(for: newVideo) else { return false } + cancelLoopBlackFrameAnalysis() isRestartingLoop = false // 切り替える前に、いま観ていた動画の位置を確定させる。 commitProgress() + if recordsPlayedStack, newVideo.id != currentVideo.id { + playedStack.append(currentVideo.id) + if playedStack.count > maxPlayedStackCount { playedStack.removeFirst() } + } + // 実際に流したものは袋から必ず抜く。手動で飛んだ動画が袋に残っていると、 + // そのあとの自動再生がもう一度同じものを選んでしまう。 + shuffleBag.removeAll { $0 == newVideo.id } self.currentVideo = newVideo self.currentTime = 0 self.duration = defaultDuration self.isSliderEditing = false + clearLoopQueue() self.player?.replaceCurrentItem(with: newItem) - if let player { startWatching(newVideo, on: player) } - self.player?.play() + if let player { + // 再開位置のシークを先に出してから準備待ちへ入る。順序が逆だと + // 暖めている最中にシークが割り込み、preroll が毎回無駄になる。 + startWatching(newVideo, on: player) + startPlaybackWhenReady(on: player, item: newItem) + } preloadNearbyAssets(around: newVideo) generateChapterPoints() + return true + } + + /// 差し替えた item が再生可能になり、デコードが暖まってから再生を始める。 + /// + /// `replaceCurrentItem` の直後に `play()` すると、先頭フレームが揃う前に走り出すので + /// 自動再生で次へ送った瞬間に画が引っかかる(`preferredForwardBufferDuration` が 1 秒しかなく、 + /// `preloadNearbyAssets` が先読みしているのも `.isPlayable` と `.duration` だけで、 + /// デコーダのバッファは冷たいまま)。同時再生の `SynchronizedPlayerGroup` が使っている + /// 「再生可能になるまで待つ → preroll → 開始」という順序をここでも踏む。 + private func startPlaybackWhenReady(on player: AVPlayer, item: AVPlayerItem) { + // 次へ次へと連打されたときは、最後の1本だけが走り出せばよい。追い越された準備が + // 後から完了しても、世代番号が合わないので再生を始めない。 + pendingStartTask?.cancel() + playbackStartGeneration &+= 1 + let generation = playbackStartGeneration + let deadline = Date().addingTimeInterval(playbackStartReadyTimeoutSeconds) + let pollNanoseconds = playbackStartPollNanoseconds + // 走らせたまま準備すると、暖め終わる前に AVPlayer が自分で新しい item を流し始めて + // preroll が無駄になる(rate は item を差し替えても引き継がれる)。 + player.pause() + + pendingStartTask = Task { @MainActor [weak self, weak player] in + var canWarmUp = false + while Date() < deadline { + guard let self, self.playbackStartGeneration == generation, + let player, player.currentItem === item else { return } + // 再開位置へのシークが走っている間に preroll すると必ず割り込まれて false が返る。 + // `isRestoringPosition` はそのシークが片付いたかどうかの目印なので、これが開くまで待つ。 + if item.status == .readyToPlay, !self.isRestoringPosition { + canWarmUp = true + break + } + // 読めないファイルをいくら待っても readyToPlay にはならない。暖めずに先へ進む。 + if item.status == .failed { break } + try? await Task.sleep(nanoseconds: pollNanoseconds) + if Task.isCancelled { return } + } + + guard let self, !Task.isCancelled, + self.playbackStartGeneration == generation, + let player, self.player === player, + player.currentItem === item else { return } + + // 速度は待ち始めた時点ではなく**ここで**読む。待っている間は player.rate が 0 なので + // applyRate() が生の rate を書き換えられず、開始時に古い値を入れると + // 画面の「1.25×」表示と実際の速度が食い違ったまま残る。 + let playbackRate = Float(self.settings.rate) + + if canWarmUp { + // preroll はシークに割り込まれると false を返す。ここは普段からシークと重なる + // 場所なので、結果は「暖まるのを待つ」ためだけに使い、成否で分岐しない。 + // 失敗を理由に止めてしまうと「次へ送ったのに何も起きない」になる。 + _ = await player.preroll(atRate: playbackRate) + guard !Task.isCancelled, + self.playbackStartGeneration == generation, + self.player === player, + player.currentItem === item else { return } + } + player.playImmediately(atRate: playbackRate) + self.isPlaybackPlaying = true + self.refreshNowPlaying() + } + } + + /// 準備待ちの取り消し。待っている間に止めたのに、暖め終わってから走り出すのを防ぐ。 + private func cancelPendingPlaybackStart() { + playbackStartGeneration &+= 1 + pendingStartTask?.cancel() + pendingStartTask = nil } // MARK: - 字幕・音声トラック @@ -311,6 +472,7 @@ final class VideoPlayerViewModel: ObservableObject { selectedSubtitleIndex = legible .flatMap { group in selection.selectedMediaOption(in: group).flatMap(group.options.firstIndex(of:)) } ?? MediaTrackChoice.offIndex + updateLoopQueue() } private static func trackName(_ option: AVMediaSelectionOption, fallbackIndex: Int) -> String { @@ -323,6 +485,7 @@ final class VideoPlayerViewModel: ObservableObject { group.options.indices.contains(index) else { return } item.select(group.options[index], in: group) selectedAudioIndex = index + updateLoopQueue() } func selectSubtitleTrack(index: Int) { @@ -336,6 +499,7 @@ final class VideoPlayerViewModel: ObservableObject { return } selectedSubtitleIndex = index + updateLoopQueue() } // MARK: - コントロールセンター表示とメディアキー @@ -374,6 +538,12 @@ final class VideoPlayerViewModel: ObservableObject { /// 「自動再生」が次へ進むかどうかの親スイッチで、「リストをリピート」は /// その上で末尾を先頭へ折り返すかを決める。1本リピートだけは進む話ではないので常に効く。 private func handlePlaybackEnded() { + // 次の周回が予約済みなら,シークを挟まずキューの自動切り替えに任せる. + if queuedLoopVideoID == currentVideo.id, + let queuePlayer = player as? AVQueuePlayer, + queuePlayer.items().count > 1 { + return + } // 最後まで観たので視聴位置は捨てる(次に開いたら頭から)。 watchState.markFinished(videoID: currentVideo.id) watchState.publishPendingChanges() @@ -399,12 +569,13 @@ final class VideoPlayerViewModel: ObservableObject { private func restartCurrentVideoSmoothly() { guard let player, let currentItem = player.currentItem else { return } let playbackRate = Float(settings.rate) - currentTime = 0 + let startTime = activeLoopPlaybackRange?.start ?? .zero + currentTime = startTime.seconds isRestartingLoop = true refreshNowPlaying() player.seek( - to: .zero, + to: startTime, toleranceBefore: .zero, toleranceAfter: .zero ) { [weak self, weak player] finished in @@ -424,12 +595,14 @@ final class VideoPlayerViewModel: ObservableObject { } /// 自動再生で次に流す動画。無ければ nil(=その場で止まる)。 + /// シャッフル中は袋から1本取り出すので、**呼ぶと袋が減る**。 + /// 減らさずに「次があるか」だけ知りたいときは `hasNextVideo` を使う。 private func nextVideoForAutoPlay() -> VideoItem? { guard allVideos.count > 1 else { return settings.repeatMode == .all ? currentVideo : nil } if settings.isShuffleEnabled { - return allVideos.filter { $0.id != currentVideo.id }.randomElement() + return takeNextShuffledVideo() } guard let index = allVideos.firstIndex(of: currentVideo) else { return allVideos.first } let nextIndex = index + 1 @@ -437,6 +610,145 @@ final class VideoPlayerViewModel: ObservableObject { return settings.repeatMode == .all ? allVideos.first : nil } + /// 次に流せる動画があるか。ボタンの活性判定はビューの描画中に何度も読まれるので、 + /// 袋を減らさずに答える必要がある(`nextVideoForAutoPlay()` は取り出してしまう)。 + /// 判断の中身は `nextVideoForAutoPlay()` と必ず揃えること。ここがズレると + /// 「ボタンは灰色なのに自動再生は次へ進む」が復活する。 + private var hasNextVideo: Bool { + guard allVideos.count > 1 else { return settings.repeatMode == .all } + if settings.isShuffleEnabled { + // 袋を作る前=まだ一巡していないので必ず次がある。 + // 使い切った後に続くのは、リストをリピートする時だけ。 + return !isShuffleBagPrepared || !shuffleBag.isEmpty || settings.repeatMode == .all + } + guard let index = allVideos.firstIndex(of: currentVideo) else { return true } + return allVideos.indices.contains(index + 1) || settings.repeatMode == .all + } + + /// 袋から次の1本を取り出す。袋が空になったのは「リストを一巡した」ということなので、 + /// 折り返すのは `リストをリピート` の時だけ。リピートなしのシャッフルは + /// 全部流し終えたら止まるのが正しい(以前はここで無条件に抽選し続けていた)。 + private func takeNextShuffledVideo() -> VideoItem? { + if !isShuffleBagPrepared { + refillShuffleBag() + } else if shuffleBag.isEmpty { + guard settings.repeatMode == .all else { return nil } + refillShuffleBag() + } + + let itemByID = Dictionary( + allVideos.lazy.map { ($0.id, $0) }, + uniquingKeysWith: { current, _ in current } + ) + // 袋を作った後にリストから消えた動画は読み飛ばす。 + while let id = shuffleBag.popLast() { + if let item = itemByID[id], item.id != currentVideo.id { return item } + } + return nil + } + + /// 袋を詰め直す。いま流している動画は入れない(次の1本として選ばれてしまう)。 + private func refillShuffleBag() { + let currentID = currentVideo.id + shuffleBag = allVideos.lazy.map(\.id).filter { $0 != currentID }.shuffled() + isShuffleBagPrepared = true + } + + /// プレイヤーを開いている間ずっと見ておくもの。 + private func observeSessionState() { + sessionObservers.removeAll() + + settings.$repeatMode.combineLatest(settings.$autoPlayNext) + .sink { [weak self] _ in + Task { @MainActor [weak self] in + self?.updateLoopQueue() + self?.skipBlackLoopEdgesIfNeeded() + } + } + .store(in: &sessionObservers) + + // シャッフルを入れ直したら袋を作り直す。使いかけの袋を持ち越すと、 + // 入れ直した直後に「もう全部観た」と誤解して自動再生が止まる。 + // `@Published` の購読は登録した時点で現在値が1回流れるので、 + // 再生開始時にシャッフルが入っていればここで袋が用意される。 + settings.$isShuffleEnabled + .removeDuplicates() + .sink { [weak self] isEnabled in + Task { @MainActor [weak self] in + guard let self else { return } + self.shuffleBag.removeAll() + self.isShuffleBagPrepared = false + if isEnabled { self.refillShuffleBag() } + } + } + .store(in: &sessionObservers) + + // iPhone やブラウザでお気に入りを付け外しすると、`/sync` の通知を受けて + // ライブラリ側が書き換わる。その時に再生画面の表示も追従させる。 + watchState.$favorites + .sink { [weak self] _ in + Task { @MainActor [weak self] in self?.refreshFavoriteState() } + } + .store(in: &sessionObservers) + } + + // MARK: - 音量・ミュート + + /// 音量を1段変える。全画面再生中はメニューバーもウィンドウのツールバーも出ないので、 + /// キーで触れないと右上へカーソルを運ぶしかない。 + func adjustVolume(by delta: Float) { + let updated = min(max(volume + delta, 0), 1) + // 音を上げたのに無音のままだと操作が効いていないように見えるので、ミュートは解く。 + if isMuted, delta > 0 { isMuted = false } + guard abs(updated - volume) > 0.0001 else { return } + volume = updated + } + + func toggleMute() { isMuted.toggle() } + + // MARK: - 映像の収め方 + + func toggleFillsScreen() { fillsScreen.toggle() } + + // MARK: - コマ送り + + /// 1コマ進める/戻す。コマ送りは止めて確かめるための操作なので、まず止める。 + /// + /// `isPlaybackPlaying` で分岐させないこと。切り替え直後の準備待ち(`startPlaybackWhenReady`)は + /// まだ rate が 0 なのでここが false になり、分岐させると待ちが畳まれないまま + /// コマを送った直後に再生が走り出す。`pause()` は待ちを畳んでから + /// 実際に止まっているかを見るので、そのまま呼んで構わない。 + func stepFrame(by count: Int) { + guard count != 0, let item = player?.currentItem else { return } + pause() + guard count > 0 ? item.canStepForward : item.canStepBackward else { return } + item.step(byCount: count) + // step 直後は currentTime がまだ動いていないことがあるので、次のループで表示を合わせる。 + Task { @MainActor [weak self] in + guard let self, let item = self.player?.currentItem else { return } + let seconds = item.currentTime().seconds + guard seconds.isFinite else { return } + self.currentTime = min(max(seconds, 0), self.duration) + self.recordCurrentProgress(force: true) + self.refreshNowPlaying() + } + } + + // MARK: - お気に入り + + /// 観ている最中に付け外しする。一覧側と同じ `LibraryViewModel.toggleFavorite` を通すので、 + /// iPhone・ブラウザへの橋渡し(`AppViewModel.bridgeFavorites()`)もそのまま働く。 + func toggleCurrentVideoFavorite() { + dataManager.toggleFavorite(videoIDs: [currentVideo.id]) + refreshFavoriteState() + } + + /// `dataManager.videos` を正として読み直す。 + private func refreshFavoriteState() { + let id = currentVideo.id + isCurrentVideoFavorite = dataManager.videos.first(where: { $0.id == id })?.isFavorite ?? false + } + // MARK: - 再生速度 /// 速度を変える。一時停止中は次に再生した時から効かせる(勝手に再生を始めない)。 @@ -459,9 +771,23 @@ final class VideoPlayerViewModel: ObservableObject { private func startWatching(_ video: VideoItem, on player: AVPlayer) { watchState.recordHistory(videoID: video.id) reloadMediaSelections(for: video) + refreshFavoriteState() refreshNowPlaying() - guard let resume = watchState.resumeSeconds(for: video.id, duration: video.duration) else { + let savedResume = pendingInitialStartTime ?? watchState.resumeSeconds(for: video.id, duration: video.duration) + pendingInitialStartTime = nil + let resume: Double? + if let range = activeLoopPlaybackRange { + let requested = savedResume ?? 0 + resume = requested >= range.end.seconds ? range.start.seconds : max(requested, range.start.seconds) + } else { + resume = savedResume + } + guard let resume, resume > 0 else { + // 続きのない動画へ移ったら、前の動画のシークを待っていた蓋をここで外す。 + // 前の seek 完了は動画 ID で弾かれるため、ここで外さないと開かずじまいになり、 + // 時刻通知が素通しされて再生位置がまったく進まなくなる。 + isRestoringPosition = false resumeNotice = nil return } @@ -481,7 +807,7 @@ final class VideoPlayerViewModel: ObservableObject { self.isRestoringPosition = false } } - showResumeNotice(seconds: resume) + if savedResume != nil { showResumeNotice(seconds: resume) } } /// 勝手に途中から始まったように見えないよう、再開位置を数秒だけ知らせる。 @@ -524,15 +850,19 @@ final class VideoPlayerViewModel: ObservableObject { return String(format: "%d:%02d", total / 60, total % 60) } + /// シャッフル中は「実際に再生した順」を遡るので、リストの並びは関係ない。 var canPlayPreviousVideo: Bool { + if settings.isShuffleEnabled { return !playedStack.isEmpty } guard let currentIndex = allVideos.firstIndex(of: currentVideo) else { return false } - return allVideos.indices.contains(currentIndex - 1) + if allVideos.indices.contains(currentIndex - 1) { return true } + // 「次へ」が末尾で先頭へ折り返すなら、「前へ」も先頭で末尾へ回れないと辻褄が合わない。 + return settings.repeatMode == .all && allVideos.count > 1 } - var canPlayNextVideo: Bool { - guard let currentIndex = allVideos.firstIndex(of: currentVideo) else { return false } - return allVideos.indices.contains(currentIndex + 1) - } + /// 自動再生が次に進めるかどうかと同じ判断を使う。 + /// ここだけ配列の index で見ていたころは、リストの末尾で + /// 「ボタンは押せないのに数秒後に勝手に先頭へ戻る」というズレが出ていた。 + var canPlayNextVideo: Bool { hasNextVideo } private func configurePlaybackMonitoring(for player: AVPlayer) { if let observer = playerTimeObserver, let observedPlayer { @@ -540,6 +870,7 @@ final class VideoPlayerViewModel: ObservableObject { } playerTimeObserver = nil observedPlayer = player + monitoredItem = player.currentItem cancellables.removeAll() currentTime = 0 duration = defaultDuration @@ -551,6 +882,32 @@ final class VideoPlayerViewModel: ObservableObject { .sink { [weak self] seconds in Task { @MainActor [weak self] in self?.duration = seconds + self?.updateLoopQueue() + } + } + .store(in: &cancellables) + + player.publisher(for: \.currentItem) + .compactMap { $0 } + .sink { [weak self, weak player] item in + Task { @MainActor [weak self, weak player] in + guard let self, let player, self.player === player, + player.currentItem === item else { return } + let didAdvanceLoop = self.queuedLoopVideoID == self.currentVideo.id + && self.monitoredItem != nil && self.monitoredItem !== item + && self.monitoredItem?.asset === item.asset + self.monitoredItem = item + if didAdvanceLoop { + self.watchState.markFinished(videoID: self.currentVideo.id) + self.watchState.publishPendingChanges() + self.isRestartingLoop = false + if !self.isSliderEditing, !self.isRestoringPosition { + let seconds = item.currentTime().seconds + self.currentTime = seconds.isFinite ? max(0, seconds) : 0 + } + self.refreshNowPlaying() + } + self.updateLoopQueue() } } .store(in: &cancellables) @@ -586,8 +943,10 @@ final class VideoPlayerViewModel: ObservableObject { Task { @MainActor [weak self] in guard let self, !self.isSliderEditing, !self.isRestoringPosition, !self.isRestartingLoop, - time.seconds.isFinite else { return } - self.currentTime = min(max(time.seconds, 0), self.duration) + let seconds = self.player?.currentTime().seconds, + seconds.isFinite else { return } + // 周回前に届いた通知でも,現在の項目の時刻を読み直して表示する. + self.currentTime = min(max(seconds, 0), self.duration) // 保管庫側で間引くので、ここは毎回呼んでよい。 self.recordCurrentProgress(force: false) } @@ -601,7 +960,10 @@ final class VideoPlayerViewModel: ObservableObject { isRestartingLoop = false let effectiveDuration = player.currentItem?.duration.seconds ?? duration let upperBound = effectiveDuration.isFinite && effectiveDuration > 0 ? effectiveDuration : duration - let clampedSeconds = min(max(seconds, 0), max(upperBound, 0)) + let range = activeLoopPlaybackRange + let lowerBound = range?.start.seconds ?? 0 + let loopUpperBound = range?.end.seconds ?? upperBound + let clampedSeconds = min(max(seconds, lowerBound), max(loopUpperBound, lowerBound)) let targetTime = CMTime(seconds: clampedSeconds, preferredTimescale: 600) currentTime = clampedSeconds player.seek(to: targetTime, toleranceBefore: .zero, toleranceAfter: .zero) @@ -616,6 +978,173 @@ final class VideoPlayerViewModel: ObservableObject { return item } + /// 現在の周回を再生している間に,次の周回の読み込みとデコードを準備する. + private func updateLoopQueue() { + guard let queuePlayer = player as? AVQueuePlayer, + let currentItem = queuePlayer.currentItem else { return } + updateLoopBlackFrameAnalysis() + let shouldLoop = settings.repeatMode == .one + || (settings.repeatMode == .all && settings.autoPlayNext && allVideos.count == 1) + guard shouldLoop, currentItem.status != .failed else { + clearLoopQueue(restoresFullRange: false) + configureLoopPlaybackRange(for: currentItem, preparesStart: false) + return + } + // 尺が確定する前や空の動画をキューに積むと,空の項目を繰り返してしまう. + let seconds = currentItem.duration.seconds + guard seconds.isFinite, seconds > 0 else { return } + + queuedLoopVideoID = currentVideo.id + queuePlayer.actionAtItemEnd = .advance + configureLoopPlaybackRange(for: currentItem, preparesStart: false) + for item in queuePlayer.items() where item !== currentItem { + copyMediaSelections(from: currentItem, to: item) + configureLoopPlaybackRange(for: item, preparesStart: true) + } + while queuePlayer.items().count < loopQueueItemCount { + let nextItem = AVPlayerItem(asset: currentItem.asset) + nextItem.preferredForwardBufferDuration = loopForwardBufferDuration + copyMediaSelections(from: currentItem, to: nextItem) + guard queuePlayer.canInsert(nextItem, after: queuePlayer.items().last) else { + // 追加できない場合は,既存の終端処理で先頭へ戻れる状態を保つ. + if queuePlayer.items().count == 1 { clearLoopQueue() } + return + } + queuePlayer.insert(nextItem, after: queuePlayer.items().last) + configureLoopPlaybackRange(for: nextItem, preparesStart: true) + } + } + + /// 再生中の項目と位置を維持し,先読みしていた周回だけを取り除く. + private func clearLoopQueue(restoresFullRange: Bool = true) { + queuedLoopVideoID = nil + guard let queuePlayer = player as? AVQueuePlayer else { return } + queuePlayer.actionAtItemEnd = .none + if restoresFullRange, let item = queuePlayer.currentItem, item.forwardPlaybackEndTime.isValid { + item.forwardPlaybackEndTime = .invalid + } + for item in queuePlayer.items() where item !== queuePlayer.currentItem { + queuePlayer.remove(item) + } + } + + /// 音声・字幕の選択を次の周回へ引き継ぐ. + private func copyMediaSelections(from source: AVPlayerItem, to destination: AVPlayerItem) { + for group in [audibleGroup, legibleGroup].compactMap({ $0 }) { + let option = source.currentMediaSelection.selectedMediaOption(in: group) + if destination.currentMediaSelection.selectedMediaOption(in: group) != option { + destination.select(option, in: group) + } + } + } + + private var activeLoopPlaybackRange: CMTimeRange? { + settings.repeatMode == .off ? nil : loopPlaybackRanges[currentVideo.id] + } + + /// ループ開始時だけ解析し,同じ再生セッション内では結果を再利用します. + private func updateLoopBlackFrameAnalysis() { + guard settings.repeatMode != .off else { + cancelLoopBlackFrameAnalysis() + return + } + let videoID = currentVideo.id + guard !analyzedLoopVideoIDs.contains(videoID), loopAnalysisVideoID != videoID, + let asset = player?.currentItem?.asset else { return } + cancelLoopBlackFrameAnalysis() + loopAnalysisVideoID = videoID + isAnalyzingLoopEdges = true + loopAnalysisNotice = "ループ用に冒頭・末尾の黒画面を解析中…" + let generation = loopAnalysisGeneration + loopAnalysisTask = Task.detached(priority: .utility) { [weak self] in + do { + let range = try await LoopBlackFrameAnalyzer().analyze(asset: asset) + try Task.checkCancellation() + await self?.finishLoopBlackFrameAnalysis( + range: range, videoID: videoID, generation: generation, errorMessage: nil + ) + } catch is CancellationError { + return + } catch { + guard !Task.isCancelled else { return } + await self?.finishLoopBlackFrameAnalysis( + range: nil, videoID: videoID, generation: generation, + errorMessage: error.localizedDescription + ) + } + } + } + + private func cancelLoopBlackFrameAnalysis() { + loopAnalysisGeneration &+= 1 + loopAnalysisTask?.cancel() + loopAnalysisTask = nil + loopAnalysisVideoID = nil + isAnalyzingLoopEdges = false + loopAnalysisNotice = nil + } + + private func finishLoopBlackFrameAnalysis( + range: CMTimeRange?, videoID: UUID, generation: Int, errorMessage: String? + ) { + guard loopAnalysisGeneration == generation, currentVideo.id == videoID, + settings.repeatMode != .off else { return } + loopAnalysisTask = nil + loopAnalysisVideoID = nil + isAnalyzingLoopEdges = false + analyzedLoopVideoIDs.insert(videoID) + loopPlaybackRanges[videoID] = range + if let errorMessage { + loopAnalysisNotice = "黒画面を省略せず再生します.\(errorMessage) ファイルの再生状態を確認してください." + } else if let range { + let originalDuration = player?.currentItem?.duration.seconds ?? duration + let trimmedTail = max(0, originalDuration - range.end.seconds) + loopAnalysisNotice = String( + format: "ループ中は冒頭%.2f秒・末尾%.2f秒の黒画面をスキップします.", + range.start.seconds, trimmedTail + ) + } else { + loopAnalysisNotice = "冒頭・末尾に省略できる黒画面はありません." + } + updateLoopQueue() + skipBlackLoopEdgesIfNeeded() + } + + private func skipBlackLoopEdgesIfNeeded() { + guard let range = activeLoopPlaybackRange, let player else { return } + let seconds = player.currentTime().seconds + if seconds.isFinite, seconds < range.start.seconds || seconds >= range.end.seconds { + seek(toSeconds: range.start.seconds) + } + } + + /// 次の周回はキューで待機中に頭出しし,切り替え時のシークを避けます. + private func configureLoopPlaybackRange(for item: AVPlayerItem, preparesStart: Bool) { + guard let range = activeLoopPlaybackRange else { + if item.forwardPlaybackEndTime.isValid { item.forwardPlaybackEndTime = .invalid } + return + } + let rangeChanged = CMTimeCompare(item.forwardPlaybackEndTime, range.end) != 0 + if rangeChanged { item.forwardPlaybackEndTime = range.end } + if preparesStart, rangeChanged, range.start.seconds > 0 { + let videoID = currentVideo.id + item.seek(to: range.start, toleranceBefore: .zero, toleranceAfter: .zero) { [weak self, weak item] finished in + guard !finished else { return } + Task { @MainActor [weak self, weak item] in + guard let self, let item, self.currentVideo.id == videoID, + self.activeLoopPlaybackRange == range, + let queue = self.player as? AVQueuePlayer, + queue.items().contains(where: { $0 === item }) else { return } + // 頭出しに失敗した項目を使い回さず,通常の範囲で周回を準備し直します. + self.loopPlaybackRanges[videoID] = nil + self.clearLoopQueue() + self.loopAnalysisNotice = "黒画面の頭出しに失敗したため,省略せずループします.動画を開き直して再試行してください." + self.updateLoopQueue() + } + } + } + } + private func cachedAsset(for video: VideoItem, url: URL) -> AVURLAsset { if let cached = assetCache[video.id] { return cached } let asset = AVURLAsset(url: url) @@ -657,16 +1186,51 @@ final class VideoPlayerViewModel: ObservableObject { } } + /// 「次へ」。自動再生と同じ選び方をする(シャッフル中は袋から、末尾では + /// リピート設定に従って折り返す)。ボタンの活性も同じ判断なので食い違わない。 func playNextVideo() { - guard let currentIndex = allVideos.firstIndex(of: currentVideo) else { return } - let nextIndex = currentIndex + 1 - if allVideos.indices.contains(nextIndex) { changeVideo(to: allVideos[nextIndex]) } + guard let next = nextVideoForAutoPlay() else { return } + // 1本しか無いリストで「リストをリピート」のときだけ、次=自分自身になる。 + // 自動再生の終端処理と同じく頭から流し直す。ここで黙って return すると + // 「ボタンは押せるのに何も起きない」になり、`hasNextVideo` との約束が破れる。 + guard next.id != currentVideo.id else { + restartCurrentVideoSmoothly() + return + } + changeVideo(to: next) } + /// 「前へ」。シャッフル中はリストの並びを遡っても意味がないので、 + /// 実際に再生した順を1つ戻る。 func playPreviousVideo() { + if settings.isShuffleEnabled { + // 履歴はまだ減らさない(`last` で覗くだけ)。先に減らしてから差し替えに失敗すると、 + // 何も起きていないのに1つ分の履歴が消え、次の ← が2本ぶん飛んでしまう。 + guard let previousID = playedStack.last, + let previous = allVideos.first(where: { $0.id == previousID }) else { return } + // いま観ていた1本は「まだ流していない」側へ戻す。戻さないと、← を押した時点で + // その動画が今回の一巡から抜け落ちる(袋にも履歴にも居なくなる)。 + // 次に取り出される位置へ入れるので、→ を押せばそのまま元へ戻れる。 + let leavingID = currentVideo.id + shuffleBag.removeAll { $0 == leavingID } + shuffleBag.append(leavingID) + guard changeVideo(to: previous, recordsPlayedStack: false) else { + // 読めないファイルだった。袋を触る前に戻す + // (戻さないと「いま流している動画が袋に入っている」状態になり、 + // → が押せるのに何も起きなくなる)。 + shuffleBag.removeAll { $0 == leavingID } + return + } + playedStack.removeLast() + return + } guard let currentIndex = allVideos.firstIndex(of: currentVideo) else { return } let previousIndex = currentIndex - 1 - if allVideos.indices.contains(previousIndex) { changeVideo(to: allVideos[previousIndex]) } + if allVideos.indices.contains(previousIndex) { + changeVideo(to: allVideos[previousIndex]) + } else if settings.repeatMode == .all, let last = allVideos.last, last.id != currentVideo.id { + changeVideo(to: last) + } } func playVideo(_ video: VideoItem) { @@ -681,3 +1245,217 @@ final class VideoPlayerViewModel: ObservableObject { allVideos.filter { $0.id != currentVideo.id } } } + +// MARK: - 巡回・シーン再生(通常の履歴や視聴位置は更新しません) + +@MainActor +final class PlaybackTourViewModel: ObservableObject { + let session: PlaybackTourSession + let player = AVPlayer() + @Published var volume: Double { + didSet { player.volume = Float(volume) } + } + @Published var isMuted: Bool { + didSet { player.isMuted = isMuted } + } + @Published private(set) var channelEntry: PlaybackTourEntry? + @Published private(set) var index = 0 + @Published private(set) var currentTime = 0.0 + @Published private(set) var isPlaying = false + @Published private(set) var isLoading = false + @Published private(set) var isFinished = false + @Published private(set) var errorMessage: String? + private let dataManager: LibraryViewModel + private var loadTask: Task? + private var observer: Any? + private var endObserver: AnyCancellable? + private var statusObserver: AnyCancellable? + private var playbackObserver: AnyCancellable? + private var generation = UUID() + private var rangeStart = 0.0 + private var rangeEnd = 0.0 + private let observerInterval = CMTime(seconds: 0.1, preferredTimescale: 600) + + init(session: PlaybackTourSession, dataManager: LibraryViewModel) { + self.session = session + self.dataManager = dataManager + self.volume = min(1, max(0, UserDefaults.standard.object(forKey: VideoPlayerViewModel.volumeDefaultsKey) as? Double ?? 1)) + self.isMuted = UserDefaults.standard.bool(forKey: VideoPlayerViewModel.mutedDefaultsKey) + player.volume = Float(volume) + player.isMuted = isMuted + } + + var currentEntry: PlaybackTourEntry? { + channelEntry ?? (session.entries.indices.contains(index) ? session.entries[index] : nil) + } + + var isChannelMode: Bool { session.kind == .channels } + + var channelName: String? { + session.channels.indices.contains(index) ? session.channels[index].name : nil + } + + var sessionRemaining: Double { + guard session.kind == .timed else { return remaining } + return remaining + session.entries.dropFirst(index + 1).reduce(0) { $0 + $1.end - $1.start } + } + + var progress: Double { + guard rangeEnd > rangeStart else { return 0 } + return min(1, max(0, (currentTime - rangeStart) / (rangeEnd - rangeStart))) + } + + var remaining: Double { max(0, rangeEnd - currentTime) } + + func start() { + guard observer == nil else { return } + observer = player.addPeriodicTimeObserver(forInterval: observerInterval, queue: .main) { [weak self] time in + Task { @MainActor [weak self] in + guard let self, !self.isLoading, time.seconds.isFinite else { return } + self.currentTime = time.seconds + } + } + playbackObserver = player.publisher(for: \.timeControlStatus) + .receive(on: DispatchQueue.main) + .sink { [weak self] status in self?.isPlaying = status != .paused } + loadCurrentEntry() + } + + func togglePlayback() { + guard !isLoading, !isFinished, errorMessage == nil else { return } + if isPlaying { player.pause() } else { player.play() } + } + + func next() { + if isChannelMode { + index = (index + 1) % session.entries.count + channelEntry = nil + loadCurrentEntry() + return + } + guard index + 1 < session.entries.count else { + finish() + return + } + index += 1 + loadCurrentEntry() + } + + func previous() { + if isChannelMode { + index = (index + session.entries.count - 1) % session.entries.count + channelEntry = nil + loadCurrentEntry() + return + } + guard index > 0 else { return } + index -= 1 + loadCurrentEntry() + } + + func restart() { + index = 0 + channelEntry = nil + loadCurrentEntry() + } + + func retry() { loadCurrentEntry() } + + func cleanup() { + generation = UUID() + loadTask?.cancel() + loadTask = nil + player.pause() + if let observer { player.removeTimeObserver(observer) } + observer = nil + endObserver = nil + statusObserver = nil + playbackObserver = nil + player.replaceCurrentItem(with: nil) + isPlaying = false + } + + private func advanceChannelProgram() { + guard session.channels.indices.contains(index) else { finish(); return } + let videos = session.channels[index].videos + let alternatives = videos.filter { $0.id != currentEntry?.video.id } + guard let video = (alternatives.isEmpty ? videos : alternatives).randomElement() else { finish(); return } + channelEntry = PlaybackTourEntry(id: UUID(), video: video, start: 0, end: video.duration) + loadCurrentEntry() + } + + private func finish() { + generation = UUID() + loadTask?.cancel() + player.pause() + isLoading = false + isFinished = true + errorMessage = nil + } + + private func loadCurrentEntry() { + loadTask?.cancel() + player.pause() + endObserver = nil + statusObserver = nil + player.replaceCurrentItem(with: nil) + errorMessage = nil + isFinished = false + isLoading = true + let token = UUID() + generation = token + guard let entry = currentEntry else { finish(); return } + currentTime = entry.start + loadTask = Task { [weak self] in + guard let self else { return } + do { + guard let url = self.dataManager.fileURL(for: entry.video), + FileManager.default.fileExists(atPath: url.path) else { throw PlaybackTourError.missingFile } + let asset = AVURLAsset(url: url) + guard try await asset.load(.isPlayable) else { throw PlaybackTourError.unplayable } + let duration = try await asset.load(.duration).seconds + try Task.checkCancellation() + guard self.generation == token else { return } + guard duration.isFinite, duration > 0 else { throw PlaybackTourError.invalidRange } + let start = min(max(0, entry.start), duration) + let end = min(entry.end, duration) + guard end > start else { throw PlaybackTourError.invalidRange } + self.rangeStart = start + self.rangeEnd = end + let item = AVPlayerItem(asset: asset) + // メディア時刻で終端を指定するため,一時停止や読み込み時間で区間が短くなりません. + item.forwardPlaybackEndTime = CMTime(seconds: end, preferredTimescale: 600) + self.player.replaceCurrentItem(with: item) + self.endObserver = NotificationCenter.default.publisher(for: .AVPlayerItemDidPlayToEndTime, object: item) + .receive(on: DispatchQueue.main) + .sink { [weak self] _ in + guard let self, self.generation == token else { return } + if self.isChannelMode { self.advanceChannelProgram() } + else { self.next() } + } + self.statusObserver = item.publisher(for: \.status) + .receive(on: DispatchQueue.main) + .sink { [weak self, weak item] status in + guard let self, self.generation == token, status == .failed else { return } + self.player.pause() + self.isLoading = false + self.errorMessage = item?.error?.localizedDescription ?? PlaybackTourError.unplayable.localizedDescription + } + let succeeded = await self.player.seek(to: CMTime(seconds: start, preferredTimescale: 600), + toleranceBefore: .zero, toleranceAfter: .zero) + try Task.checkCancellation() + guard self.generation == token else { return } + guard succeeded else { throw PlaybackTourError.unplayable } + self.currentTime = start + self.isLoading = false + self.player.play() + } catch is CancellationError { + // 次の区間へ移った処理や,画面を閉じた処理からのキャンセルです. + } catch { + guard self.generation == token else { return } + self.isLoading = false + self.errorMessage = error.localizedDescription + } + } + } +} diff --git a/AllServerForMac/Features/Playback/ViewModels/WatchStateStore.swift b/AllServerForMac/Features/Playback/ViewModels/WatchStateStore.swift index 54ced42..019e2f4 100644 --- a/AllServerForMac/Features/Playback/ViewModels/WatchStateStore.swift +++ b/AllServerForMac/Features/Playback/ViewModels/WatchStateStore.swift @@ -74,6 +74,18 @@ final class WatchStateStore: ObservableObject { return seconds } + /// 「続きを見る」に並べてよいか(=途中でやめた動画か)。 + /// + /// 判定は `resumeSeconds` と同じだが、見るのは表示用の `progress` の方。 + /// あちらは再生中に毎秒動く `liveProgress` を見るので、一覧の描画に使うと + /// SwiftUI の更新(`@Published` の発火)と足並みが揃わない。 + func resumableSeconds(for videoID: UUID, duration: TimeInterval) -> Double? { + guard let seconds = progress[videoID], seconds.isFinite else { return nil } + guard seconds >= minimumResumeSeconds else { return nil } + guard duration <= 0 || seconds < duration - finishedTailSeconds else { return nil } + return seconds + } + /// 視聴済みバーの長さ(0...1)。観ていない動画は 0。 func watchedFraction(for videoID: UUID, duration: TimeInterval) -> Double { guard duration > 0, let seconds = progress[videoID], seconds > 0 else { return 0 } diff --git a/AllServerForMac/Features/Playback/Views/MediaPreviewView.swift b/AllServerForMac/Features/Playback/Views/MediaPreviewView.swift index d7381a7..06b9226 100644 --- a/AllServerForMac/Features/Playback/Views/MediaPreviewView.swift +++ b/AllServerForMac/Features/Playback/Views/MediaPreviewView.swift @@ -67,7 +67,7 @@ struct MediaPreviewView: View { if item.mediaType == .video, item.duration > 0 { Text(formatDuration(item.duration)) - .font(.system(size: 11)) + .font(.appMicro) .monospacedDigit() .foregroundStyle(.secondary) } @@ -79,8 +79,8 @@ struct MediaPreviewView: View { isMangaMode.toggle() }) { Text(isMangaMode ? "漫画モード" : "通常モード") - .font(.system(size: 11)) - .foregroundColor(isMangaMode ? .accentColor : .primary) + .font(.appMicro) + .foregroundColor(.primary) } .buttonStyle(.plain) .padding(.horizontal, 8) @@ -89,7 +89,7 @@ struct MediaPreviewView: View { .cornerRadius(4) Text("\(currentIndex! + 1) / \(items.count)") - .font(.system(size: 11)) + .font(.appMicro) .monospacedDigit() .foregroundStyle(.secondary) } @@ -99,7 +99,7 @@ struct MediaPreviewView: View { openFullScreenPhoto() } label: { Label("全画面表示", systemImage: "arrow.up.left.and.arrow.down.right") - .font(.system(size: 11)) + .font(.appMicro) } .buttonStyle(.borderless) } @@ -110,7 +110,7 @@ struct MediaPreviewView: View { } } label: { Label("外部プレイヤーで開く", systemImage: "arrow.up.forward.app") - .font(.system(size: 11)) + .font(.appMicro) } .buttonStyle(.borderless) diff --git a/AllServerForMac/Features/Playback/Views/MultiVideoPlayerView.swift b/AllServerForMac/Features/Playback/Views/MultiVideoPlayerView.swift index 09df383..b149b07 100644 --- a/AllServerForMac/Features/Playback/Views/MultiVideoPlayerView.swift +++ b/AllServerForMac/Features/Playback/Views/MultiVideoPlayerView.swift @@ -180,17 +180,17 @@ struct MultiVideoPlayerView: View { VStack(spacing: 10) { HStack(spacing: 12) { Label("音声ミキサー", systemImage: "slider.horizontal.3") - .font(.headline) + .font(.appHeadline) Spacer() Button("全部鳴らす") { viewModel.unmuteAllTiles() } .help("すべてのミュートを解除") Button("定位を配置どおりに") { viewModel.resetPansToLayout() } - .help("左右の振り分けを、いまのタイル配置から決まる既定値へ戻す") + .help("左右の振り分けを,いまのタイル配置から決まる既定値へ戻す") Button { withAnimation(.easeOut(duration: 0.18)) { isAudioConsoleVisible = false } } label: { Image(systemName: "xmark.circle.fill") - .font(.title3) + .font(.appTitle) .symbolRenderingMode(.hierarchical) } .buttonStyle(.plain) @@ -207,12 +207,8 @@ struct MultiVideoPlayerView: View { } .padding(16) .frame(maxWidth: 920) - .background(RoundedRectangle(cornerRadius: 14, style: .continuous).fill(.ultraThinMaterial)) - .overlay( - RoundedRectangle(cornerRadius: 14, style: .continuous) - .strokeBorder(.white.opacity(0.15), lineWidth: 1) - ) - .shadow(color: .black.opacity(0.45), radius: 20, y: 8) + .playerPanel(cornerRadius: 14) + .environment(\.colorScheme, .dark) .padding(24) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom) } @@ -228,7 +224,7 @@ struct MultiVideoPlayerView: View { .frame(width: 20, height: 20) .background(Circle().fill(.white.opacity(0.18))) Text(tile.title) - .font(.caption) + .font(.appCaption) .lineLimit(1) .truncationMode(.middle) Spacer(minLength: 0) @@ -245,7 +241,7 @@ struct MultiVideoPlayerView: View { Button { viewModel.soloTile(at: index) } label: { - Text("SOLO").font(.system(size: 9, weight: .bold)) + Text("SOLO").font(.appMicro.weight(.bold)) } .buttonStyle(.plain) .help("これだけ鳴らす(他を全部ミュート)") @@ -271,7 +267,7 @@ struct MultiVideoPlayerView: View { HStack(spacing: 6) { Text("L") - .font(.system(size: 10, weight: .bold)) + .font(.appMicro.weight(.bold)) .foregroundStyle(.secondary) Slider( value: Binding( @@ -286,7 +282,7 @@ struct MultiVideoPlayerView: View { .controlSize(.mini) .disabled(tile.isMuted) Text("R") - .font(.system(size: 10, weight: .bold)) + .font(.appMicro.weight(.bold)) .foregroundStyle(.secondary) } } @@ -307,33 +303,31 @@ struct MultiVideoPlayerView: View { private var controls: some View { HStack { - Button { + // 通常再生と同じ、白い丸の再生/一時停止ボタン。 + PlayerPlayButton( + isPlaying: viewModel.isPlaying, + help: viewModel.isPlaying ? "一時停止(Space)" : "再生(Space)" + ) { togglePlayPause() - } label: { - Image(systemName: viewModel.isPlaying ? "pause.fill" : "play.fill") - .font(.system(size: 16)) - .frame(width: 20) } - .buttonStyle(.plain) - .help(viewModel.isPlaying ? "一時停止(Space)" : "再生(Space)") - .accessibilityLabel(viewModel.isPlaying ? "一時停止" : "再生") Text(formatTime(viewModel.commonCurrentTime)) - .font(.caption.monospacedDigit()) + .font(.system(size: 12, weight: .medium).monospacedDigit()) + .foregroundStyle(PlayerChrome.iconMuted) + .frame(minWidth: 44, alignment: .trailing) Slider(value: $viewModel.commonCurrentTime, in: 0...max(viewModel.commonDuration, 0.1)) { isEditing in viewModel.commonSliderEditingChanged(isEditing: isEditing) } + .tint(.white.opacity(0.92)) Text(formatTime(viewModel.commonDuration)) - .font(.caption.monospacedDigit()) + .font(.system(size: 12, weight: .medium).monospacedDigit()) + .foregroundStyle(PlayerChrome.iconMuted) + .frame(minWidth: 44, alignment: .leading) } .padding(.horizontal, 14) .padding(.vertical, 10) - .background(RoundedRectangle(cornerRadius: 14, style: .continuous).fill(.ultraThinMaterial)) - .overlay( - RoundedRectangle(cornerRadius: 14, style: .continuous) - .strokeBorder(.white.opacity(0.15), lineWidth: 1) - ) - .shadow(color: .black.opacity(0.45), radius: 18, y: 6) + .playerPanel(cornerRadius: 14) + .environment(\.colorScheme, .dark) .padding(16) .frame(maxWidth: 1200) } diff --git a/AllServerForMac/Features/Playback/Views/PhotoViewerView.swift b/AllServerForMac/Features/Playback/Views/PhotoViewerView.swift index f8be033..6d5fddd 100644 --- a/AllServerForMac/Features/Playback/Views/PhotoViewerView.swift +++ b/AllServerForMac/Features/Playback/Views/PhotoViewerView.swift @@ -242,7 +242,7 @@ struct PhotoViewerView: View { if visiblePhotos.count > 1, let idx = currentIndex { Text("\(idx + 1) / \(visiblePhotos.count)") - .font(.system(size: 12)) + .font(.appCaption) .monospacedDigit() .foregroundStyle(.white.opacity(0.7)) } @@ -252,12 +252,13 @@ struct PhotoViewerView: View { if visiblePhotos.count > 1 { Button { isMangaMode.toggle() } label: { Text(isMangaMode ? "漫画モード" : "通常モード") - .font(.system(size: 12)) - .foregroundColor(isMangaMode ? .accentColor : .white) + .font(.appCaption) + .foregroundColor(.white) .padding(.horizontal, 8) .padding(.vertical, 4) - .background(Color.white.opacity(0.12)) - .cornerRadius(4) + // 入っているモードは面を一段明るくして示す(色は付けない)。 + .background(isMangaMode ? PlayerChrome.chip : PlayerChrome.hover) + .cornerRadius(5) } .buttonStyle(.plain) } @@ -405,7 +406,6 @@ struct PhotoViewerView: View { } } .frame(width: filmstripPreviewWidth, height: filmstripPreviewHeight) - .shadow(color: .black.opacity(0.22), radius: 10, x: 0, y: 4) } .frame(width: filmstripPreviewWidth, height: filmstripPreviewHeight) .task(id: targetItem?.id) { @@ -437,22 +437,22 @@ struct PhotoViewerView: View { .frame(width: filmstripThumbSize, height: filmstripThumbSize) .overlay( RoundedRectangle(cornerRadius: 8, style: .continuous) - .strokeBorder(isCurrent ? Color.accentColor : .white.opacity(0.15), lineWidth: isCurrent ? 2.5 : 1) + .strokeBorder(isCurrent ? Color.white.opacity(0.9) : .white.opacity(0.15), lineWidth: isCurrent ? 2 : 0.5) ) .overlay(alignment: .topTrailing) { if isCurrent { Text("現在") - .font(.system(size: 10, weight: .semibold)) + .font(.appMicro.weight(.semibold)) .foregroundStyle(.black) .padding(.horizontal, 5) .padding(.vertical, 2) - .background(Color.accentColor, in: Capsule()) + .background(Color.white.opacity(0.9), in: Capsule()) .padding(6) } } Text(photo.originalFilename) - .font(.system(size: 10)) + .font(.appMicro) .lineLimit(1) .truncationMode(.middle) .foregroundStyle(.white.opacity(0.82)) diff --git a/AllServerForMac/Features/Playback/Views/SlideshowPlayerView.swift b/AllServerForMac/Features/Playback/Views/SlideshowPlayerView.swift index f558d8d..61f8761 100644 --- a/AllServerForMac/Features/Playback/Views/SlideshowPlayerView.swift +++ b/AllServerForMac/Features/Playback/Views/SlideshowPlayerView.swift @@ -43,7 +43,7 @@ struct SlideshowPlayerView: View { ) case .error(let message): VStack(spacing: 10) { - Image(systemName: "xmark.octagon.fill").font(.largeTitle).foregroundStyle(.red) + Image(systemName: "xmark.octagon.fill").font(.appLargeTitle).foregroundStyle(.red) Text(message).foregroundStyle(.white).padding() Button("閉じる") { coordinator.close() } } @@ -59,10 +59,10 @@ struct SlideshowPlayerView: View { .font(.system(size: 40)) .foregroundStyle(.white) Text("スライドショー") - .font(.title2.weight(.semibold)) + .font(.appTitle.weight(.semibold)) .foregroundStyle(.white) Text("\(videos.count)本の動画から各クリップを切り出して連続再生します") - .font(.callout) + .font(.appBody) .foregroundStyle(.white.opacity(0.7)) } @@ -117,7 +117,7 @@ private struct SlideshowChapterRow: View { .cornerRadius(4) .clipped() - Text(chapter.title).font(.caption).lineLimit(2) + Text(chapter.title).font(.appCaption).lineLimit(2) } .padding(.vertical, 4) .task(id: chapter.id) { await generateThumbnail() } @@ -187,7 +187,7 @@ private struct SlideshowContentView: View { SlideshowChapterRow(chapter: chapter).tag(chapter.id) } .frame(width: sidebarWidth) - .background(.regularMaterial) + .background(Color(white: 0.07)) .offset(x: isSidebarVisible ? 0 : -sidebarWidth + triggerWidth) .onHover { hovering in isSidebarVisible = hovering } diff --git a/AllServerForMac/Features/Playback/Views/SplitVideoPlayerView.swift b/AllServerForMac/Features/Playback/Views/SplitVideoPlayerView.swift index 90803eb..d73caed 100644 --- a/AllServerForMac/Features/Playback/Views/SplitVideoPlayerView.swift +++ b/AllServerForMac/Features/Playback/Views/SplitVideoPlayerView.swift @@ -115,7 +115,7 @@ struct SplitVideoPlayerView: View { private var header: some View { HStack { Text("\(filename) — \(splitCount)分割再生") - .font(.caption) + .font(.appCaption) .foregroundStyle(.secondary) .lineLimit(1) Spacer() @@ -124,16 +124,17 @@ struct SplitVideoPlayerView: View { let start = viewModel.totalDuration / Double(splitCount) * Double(i) let end = start + viewModel.totalDuration / Double(splitCount) Text("\(formatTime(start))–\(formatTime(end))") - .font(.system(size: 10).monospacedDigit()) + .font(.appMicro.monospacedDigit()) .padding(.horizontal, 6) .padding(.vertical, 2) - .background(Color.accentColor.opacity(0.15)) + .background(PlayerChrome.hover) .cornerRadius(4) } } .padding(.horizontal, 12) .padding(.vertical, 6) - .background(.regularMaterial) + .background(Color(white: 0.09)) + .environment(\.colorScheme, .dark) } // MARK: - グリッド(MultiVideoPlayerViewと同じレイアウト) @@ -271,30 +272,33 @@ struct SplitVideoPlayerView: View { // MARK: - コントロール private var controls: some View { HStack { - Button { + // 通常再生と同じ、白い丸の再生/一時停止ボタン。 + PlayerPlayButton( + isPlaying: viewModel.isPlaying, + help: viewModel.isPlaying ? "一時停止(Space)" : "再生(Space)" + ) { togglePlayPause() - } label: { - Image(systemName: viewModel.isPlaying ? "pause.fill" : "play.fill") - .font(.system(size: 16)) - .frame(width: 20) } - .buttonStyle(.plain) - .help(viewModel.isPlaying ? "一時停止(Space)" : "再生(Space)") - .accessibilityLabel(viewModel.isPlaying ? "一時停止" : "再生") Text(formatTime(viewModel.commonCurrentTime)) - .font(.caption.monospacedDigit()) + .font(.system(size: 12, weight: .medium).monospacedDigit()) + .foregroundStyle(PlayerChrome.iconMuted) + .frame(minWidth: 44, alignment: .trailing) Slider( value: $viewModel.commonCurrentTime, in: 0...max(viewModel.commonDuration, 0.1) ) { isEditing in viewModel.commonSliderEditingChanged(isEditing: isEditing) } + .tint(.white.opacity(0.92)) Text(formatTime(viewModel.commonDuration)) - .font(.caption.monospacedDigit()) + .font(.system(size: 12, weight: .medium).monospacedDigit()) + .foregroundStyle(PlayerChrome.iconMuted) + .frame(minWidth: 44, alignment: .leading) } .padding() - .background(.regularMaterial) + .background(Color(white: 0.09)) + .environment(\.colorScheme, .dark) } // MARK: - キーボード diff --git a/AllServerForMac/Features/Playback/Views/VariantSwitchPlayerView.swift b/AllServerForMac/Features/Playback/Views/VariantSwitchPlayerView.swift index 03d8dd6..e4e9867 100644 --- a/AllServerForMac/Features/Playback/Views/VariantSwitchPlayerView.swift +++ b/AllServerForMac/Features/Playback/Views/VariantSwitchPlayerView.swift @@ -178,9 +178,9 @@ struct VariantSwitchPlayerView: View { .controlSize(.large) .tint(.white) Text("映像の共通場面を探しています…") - .font(.headline) + .font(.appHeadline) Text("動画全体から複数の類似ポイントを探し,時間の対応表を作成します") - .font(.caption) + .font(.appCaption) .foregroundStyle(.white.opacity(0.7)) } .foregroundStyle(.white) @@ -190,12 +190,12 @@ struct VariantSwitchPlayerView: View { } else if let message = viewModel.alignmentErrorMessage { VStack(spacing: 14) { Image(systemName: "exclamationmark.triangle.fill") - .font(.largeTitle) + .font(.appLargeTitle) .foregroundStyle(.yellow) Text("内容で位置合わせできませんでした") - .font(.headline) + .font(.appHeadline) Text(message) - .font(.callout) + .font(.appBody) .foregroundStyle(.white.opacity(0.75)) .multilineTextAlignment(.center) HStack { @@ -216,12 +216,12 @@ struct VariantSwitchPlayerView: View { private var activeBadge: some View { HStack(spacing: 8) { Image(systemName: "eye.fill") - .font(.system(size: 11)) + .font(.appMicro) .foregroundStyle(.white.opacity(0.72)) Text("\(viewModel.activeIndex + 1) / \(viewModel.variantCount)") .font(.system(size: 13, weight: .bold).monospacedDigit()) Text(activeTitle) - .font(.system(size: 12)) + .font(.appCaption) .lineLimit(1) .truncationMode(.middle) .frame(width: Self.activeTitleWidth, alignment: .leading) @@ -242,7 +242,7 @@ struct VariantSwitchPlayerView: View { : viewModel.isNextSwitchBeatAligned ? "拍同期" : "通常間隔", systemImage: "waveform.path.ecg" ) - .font(.system(size: 11)) + .font(.appMicro) .foregroundStyle(.white.opacity(0.7)) } if viewModel.isAutoSwitching, @@ -288,12 +288,8 @@ struct VariantSwitchPlayerView: View { } .padding(.horizontal, 14) .padding(.vertical, 10) - .background(RoundedRectangle(cornerRadius: 14, style: .continuous).fill(.ultraThinMaterial)) - .overlay( - RoundedRectangle(cornerRadius: 14, style: .continuous) - .strokeBorder(.white.opacity(0.15), lineWidth: 1) - ) - .shadow(color: .black.opacity(0.45), radius: 18, y: 6) + .playerPanel(cornerRadius: 14) + .environment(\.colorScheme, .dark) .padding(16) .frame(maxWidth: 1200) } @@ -323,7 +319,7 @@ struct VariantSwitchPlayerView: View { viewModel.toggleMark(at: index) } label: { Image(systemName: isMarked ? "checkmark.circle.fill" : "circle") - .font(.system(size: 13)) + .font(.appBody) .symbolRenderingMode(.palette) .foregroundStyle(.white, isMarked ? Color.red : Color.secondary) } @@ -339,7 +335,7 @@ struct VariantSwitchPlayerView: View { .frame(width: 18, height: 18) .background(Circle().fill(.white.opacity(0.18))) Text(variant.title) - .font(.caption) + .font(.appCaption) .lineLimit(1) .truncationMode(.middle) } @@ -355,7 +351,7 @@ struct VariantSwitchPlayerView: View { ) .overlay(alignment: .bottom) { Capsule() - .fill(isActive ? Color.accentColor.opacity(0.78) : Color.clear) + .fill(isActive ? Color.white.opacity(0.85) : Color.clear) .frame(height: 3) .padding(.horizontal, 10) .offset(y: 3) @@ -367,16 +363,16 @@ struct VariantSwitchPlayerView: View { private var deleteBar: some View { HStack(spacing: 10) { Label("削除モード", systemImage: "trash") - .font(.caption.weight(.semibold)) + .font(.appCaption.weight(.semibold)) .foregroundStyle(.red) Text("消したい差分に印を付けてください(表示中のものは \(keyLabel(.variantMarkForDeletion)))") - .font(.caption) + .font(.appCaption) .foregroundStyle(.secondary) Spacer() Text("\(viewModel.markedForDeletionIDs.count)本を選択中") - .font(.caption.monospacedDigit()) + .font(.appCaption.monospacedDigit()) Button("やめる") { viewModel.isDeleteMode = false } - .font(.caption) + .font(.appCaption) Button(role: .destructive) { showDeleteConfirmation = true } label: { @@ -444,7 +440,7 @@ struct VariantSwitchPlayerView: View { viewModel.isDeleteMode.toggle() } label: { Image(systemName: viewModel.isDeleteMode ? "trash.fill" : "trash") - .font(.system(size: 13)) + .font(.appBody) } .buttonStyle(.plain) .foregroundStyle(viewModel.isDeleteMode ? Color.red : Color.primary) @@ -452,20 +448,25 @@ struct VariantSwitchPlayerView: View { .accessibilityLabel("削除モード") Text(formatTime(viewModel.commonCurrentTime)) - .font(.caption.monospacedDigit()) + .font(.system(size: 12, weight: .medium).monospacedDigit()) + .foregroundStyle(PlayerChrome.iconMuted) + .frame(minWidth: 44, alignment: .trailing) Slider(value: $viewModel.commonCurrentTime, in: 0...max(viewModel.commonDuration, 0.1)) { isEditing in viewModel.sliderEditingChanged(isEditing: isEditing) } + .tint(.white.opacity(0.92)) .frame(minWidth: 160) Text(formatTime(viewModel.commonDuration)) - .font(.caption.monospacedDigit()) + .font(.system(size: 12, weight: .medium).monospacedDigit()) + .foregroundStyle(PlayerChrome.iconMuted) + .frame(minWidth: 44, alignment: .leading) } } private var intervalControls: some View { HStack(spacing: 10) { Toggle(isOn: $viewModel.isAutoSwitching) { - Text("自動切り替え").font(.caption) + Text("自動切り替え").font(.appCaption) } .toggleStyle(.switch) .controlSize(.mini) @@ -473,20 +474,20 @@ struct VariantSwitchPlayerView: View { HStack(spacing: 4) { Text(viewModel.synchronizesSwitchesToBeats ? "予備間隔" : "間隔") - .font(.caption) + .font(.appCaption) .foregroundStyle(.secondary) intervalField( value: viewModel.minInterval, label: "下限の秒数", set: viewModel.setMinInterval ) - Text("〜").font(.caption).foregroundStyle(.secondary) + Text("〜").font(.appCaption).foregroundStyle(.secondary) intervalField( value: viewModel.maxInterval, label: "上限の秒数", set: viewModel.setMaxInterval ) - Text("秒").font(.caption).foregroundStyle(.secondary) + Text("秒").font(.appCaption).foregroundStyle(.secondary) } .opacity(viewModel.isAutoSwitching ? 1 : 0.4) .disabled(!viewModel.isAutoSwitching) @@ -495,7 +496,7 @@ struct VariantSwitchPlayerView: View { : "この範囲からランダムに選んだ秒数ごとに切り替えます.上下を同じ値にすれば固定間隔です.") Toggle(isOn: $viewModel.avoidsImmediateRepeat) { - Text("同じものを続けない").font(.caption) + Text("同じものを続けない").font(.appCaption) } .toggleStyle(.checkbox) .controlSize(.mini) @@ -507,7 +508,7 @@ struct VariantSwitchPlayerView: View { HStack(spacing: 10) { Toggle(isOn: $viewModel.normalizesBGMVolume) { Text("BGM音量を揃える") - .font(.caption.weight(.semibold)) + .font(.appCaption.weight(.semibold)) } .toggleStyle(.switch) .controlSize(.mini) @@ -517,17 +518,17 @@ struct VariantSwitchPlayerView: View { ProgressView() .controlSize(.small) Text("共通場面の音量を解析中…") - .font(.caption) + .font(.appCaption) .foregroundStyle(.secondary) } else if let status = viewModel.activeBGMNormalizationText { Label(status, systemImage: "waveform") - .font(.caption.monospacedDigit()) + .font(.appCaption.monospacedDigit()) .foregroundStyle(.secondary) } Spacer() Text("切り替え時の急な音量差を抑えます") - .font(.caption) + .font(.appCaption) .foregroundStyle(.secondary) } .padding(.horizontal, 4) @@ -537,7 +538,7 @@ struct VariantSwitchPlayerView: View { HStack(spacing: 10) { Toggle(isOn: $viewModel.synchronizesSwitchesToBeats) { Text("BGMの拍に合わせる") - .font(.caption.weight(.semibold)) + .font(.appCaption.weight(.semibold)) } .toggleStyle(.switch) .controlSize(.mini) @@ -571,7 +572,7 @@ struct VariantSwitchPlayerView: View { .fixedSize() Text("拍ごと") - .font(.caption) + .font(.appCaption) .foregroundStyle(.secondary) } .help("何拍ごとに差分を切り替えるかを選びます.4拍で約1小節,8拍で約2小節,1/2拍・1/4拍は拍と拍のあいだでも切り替えます.") @@ -583,7 +584,7 @@ struct VariantSwitchPlayerView: View { } if let status = viewModel.beatSynchronizationStatusText { Label(status, systemImage: "waveform.path.ecg") - .font(.caption.monospacedDigit()) + .font(.appCaption.monospacedDigit()) .foregroundStyle(.secondary) } @@ -591,7 +592,7 @@ struct VariantSwitchPlayerView: View { Text(viewModel.synchronizesSwitchesToBeats ? "4拍子の小節先頭を推定し,選んだ拍数ごとに切り替えます(1拍未満も可)" : "テンポと小節の区切りを解析してから切り替えます") - .font(.caption) + .font(.appCaption) .foregroundStyle(.secondary) } .padding(.horizontal, 4) @@ -623,7 +624,7 @@ struct VariantSwitchPlayerView: View { } ) { Text(String(format: "%.1f", value)) - .font(.caption.monospacedDigit()) + .font(.appCaption.monospacedDigit()) .frame(width: 30, alignment: .trailing) } .controlSize(.mini) @@ -655,7 +656,7 @@ struct VariantSwitchPlayerView: View { ("− / +", "切り替え間隔を調整(0.5秒以下は0.1秒刻み)"), ("P", "操作パネルを出しっぱなしにする/自動で隠す"), ("マウスを動かす", "隠れている操作パネルを出す(2.5秒後に自動で隠れます)"), - ("差分の切り替え", "映像に被らないよう、操作パネルは出しません"), + ("差分の切り替え", "映像に被らないよう,操作パネルは出しません"), ("?", "ショートカット一覧を表示"), ("Esc", "プレイヤーを閉じる") ] diff --git a/AllServerForMac/Features/Playback/Views/VideoPlayerView.swift b/AllServerForMac/Features/Playback/Views/VideoPlayerView.swift index 4b874d6..ccf0f92 100644 --- a/AllServerForMac/Features/Playback/Views/VideoPlayerView.swift +++ b/AllServerForMac/Features/Playback/Views/VideoPlayerView.swift @@ -21,7 +21,7 @@ private struct ChapterRow: View { .aspectRatio(16 / 9, contentMode: .fit) .cornerRadius(4) Text(chapter.timeString) - .font(.caption.monospacedDigit()) + .font(.appCaption.monospacedDigit()) } .contentShape(Rectangle()) } @@ -42,18 +42,10 @@ private struct PlaybackVideoStrip: View { VStack(alignment: .leading, spacing: 14) { HStack { Text("他の動画") - .font(.callout.weight(.semibold)) - .foregroundStyle(.white.opacity(0.82)) + .font(.system(size: 13, weight: .semibold)) + .foregroundStyle(PlayerChrome.icon) Spacer() - Button(action: onClose) { - Image(systemName: "xmark.circle.fill") - .symbolRenderingMode(.hierarchical) - .font(.title3) - } - .buttonStyle(.plain) - .foregroundStyle(.white.opacity(0.78)) - .help("動画一覧を閉じる") - .accessibilityLabel("動画一覧を閉じる") + PlayerRoundButton(systemImage: "xmark", help: "動画一覧を閉じる", action: onClose) } ScrollView(.horizontal, showsIndicators: false) { @@ -73,11 +65,7 @@ private struct PlaybackVideoStrip: View { } } .padding(16) - .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 8, style: .continuous)) - .overlay( - RoundedRectangle(cornerRadius: 8, style: .continuous) - .strokeBorder(.white.opacity(0.12), lineWidth: 1) - ) + .playerPanel() .padding(.horizontal, 30) } @@ -109,7 +97,7 @@ private struct PlaybackVideoThumbnailButton: View { ) Text(displayName) - .font(.caption.weight(.semibold)) + .font(.appCaption.weight(.semibold)) .lineLimit(1) .foregroundStyle(.white) .padding(.horizontal, 10) @@ -140,7 +128,7 @@ private struct PlaybackVideoThumbnailButton: View { ZStack { Rectangle().fill(.black.opacity(0.35)) Image(systemName: "film") - .font(.title3) + .font(.appTitle) .foregroundStyle(.white.opacity(0.48)) } } @@ -181,7 +169,7 @@ private struct UpNextVideoRow: View { .clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous)) Text(durationString) - .font(.caption2.monospacedDigit().weight(.semibold)) + .font(.appMicro.monospacedDigit().weight(.semibold)) .foregroundStyle(.white) .padding(.horizontal, 4) .padding(.vertical, 2) @@ -190,7 +178,7 @@ private struct UpNextVideoRow: View { } Text(displayName) - .font(.footnote.weight(.medium)) + .font(.appBody.weight(.medium)) .foregroundStyle(.white.opacity(0.9)) .lineLimit(2) .multilineTextAlignment(.leading) @@ -399,6 +387,8 @@ struct VideoPlayerView: View { private let playbackControlsHorizontalPadding: CGFloat = 28 private let playbackControlsBottomPadding: CGFloat = 24 private let playbackControlButtonWidth: CGFloat = 26 + /// キー1打ちで動かす音量の幅。20回で無音から最大まで届く。 + private let volumeStep: Float = 0.05 private let minimumSliderDuration: Double = 0.1 private let videoStripScrollThreshold: CGFloat = 2 private let secondsPerMinute = 60 @@ -413,7 +403,8 @@ struct VideoPlayerView: View { currentVideo: VideoItem, dataManager: LibraryViewModel, watchState: WatchStateStore, - settings: PlaybackSettings + settings: PlaybackSettings, + initialStartTime: Double? = nil ) { self.dataManager = dataManager _settings = ObservedObject(wrappedValue: settings) @@ -423,7 +414,8 @@ struct VideoPlayerView: View { currentVideo: currentVideo, dataManager: dataManager, watchState: watchState, - settings: settings + settings: settings, + initialStartTime: initialStartTime ) ) } @@ -449,7 +441,14 @@ struct VideoPlayerView: View { .videoCycleRepeat, .videoRateDown, .videoRateUp, - .videoTogglePictureInPicture + .videoTogglePictureInPicture, + .videoVolumeUp, + .videoVolumeDown, + .videoToggleMute, + .videoToggleFavorite, + .videoStepBackward, + .videoStepForward, + .videoToggleFillScreen ], extraItems: [ ("0〜9", "動画の 0%〜90% の位置へジャンプ"), @@ -515,20 +514,39 @@ struct VideoPlayerView: View { } } + // 再生中の動画名。タイトルバーが出ない画面なので,ここに出さないと何を見ているか分からない。 + // 右上の操作と同じタイミングで出し入れし,右側は操作群と重ならないよう空けておく。 + Text(viewModel.currentVideo.originalFilename) + .font(.system(size: 13, weight: .medium)) + .foregroundStyle(PlayerChrome.icon) + .lineLimit(1) + .truncationMode(.middle) + .padding(.horizontal, 14) + .frame(height: 32) + .playerPanel(cornerRadius: 16) + .padding() + .padding(.top, PlayerCornerControls.titlebarClearance) + .padding(.trailing, 300) + .frame(maxWidth: .infinity, alignment: .leading) + .opacity(areCornerControlsVisible || showShortcutHelp ? 1 : 0) + .allowsHitTesting(false) + .accessibilityHidden(!(areCornerControlsVisible || showShortcutHelp)) + // シークバーと同じく,カーソル操作中だけ右上の補助操作を表示する。 // パネルの開閉に関わらず常にウィンドウ右上端に留める。 - if areCornerControlsVisible || showShortcutHelp { - PlayerCornerControls( - showShortcutHelp: $showShortcutHelp, - volume: $viewModel.volume, - isMuted: $viewModel.isMuted - ) { - coordinator.close() - } - .transition(.opacity) + // 条件付きで挿入すると,隠れている間に右上の × を押しても「表示するだけ」で閉じられない。 + // 常に置いたまま透明度だけ切り替え,見えていなくても押せるようにする。 + PlayerCornerControls( + showShortcutHelp: $showShortcutHelp, + volume: $viewModel.volume, + isMuted: $viewModel.isMuted + ) { + coordinator.close() } + .opacity(areCornerControlsVisible || showShortcutHelp ? 1 : 0) - if let notice = viewModel.resumeNotice { + if let notice = viewModel.resumeNotice + ?? (viewModel.isAnalyzingLoopEdges ? viewModel.loopAnalysisNotice : nil) { resumeNoticeBadge(notice) } @@ -567,7 +585,7 @@ struct VideoPlayerView: View { private var miniPlayerView: some View { ZStack(alignment: .bottom) { Color.black - PlayerLayerContainerView(player: viewModel.player) + PlayerLayerContainerView(player: viewModel.player, videoGravity: viewModel.videoGravity) if isMiniControlsVisible { HStack(spacing: 8) { @@ -640,7 +658,10 @@ struct VideoPlayerView: View { Color.black // AVKit標準コントロールは表示時に動画全体を暗くするため使わず、 // 下部に独自のシークバーを重ねる。 - PlayerLayerContainerView(player: viewModel.player) { layer in + PlayerLayerContainerView( + player: viewModel.player, + videoGravity: viewModel.videoGravity + ) { layer in pictureInPicture.attach(playerLayer: layer) } .scaleEffect(x: videoZoom.scaleX, y: videoZoom.scaleY, anchor: .topLeading) @@ -713,12 +734,11 @@ struct VideoPlayerView: View { Image(systemName: "clock.arrow.circlepath") Text(notice) } - .font(.callout.weight(.medium)) - .foregroundStyle(.white) + .font(.system(size: 13, weight: .medium)) + .foregroundStyle(PlayerChrome.icon) .padding(.horizontal, 14) - .padding(.vertical, 9) - .background(Capsule().fill(.black.opacity(0.62))) - .overlay(Capsule().strokeBorder(.white.opacity(0.14), lineWidth: 1)) + .frame(height: 34) + .playerPanel(cornerRadius: 17) .padding(24) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) .transition(.opacity) @@ -729,7 +749,7 @@ struct VideoPlayerView: View { private var upNextPanel: some View { VStack(alignment: .leading, spacing: 0) { Text("同じアルバムの動画") - .font(.callout.weight(.semibold)) + .font(.appBody.weight(.semibold)) .foregroundStyle(.white.opacity(0.82)) .padding(.horizontal, 16) .padding(.top, 22) @@ -738,7 +758,7 @@ struct VideoPlayerView: View { if viewModel.otherVideos.isEmpty { Spacer() Text("他に動画がありません") - .font(.caption) + .font(.appCaption) .foregroundStyle(.white.opacity(0.5)) .frame(maxWidth: .infinity) Spacer() @@ -803,45 +823,40 @@ struct VideoPlayerView: View { /// AVKit標準の暗転を避けるための通常再生用コントロール。 private var playbackControls: some View { - HStack(spacing: 12) { - Button { + HStack(spacing: 10) { + PlayerIconButton( + systemImage: "backward.end", + help: "前の動画", + accessibilityLabel: "前の動画" + ) { viewModel.playPreviousVideo() - } label: { - Image(systemName: "backward.end.fill") - .font(.system(size: 15)) - .frame(width: playbackControlButtonWidth) } - .buttonStyle(.plain) .disabled(!viewModel.canPlayPreviousVideo) - .help("前の動画") - .accessibilityLabel("前の動画") - Button { + // 主役の再生/一時停止だけを白い丸にして目立たせる。 + PlayerPlayButton( + isPlaying: viewModel.isPlaybackPlaying, + help: viewModel.isPlaybackPlaying ? "一時停止(Space)" : "再生(Space)" + ) { viewModel.playPause() - } label: { - Image(systemName: viewModel.isPlaybackPlaying ? "pause.fill" : "play.fill") - .font(.system(size: 16)) - .frame(width: playbackControlButtonWidth) } - .buttonStyle(.plain) - .help(viewModel.isPlaybackPlaying ? "一時停止(Space)" : "再生(Space)") - .accessibilityLabel(viewModel.isPlaybackPlaying ? "一時停止" : "再生") - Button { + PlayerIconButton( + systemImage: "forward.end", + help: "次の動画", + accessibilityLabel: "次の動画" + ) { viewModel.playNextVideo() - } label: { - Image(systemName: "forward.end.fill") - .font(.system(size: 15)) - .frame(width: playbackControlButtonWidth) } - .buttonStyle(.plain) .disabled(!viewModel.canPlayNextVideo) - .help("次の動画") - .accessibilityLabel("次の動画") + + StockMomentButton(video: viewModel.currentVideo, time: viewModel.currentTime, + duration: viewModel.duration, dataManager: dataManager, compact: true) Text(formatTime(viewModel.currentTime)) - .font(.caption.monospacedDigit()) - .frame(minWidth: 46, alignment: .trailing) + .font(.system(size: 12, weight: .medium).monospacedDigit()) + .foregroundStyle(PlayerChrome.iconMuted) + .frame(minWidth: 48, alignment: .trailing) Slider( value: $viewModel.currentTime, @@ -849,6 +864,7 @@ struct VideoPlayerView: View { ) { isEditing in viewModel.playbackSliderEditingChanged(isEditing: isEditing) } + .tint(.white.opacity(0.92)) .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { seekBarWidth = $0 } .onContinuousHover(coordinateSpace: .local) { phase in handleSeekBarHover(phase) @@ -861,58 +877,72 @@ struct VideoPlayerView: View { } Text(formatTime(viewModel.duration)) - .font(.caption.monospacedDigit()) - .frame(minWidth: 46, alignment: .leading) - - Divider().frame(height: 18) - - Button { + .font(.system(size: 12, weight: .medium).monospacedDigit()) + .foregroundStyle(PlayerChrome.iconMuted) + .frame(minWidth: 48, alignment: .leading) + + Rectangle() + .fill(PlayerChrome.panelBorder) + .frame(width: 1, height: 16) + + PlayerIconButton( + systemImage: "shuffle", + isActive: settings.isShuffleEnabled, + help: settings.isShuffleEnabled ? "シャッフル: オン" : "シャッフル: オフ", + accessibilityLabel: "シャッフル" + ) { settings.isShuffleEnabled.toggle() - } label: { - Image(systemName: "shuffle") - .font(.system(size: 13, weight: .semibold)) - .frame(width: playbackControlButtonWidth) - .foregroundStyle(settings.isShuffleEnabled ? Color.accentColor : Color.primary) } - .buttonStyle(.plain) - .help(settings.isShuffleEnabled ? "シャッフル: オン" : "シャッフル: オフ") - .accessibilityLabel("シャッフル") - Button { + PlayerIconButton( + systemImage: settings.repeatMode.symbolName, + isActive: settings.repeatMode != .off, + help: viewModel.loopAnalysisNotice ?? settings.repeatMode.title, + accessibilityLabel: settings.repeatMode.title + ) { settings.repeatMode = settings.repeatMode.next - } label: { - Image(systemName: settings.repeatMode.symbolName) - .font(.system(size: 13, weight: .semibold)) - .frame(width: playbackControlButtonWidth) - .foregroundStyle(settings.repeatMode == .off ? Color.primary : Color.accentColor) } - .buttonStyle(.plain) - .help(settings.repeatMode.title) - .accessibilityLabel(settings.repeatMode.title) + + PlayerIconButton( + systemImage: viewModel.isCurrentVideoFavorite ? "heart.fill" : "heart", + isActive: viewModel.isCurrentVideoFavorite, + help: viewModel.isCurrentVideoFavorite ? "お気に入りから外す" : "お気に入りに追加", + accessibilityLabel: "お気に入り" + ) { + viewModel.toggleCurrentVideoFavorite() + } + + PlayerIconButton( + systemImage: viewModel.fillsScreen + ? "arrow.down.right.and.arrow.up.left" + : "arrow.up.left.and.arrow.down.right", + isActive: viewModel.fillsScreen, + help: viewModel.fillsScreen ? "全体が収まる表示に戻す" : "画面いっぱいに広げる(黒帯を切り落とす)", + accessibilityLabel: "画面いっぱい" + ) { + viewModel.toggleFillsScreen() + } if PictureInPictureCoordinator.isSupported { - Button { + PlayerIconButton( + systemImage: pictureInPicture.isActive ? "pip.exit" : "pip.enter", + isActive: pictureInPicture.isActive, + help: pictureInPicture.isActive ? "小窓をやめて戻す" : "ピクチャインピクチャ(P)", + accessibilityLabel: "ピクチャインピクチャ" + ) { pictureInPicture.toggle() - } label: { - Image(systemName: pictureInPicture.isActive - ? "pip.exit" - : "pip.enter") - .font(.system(size: 13, weight: .semibold)) - .frame(width: playbackControlButtonWidth) - .foregroundStyle(pictureInPicture.isActive ? Color.accentColor : Color.primary) } - .buttonStyle(.plain) .disabled(!pictureInPicture.isPossible && !pictureInPicture.isActive) - .help(pictureInPicture.isActive ? "小窓をやめて戻す" : "ピクチャインピクチャ(P)") - .accessibilityLabel("ピクチャインピクチャ") } playbackOptionsMenu } .padding(.horizontal, 14) - .padding(.vertical, 10) + .padding(.vertical, 8) .frame(maxWidth: playbackControlsMaxWidth) - .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 8, style: .continuous)) + .playerPanel() + // 暗い面に白で組むので、スライダーやメニューも暗い外観で描かせる。 + .environment(\.colorScheme, .dark) .padding(.horizontal, playbackControlsHorizontalPadding) .padding(.bottom, playbackControlsBottomPadding) } @@ -952,14 +982,19 @@ struct VideoPlayerView: View { } label: { HStack(spacing: 4) { if viewModel.selectedSubtitleIndex != VideoPlayerViewModel.MediaTrackChoice.offIndex { - Image(systemName: "captions.bubble.fill") - .font(.system(size: 10, weight: .semibold)) + Image(systemName: "captions.bubble") + .font(.system(size: 11, weight: .regular)) } Text(settings.rateLabel) - .font(.caption.weight(.semibold).monospacedDigit()) + .font(.system(size: 12, weight: .medium).monospacedDigit()) } + .foregroundStyle(PlayerChrome.icon) + .padding(.horizontal, 6) + .frame(height: 30) } .menuStyle(.borderlessButton) + // メニューの文字がアクセントの青になるのを避け、他のボタンと同じ白にそろえる。 + .tint(PlayerChrome.icon) .fixedSize() .help("再生速度・音声・字幕・自動再生") .accessibilityLabel("再生の設定") @@ -986,11 +1021,11 @@ struct VideoPlayerView: View { ) Text(formatTime(hoveredSeconds ?? 0)) - .font(.caption2.monospacedDigit().weight(.semibold)) + .font(.appMicro.monospacedDigit().weight(.semibold)) .foregroundStyle(.white) } .padding(5) - .background(.black.opacity(0.72), in: RoundedRectangle(cornerRadius: 7, style: .continuous)) + .playerPanel(cornerRadius: 8) .allowsHitTesting(false) } @@ -1074,7 +1109,7 @@ struct VideoPlayerView: View { .padding(8) } .frame(width: sidebarWidth) - .background(.regularMaterial) + .background(Color(white: 0.07)) .offset(x: isSidebarVisible ? 0 : -sidebarWidth + triggerWidth) } .frame(width: isSidebarVisible ? sidebarWidth : triggerWidth) @@ -1164,6 +1199,31 @@ struct VideoPlayerView: View { } else if MediaShortcutSettings.matches(.videoTogglePictureInPicture, press: press) { pictureInPicture.toggle() return .handled + } else if MediaShortcutSettings.matches(.videoVolumeUp, press: press) { + viewModel.adjustVolume(by: volumeStep) + revealCornerControls() + return .handled + } else if MediaShortcutSettings.matches(.videoVolumeDown, press: press) { + viewModel.adjustVolume(by: -volumeStep) + revealCornerControls() + return .handled + } else if MediaShortcutSettings.matches(.videoToggleMute, press: press) { + viewModel.toggleMute() + revealCornerControls() + return .handled + } else if MediaShortcutSettings.matches(.videoToggleFavorite, press: press) { + viewModel.toggleCurrentVideoFavorite() + revealCornerControls() + return .handled + } else if MediaShortcutSettings.matches(.videoStepBackward, press: press) { + viewModel.stepFrame(by: -1) + return .handled + } else if MediaShortcutSettings.matches(.videoStepForward, press: press) { + viewModel.stepFrame(by: 1) + return .handled + } else if MediaShortcutSettings.matches(.videoToggleFillScreen, press: press) { + viewModel.toggleFillsScreen() + return .handled } return .ignored @@ -1183,3 +1243,249 @@ struct VideoPlayerView: View { return String(format: "%d:%02d", totalSeconds / secondsPerMinute, totalSeconds % secondsPerMinute) } } + +// MARK: - 一覧から開始する巡回メニュー + +struct LibraryTourMenu: View { + let videos: [VideoItem] + let dataManager: LibraryViewModel + let beforePlay: () -> Void + @EnvironmentObject private var watchState: WatchStateStore + @EnvironmentObject private var coordinator: PlaybackCoordinator + @State private var errorMessage: String? + + var body: some View { + Menu { + Section("新しい楽しみ方") { + Button("マイチャンネル(全動画アルバム)") { + start { try PlaybackTourSession.channelSession(albums: dataManager.albums, videos: dataManager.videos) } + } + Menu("気分でミックス") { + ForEach(PlaybackTourSession.Mood.allCases, id: \.rawValue) { mood in + Button(mood.rawValue) { + start { + try PlaybackTourSession.mix(videos: videos, mood: mood, + seenIDs: Set(watchState.historyOrder).union(watchState.progress.keys)) + } + } + } + } + Menu("時間ぴったり再生") { + ForEach([5, 10, 15, 30], id: \.self) { minutes in + Button("\(minutes)分") { + start { try PlaybackTourSession.timed(videos: videos, seconds: Double(minutes * 60)) } + } + } + } + Button("ストックした場面を再生") { + start { try PlaybackTourSession.highlights(videos: videos, urlForVideo: dataManager.fileURL) } + } + } + Section("プレビュー巡回") { + Button("15秒ずつ試聴") { startPreview(seconds: 15) } + Button("30秒ずつ試聴") { startPreview(seconds: 30) } + } + Section("採用した区間を楽しむ") { + Button("シーンシャッフル") { + start { try PlaybackTourSession.scenes(videos: videos, urlForVideo: dataManager.fileURL) } + } + } + } label: { + Label("お楽しみ再生", systemImage: "play.rectangle.on.rectangle") + } + .help("チャンネル・気分ミックス・時間指定・ストック・プレビュー巡回・シーン再生") + .disabled(videos.isEmpty) + .alert("再生を開始できません", isPresented: Binding( + get: { errorMessage != nil }, set: { if !$0 { errorMessage = nil } } + )) { + Button("閉じる", role: .cancel) { errorMessage = nil } + } message: { Text(errorMessage ?? "") } + } + + private func startPreview(seconds: Double) { + start { try PlaybackTourSession.preview(videos: videos, seconds: seconds) } + } + + private func start(_ makeSession: () throws -> PlaybackTourSession) { + do { + let session = try makeSession() + beforePlay() + coordinator.startTour(session) + } catch { + errorMessage = error.localizedDescription + } + } +} + +// MARK: - 履歴を更新せずに区間を試す専用プレイヤー + +struct PlaybackTourView: View { + @StateObject private var model: PlaybackTourViewModel + @EnvironmentObject private var coordinator: PlaybackCoordinator + private let session: PlaybackTourSession + private let dataManager: LibraryViewModel + + init(session: PlaybackTourSession, dataManager: LibraryViewModel) { + self.session = session + self.dataManager = dataManager + _model = StateObject(wrappedValue: PlaybackTourViewModel(session: session, dataManager: dataManager)) + } + + var body: some View { + VStack(spacing: 0) { + HStack(spacing: 16) { + VStack(alignment: .leading, spacing: 5) { + Text(model.channelName.map { "マイチャンネル · \($0)" } ?? session.title).font(.appTitle.bold()) + Text(model.currentEntry?.video.originalFilename ?? "") + .font(.appBody).lineLimit(1).truncationMode(.middle) + } + Spacer() + Text("\(model.index + 1) / \(session.entries.count)").monospacedDigit() + Button("一覧に戻る", systemImage: "xmark") { coordinator.close() } + .keyboardShortcut(.escape, modifiers: []) + } + .padding(20) + + ZStack { + Color.black + PlayerLayerContainerView(player: model.player) + if model.isLoading { + ProgressView("動画を読み込み中…").tint(.white) + } + if let error = model.errorMessage { + VStack(spacing: 16) { + Text("この項目を再生できません").font(.appTitle.bold()) + Text(error).multilineTextAlignment(.center) + HStack { + Button("再試行") { model.retry() } + Button("次へ進む") { model.next() } + } + } + .padding(24) + .background(.black.opacity(0.85), in: RoundedRectangle(cornerRadius: 16)) + } + if model.isFinished { + VStack(spacing: 16) { + Text("一巡しました").font(.appLargeTitle.bold()) + Text("\(session.entries.count)件の区間の巡回が終了しました.") + HStack { + Button("もう一度巡回") { model.restart() } + Button("一覧に戻る") { coordinator.close() } + } + } + .padding(24) + .background(.black.opacity(0.85), in: RoundedRectangle(cornerRadius: 16)) + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + + VStack(spacing: 12) { + ProgressView(value: model.progress) + HStack(spacing: 16) { + Button(model.isChannelMode ? "前のCH" : "前へ", systemImage: "backward.end") { model.previous() } + .keyboardShortcut(model.isChannelMode ? .upArrow : .leftArrow, modifiers: []) + .disabled(!model.isChannelMode && model.index == 0) + Button(model.isPlaying ? "一時停止" : "再生", systemImage: model.isPlaying ? "pause.fill" : "play.fill") { + model.togglePlayback() + } + .keyboardShortcut(.space, modifiers: []) + .disabled(model.isLoading || model.isFinished || model.errorMessage != nil) + Button(model.isChannelMode ? "次のCH" : "次へ", systemImage: "forward.end") { model.next() } + .keyboardShortcut(model.isChannelMode ? .downArrow : .rightArrow, modifiers: []) + .disabled(model.isFinished) + Text("残り\(Int(ceil(model.sessionRemaining)))秒").monospacedDigit() + Spacer() + Button(model.isMuted ? "消音を解除" : "消音", systemImage: model.isMuted ? "speaker.slash" : "speaker.wave.2") { + model.isMuted.toggle() + } + .labelStyle(.iconOnly) + .accessibilityLabel(model.isMuted ? "消音を解除" : "消音") + Slider(value: $model.volume, in: 0...1) + .frame(width: 90) + .accessibilityLabel("音量") + Button("このまま見る", systemImage: "play.rectangle") { continueWatching() } + .buttonStyle(.borderedProminent) + .keyboardShortcut(.return, modifiers: []) + .disabled(model.isLoading || model.errorMessage != nil || model.isFinished) + } + HStack { + if let entry = model.currentEntry { + StockMomentButton(video: entry.video, time: model.currentTime, + duration: entry.video.duration, dataManager: dataManager) + .disabled(model.isLoading || model.errorMessage != nil || model.isFinished) + } + Spacer() + if session.kind == .timed { + Text("予定:\(Int((session.requestedSeconds ?? 0) / 60))分 · 一時停止・読み込み・手動送りで終了時刻は変わります.") + .font(.appCaption) + } + } + Text("試聴中は視聴位置・履歴を変更しません.「このまま見る」で通常再生へ切り替わります.") + .font(.appCaption).foregroundStyle(.white.opacity(0.75)) + } + .padding(20) + } + .foregroundStyle(.white) + .background(Color.black) + .tint(NeomorphicTheme.accent) + .buttonStyle(.bordered) + .preferredColorScheme(.dark) + .onAppear { + coordinator.setPlaybackActive(false) + model.start() + } + .onChange(of: model.isPlaying) { _, playing in coordinator.setPlaybackActive(playing) } + .onChange(of: model.isFinished) { _, finished in + if finished { coordinator.setPlaybackActive(false) } + } + .onDisappear { model.cleanup() } + } + + private func continueWatching() { + guard let entry = model.currentEntry else { return } + let time = model.currentTime + model.cleanup() + var seen = Set() + let source = model.isChannelMode ? session.channels[model.index].videos : session.entries.map(\.video) + let videos = source.filter { seen.insert($0.id).inserted } + coordinator.playSingle(playlist: videos, current: entry.video, startAt: time) + } +} + +// MARK: - 再生中の前後10秒をワンアクションで保存 + +struct StockMomentButton: View { + let video: VideoItem + let time: Double + let duration: Double + let dataManager: LibraryViewModel + var compact = false + @State private var notice: String? + @State private var errorMessage: String? + + var body: some View { + Button { + do { + guard let url = dataManager.fileURL(for: video) else { throw PlaybackTourError.missingFile } + try HighlightStore.capture(url: url, time: time, duration: duration) + notice = "前後10秒を保存しました.一覧の「お楽しみ再生 → ストックした場面を再生」から見返せます." + } catch { + errorMessage = "場面を保存できませんでした.\(error.localizedDescription)" + } + } label: { + if compact { Image(systemName: "bookmark.badge.plus") } + else { Label("場面を保存", systemImage: "bookmark.badge.plus") } + } + .keyboardShortcut("b", modifiers: [.command]) + .accessibilityLabel("場面を保存") + .help("現在位置の前後10秒をストックします(⌘B)") + .popover(isPresented: Binding(get: { notice != nil }, set: { if !$0 { notice = nil } })) { + Text(notice ?? "").font(.appBody).padding(16).frame(width: 300) + } + .alert("保存できません", isPresented: Binding( + get: { errorMessage != nil }, set: { if !$0 { errorMessage = nil } } + )) { + Button("閉じる", role: .cancel) { errorMessage = nil } + } message: { Text(errorMessage ?? "") } + } +} diff --git a/AllServerForMac/Features/SceneExtraction/Services/DatasetManager.swift b/AllServerForMac/Features/SceneExtraction/Services/DatasetManager.swift index 5faf952..02826d6 100644 --- a/AllServerForMac/Features/SceneExtraction/Services/DatasetManager.swift +++ b/AllServerForMac/Features/SceneExtraction/Services/DatasetManager.swift @@ -130,3 +130,53 @@ nonisolated struct DatasetManager: Sendable { return result.isEmpty ? "dataset" : result } } + +// MARK: - シーンシャッフルで使う採用済み区間 + +/// 特徴量や映像は保存せず,採用した区間だけをローカル設定に保持します. +/// 読み込みエラー時は上書きせず,呼び出し元へエラーを返します. +@MainActor +enum AcceptedSceneStore { + nonisolated static let defaultsKey = "playback.acceptedScenes.v1" + + static func sourceKey(_ url: URL) -> String { + url.standardizedFileURL.resolvingSymlinksInPath().path + } + + static func load(defaults: UserDefaults = .standard, key: String = defaultsKey) throws -> [String: [CandidateSegment]] { + guard let data = defaults.data(forKey: key) else { return [:] } + return try JSONDecoder().decode([String: [CandidateSegment]].self, from: data) + } + + static func save(url: URL, candidates: [CandidateSegment], defaults: UserDefaults = .standard, key: String = defaultsKey) throws { + var stored = try load(defaults: defaults, key: key) + stored[sourceKey(url)] = candidates.filter { + $0.userLabel == .accepted && $0.startTime.isFinite && $0.endTime.isFinite + && $0.startTime >= 0 && $0.endTime > $0.startTime + } + let data = try JSONEncoder().encode(stored) + defaults.set(data, forKey: key) + } +} + +/// 採用シーンとは別に,視聴中に気になった場面を保存します. +@MainActor +enum HighlightStore { + nonisolated static let defaultsKey = "playback.highlights.v1" + static let beforeSeconds = 10.0 + static let afterSeconds = 10.0 + + static func capture(url: URL, time: Double, duration: Double, defaults: UserDefaults = .standard) throws { + guard time.isFinite, duration.isFinite, duration > 0 else { throw PlaybackTourError.invalidRange } + let start = max(0, time - beforeSeconds) + let end = min(duration, time + afterSeconds) + guard end > start else { throw PlaybackTourError.invalidRange } + let stored = try AcceptedSceneStore.load(defaults: defaults, key: defaultsKey) + var scenes = stored[AcceptedSceneStore.sourceKey(url)] ?? [] + guard !scenes.contains(where: { abs($0.peakTime - time) < 1 }) else { return } + scenes.append(CandidateSegment(startTime: start, endTime: end, peakTime: time, + score: 1, audioScore: 0, visualScore: 0, transitionScore: 0, + reason: ["再生中にストック"], userLabel: .accepted)) + try AcceptedSceneStore.save(url: url, candidates: scenes, defaults: defaults, key: defaultsKey) + } +} diff --git a/AllServerForMac/Features/SceneExtraction/ViewModels/SceneExtractionViewModel.swift b/AllServerForMac/Features/SceneExtraction/ViewModels/SceneExtractionViewModel.swift index c82aafd..b3ff1d5 100644 --- a/AllServerForMac/Features/SceneExtraction/ViewModels/SceneExtractionViewModel.swift +++ b/AllServerForMac/Features/SceneExtraction/ViewModels/SceneExtractionViewModel.swift @@ -79,6 +79,7 @@ final class SceneExtractionViewModel: ObservableObject { videoDocument = document currentTime = 0 candidates = [] + candidates = try AcceptedSceneStore.load()[AcceptedSceneStore.sourceKey(url)] ?? [] features = [] analysisResult = nil analysisProgress = nil @@ -113,7 +114,9 @@ final class SceneExtractionViewModel: ObservableObject { try Task.checkCancellation() self.analysisResult = result self.features = result.mergedFeatures - self.candidates = result.candidates + // 再解析しても,以前採用した区間を失わないように保持します. + let accepted = self.candidates.filter { $0.userLabel == .accepted } + self.candidates = accepted + result.candidates self.selectedCandidateID = result.candidates.first?.id } catch is CancellationError { self.analysisProgress = nil @@ -188,6 +191,7 @@ final class SceneExtractionViewModel: ObservableObject { func setLabel(_ label: CandidateLabel, for candidateID: UUID) { guard let index = candidates.firstIndex(where: { $0.id == candidateID }) else { return } candidates[index].userLabel = label + saveAcceptedScenes() } /// ラベルを保存し,スコア順で次の未判定候補を自動プレビューします. @@ -220,6 +224,7 @@ final class SceneExtractionViewModel: ObservableObject { max(0, startTime), candidates[index].endTime - 0.1 ) + saveAcceptedScenes() } func updateCandidateEnd(_ endTime: Double, candidateID: UUID) { @@ -228,6 +233,7 @@ final class SceneExtractionViewModel: ObservableObject { candidates[index].startTime + 0.1, min(duration, endTime) ) + saveAcceptedScenes() } func exportClip(_ candidate: CandidateSegment) { @@ -327,6 +333,16 @@ final class SceneExtractionViewModel: ObservableObject { candidates.append(groundTruth) candidates.sort { $0.peakTime < $1.peakTime } selectedCandidateID = groundTruth.id + saveAcceptedScenes() + } + + private func saveAcceptedScenes() { + guard let videoDocument else { return } + do { + try AcceptedSceneStore.save(url: videoDocument.url, candidates: candidates) + } catch { + errorMessage = "採用シーンを保存できませんでした.既存の保存内容は変更していません.\(error.localizedDescription)" + } } func clearError() { diff --git a/AllServerForMac/Features/SceneExtraction/Views/AnalysisPlayerView.swift b/AllServerForMac/Features/SceneExtraction/Views/AnalysisPlayerView.swift index ee4e163..05b2efb 100644 --- a/AllServerForMac/Features/SceneExtraction/Views/AnalysisPlayerView.swift +++ b/AllServerForMac/Features/SceneExtraction/Views/AnalysisPlayerView.swift @@ -77,7 +77,7 @@ struct AnalysisPlayerView: View { systemImage: viewModel.isPlaying ? "pause.fill" : "play.fill" ) .labelStyle(.iconOnly) - .font(.title3) + .font(.appTitle) } .keyboardShortcut(.space, modifiers: []) @@ -98,10 +98,13 @@ struct AnalysisPlayerView: View { Spacer() Text("\(timeText(viewModel.currentTime)) / \(timeText(viewModel.duration))") - .font(.system(.body, design: .monospaced)) - .foregroundStyle(.secondary) + .font(.system(size: 13, design: .monospaced)) + .foregroundStyle(NeomorphicTheme.muted) } .buttonStyle(.borderless) + // 操作アイコンは青でなく文字色にする(青は進捗・選択の目印だけに使う)。 + .tint(NeomorphicTheme.ink) + .foregroundStyle(NeomorphicTheme.ink) .disabled(viewModel.videoDocument == nil) } diff --git a/AllServerForMac/Features/SceneExtraction/Views/CandidateListView.swift b/AllServerForMac/Features/SceneExtraction/Views/CandidateListView.swift index 2eb4fa0..e3e8bbd 100644 --- a/AllServerForMac/Features/SceneExtraction/Views/CandidateListView.swift +++ b/AllServerForMac/Features/SceneExtraction/Views/CandidateListView.swift @@ -33,7 +33,7 @@ struct CandidateListView: View { } var body: some View { - GroupBox("候補区間") { + SectionCard(title: "候補区間") { if candidates.isEmpty { ContentUnavailableView( "候補がありません", @@ -61,9 +61,9 @@ struct CandidateListView: View { HStack(spacing: 10) { VStack(alignment: .leading, spacing: 2) { Text(positionText) - .font(.headline.monospacedDigit()) + .font(.appHeadline.monospacedDigit()) Text("判定済み \(reviewedCount)/\(candidates.count)") - .font(.caption) + .font(.appCaption) .foregroundStyle(.secondary) } .frame(minWidth: 105, alignment: .leading) @@ -129,9 +129,9 @@ struct CandidateListView: View { VStack(alignment: .leading, spacing: 4) { HStack(spacing: 10) { Text("ピーク \(timeText(candidate.peakTime))") - .font(.headline) + .font(.appBody.weight(.semibold)) Text(String(format: "score %.3f", candidate.score)) - .font(.system(.caption, design: .monospaced)) + .font(.system(size: 12, design: .monospaced)) .foregroundStyle(.secondary) labelBadge(candidate.userLabel) } @@ -156,20 +156,21 @@ struct CandidateListView: View { format: .number.precision(.fractionLength(2)) ) } - .font(.system(.caption, design: .monospaced)) + .font(.system(size: 12, design: .monospaced)) .textFieldStyle(.roundedBorder) .frame(maxWidth: 245) Text(candidate.reason.joined(separator: ",")) - .font(.caption) + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) .lineLimit(1) } Spacer() Text(String(format: "A %.2f B %.2f C %.2f", candidate.audioScore, candidate.visualScore, candidate.transitionScore)) - .font(.system(.caption2, design: .monospaced)) - .foregroundStyle(.secondary) + .font(.system(size: 11, design: .monospaced)) + .foregroundStyle(NeomorphicTheme.muted) HStack(spacing: 5) { ForEach(CandidateLabel.allCases, id: \.self) { label in @@ -189,7 +190,12 @@ struct CandidateListView: View { .padding(10) .background( RoundedRectangle(cornerRadius: 8, style: .continuous) - .fill(candidate.id == selectedCandidateID ? Color.accentColor.opacity(0.15) : Color.secondary.opacity(0.08)) + .fill(candidate.id == selectedCandidateID ? NeomorphicTheme.selection : NeomorphicTheme.control) + ) + .overlay( + // 選んでいる行は、面の明るさに加えて細い青の縁で示す(選択の目印)。 + RoundedRectangle(cornerRadius: 8, style: .continuous) + .strokeBorder(candidate.id == selectedCandidateID ? NeomorphicTheme.accent.opacity(0.8) : Color.clear, lineWidth: 1) ) .contentShape(Rectangle()) .onTapGesture { @@ -209,15 +215,16 @@ struct CandidateListView: View { } label: { VStack(spacing: 2) { Label(label.displayName, systemImage: labelIcon(label)) - .font(.headline) + .font(.appHeadline) Text("キー \(shortcut)") - .font(.caption2.monospaced()) + .font(.appMicro.monospaced()) .opacity(0.85) } .frame(minWidth: 86) .padding(.vertical, 5) } - .buttonStyle(.borderedProminent) + // 塗りつぶさず、色は文字と薄い面だけにする(3色の塗りが並ぶと、判定ボタンが画面で一番目立ってしまう)。 + .buttonStyle(.bordered) .tint(labelColor(label)) } @@ -250,13 +257,13 @@ struct CandidateListView: View { private func labelBadge(_ label: CandidateLabel?) -> some View { Text(label?.displayName ?? "未判定") - .font(.caption2.weight(.semibold)) - .foregroundStyle(label.map(labelColor) ?? Color.secondary) + .font(.appMicro.weight(.semibold)) + .foregroundStyle(label.map(labelColor) ?? NeomorphicTheme.muted) .padding(.horizontal, 7) .padding(.vertical, 2) .background( Capsule() - .fill((label.map(labelColor) ?? Color.secondary).opacity(0.12)) + .fill((label.map(labelColor) ?? NeomorphicTheme.muted).opacity(0.14)) ) } @@ -297,11 +304,11 @@ struct CandidateListView: View { private func labelColor(_ label: CandidateLabel) -> Color { switch label { case .accepted: - return .green + return NeomorphicTheme.online case .rejected: - return .red + return NeomorphicTheme.negative case .uncertain: - return .orange + return NeomorphicTheme.caution } } diff --git a/AllServerForMac/Features/SceneExtraction/Views/CandidateTimelineView.swift b/AllServerForMac/Features/SceneExtraction/Views/CandidateTimelineView.swift index f38e945..dd8728d 100644 --- a/AllServerForMac/Features/SceneExtraction/Views/CandidateTimelineView.swift +++ b/AllServerForMac/Features/SceneExtraction/Views/CandidateTimelineView.swift @@ -20,8 +20,8 @@ struct CandidateTimelineView: View { let width = geometry.size.width ZStack(alignment: .leading) { - RoundedRectangle(cornerRadius: 7, style: .continuous) - .fill(.black.opacity(0.3)) + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(NeomorphicTheme.control) timelineTicks(width: width) @@ -62,8 +62,8 @@ struct CandidateTimelineView: View { .fill(.white.opacity(0.2)) .frame(width: 1, height: 28) Text(timeText(tickTime)) - .font(.system(size: 9, design: .monospaced)) - .foregroundStyle(.white.opacity(0.65)) + .font(.system(size: 11, design: .monospaced)) + .foregroundStyle(NeomorphicTheme.muted) } .offset(x: max(0, xPosition(for: tickTime, width: width) - 18)) .allowsHitTesting(false) @@ -100,13 +100,14 @@ struct CandidateTimelineView: View { private func markerColor(for candidate: CandidateSegment) -> Color { switch candidate.userLabel { case .accepted: - return .green + return NeomorphicTheme.online case .rejected: - return .red + return NeomorphicTheme.negative case .uncertain: - return .yellow + return NeomorphicTheme.caution case nil: - return .orange + // 未判定の候補は色を付けず、判定済みの色(緑・赤・琥珀)だけが目立つようにする。 + return NeomorphicTheme.ink.opacity(0.65) } } diff --git a/AllServerForMac/Features/SceneExtraction/Views/FeatureScoreChartView.swift b/AllServerForMac/Features/SceneExtraction/Views/FeatureScoreChartView.swift index 3c1bbe7..3971555 100644 --- a/AllServerForMac/Features/SceneExtraction/Views/FeatureScoreChartView.swift +++ b/AllServerForMac/Features/SceneExtraction/Views/FeatureScoreChartView.swift @@ -7,7 +7,7 @@ struct FeatureScoreChartView: View { let features: [FeatureVector] var body: some View { - GroupBox("特徴量スコア") { + SectionCard(title: "特徴量スコア") { if features.isEmpty { ContentUnavailableView( "解析結果がありません", @@ -45,6 +45,13 @@ struct FeatureScoreChartView: View { .foregroundStyle(by: .value("系列", "合成")) .lineStyle(StrokeStyle(lineWidth: 2.5)) } + // 音声・映像・遷移は明るさの違う無彩色にし、結論である合成スコアだけを青の太線にする。 + .chartForegroundStyleScale([ + "音声 A": NeomorphicTheme.ink.opacity(0.38), + "映像 B": NeomorphicTheme.ink.opacity(0.58), + "遷移 C": NeomorphicTheme.ink.opacity(0.80), + "合成": NeomorphicTheme.accent, + ]) .chartYScale(domain: 0...1) .chartXAxisLabel("時刻[秒]") .chartYAxisLabel("正規化スコア") diff --git a/AllServerForMac/Features/SceneExtraction/Views/SceneExtractionSettingsView.swift b/AllServerForMac/Features/SceneExtraction/Views/SceneExtractionSettingsView.swift index 30fff74..78eb530 100644 --- a/AllServerForMac/Features/SceneExtraction/Views/SceneExtractionSettingsView.swift +++ b/AllServerForMac/Features/SceneExtraction/Views/SceneExtractionSettingsView.swift @@ -6,8 +6,8 @@ struct SceneExtractionSettingsView: View { @Binding var settings: AnalysisSettings var body: some View { - GroupBox("解析・書き出し設定") { - Form { + SectionCard(title: "解析・書き出し設定") { + VStack(alignment: .leading, spacing: 12) { Grid(alignment: .leading, horizontalSpacing: 12, verticalSpacing: 8) { valueRow("候補区間[秒]") { TextField("秒", value: $settings.clipDuration, format: .number.precision(.fractionLength(1))) @@ -44,18 +44,17 @@ struct SceneExtractionSettingsView: View { } } - Divider() + Rectangle().fill(NeomorphicTheme.separator).frame(height: 0.5) - Toggle("音声を含める", isOn: $settings.includesAudio) - Toggle("HEVCで書き出す", isOn: $settings.usesHEVC) - Toggle("sidecar JSONを出力", isOn: $settings.writesSidecarJSON) - Toggle("特徴量CSVを出力", isOn: $settings.writesDatasetCSV) + SettingToggleRow(title: "音声を含める", isOn: $settings.includesAudio) + SettingToggleRow(title: "HEVCで書き出す", isOn: $settings.usesHEVC) + SettingToggleRow(title: "sidecar JSONを出力", isOn: $settings.writesSidecarJSON) + SettingToggleRow(title: "特徴量CSVを出力", isOn: $settings.writesDatasetCSV) Text(String(format: "実出力時間 %.3f秒", settings.outputDuration)) - .font(.caption) - .foregroundStyle(.secondary) + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) } - .formStyle(.grouped) } } @@ -65,8 +64,8 @@ struct SceneExtractionSettingsView: View { ) -> some View { GridRow { Text(title) - .font(.caption) - .foregroundStyle(.secondary) + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) content() .textFieldStyle(.roundedBorder) .frame(width: 90) diff --git a/AllServerForMac/Features/SceneExtraction/Views/SceneExtractionTutorialView.swift b/AllServerForMac/Features/SceneExtraction/Views/SceneExtractionTutorialView.swift index b87612f..e4fc2c3 100644 --- a/AllServerForMac/Features/SceneExtraction/Views/SceneExtractionTutorialView.swift +++ b/AllServerForMac/Features/SceneExtraction/Views/SceneExtractionTutorialView.swift @@ -202,28 +202,28 @@ struct SceneExtractionTutorialView: View { } } .frame(width: sheetWidth, height: sheetHeight) - .background(NeomorphicTheme.background) + .appSheet() } private var header: some View { HStack(spacing: 16) { VStack(alignment: .leading, spacing: 3) { Text("シーン抽出の使い方") - .font(.title2.bold()) + .font(.appTitle) Text("操作手順と用語の意味をいつでも確認できます.") - .font(.caption) - .foregroundStyle(.secondary) + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) } Spacer() - Picker("表示内容", selection: $selectedSection) { - ForEach(SceneExtractionTutorialSection.allCases) { section in - Text(section.rawValue).tag(section) - } - } - .pickerStyle(.segmented) - .frame(width: 240) + FlatSegmentedControl( + options: Array(SceneExtractionTutorialSection.allCases), + title: { $0.rawValue }, + selection: $selectedSection, + width: 240 + ) + .accessibilityLabel("表示内容") Button("閉じる") { dismiss() @@ -246,20 +246,20 @@ struct SceneExtractionTutorialView: View { VStack(alignment: .leading, spacing: 22) { HStack(alignment: .top, spacing: 18) { Image(systemName: step.systemImage) - .font(.system(size: 36, weight: .semibold)) - .foregroundStyle(Color.accentColor) + .font(.system(size: 30, weight: .light)) + .foregroundStyle(NeomorphicTheme.ink) .frame(width: 58, height: 58) - .background(Color.accentColor.opacity(0.12), in: RoundedRectangle(cornerRadius: 14)) + .background(NeomorphicTheme.control, in: RoundedRectangle(cornerRadius: 14, style: .continuous)) VStack(alignment: .leading, spacing: 7) { Text("STEP \(step.id)") - .font(.caption.bold()) - .foregroundStyle(Color.accentColor) + .font(.system(size: 12, weight: .semibold)) + .foregroundStyle(NeomorphicTheme.muted) Text(step.title) - .font(.title.bold()) + .font(.appLargeTitle) Text(step.summary) - .font(.title3) - .foregroundStyle(.secondary) + .font(.system(size: 15)) + .foregroundStyle(NeomorphicTheme.muted) } } @@ -268,26 +268,27 @@ struct SceneExtractionTutorialView: View { Label { Text(detail) } icon: { - Image(systemName: "checkmark.circle.fill") - .foregroundStyle(Color.accentColor) + Image(systemName: "checkmark.circle") + .foregroundStyle(NeomorphicTheme.muted) } } } - .font(.body) + .font(.appBody) HStack(alignment: .top, spacing: 10) { - Image(systemName: "lightbulb.fill") - .foregroundStyle(.yellow) + Image(systemName: "lightbulb") + .foregroundStyle(NeomorphicTheme.caution) VStack(alignment: .leading, spacing: 3) { Text("ヒント") - .font(.headline) + .font(.appBody.weight(.semibold)) Text(step.tip) - .foregroundStyle(.secondary) + .font(.appBody) + .foregroundStyle(NeomorphicTheme.muted) } } .padding(14) .frame(maxWidth: .infinity, alignment: .leading) - .background(Color.yellow.opacity(0.1), in: RoundedRectangle(cornerRadius: 10)) + .background(NeomorphicTheme.control, in: RoundedRectangle(cornerRadius: 10, style: .continuous)) } .padding(28) } @@ -305,15 +306,17 @@ struct SceneExtractionTutorialView: View { } label: { VStack(spacing: 5) { Text("\(step.id)") - .font(.caption.bold()) + .font(.appCaption.bold()) .frame(width: 28, height: 28) + // いまの手順は白い丸に暗い数字(再生ボタンと同じ表し方)、ほかは薄い面。 .background( - index == selectedStepIndex ? Color.accentColor : Color.secondary.opacity(0.15), + index == selectedStepIndex ? NeomorphicTheme.ink : NeomorphicTheme.control, in: Circle() ) - .foregroundStyle(index == selectedStepIndex ? Color.white : Color.primary) + .foregroundStyle(index == selectedStepIndex ? NeomorphicTheme.canvas : NeomorphicTheme.muted) Text(step.title) - .font(.system(size: 9)) + .font(.appMicro) + .foregroundStyle(index == selectedStepIndex ? NeomorphicTheme.ink : NeomorphicTheme.muted) .lineLimit(1) } .frame(maxWidth: .infinity) @@ -322,7 +325,7 @@ struct SceneExtractionTutorialView: View { if index < SceneExtractionTutorialContent.steps.count - 1 { Rectangle() - .fill(Color.secondary.opacity(0.2)) + .fill(NeomorphicTheme.separator) .frame(width: 18, height: 1) } } @@ -339,8 +342,8 @@ struct SceneExtractionTutorialView: View { Spacer() Text("\(selectedStepIndex + 1) / \(SceneExtractionTutorialContent.steps.count)") - .font(.caption.monospacedDigit()) - .foregroundStyle(.secondary) + .font(.system(size: 12).monospacedDigit()) + .foregroundStyle(NeomorphicTheme.muted) Spacer() @@ -370,6 +373,7 @@ struct SceneExtractionTutorialView: View { Text(category.rawValue).tag(category) } } + .tint(NeomorphicTheme.ink) .frame(width: 160) } .padding(16) @@ -407,27 +411,28 @@ struct SceneExtractionTutorialView: View { VStack(alignment: .leading, spacing: 8) { HStack { Text(glossaryTerm.term) - .font(.headline) + .font(.appBody.weight(.semibold)) Text(glossaryTerm.category.rawValue) - .font(.caption2.bold()) + .font(.system(size: 11, weight: .medium)) + .foregroundStyle(NeomorphicTheme.muted) .padding(.horizontal, 7) .padding(.vertical, 3) - .background(Color.accentColor.opacity(0.12), in: Capsule()) + .background(NeomorphicTheme.control, in: Capsule()) Spacer() if let relatedSetting = glossaryTerm.relatedSetting { Label(relatedSetting, systemImage: "slider.horizontal.3") - .font(.caption) - .foregroundStyle(.secondary) + .font(.appCaption) + .foregroundStyle(NeomorphicTheme.muted) } } Text(glossaryTerm.shortDefinition) - .font(.body.weight(.medium)) + .font(.appBody.weight(.medium)) Text(glossaryTerm.detail) - .font(.callout) - .foregroundStyle(.secondary) + .font(.appBody) + .foregroundStyle(NeomorphicTheme.muted) } .padding(14) .frame(maxWidth: .infinity, alignment: .leading) - .background(Color.secondary.opacity(0.07), in: RoundedRectangle(cornerRadius: 10)) + .background(NeomorphicTheme.card, in: RoundedRectangle(cornerRadius: 12, style: .continuous)) } } diff --git a/AllServerForMac/Features/SceneExtraction/Views/SceneExtractionView.swift b/AllServerForMac/Features/SceneExtraction/Views/SceneExtractionView.swift index ecf0c23..19de828 100644 --- a/AllServerForMac/Features/SceneExtraction/Views/SceneExtractionView.swift +++ b/AllServerForMac/Features/SceneExtraction/Views/SceneExtractionView.swift @@ -20,7 +20,7 @@ struct SceneExtractionView: View { HStack(spacing: 10) { ProgressView(value: progress.fractionCompleted) Text("\(progress.stage.displayName) \(Int(progress.fractionCompleted * 100))%") - .font(.caption) + .font(.appCaption) .foregroundStyle(.secondary) .frame(width: 150, alignment: .trailing) } @@ -107,7 +107,7 @@ struct SceneExtractionView: View { } Text(viewModel.outputDirectoryURL?.path ?? "出力先が選択されていません") - .font(.caption) + .font(.appCaption) .foregroundStyle(.secondary) .lineLimit(1) .truncationMode(.middle) @@ -121,7 +121,7 @@ struct SceneExtractionView: View { if viewModel.isExportingClip { Text("クリップを作成中です.完了後に最終MP4が表示されます.") - .font(.caption) + .font(.appCaption) .foregroundStyle(.secondary) Button(role: .cancel) { @@ -165,6 +165,9 @@ struct SceneExtractionView: View { } label: { Label("候補を解析", systemImage: "waveform.path.ecg") } + // この画面の主役の操作なので、ここだけ青の塗りにする。 + .buttonStyle(.borderedProminent) + .tint(NeomorphicTheme.accent) .disabled(viewModel.videoDocument == nil || viewModel.isLoadingVideo) } @@ -189,10 +192,10 @@ struct SceneExtractionView: View { if let document = viewModel.videoDocument { VStack(alignment: .trailing, spacing: 2) { Text(document.url.lastPathComponent) - .font(.headline) + .font(.appHeadline) .lineLimit(1) Text(metadataText(document)) - .font(.caption) + .font(.appCaption) .foregroundStyle(.secondary) } } diff --git a/AllServerForMac/Features/Server/Services/WebClientHTML.swift b/AllServerForMac/Features/Server/Services/WebClientHTML.swift index f2a8ab4..433e27d 100644 --- a/AllServerForMac/Features/Server/Services/WebClientHTML.swift +++ b/AllServerForMac/Features/Server/Services/WebClientHTML.swift @@ -12,8 +12,8 @@ enum WebClientHTML { "start_url": "/#home", "scope": "/", "display": "standalone", - "background_color": "#0D0D14", - "theme_color": "#0D0D14", + "background_color": "#1B1B1B", + "theme_color": "#1B1B1B", "icons": [ { "src": "/pwa-icon.png", "sizes": "512x512", "type": "image/png", "purpose": "any maskable" } ] @@ -26,7 +26,7 @@ enum WebClientHTML { - + @@ -35,15 +35,18 @@ enum WebClientHTML { Mac Media Server