From eb386a52c3daa7a6ec49abc2fa174ff975aa5074 Mon Sep 17 00:00:00 2001 From: Scott Garrett Date: Wed, 25 Nov 2026 19:48:34 -0500 Subject: [PATCH] Open and edit Matroska files in place, including track removal .mkv/.mka/.mks now open directly into a tags-only document instead of forcing the convert-import sheet: - Metadata, cover art, and the four per-track fields Matroska stores (name, language, enabled, subtitle forced) save back into the same file via MP42MkvTagWriter; MP4-only properties stay read-only. - Real tracks can be deleted and Save-As is enabled; both go through MP42MkvRemuxer's stream-copy rebuild (Document keeps an importer-order track snapshot and pairs TrackEntry elements by object identity). Destinations must stay .mkv/.mka/.mks. - Info.plist: the Matroska document type becomes Editor so NSDocument offers .mkv Save-As instead of defaulting to the MP4 type. - Delete on MKV docs skips organizeAlternateGroups/ inferMediaCharacteristics because they reorder the model, which the TrackEntry pairing depends on; chapter rows stay undeletable. Bumps MP42Foundation for the Matroska tagging/remux support. Co-Authored-By: Claude Code --- CLAUDE.md | 63 ++++++ Classes/AppDelegate.swift | 5 +- Classes/Document.swift | 181 ++++++++++++++++-- Classes/DocumentWindowController.swift | 61 ++++-- .../PropertyView/ChapterViewController.swift | 8 +- .../PropertyView/MediaTagsController.swift | 10 + .../PropertyView/MovieViewController.swift | 114 +++++++++++ Classes/PropertyView/PropertyView.swift | 34 ++++ .../PropertyView/SoundViewController.swift | 4 + .../PropertyView/VideoViewController.swift | 18 ++ Classes/TracksViewController.swift | 56 +++++- Classes/Utilities.swift | 14 ++ Info.plist | 2 +- MP42Foundation | 2 +- 14 files changed, 540 insertions(+), 32 deletions(-) create mode 100644 CLAUDE.md diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..b22ea93 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,63 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project Overview + +Subler is a macOS AppKit application for muxing and tagging MP4/M4V/M4A files: it demuxes video/audio/subtitle/chapter tracks from mov, mp4, mkv, and raw formats, muxes them into QuickTime-compatible MP4 files (including Apple-compatible tx3g subtitle tracks), and edits metadata with lookups against TMDb, TVDB, and the iTunes Store. + +- App layer (`Classes/`) is pure Swift 5; the app has no storyboards — UI is XIB-based AppKit (`MainMenu.xib` plus per-controller `.xib`/`.strings`). +- All container-level demux/mux/encode work lives in the **MP42Foundation** git submodule (Objective-C/Objective-C++), built as a framework. +- Single app target (`Subler`, legacy productName "MP4Sub", bundle id `org.galad.Subler`), deployment target macOS 10.13. Only external dependency is Sparkle (SPM) for auto-updates. + +## Build + +The MP42Foundation submodule must be initialized or the app will not compile: + +``` +git submodule update --init --recursive +``` + +Build with Xcode (Subler scheme) or CLI: + +``` +xcodebuild -project Subler.xcodeproj -scheme Subler -configuration Debug build MACOSX_DEPLOYMENT_TARGET=12.0 +``` + +Recent Xcode toolchains refuse the projects' 10.13 deployment target on command-line builds; the `MACOSX_DEPLOYMENT_TARGET=12.0` override is CLI-only — don't change the project settings. + +There is **no test target and no CI** — changes are verified by building and running the app manually. The `Utilities/` tools (MP4Dump legacy ObjC debugging tool, ParseFilename Perl script) are not part of the app build. + +## Architecture + +Two layers with a strict boundary: + +### 1. App layer (`Classes/`, Swift) + +- **Document flow**: `Document.swift` (NSDocument subclass) owns the opened file; `read(from:)` produces an `MP42File`. `DocumentWindowController` hosts the per-document window (tracks table, property view tabs). Export goes through `Document.save(to:...)` / `SaveOptions` and runs asynchronously; `sendToQueue` hands the document to the queue instead. +- **MKV tags-only mode**: `.mkv/.mka/.mks` open directly (`DocumentController.openDocument` in `AppDelegate.swift` passes them through instead of forcing the convert-import sheet). `Document.isMatroska` then drives everything: the model is an in-memory `MP42File` filled from `MP42FileImporter` in **tagsOnly mode** (`initWithURL:tagsOnly:` — mirrors the file's own `TrackFlagEnabled` instead of the MP4 "first-of-type enabled" heuristic, so untouched tracks don't look edited), Save branches in `Document.writeMatroska`: plain edits rewrite metadata + per-track fields in place via `MP42MkvTagWriter` (never touching clusters), while **deleted tracks or Save-As** trigger a stream-copy rebuild via `MP42MkvRemuxer` (temp file + atomic rename even in place; `hasFileRepresentation == false` still keeps `sendToQueue` on its conversion branch; destination must stay mkv/mka/mks). The remuxer pairs `TrackEntry` elements against `Document.mkvSourceTracks` — an importer-order snapshot taken in `readMatroska` — with keep/drop decided by **object identity**, so the deletion check is immune to model index shifts; after a successful remux the snapshot is re-filtered in the same order. Reordering must never happen on MKV docs (it would break the pairing): drag stays blocked and `DocumentWindowController.delete(tracks:)` skips `organizeAlternateGroups`/`inferMediaCharacteristics` for MKV. Save-As is enabled for MKV; Duplicate/save-and-optimize stay disabled. Track **add/reorder and MP4-only properties stay gated** (`PropertyView.isReadOnly` disables the tabs; metadata tabs stay editable), but real (non-chapter) tracks can be **deleted** (`TracksViewController.deleteSelection` filters chapter rows on MKV; the menu item validates the same rule), and the four fields Matroska actually stores per track are editable and saved — name, language, enabled, subtitle forced. UI split: `TracksViewController.isReadOnly` gates drag/reorder while `isFieldEditable(_:)` re-enables the name/language/enabled cells on real (non-chapter) rows; `PropertyView.allowsTrackEditing` lets `VideoViewController` re-enable just the subtitle forced popup (Never/All only — the per-sample "Any samples" option has no Matroska equivalent). Chapters remain read-only (Chapters-element writing deferred). +- **Queue engine**: `QueueController` (window UI) → `Queue` (serial `DispatchQueue` worker, persists `[QueueItem]` to disk via `NSKeyedArchiver`, holds IOKit sleep assertions while working) → `QueueItem` (imports a source file into an `MP42File`, then muxes to the destination) → `QueueAction` objects (`QueueActionProtocol`, `.pre`/`.post` types) apply individual transformations (set metadata, force subtitles, language fixes, etc.) to a queue item. Watch for `Queue.Working/Completed/Failed/Cancelled` notifications driving UI updates. +- **Import**: `FileImportController` wraps `MP42FileImporter` to let users pick which source tracks to import; `isTrackMuxable` / `trackNeedConversion` (in `Utilities.swift`) gate which tracks pass through vs. get converted. +- **Metadata**: `Classes/MetadataImporters/` holds a `MetadataImporter` protocol with concrete importers (TheMovieDB, TheTVDB, iTunesStore, AppleTV, SquaredTVArt, chapter DBs). Search results (`MetadataResult`/`MetadataResultMap`) are applied onto `MP42Metadata` via `MetadataSearchController`. API tokens are stored/refreshed through `Token.swift`. +- **Presets**: `Preset` / `QueuePreset` / `MetadataPreset` + `PresetManager` — user-defined rule sets that auto-apply actions and metadata to queue items. +- **Preferences**: `Prefs.swift` is the single source of truth for settings — nested enums of `@Stored` / `@StoredEnum` property-wrapped `UserDefaults` keys (defaults are auto-registered at startup). Add new settings here, not ad-hoc `UserDefaults` calls. +- **AppleScript**: `Subler.sdef` defines the scripting dictionary; `ScriptCommand.swift` / `QueueScriptCommand.swift` implement the commands (e.g., "send to queue"). +- **Logging**: `Logger.shared` is the app-wide log sink; `ActivityWindowController` renders the log UI. + +### 2. MP42Foundation (git submodule, own `MP42Foundation.xcodeproj`) + +Referenced by the main project; `MP42Foundation.framework` is linked and copied into the app bundle. Imported throughout the app as `import MP42Foundation`. Key types: `MP42File` (in-memory MP4 model + muxing/writing), `MP42FileImporter` (demuxing mov/mp4/mkv/subtitle sources, FFmpeg-based), track classes (`MP42VideoTrack`, `MP42AudioTrack`, `MP42SubtitleTrack`, `MP42ChapterTrack`), `MP42Metadata` / `MP42MetadataItem`, `MP42AudioMixdown` / `MP42AudioConversionSettings`, `MP42Languages`. + +The app never parses MP4/atom data directly — codec, container, and subtitle-conversion work belongs in the submodule, not in `Classes/`. `Classes/MP42FileAdditions.swift` extends framework types with app-level conveniences. + +Matroska tagging in the submodule: `MP42Ebml` provides EBML vint/ID primitives and a Segment top-level scanner (element extents + Void slack); `MP42MatroskaTagMapping` holds the read/write tag maps shared with `MP42MkvImporter` (reader and writer can't drift — a metadata key with no SimpleTag name in the map is **silently dropped** on save, so any new editable metadata key needs a map entry); `MP42MkvTagWriter.writeMetadata:tracks:` rewrites the `Tags` element, cover-art `AttachedFile`, and per-track `TrackEntry` fields (name/language/enabled/forced) in place (mkvpropedit-style: reuse the old extent + Void padding when the payload fits, otherwise rebuild the file tail with recomputed SeekHead/Cues positions through a temp file + atomic replace; size+mtime staleness guard refuses writes on files changed since open; foreign tag groups, unknown TrackEntry children, and non-cover attachments are preserved verbatim; each TrackEntry is diffed against the model's **effective** values so an untouched save is byte-for-byte a no-op). `MP42MkvTagWriter+Internal.h` (framework-internal, not in the umbrella) shares its kid/file model types and payload builders with `MP42MkvRemuxer`, the stream-copy track-removal engine: it rebuilds the whole file, copying every block verbatim except blocks whose unmarked-vint track number (`MP42Ebml.blockTrackNumberAt:`, ≤255) belongs to a removed track — kept tracks keep their original TrackNumbers, so **gaps after a removal are intentional** and no block header is ever rewritten; clusters are scanned header-only (BlockGroup track decided from a ≤64KB peek at its `Block` child), emptied clusters skipped, the trailing unknown-size cluster materialized; SeekHead is written with 8-wide placeholder positions pwrite-patched at the end, and Cues are regenerated at EOF (per-track `CueTrackPositions` incl. `CueRelativePosition`) only when the source had them; `Info`/`Duration` copy verbatim (may overstate a dropped track) and dangling `DefaultTrackUID`/`ChapterTrackUID` refs are preserved. It refuses multiple Segments, stray unknown-size elements, count mismatches between TrackEntry and the passed-in `sourceTracks`, and zero-remaining-track remuxes. + +Movie-tab fields that have no Matroska-spec tag (Rating, ContentRating, MediaKind, HDVideo, Cast, TVNetwork, TVEpisodeID) round-trip through community-style SimpleTag names `RATING`/`CONTENTRATING`/`MEDIAKIND`/`HD`/`CAST`/`NETWORK`/`EPISODEID`. Array-typed model values (Cast, Director, Producer, Screenwriters) are written joined with `", "` and re-split by the importer. The importer only synthesizes a TVEpisodeID from season/episode on the **conversion** path — in tagsOnly mode a synthesized value would leak into the file as a tag the user never set. + +The Matroska track-field element ids are a trap: the ids that actually work in the wild (libebml/mkvtoolnix/ffmpeg and every reader) are `0x22B59C` = ISO-639-2/B `Language`, `0x22B59D` = BCP-47 `LanguageIETF`, `0xB9` = `TrackFlagEnabled`. The EBML spec's later `0x447A` carries the same ISO value but mkvtoolnix never writes it — `MatroskaParser.c` reads it defensively, the writer normalizes it to `0x22B59C`. Modern mkvtoolnix files may carry **only** `0x22B59D` (mkvmerge derives the ISO code from the IETF tag), so `Language` can be absent; the importer/writer prefer `LanguageIETF` when present and fall back to the ISO element. Match TrackEntry↔model by file order (chapter pseudo-track filtered); a count mismatch refuses the write. + +## Cross-cutting concerns + +- **Sandbox vs non-sandbox builds**: `#if SB_SANDBOX` guards App Store code paths (security-scoped bookmarks via `MP42SecurityAccessToken`); the default build is the non-sandboxed Sparkle-updatable variant (`Subler.entitlements` exist for the sandboxed config). +- **Localization**: 183 `.strings` files live in per-locale `.lproj` directories scattered next to the code/XIBs they localize (repo root, `Classes/`, `Classes/PropertyView/`), not one central file. Locales: Base (English), it, fr, es-419, pt-BR, zh-CN, zh-Hans. When adding a UI string, find the sibling `.strings` used by that XIB/view. +- **Static data**: `Resources/*.json` — `Alpha2.json` (ISO language codes, used by `LanguageTransformer`), `iTunesStores.json`, `Storefronts.json`, `Ratings.json`. diff --git a/Classes/AppDelegate.swift b/Classes/AppDelegate.swift index 00f3060..0220d58 100644 --- a/Classes/AppDelegate.swift +++ b/Classes/AppDelegate.swift @@ -40,7 +40,10 @@ final class DocumentController : NSDocumentController { override func openDocument(withContentsOf url: URL, display displayDocument: Bool, completionHandler: @escaping (NSDocument?, Bool, Error?) -> Void) { let ext = url.pathExtension.lowercased() - if ["mkv", "mka", "mks", "mov", "264", "h264"].contains(ext) { + // Matroska files open directly as tags-only documents (see + // Document.read); the remaining formats below can only be converted + // to MP4, so offer the import sheet on a fresh untitled document. + if ["mov", "264", "h264"].contains(ext) { do { let doc = try self.openUntitledDocumentAndDisplay(displayDocument) completionHandler(doc, false, nil) diff --git a/Classes/Document.swift b/Classes/Document.swift index a8dc15b..997ef50 100644 --- a/Classes/Document.swift +++ b/Classes/Document.swift @@ -15,6 +15,20 @@ final class Document: NSDocument { private(set) var mp4: MP42File private var unsupportedMp4Brand: Bool + // Matroska documents open in tags-only mode: the model is an in-memory + // MP42File whose tracks are demuxed for display and whose metadata is + // written back into the original file (Tags + cover attachment) by + // MP42MkvTagWriter on save. + private(set) var isMatroska = false + private var mkvWriter: MP42MkvTagWriter? + private var mkvRemuxer: MP42MkvRemuxer? + // Tracks exactly as the importer produced them (file order, chapter + // pseudo-track filtered): the baseline MP42MkvRemuxer pairs TrackEntry + // elements against, so a deleted track is detected by object identity. + private var mkvSourceTracks: [MP42Track] = [] + private var mkvFileSize: UInt64 = 0 + private var mkvFileModificationDate: Date? + override init() { self.cancelled = false self.options = [:] @@ -60,6 +74,11 @@ final class Document: NSDocument { override public var isEntireFileLoaded: Bool { get { return false } } override func read(from url: URL, ofType typeName: String) throws { + if MP42FileImporter.isMatroskaFileType(url.pathExtension) { + try readMatroska(from: url) + return + } + do { mp4 = try MP42File(url: url) mp4.undo = undoManager @@ -69,8 +88,12 @@ final class Document: NSDocument { } override func revert(toContentsOf url: URL, ofType typeName: String) throws { - mp4 = try MP42File(url: url) - mp4.undo = undoManager + if isMatroska || MP42FileImporter.isMatroskaFileType(url.pathExtension) { + try readMatroska(from: url) + } else { + mp4 = try MP42File(url: url) + mp4.undo = undoManager + } if let docController = windowControllers.first as? DocumentWindowController { docController.reloadData() @@ -80,6 +103,60 @@ final class Document: NSDocument { updateChangeCount(.changeCleared) } + private func readMatroska(from url: URL) throws { + // tagsOnly: the importer mirrors the file's own track flags instead of + // applying the MP4 conversion heuristic, so the model matches the file + // (MP42MkvTagWriter diffs track fields against it on save). + let importer = try MP42FileImporter(url: url, tagsOnly: true) + let file = MP42File() + file.metadata.merge(importer.metadata, overwrite: true) + var displayTrackId: MP42TrackId = 0 + for track in importer.tracks { + // -[MP42File addTrack:] asserts that tracks whose codec cannot be + // muxed into MP4 as-is (mp3, vorbis, srt, pgs, …) carry conversion + // settings. Tags-only documents never mux these tracks, but + // satisfy the invariant with the same defaults the convert-import + // flow uses (see FileImportController.addTracks). + if trackNeedConversion(track.format), track.isMember(of: MP42ChapterTrack.self) == false { + switch track { + case let audioTrack as MP42AudioTrack: + audioTrack.conversionSettings = MP42AudioConversionSettings.audioConversion(withBitRate: Prefs.audioBitrate, + mixDown: MP42AudioMixdown(Prefs.audioMixdown), + drc: Prefs.audioDRC) + case let subtitleTrack as MP42SubtitleTrack: + subtitleTrack.conversionSettings = MP42ConversionSettings.subtitlesConversion() + default: + break + } + } + file.addTrack(track) + // addTrack: zeroes trackId (pending-mux bookkeeping, the real + // IDs come from the muxer) and tags-only documents are never + // muxed, so assign display IDs 1-based like MKV players number + // tracks. The chapter track is numbered too, matching how the + // muxer would eventually number it. + // (file.undo is not wired yet at this point, so this does not + // open an undo group.) + displayTrackId += 1 + track.trackId = displayTrackId + } + mp4 = file + mp4.undo = undoManager + isMatroska = true + // Order-sensitive snapshot for the remuxer's TrackEntry pairing; the + // chapter pseudo-track has no TrackEntry and must not shift positions. + mkvSourceTracks = importer.tracks.filter { $0.isMember(of: MP42ChapterTrack.self) == false } + snapshotMatroskaFile(at: url) + } + + // The tag writer refuses to overwrite a file that changed on disk since + // we read it; NSDocument doesn't perform that check for us here. + private func snapshotMatroskaFile(at url: URL) { + let attributes = try? FileManager.default.attributesOfItem(atPath: url.path) + mkvFileSize = (attributes?[.size] as? NSNumber)?.uint64Value ?? 0 + mkvFileModificationDate = attributes?[.modificationDate] as? Date + } + // MARK: Save override nonisolated class var autosavesInPlace: Bool { return false } @@ -125,6 +202,12 @@ final class Document: NSDocument { if let error = error { completionHandler(error); + } else if self.isMatroska { + // The file was retagged in place; the tracks in the model are + // still the ones on disk, so only the undo stack needs reset. + self.undoManager?.removeAllActions() + docController?.reloadData() + completionHandler(error) } else { do { let reloadedFile = try MP42File(url: url) @@ -148,6 +231,8 @@ final class Document: NSDocument { func cancelSave() { cancelled = true + mkvWriter?.cancel() + mkvRemuxer?.cancel() mp4.cancel() } @@ -173,6 +258,20 @@ final class Document: NSDocument { unblockUserInteraction() preventSleep() + defer { + allowSleep() + optimize = false + options = [:] + mkvWriter = nil + mkvRemuxer = nil + } + + if isMatroska { + try writeMatroska(to: url, for: saveOperation) + cancelled = false + return + } + if Prefs.organizeAlternateGroups { mp4.organizeAlternateGroups() if Prefs.inferMediaCharacteristics { @@ -181,19 +280,14 @@ final class Document: NSDocument { } } - defer { - allowSleep() - optimize = false - options = [:] - } - switch saveOperation { case .saveOperation: try mp4.update(options: options) case .saveAsOperation: try mp4.write(to: url, options: options) default: - fatalError("Unsupported save operation") + throw NSError(domain: NSCocoaErrorDomain, code: NSFileWriteUnknownError, + userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("The save operation is not supported.", comment: "Document unsupported save operation error.")]) } if optimize && cancelled == false { @@ -207,6 +301,67 @@ final class Document: NSDocument { cancelled = false } + private func writeMatroska(to url: URL, for saveOperation: NSDocument.SaveOperationType) throws { + guard MP42FileImporter.isMatroskaFileType(url.pathExtension) else { + throw NSError(domain: NSCocoaErrorDomain, code: NSFileWriteUnknownError, + userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("Matroska documents can only be saved as a .mkv, .mka or .mks file.", comment: "Document MKV save destination type error.")]) + } + + let currentTracks = mp4.tracks.filter { $0.isMember(of: MP42ChapterTrack.self) == false } + // Structural change == some importer-created track is gone. Tracks are + // paired by object identity, so a reordered (impossible: reorder is + // gated on MKV docs) or merely renamed track still compares equal. + let tracksRemoved = currentTracks.count != mkvSourceTracks.count || + currentTracks.contains { track in mkvSourceTracks.contains(where: { $0 === track }) == false } + + if tracksRemoved || saveOperation != .saveOperation { + try remuxMatroska(to: url, currentTracks: currentTracks) + return + } + + let writer = MP42MkvTagWriter(url: url) + writer.expectedFileSize = mkvFileSize + writer.expectedModificationDate = mkvFileModificationDate + // The save sheet listens on the model's progress handler (see + // DocumentWindowController.startProgressReporting); forward through it. + writer.progressHandler = { [weak self] progress in + self?.mp4.progressHandler?(progress) + } + mkvWriter = writer + // Track edits (name/language/enabled/subtitle forced) ride along; the + // chapter pseudo-track is skipped by the writer. + try writer.write(mp4.metadata, tracks: mp4.tracks) + mkvWriter = nil + // The file we just wrote is the new baseline for the staleness check. + snapshotMatroskaFile(at: url) + } + + // Stream-copy rebuild: blocks are copied verbatim except those of removed + // tracks, and metadata/cover/track-field edits ride in the same pass. + // Writes a temp file and renames atomically; see MP42MkvRemuxer.h. + private func remuxMatroska(to url: URL, currentTracks: [MP42Track]) throws { + guard let sourceURL = fileURL else { + throw NSError(domain: NSCocoaErrorDomain, code: NSFileWriteUnknownError, + userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("The Matroska source file is unknown.", comment: "Document MKV remux missing source error.")]) + } + let remuxer = MP42MkvRemuxer(sourceURL: sourceURL) + remuxer.expectedFileSize = mkvFileSize + remuxer.expectedModificationDate = mkvFileModificationDate + remuxer.progressHandler = { [weak self] progress in + self?.mp4.progressHandler?(progress) + } + mkvRemuxer = remuxer + try remuxer.remux(to: url, metadata: mp4.metadata, + sourceTracks: mkvSourceTracks, currentTracks: currentTracks) + mkvRemuxer = nil + // The output keeps the surviving TrackEntry elements in source file + // order, so re-snapshot the pairing baseline in that same order. + mkvSourceTracks = mkvSourceTracks.filter { track in + currentTracks.contains(where: { $0 === track }) + } + snapshotMatroskaFile(at: url) + } + // MARK: Save panel private var accessoryViewController: SaveOptions? @@ -267,8 +422,12 @@ final class Document: NSDocument { return true case #selector(save(_:)) where isDocumentEdited == true: return true - case #selector(saveAs(_:)), - #selector(sendToQueue(_:)): + case #selector(saveAs(_:)): + // MKV Save-As runs through MP42MkvRemuxer (stream copy, same + // container — the destination must stay .mkv/.mka/.mks, checked + // in writeMatroska). + return true + case #selector(sendToQueue(_:)): return true case #selector(saveAndOptimize(_:)) where isDocumentEdited == false && mp4.hasFileRepresentation == true: return true diff --git a/Classes/DocumentWindowController.swift b/Classes/DocumentWindowController.swift index 1a144e0..01bd4d4 100644 --- a/Classes/DocumentWindowController.swift +++ b/Classes/DocumentWindowController.swift @@ -235,15 +235,38 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac trackViewController.view.autoresizingMask = [NSView.AutoresizingMask.width, NSView.AutoresizingMask.height] detailsItem.viewController.view.addSubview(trackViewController.view) + // Tags-only mode: tracks are displayed but cannot be modified, except + // for the fields MP42MkvTagWriter writes back (see allowsTrackEditing). + // Set after the view is loaded so it wins over controls that the view + // controllers enable during their own updates. + trackViewController.isMatroskaDocument = doc.isMatroska + if doc.isMatroska, !(trackViewController is MovieViewController) { + trackViewController.allowsTrackEditing = true + trackViewController.isReadOnly = true + } else { + trackViewController.allowsTrackEditing = false + trackViewController.isReadOnly = false + } + selectTabViewItem(for: trackViewController) } func delete(tracks: [MP42Track]) { + var tracks = tracks + if doc.isMatroska { + // Only real tracks are deletable on tags-only documents; the save + // path stream-copy-remuxes their blocks away (MP42MkvRemuxer). + tracks = tracks.filter { $0.isMember(of: MP42ChapterTrack.self) == false } + } if tracks.isEmpty == false { mp4.removeTracks(tracks) - if Prefs.organizeAlternateGroups { mp4.organizeAlternateGroups() } - if Prefs.inferMediaCharacteristics { mp4.inferMediaCharacteristics() } + if doc.isMatroska == false { + // Both heuristics reorder the track model, which would break + // the TrackEntry/order pairing the MKV writers depend on. + if Prefs.organizeAlternateGroups { mp4.organizeAlternateGroups() } + if Prefs.inferMediaCharacteristics { mp4.inferMediaCharacteristics() } + } tracksViewController.reloadData() } @@ -254,22 +277,25 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool { switch item.action { - case #selector(selectFile(_:)), - #selector(selectMetadataFile(_:)), + case #selector(selectMetadataFile(_:)), #selector(searchMetadata(_:)), + #selector(sendToQueue(_:)): + return true + + // Track/chapter modifications: unavailable in Matroska tags-only mode. + case #selector(selectFile(_:)), #selector(searchChapters(_:)), #selector(addChaptersEvery(_:)), #selector(iTunesFriendlyTrackGroups(_:)), #selector(clearTrackNames(_:)), #selector(prettifyAudioTrackNames(_:)), - #selector(fixAudioFallbacks(_:)), - #selector(sendToQueue(_:)): - return true + #selector(fixAudioFallbacks(_:)): + return !doc.isMatroska case #selector(sendToExternalApp(_:)) where mp4.hasFileRepresentation && doc.isDocumentEdited == false: return true - case #selector(showTrackOffsetSheet(_:)) where tracksViewController.selectedTracks.isEmpty == false: + case #selector(showTrackOffsetSheet(_:)) where doc.isMatroska == false && tracksViewController.selectedTracks.isEmpty == false: return true case #selector(export(_:)) where tracksViewController.selectedTracks.isEmpty == false: @@ -280,7 +306,12 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac } case #selector(DocumentWindowController.deleteTrack(_:)): - return tracksViewController.selectedTracks.isEmpty == false && NSApp.isActive + // MKV documents allow deleting real tracks (stream-copy remux on + // save); a chapter-row-only or empty selection stays invalid. + let hasDeletable = tracksViewController.selectedTracks.contains { + doc.isMatroska == false || $0.isMember(of: MP42ChapterTrack.self) == false + } + return hasDeletable && NSApp.isActive default: return false @@ -558,6 +589,8 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac } func showImportSheet(fileURLs: [URL]) { + guard doc.isMatroska == false else { return } + do { let controller = try FileImportController(fileURLs: fileURLs, delegate: self) @@ -639,9 +672,13 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac let items = pasteboard.readObjects(forClasses: [NSURL.classForCoder()], options: [:]) as? [URL] else { return false } - let chapters = items.filter { $0.pathExtension.lowercased() == "txt" } - if let url = chapters.first { - addChapters(fileURL: url) + // Metadata drops are fine in tags-only mode; chapter and track + // imports modify tracks, which Matroska documents cannot do. + if doc.isMatroska == false { + let chapters = items.filter { $0.pathExtension.lowercased() == "txt" } + if let url = chapters.first { + addChapters(fileURL: url) + } } let metadata = items.filter { let ext = $0.pathExtension.lowercased(); return ext == "xml" || ext == "nfo" } diff --git a/Classes/PropertyView/ChapterViewController.swift b/Classes/PropertyView/ChapterViewController.swift index 9463424..afc53af 100644 --- a/Classes/PropertyView/ChapterViewController.swift +++ b/Classes/PropertyView/ChapterViewController.swift @@ -76,7 +76,11 @@ final class ChapterViewController : PropertyView, NSTableViewDataSource, NSTable } func tableViewSelectionDidChange(_ notification: Notification) { - removeChapter.isEnabled = tableView.selectedRow != -1 ? true : false + removeChapter.isEnabled = tableView.selectedRow != -1 && isReadOnly == false + } + + func tableView(_ tableView: NSTableView, shouldEdit tableColumn: NSTableColumn?, row: Int) -> Bool { + return isReadOnly == false } @IBAction func setChapterTitle(_ sender: NSTextField) { @@ -101,12 +105,14 @@ final class ChapterViewController : PropertyView, NSTableViewDataSource, NSTable } @IBAction func doubleClickAction(_ sender: NSTableView) { + guard isReadOnly == false else { return } if sender.clickedRow > -1 && sender.clickedColumn > -1 { sender.editColumn(sender.clickedColumn, row: sender.clickedRow, with: nil, select: true) } } func deleteSelection(in tableview: NSTableView) { + guard isReadOnly == false else { return } let indexes = tableView.selectedRowIndexes if indexes.isEmpty == false { track.removeChapters(at: indexes) diff --git a/Classes/PropertyView/MediaTagsController.swift b/Classes/PropertyView/MediaTagsController.swift index 8fc5358..917f8b7 100644 --- a/Classes/PropertyView/MediaTagsController.swift +++ b/Classes/PropertyView/MediaTagsController.swift @@ -101,6 +101,15 @@ final class MediaTagsController: NSViewController, NSTableViewDataSource, NSTabl } private var tags: [MediaTag] + /// Propagated from the hosting PropertyView (Matroska tags-only mode). + var isReadOnly = false { + didSet { + if isViewLoaded, isReadOnly != oldValue { + tableView.reloadData() + } + } + } + override var nibName: NSNib.Name? { return "MediaTagsController" } @@ -162,6 +171,7 @@ final class MediaTagsController: NSViewController, NSTableViewDataSource, NSTabl func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let view = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "SBCheckBoxTableCellView"), owner: self) as? CheckBoxTableCellView view?.representedTag = tags[row] + view?.checkBox.isEnabled = !isReadOnly return view } diff --git a/Classes/PropertyView/MovieViewController.swift b/Classes/PropertyView/MovieViewController.swift index 1361a66..472201d 100644 --- a/Classes/PropertyView/MovieViewController.swift +++ b/Classes/PropertyView/MovieViewController.swift @@ -122,6 +122,12 @@ class MovieViewController: PropertyView, NSTableViewDataSource, ExpandedTableVie } } + // The document may already be known to be Matroska (the flag is set + // after this view loads in DocumentWindowController, but subclasses + // of the preset editor never set it — the viewDidLoad pass keeps + // this view correct either way). + updateMatroskaFieldHints() + if #available(macOS 26, *) { setsPopUp.menu?.items.first?.image = NSImage.init(systemSymbolName: "ellipsis", accessibilityDescription: nil) } @@ -165,6 +171,59 @@ class MovieViewController: PropertyView, NSTableViewDataSource, ExpandedTableVie removeTagButton.isEnabled = self.metadataTableView.selectedRow != -1 } + // MARK: Matroska field hints + + /// Fonts used to flag metadata fields that `MP42MkvTagWriter` cannot save + /// (MP4-only keys). They stay selectable on purpose: an MKV document can + /// still be converted to MP4 via the queue, where these values do apply. + private static let italicMenuFont: NSFont = { + return NSFontManager.shared.convert(NSFont.menuFont(ofSize: 0), toHaveTrait: .italicFontMask) + }() + + private func isPersistedInMatroska(identifier: String) -> Bool { + return MP42MkvMetadataKeyIsPersisted(identifier) + } + + override func updateMatroskaFieldHints() { + guard isViewLoaded else { return } + + if let menu = tagsPopUp.menu { + let identifiers = MP42Metadata.writableMetadata + for item in menu.items where item.isHidden == false && item.tag >= 0 && item.tag < identifiers.count { + if isMatroskaDocument && !isPersistedInMatroska(identifier: identifiers[item.tag]) { + item.attributedTitle = NSAttributedString(string: item.title, attributes: [ + .font: MovieViewController.italicMenuFont, + .foregroundColor: NSColor.secondaryLabelColor, + ]) + item.toolTip = NSLocalizedString("This field cannot be saved to a Matroska file.", + comment: "Metadata tag menu hint for MP4-only fields") + // Italics/color are invisible to assistive tech; carry the + // hint in the accessibility label too. + item.setAccessibilityLabel(item.title + ", " + NSLocalizedString("cannot be saved to a Matroska file", + comment: "Metadata tag menu hint for MP4-only fields")) + } else { + // Empty attributed title: AppKit falls back to `title`. + item.attributedTitle = NSAttributedString(string: "") + item.toolTip = nil + item.setAccessibilityLabel(nil) + } + } + // Track # and TV Episode # share the single PART_NUMBER tag on + // Matroska files (see syncMatroskaEpisodeFields) — say so. + if isMatroskaDocument { + for key in [MP42MetadataKeyTrackNumber, MP42MetadataKeyTVEpisodeNumber] { + // items are addressed by tag, not position: the pulls-down + // title item occupies position 0 + if let index = identifiers.firstIndex(of: key), + let item = menu.items.first(where: { $0.isHidden == false && $0.tag == index }) { + item.toolTip = NSLocalizedString("In Matroska files these two fields share one tag: editing either updates both.", + comment: "Metadata tag menu note for Track #/TV Episode #") + } + } + } + } + } + // MARK: Metadata private func updateMetadataArray() { @@ -539,6 +598,19 @@ class MovieViewController: PropertyView, NSTableViewDataSource, ExpandedTableVie else { cell?.textField?.textColor = .disabledControlTextColor } + if let textField = cell?.textField { + // Cells are reused: strip any italic from a previous row first, + // then italicize MP4-only fields on Matroska documents. + let baseFont = NSFontManager.shared.convert(textField.font ?? NSFont.systemFont(ofSize: 0), + toNotHaveTrait: .italicFontMask) + let flagField = isMatroskaDocument && !isPersistedInMatroska(identifier: item.identifier) + textField.font = flagField ? NSFontManager.shared.convert(baseFont, toHaveTrait: .italicFontMask) : baseFont + let label = localizedMetadataKeyName(item.identifier) ?? item.identifier + textField.setAccessibilityLabel(flagField ? + label + ", " + NSLocalizedString("cannot be saved to a Matroska file", + comment: "Metadata field hint for MP4-only fields") : + nil) + } return cell } else if tableColumn?.identifier == valueColumn { @@ -665,6 +737,48 @@ class MovieViewController: PropertyView, NSTableViewDataSource, ExpandedTableVie let editedItem = MP42MetadataItem(identifier: item.identifier, value: value as! NSCopying & NSObjectProtocol, dataType: type, extendedLanguageTag: item.extendedLanguageTag) replace(metadataItem: item, withItem: editedItem) + syncMatroskaEpisodeFields(from: editedItem) + } + + /// Matroska stores a single movie-level `PART_NUMBER` tag, and the importer + /// fills both Track # and TV Episode # from it. On Matroska documents the + /// two rows must therefore move together: whichever one the user edits + /// updates the other, so the edit is what `MP42MkvTagWriter` regenerates + /// `PART_NUMBER` from. No-op on MP4 documents, where the two are separate + /// atoms. + private func syncMatroskaEpisodeFields(from editedItem: MP42MetadataItem) { + guard isMatroskaDocument else { return } + + let numbers = (editedItem.arrayValue as? [Any])?.compactMap { ($0 as? NSNumber)?.intValue } ?? [] + + switch editedItem.identifier { + case MP42MetadataKeyTrackNumber: + let newIndex = numbers.first ?? 0 + guard let episode = metadata.metadataItemsFiltered(byIdentifier: MP42MetadataKeyTVEpisodeNumber).first, + episode.numberValue?.intValue != newIndex else { return } + let replacement = MP42MetadataItem(identifier: MP42MetadataKeyTVEpisodeNumber, + value: NSNumber(value: newIndex) as NSCopying & NSObjectProtocol, + dataType: episode.dataType, + extendedLanguageTag: episode.extendedLanguageTag) + replace(metadataItem: episode, withItem: replacement) + + case MP42MetadataKeyTVEpisodeNumber: + let newNumber = editedItem.numberValue?.intValue ?? 0 + guard let track = metadata.metadataItemsFiltered(byIdentifier: MP42MetadataKeyTrackNumber).first else { + return // no Track # row: the writer falls back to TV Episode # itself + } + let parts = (track.arrayValue as? [Any])?.compactMap { ($0 as? NSNumber)?.intValue } ?? [] + let total = parts.count > 1 ? parts[1] : 0 + guard (parts.first ?? 0) != newNumber else { return } + let replacement = MP42MetadataItem(identifier: MP42MetadataKeyTrackNumber, + value: [NSNumber(value: newNumber), NSNumber(value: total)] as NSCopying & NSObjectProtocol, + dataType: .integerArray, + extendedLanguageTag: track.extendedLanguageTag) + replace(metadataItem: track, withItem: replacement) + + default: + break + } } @IBAction func setMetadataBoolValue(_ sender: NSButton) { diff --git a/Classes/PropertyView/PropertyView.swift b/Classes/PropertyView/PropertyView.swift index cdc20b1..768c5a6 100644 --- a/Classes/PropertyView/PropertyView.swift +++ b/Classes/PropertyView/PropertyView.swift @@ -10,6 +10,40 @@ import Cocoa class PropertyView : NSViewController { @IBOutlet var tabView: NSTabView? + /// True when the view must be displayed but not edited (Matroska + /// tags-only documents). Set by DocumentWindowController; subclasses that + /// host tables or re-enable controls dynamically must honor it. + var isReadOnly = false { + didSet { + if isViewLoaded, isReadOnly { + view.setAllControlsEnabled(false) + } + } + } + + /// Companion to `isReadOnly` for Matroska documents: the blanket disable + /// still applies, but subclasses may re-enable the handful of controls + /// whose values `MP42MkvTagWriter` can write back (currently the subtitle + /// forced flag). Never consulted when `isReadOnly` is false. + var allowsTrackEditing = false + + /// True when the document is a Matroska tags-only document. Unlike + /// `isReadOnly` this is set on *every* property view — including the + /// metadata tab, which stays editable — so views can visually flag the + /// fields `MP42MkvTagWriter` cannot save. Subclasses override + /// `updateMatroskaFieldHints()` to apply the styling. + var isMatroskaDocument = false { + didSet { + if isViewLoaded, isMatroskaDocument != oldValue { + updateMatroskaFieldHints() + } + } + } + + /// Hook for `isMatroskaDocument` changes; called by subclasses after + /// their views are loaded too. Default: nothing to flag. + func updateMatroskaFieldHints() {} + func navigate(direction: Int) { if direction == NSRightArrowFunctionKey { tabView?.selectNextTabViewItem(self) diff --git a/Classes/PropertyView/SoundViewController.swift b/Classes/PropertyView/SoundViewController.swift index 2013a7c..12c6716 100644 --- a/Classes/PropertyView/SoundViewController.swift +++ b/Classes/PropertyView/SoundViewController.swift @@ -20,6 +20,10 @@ final class SoundViewController : PropertyView { let mediaTagsController: MediaTagsController + override var isReadOnly: Bool { + didSet { mediaTagsController.isReadOnly = isReadOnly } + } + @IBOutlet var mediaTagsView: NSView! @IBOutlet var volume: NSSlider! @IBOutlet var alternateGroup: NSPopUpButton! diff --git a/Classes/PropertyView/VideoViewController.swift b/Classes/PropertyView/VideoViewController.swift index caeb1d8..59fea21 100644 --- a/Classes/PropertyView/VideoViewController.swift +++ b/Classes/PropertyView/VideoViewController.swift @@ -20,6 +20,24 @@ final class VideoViewController: PropertyView { private let mediaTagsController: MediaTagsController + override var isReadOnly: Bool { + didSet { + mediaTagsController.isReadOnly = isReadOnly + // Matroska tags-only: FlagForced is writable (Never/All — the + // per-sample "Any samples" option has no Matroska equivalent). + if isReadOnly, allowsTrackEditing, isViewLoaded, track is MP42SubtitleTrack { + let anySamplesIndex = forcedSubs.indexOfItem(withTag: 1) + if anySamplesIndex >= 0 { + forcedSubs.removeItem(at: anySamplesIndex) + } + if forcedSubs.indexOfSelectedItem == -1 { + forcedSubs.selectItem(withTag: 0) + } + forcedSubs.isEnabled = true + } + } + } + override var nibName: NSNib.Name? { return "VideoView" } diff --git a/Classes/TracksViewController.swift b/Classes/TracksViewController.swift index 147bf96..1617583 100644 --- a/Classes/TracksViewController.swift +++ b/Classes/TracksViewController.swift @@ -31,6 +31,21 @@ final class TracksViewController: NSViewController, NSTableViewDataSource, NSTab @IBOutlet var tracksTable: ExpandedTableView! + // In Matroska tags-only mode the track list cannot be structurally + // changed: no deletion, reordering or import. + private var isReadOnly: Bool { + return document.isMatroska + } + + // The per-track fields whose values MP42MkvTagWriter writes back into the + // file's Tracks element (name, language, enabled, subtitle forced) stay + // editable even in tags-only mode; the chapter pseudo-track has no + // Matroska counterpart. + private func isFieldEditable(_ track: MP42Track?) -> Bool { + guard let track = track else { return false } + return document.isMatroska == false || track.isMember(of: MP42ChapterTrack.self) == false + } + private static let languagesMenu: NSMenu = { let menu = NSMenu() menu.autoenablesItems = false @@ -100,16 +115,28 @@ final class TracksViewController: NSViewController, NSTableViewDataSource, NSTab @IBAction func doubleClickAction(_ sender: NSTableView) { // make sure they clicked a real cell and not a header or empty row - if sender.clickedRow >= 1 { + if sender.clickedRow >= 1, let track = track(at: sender.clickedRow) { let column = sender.tableColumns[sender.clickedColumn] - if column.identifier == trackNameColumn { + if column.identifier == trackNameColumn, isFieldEditable(track) { sender.editColumn(sender.clickedColumn, row: sender.clickedRow, with: nil, select: true) } } } func deleteSelection(in tableview: NSTableView) { - delegate?.delete(tracks: selectedTracks) + // On MKV documents real tracks are deletable too (the remuxer drops + // their blocks on save); the chapter pseudo-track still is not. + let deletable = document.isMatroska ? selectedTracks.filter { isFieldEditable($0) } : selectedTracks + guard deletable.isEmpty == false else { return } + delegate?.delete(tracks: deletable) + } + + func tableView(_ tableView: NSTableView, shouldEdit tableColumn: NSTableColumn?, row: Int) -> Bool { + if isReadOnly == false { + return true + } + // tags-only mode still allows inline renaming of real tracks + return tableColumn?.identifier == trackNameColumn && isFieldEditable(track(at: row)) } // MARK: Actions @@ -180,12 +207,13 @@ final class TracksViewController: NSViewController, NSTableViewDataSource, NSTab case trackEnabledColumn?: let cell = tableView.makeView(withIdentifier: trackEnabledColumn, owner:self) as? CheckBoxCellView cell?.checkboxButton?.state = track.isEnabled ? NSControl.StateValue.on : NSControl.StateValue.off + cell?.checkboxButton?.isEnabled = isFieldEditable(track) return cell case trackNameColumn?: let cell = tableView.makeView(withIdentifier: trackNameColumn, owner:self) as? NSTableCellView cell?.textField?.stringValue = track.name - cell?.textField?.isEditable = true + cell?.textField?.isEditable = isFieldEditable(track) return cell case trackDurationColumn?: @@ -208,11 +236,25 @@ final class TracksViewController: NSViewController, NSTableViewDataSource, NSTab } cell?.textField?.stringValue = MP42Languages.defaultManager.localizedLang(forExtendedTag: track.language) + cell?.popUpButton?.isEnabled = isFieldEditable(track) return cell case trackInfoColumn?: let cell = tableView.makeView(withIdentifier: trackInfoColumn, owner:self) as? NSTableCellView - cell?.textField?.stringValue = track.formatSummary + if isReadOnly { + // Tags-only documents never mux, and the default conversion + // settings attached at import (see Document.readMatroska) + // would make formatSummary advertise a conversion target + // instead of the actual source codec. + var summary = localizedDisplayName(track.mediaType, track.format) ?? "Unknown" + if let audioTrack = track as? MP42AudioTrack, audioTrack.channels > 0, + track.format != kMP42AudioCodecType_DTS { + summary = "\(summary), \(audioTrack.channels) ch" + } + cell?.textField?.stringValue = summary + } else { + cell?.textField?.stringValue = track.formatSummary + } return cell default: @@ -260,6 +302,9 @@ final class TracksViewController: NSViewController, NSTableViewDataSource, NSTab func tableView(_ tableView: NSTableView, pasteboardWriterForRow row: Int) -> (any NSPasteboardWriting)? { + if isReadOnly { + return nil + } if let track = track(at: row), track.isMuxed == false { return PasteboardItem(index: row, type: .tableViewIndex) } else { @@ -271,6 +316,7 @@ final class TracksViewController: NSViewController, NSTableViewDataSource, NSTab validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation { + if isReadOnly { return [] } guard dropOperation == .above else { return [] } guard let source = info.draggingSource as? NSTableView, diff --git a/Classes/Utilities.swift b/Classes/Utilities.swift index 5358f54..d9e3754 100644 --- a/Classes/Utilities.swift +++ b/Classes/Utilities.swift @@ -128,3 +128,17 @@ extension String { return matrix[m][n] } } + +extension NSView { + /// Enables or disables every NSControl in this view hierarchy. Used to + /// present the track property views read-only in Matroska (tags-only) + /// documents, where the tracks cannot be modified. + func setAllControlsEnabled(_ enabled: Bool) { + if let control = self as? NSControl { + control.isEnabled = enabled + } + for subview in subviews { + subview.setAllControlsEnabled(enabled) + } + } +} diff --git a/Info.plist b/Info.plist index cf3c3e8..14ba395 100644 --- a/Info.plist +++ b/Info.plist @@ -104,7 +104,7 @@ CFBundleTypeName Matroska video CFBundleTypeRole - Viewer + Editor LSHandlerRank Alternate NSDocumentClass diff --git a/MP42Foundation b/MP42Foundation index 4648f9d..1040f47 160000 --- a/MP42Foundation +++ b/MP42Foundation @@ -1 +1 @@ -Subproject commit 4648f9d585b38957a797bdb13632497abdbe4dfe +Subproject commit 1040f4754233cf590c420e2ee010ec65c5b3ad24