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:
Scott GarrettandClaude Code committed 2026-11-25 19:48:34 -05:00
1 parent 0c3d7de364
commit eb386a52c3
14 files changed
+540 -32

No files matched your search

@@ -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) {
+34
View File
@@ -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"
}