From f457b4e89c244521b5b293c02e413f9925d5ca6f Mon Sep 17 00:00:00 2001 From: Scott Garrett Date: Thu, 26 Nov 2026 18:17:37 -0500 Subject: [PATCH] Make chapter tracks deletable, insertable, and language-editable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Delete: the phase-1 gate against deleting the chapter pseudo-track on Matroska documents is obsolete now that chapter changes ride the stream-copy remuxer — a removed pseudo-track simply makes the model report "no chapters", which removes the Chapters element on save (the same path emptying the Chapters tab already took). The toolbar Delete button's validation is corrected too; it still rejected chapter-only selections after deleteSelection was opened up. Insert: the Actions toolbar gets a single "Insert a chapter" item, and "Insert a chapter every" (previously MP4-only) is enabled on Matroska. Both create the chapter track when the document has none, doing the tags-only bookkeeping the model needs (dense display trackId, updateChangeCount). A single insert lands 1s after the latest start, clamped to the track duration, so it can never tie with a stored chapter — ties get clamped +1ms on write and would silently shift the user's own chapter times. Language: the chapter row's language popup stays editable on MKV documents (the value rides the remuxer's chapter rebuild, not the tag writer, since the pseudo-track has no TrackEntry), and the Matroska chapters snapshot carries it so a language-only edit triggers the remux. Pairs with the submodule's ChapterLanguage round trip. Co-Authored-By: Claude Code --- CLAUDE.md | 4 +- Classes/Document.swift | 24 ++++-- Classes/DocumentToolbarDelegate.swift | 5 ++ Classes/DocumentWindowController.swift | 83 +++++++++++++++---- .../PropertyView/ChapterViewController.swift | 12 +++ Classes/TracksViewController.swift | 18 +++- MP42Foundation | 2 +- es-419.lproj/Localizable.strings | 1 + fr.lproj/Localizable.strings | 1 + it.lproj/Localizable.strings | 1 + pt-BR.lproj/Localizable.strings | 1 + zh-CN.lproj/Localizable.strings | 1 + zh-Hans.lproj/Localizable.strings | 1 + 13 files changed, 124 insertions(+), 30 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index bc43957..0a29eca 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -35,7 +35,7 @@ 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/added 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 **plus the added tracks appended** (matching the order the remuxer writes their TrackEntry elements last in the output). Subtitle tracks can be **added** to MKV docs (`.srt`/`.ssa`/`.ass` only): `DocumentWindowController.selectFile`/`showImportSheet` route MKV docs to `importSubtitleTracksForMatroska` (direct `MP42FileImporter` per file, no track-selection sheet; the accepted-extension list `matroskaSubtitleExtensions` must stay in sync with the remuxer's gate), and the `didSelect`/AppleScript `importFilesDirectly` path skips `organizeAlternateGroups`/`inferMediaCharacteristics` for MKV for the same pairing-protection reason. The AppleScript `save as` command (ScriptCommand.swift) must route Matroska docs through `Document.save(...)` — the raw `mp4.write(to:)` path would mux QuickTime atoms over an MKV document. 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 **reorder and MP4-only properties stay gated** (`PropertyView.isReadOnly` disables the tabs; metadata tabs stay editable; adding stays restricted to the subtitle files and chapter txt/csv described here), 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 are **editable** on MKV docs (`didSelect` exempts `ChapterViewController` from the read-only blanket alongside `MovieViewController`) and chapter-less docs can **gain chapters** via `.txt` import (OGG/mp4chaps format → `addChapters`, which replaces the model's chapter track since `MP42File addTrack:` replaces previous chapter tracks) or update an existing track via `.csv` (`updateChapters`) — routed from `selectFile`'s MKV branch and drag-drop. Chapter changes ride the **remuxer**, not the tag writer: `Document.mkvChaptersSnapshot` (model rows at read/save time; compared model-vs-model because the importer silently drops some atoms — duplicate zero timestamps — so file-vs-model would report phantom edits) drives `chaptersChanged` into the structural condition, and `remuxMatroska` passes `mp4.chapters` (or an empty `MP42ChapterTrack` when the model has none, to delete the element) as the remuxer's `replacementChapters`; nil means verbatim copy. +- **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/added 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 **plus the added tracks appended** (matching the order the remuxer writes their TrackEntry elements last in the output). Subtitle tracks can be **added** to MKV docs (`.srt`/`.ssa`/`.ass` only): `DocumentWindowController.selectFile`/`showImportSheet` route MKV docs to `importSubtitleTracksForMatroska` (direct `MP42FileImporter` per file, no track-selection sheet; the accepted-extension list `matroskaSubtitleExtensions` must stay in sync with the remuxer's gate), and the `didSelect`/AppleScript `importFilesDirectly` path skips `organizeAlternateGroups`/`inferMediaCharacteristics` for MKV for the same pairing-protection reason. The AppleScript `save as` command (ScriptCommand.swift) must route Matroska docs through `Document.save(...)` — the raw `mp4.write(to:)` path would mux QuickTime atoms over an MKV document. 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 **reorder and MP4-only properties stay gated** (`PropertyView.isReadOnly` disables the tabs; metadata tabs stay editable; adding stays restricted to the subtitle files and chapter txt/csv described here), but real tracks **and the chapter pseudo-track** can be **deleted** (deleting the chapter track empties the model, so the save remuxes and removes the `Chapters` element — same as emptying the Chapters tab), 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 are **editable** on MKV docs (`didSelect` exempts `ChapterViewController` from the read-only blanket alongside `MovieViewController`) and chapter-less docs can **gain chapters** via `.txt` import (OGG/mp4chaps format → `addChapters`, which replaces the model's chapter track since `MP42File addTrack:` replaces previous chapter tracks) or update an existing track via `.csv` (`updateChapters`) — routed from `selectFile`'s MKV branch and drag-drop; or one chapter at a time via the Actions toolbar's **Insert a chapter** (`DocumentWindowController.insertChapter`, works on both containers, creates the chapter track when absent and timestamps the new chapter 1s past the latest start clamped to the track duration, so it never ties with — and clamp-cascades — existing chapters) or in bulk via **Insert a chapter every** (`addChaptersEvery`); both do the tags-only trackId/`updateChangeCount` bookkeeping when they create the track, and both work on either container. Chapter changes ride the **remuxer**, not the tag writer: `Document.mkvChaptersSnapshot` (model rows at read/save time; compared model-vs-model because the importer silently drops some atoms — duplicate zero timestamps — so file-vs-model would report phantom edits) drives `chaptersChanged` into the structural condition, and `remuxMatroska` passes `mp4.chapters` (or an empty `MP42ChapterTrack` when the model has none, to delete the element) as the remuxer's `replacementChapters`; nil means verbatim copy. - **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`. @@ -56,7 +56,7 @@ Movie-tab fields that have no Matroska-spec tag (Rating, ContentRating, MediaKin 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. -Chapter elements are their own trap set (all verified empirically against mkvmerge-written files): `ChapterAtom` is `0xB6` — **not** `0xB0`, which is PixelWidth in TrackEntry scope (`MatroskaParser.c` has always parsed 0xB6 correctly; don't "fix" it). Chapter timecodes are absolute **nanoseconds**, not TimecodeScale units like nearly every other Matroska time — libmatroska writes and mkvtoolnix/ffmpeg both read them as ns regardless of segment scale, so the importer's plain `/1e6` to ms and the remuxer's plain `×1e6` back are right. `ChapterUID` (`0x73C4`) is mandatory in practice: ffmpeg **silently skips** atoms without it (mkvtoolnix still lists them, which makes the loss easy to miss); `EditionUID` likewise. The writer derives both deterministically from the chapter content so re-saving unchanged input reproduces the file. Note the reader asymmetry: `MP42MkvImporter` forces the first chapter to 0 and skips non-first zero-timestamp chapters, so atoms it dropped are permanently lost once an edit rewrites the Chapters element. +Chapter elements are their own trap set (all verified empirically against mkvmerge-written files): `ChapterAtom` is `0xB6` — **not** `0xB0`, which is PixelWidth in TrackEntry scope (`MatroskaParser.c` has always parsed 0xB6 correctly; don't "fix" it). Chapter timecodes are absolute **nanoseconds**, not TimecodeScale units like nearly every other Matroska time — libmatroska writes and mkvtoolnix/ffmpeg both read them as ns regardless of segment scale, so the importer's plain `/1e6` to ms and the remuxer's plain `×1e6` back are right. `ChapterUID` (`0x73C4`) is mandatory in practice: ffmpeg **silently skips** atoms without it (mkvtoolnix still lists them, which makes the loss easy to miss); `EditionUID` likewise. The writer derives both deterministically from the chapter content so re-saving unchanged input reproduces the file. Note the reader asymmetry: `MP42MkvImporter` forces the first chapter to 0 and skips non-first zero-timestamp chapters, so atoms it dropped are permanently lost once an edit rewrites the Chapters element. Chapter language round-trips at **track level**: the importer adopts the first `ChapterDisplay/ChapterLanguage` (0x437C) it finds as the model track's `language`, and the remuxer stamps that track language into every atom — omitted when nil/absent or when it maps to ISO `eng` (the spec default; keeps rewrites byte-identical to language-less files). `MP42Languages ISO_639_2CodeForExtendedTag:` answers unknown tags with `"und"`, so a garbage language explicitly writes `und` rather than silently defaulting — extended tags are locale-identifier style (`"en"`, `"it"`), not English names. The chapter-row language popup stays enabled on MKV (`TracksViewController.isLanguageEditable`) because the value rides the remuxer's chapter rebuild, not the tag writer (no TrackEntry), and the `mkvChaptersSnapshot` rows carry the language so a language-only edit flips `chaptersChanged`. Note: `ffprobe -show_chapters` does NOT surface ChapterLanguage in its chapter tags — assert it with `mkvinfo` ("Chapter language: …"). ## Cross-cutting concerns diff --git a/Classes/Document.swift b/Classes/Document.swift index 550f6d2..876e8cd 100644 --- a/Classes/Document.swift +++ b/Classes/Document.swift @@ -26,12 +26,13 @@ final class Document: NSDocument { // pseudo-track filtered): the baseline MP42MkvRemuxer pairs TrackEntry // elements against, so a deleted track is detected by object identity. private var mkvSourceTracks: [MP42Track] = [] - // Chapter rows as the file's baseline holds them (model milliseconds). - // nil when the last read/written file had no chapters. Compared against - // the model on save: model-vs-snapshot (not model-vs-file) because the - // importer itself drops some atoms (duplicate zero timestamps), and - // those silently-dropped atoms must not look like a user edit. - private var mkvChaptersSnapshot: [(timestamp: UInt64, title: String)]? + // Chapter rows as the file's baseline holds them (model milliseconds, + // plus the track-level chapter language the remuxer stamps as + // ChapterLanguage). nil when the last read/written file had no chapters. + // Compared against the model on save: model-vs-snapshot (not model-vs- + // file) because the importer itself drops some atoms (duplicate zero + // timestamps), and those silently-dropped atoms must not look like an edit. + private var mkvChaptersSnapshot: [(timestamp: UInt64, title: String, language: String)]? private var mkvFileSize: UInt64 = 0 private var mkvFileModificationDate: Date? @@ -333,7 +334,8 @@ final class Document: NSDocument { case (nil, nil): chaptersChanged = false case let (model?, snapshot?): chaptersChanged = model.count != snapshot.count || - zip(model, snapshot).contains { $0.timestamp != $1.timestamp || $0.title != $1.title } + zip(model, snapshot).contains { $0.timestamp != $1.timestamp + || $0.title != $1.title || $0.language != $1.language } default: chaptersChanged = true } @@ -366,9 +368,13 @@ final class Document: NSDocument { // 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 static func matroskaChapterRows(_ track: MP42ChapterTrack?) -> [(timestamp: UInt64, title: String)]? { + private static func matroskaChapterRows(_ track: MP42ChapterTrack?) + -> [(timestamp: UInt64, title: String, language: String)]? { guard let track else { return nil } - return track.chapters.map { ($0.timestamp, $0.title) } + // The language is track-level; repeated per row so the zip comparison + // above covers language-only edits. + let language = track.language + return track.chapters.map { ($0.timestamp, $0.title, language) } } private func remuxMatroska(to url: URL, currentTracks: [MP42Track], diff --git a/Classes/DocumentToolbarDelegate.swift b/Classes/DocumentToolbarDelegate.swift index b8dc630..1e031b9 100644 --- a/Classes/DocumentToolbarDelegate.swift +++ b/Classes/DocumentToolbarDelegate.swift @@ -58,11 +58,16 @@ class DocumentToolbarDelegate: NSObject, NSToolbarDelegate { submenu.addItem(menuItem) } + let insertChapter = NSMenuItem() + insertChapter.title = NSLocalizedString("Insert a chapter", comment: "Toolbar") + insertChapter.action = #selector(DocumentWindowController.insertChapter(_:)) + let chapters = NSMenuItem() chapters.title = NSLocalizedString("Insert a chapter every", comment: "Toolbar") chapters.submenu = submenu let menu = NSMenu() + menu.addItem(insertChapter) menu.addItem(chapters) menu.addItem(NSMenuItem.separator()) menu.addItem(withTitle: NSLocalizedString("Organize alternate groups", comment: "Toolbar"), diff --git a/Classes/DocumentWindowController.swift b/Classes/DocumentWindowController.swift index 9255822..6d167fd 100644 --- a/Classes/DocumentWindowController.swift +++ b/Classes/DocumentWindowController.swift @@ -254,12 +254,9 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac } 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 } - } + // On MKV docs the save path stream-copy-remuxes removed real tracks' + // blocks away (MP42MkvRemuxer); a removed chapter pseudo-track makes + // the model report "no chapters", which deletes the Chapters element. if tracks.isEmpty == false { mp4.removeTracks(tracks) @@ -281,7 +278,9 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac case #selector(selectMetadataFile(_:)), #selector(searchMetadata(_:)), - #selector(sendToQueue(_:)): + #selector(sendToQueue(_:)), + #selector(insertChapter(_:)), + #selector(addChaptersEvery(_:)): return true // Matroska documents may import subtitle text files (written as @@ -289,9 +288,11 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac case #selector(selectFile(_:)): return true - // Chapter/track bulk modifications: unavailable in Matroska tags-only mode. + // Track bulk modifications (and the chapter-DB search, whose apply + // path lacks the tags-only bookkeeping): unavailable in Matroska + // tags-only mode. The Insert-a-chapter actions are NOT on this list — + // chapter changes ride the stream-copy remuxer, so they work on MKV. case #selector(searchChapters(_:)), - #selector(addChaptersEvery(_:)), #selector(iTunesFriendlyTrackGroups(_:)), #selector(clearTrackNames(_:)), #selector(prettifyAudioTrackNames(_:)), @@ -313,11 +314,9 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac case #selector(DocumentWindowController.deleteTrack(_:)): // 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 + // save) and the chapter pseudo-track (the Chapters element is + // removed on save), so any non-empty selection is deletable. + return tracksViewController.selectedTracks.isEmpty == false && NSApp.isActive default: return false @@ -375,8 +374,58 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac delete(tracks: tracksViewController.selectedTracks) } + // Single-chapter insert that also bootstraps the chapter track, so it + // works on documents without any chapters yet (both containers: on MKV + // the new rows ride the remuxer on save, like the Chapters tab's edits). + @IBAction func insertChapter(_ sender: Any) { + let track: MP42ChapterTrack + if let existing = mp4.chapters { + track = existing + } else { + track = MP42ChapterTrack() + mp4.addTrack(track) // addTrack: replaces any previous chapter track + if doc.isMatroska { + // addTrack: zeroes trackId; keep the table numbering dense. + track.trackId = (mp4.tracks.map { $0.trackId }.max() ?? 0) + 1 + } + } + + // A brand-new track gets its first chapter at 0; inserting into an + // existing track places the chapter 1s after the latest start, so it + // never ties with a stored chapter (ties get clamped +1ms on write, + // which would silently shift the user's own chapter times). The user + // retimes/renames the row either way. + var newTimestamp: UInt64 = 0 + if let last = track.chapters.max(by: { $0.timestamp < $1.timestamp }) { + newTimestamp = last.timestamp + 1000 + if track.duration > last.timestamp + 1, newTimestamp >= track.duration { + newTimestamp = track.duration - 1 + } + } + let index = track.addChapter("Chapter", timestamp: newTimestamp) + + if doc.isMatroska { + // The tags-only model has no muxing step to mark the document. + doc.updateChangeCount(.changeDone) + } + + tracksViewController.reloadData() + tracksViewController.selectTracks([track]) + chapterViewController?.selectChapter(at: Int(index)) + } + @IBAction func addChaptersEvery(_ sender: NSMenuItem) { - let track: MP42ChapterTrack = mp4.chapters ?? { let track = MP42ChapterTrack(); self.mp4.addTrack(track); return track }() + // Creates the chapter track when the document has none (same + // bookkeeping as insertChapter: addTrack: zeroes trackId and the + // tags-only model has no muxing step to mark the document dirty). + let existing = mp4.chapters + let track: MP42ChapterTrack = existing ?? MP42ChapterTrack() + if existing == nil { + mp4.addTrack(track) // addTrack: replaces any previous chapter track + if doc.isMatroska { + track.trackId = (mp4.tracks.map { $0.trackId }.max() ?? 0) + 1 + } + } let minutes = sender.tag * 60 * 1000 if minutes > 0 { @@ -388,6 +437,10 @@ final class DocumentWindowController: NSWindowController, NSWindowDelegate, Trac track.addChapter("Chapter 1", timestamp: 0) } + if doc.isMatroska { + doc.updateChangeCount(.changeDone) + } + tracksViewController.reloadData() tracksViewController.selectTracks([track]) } diff --git a/Classes/PropertyView/ChapterViewController.swift b/Classes/PropertyView/ChapterViewController.swift index afc53af..cc3e8d0 100644 --- a/Classes/PropertyView/ChapterViewController.swift +++ b/Classes/PropertyView/ChapterViewController.swift @@ -129,6 +129,18 @@ final class ChapterViewController : PropertyView, NSTableViewDataSource, NSTable deleteSelection(in: tableView) } + // Selects and scrolls to a row (used after the window controller appends + // a chapter from the Actions menu, when the tab may not have shown this + // track's table yet). + func selectChapter(at index: Int) { + guard isViewLoaded, index >= 0, index < track.chapters.count else { return } + tableView.reloadData() + tableView.scrollRowToVisible(index) + let indexSet = IndexSet(integer: index) + tableView.selectRowIndexes(indexSet, byExtendingSelection: false) + view.window?.makeFirstResponder(tableView) + } + @IBAction func addChapter(_ sender: Any) { let index = track.addChapter("Chapter", timestamp: 0) let indexSet = IndexSet(integer: Int(index)) diff --git a/Classes/TracksViewController.swift b/Classes/TracksViewController.swift index 1617583..ef3ab4b 100644 --- a/Classes/TracksViewController.swift +++ b/Classes/TracksViewController.swift @@ -46,6 +46,14 @@ final class TracksViewController: NSViewController, NSTableViewDataSource, NSTab return document.isMatroska == false || track.isMember(of: MP42ChapterTrack.self) == false } + // The chapter pseudo-track has no TrackEntry for the tag writer, but it + // carries the language the remuxer stamps into every ChapterDisplay on + // save, so its language popup is editable on Matroska documents too. + private func isLanguageEditable(_ track: MP42Track?) -> Bool { + guard let track = track else { return false } + return isFieldEditable(track) || track.isMember(of: MP42ChapterTrack.self) + } + private static let languagesMenu: NSMenu = { let menu = NSMenu() menu.autoenablesItems = false @@ -125,8 +133,12 @@ final class TracksViewController: NSViewController, NSTableViewDataSource, NSTab func deleteSelection(in tableview: NSTableView) { // 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 + // their blocks on save) and so is the chapter pseudo-track: with it + // gone the model reports "no chapters", so the save remuxes and the + // Chapters element is deleted (same as emptying the Chapters tab). + let deletable = document.isMatroska + ? selectedTracks.filter { isFieldEditable($0) || $0.isMember(of: MP42ChapterTrack.self) } + : selectedTracks guard deletable.isEmpty == false else { return } delegate?.delete(tracks: deletable) } @@ -236,7 +248,7 @@ final class TracksViewController: NSViewController, NSTableViewDataSource, NSTab } cell?.textField?.stringValue = MP42Languages.defaultManager.localizedLang(forExtendedTag: track.language) - cell?.popUpButton?.isEnabled = isFieldEditable(track) + cell?.popUpButton?.isEnabled = isLanguageEditable(track) return cell case trackInfoColumn?: diff --git a/MP42Foundation b/MP42Foundation index 0cf79ec..10dcee3 160000 --- a/MP42Foundation +++ b/MP42Foundation @@ -1 +1 @@ -Subproject commit 0cf79eca1c4b1c56f521d914d83bd07d89ec3318 +Subproject commit 10dcee30a6ea41203a31abfe6007e3cd81f92797 diff --git a/es-419.lproj/Localizable.strings b/es-419.lproj/Localizable.strings index 3f6ceeb..bc64dfc 100644 --- a/es-419.lproj/Localizable.strings +++ b/es-419.lproj/Localizable.strings @@ -266,6 +266,7 @@ Undo tag insert. */ "Insert" = "insertar"; /* Toolbar */ +"Insert a chapter" = "Insertar un capítulo"; "Insert a chapter every" = "Insertar un capítulo cada"; /* color profile */ diff --git a/fr.lproj/Localizable.strings b/fr.lproj/Localizable.strings index 97c258b..af8ad67 100644 --- a/fr.lproj/Localizable.strings +++ b/fr.lproj/Localizable.strings @@ -249,6 +249,7 @@ Undo tag insert. */ "Insert" = "Insérer"; /* Toolbar */ +"Insert a chapter" = "Insérer un chapitre"; "Insert a chapter every" = "Insérer un chapitre à chaque"; /* nil */ diff --git a/it.lproj/Localizable.strings b/it.lproj/Localizable.strings index 200534c..3870ca8 100644 --- a/it.lproj/Localizable.strings +++ b/it.lproj/Localizable.strings @@ -251,6 +251,7 @@ Enable subtitles track local description */ "Import tracks from external files" = "Importa le tracce da un file esterno"; /* Toolbar */ +"Insert a chapter" = "Inserisci un capitolo"; "Insert a chapter every" = "Inserisci un capitolo ogni"; /* color profile */ diff --git a/pt-BR.lproj/Localizable.strings b/pt-BR.lproj/Localizable.strings index 245e37a..1111905 100644 --- a/pt-BR.lproj/Localizable.strings +++ b/pt-BR.lproj/Localizable.strings @@ -266,6 +266,7 @@ Undo tag insert. */ "Insert" = "Inserir"; /* Toolbar */ +"Insert a chapter" = "Inserir um capítulo"; "Insert a chapter every" = "Inserir um Capítulo a Cada"; /* color profile */ diff --git a/zh-CN.lproj/Localizable.strings b/zh-CN.lproj/Localizable.strings index 28cec1a..70c1a33 100644 --- a/zh-CN.lproj/Localizable.strings +++ b/zh-CN.lproj/Localizable.strings @@ -237,6 +237,7 @@ Undo tag insert. */ "Insert" = "插入"; /* Toolbar */ +"Insert a chapter" = "插入一个章节标记"; "Insert a chapter every" = "插入章节标记 每隔"; /* nil */ diff --git a/zh-Hans.lproj/Localizable.strings b/zh-Hans.lproj/Localizable.strings index f31183d..ebbfb6c 100644 --- a/zh-Hans.lproj/Localizable.strings +++ b/zh-Hans.lproj/Localizable.strings @@ -237,6 +237,7 @@ "Insert" = "插入"; /* Toolbar */ +"Insert a chapter" = "插入一个章节标记"; "Insert a chapter every" = "插入章节标记 每隔"; /* No comment provided by engineer. */