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 <noreply@anthropic.com>
This commit is contained in:
1 parent
0c3d7de364
commit
eb386a52c3
14 files changed
+540
-32
No files matched your search
@@ -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)
|
||||
|
||||
+170
-11
@@ -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
|
||||
|
||||
@@ -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" }
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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!
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user