Skip to content
Permalink
Browse files

Rewrite keybinding tableview using ArrayController

  • Loading branch information...
alejx committed Feb 28, 2019
1 parent b2859e6 commit a2e9c6d1970c8dfe9ff002e4efb23aea2b28f264
@@ -106,4 +106,5 @@ extension Notification.Name {
static let iinaFileLoaded = Notification.Name("IINAFileLoaded")
static let iinaHistoryUpdated = Notification.Name("IINAHistoryUpdated")
static let iinaLegacyFullScreen = Notification.Name("IINALegacyFullScreen")
static let iinaKeyBindingChange = Notification.Name("IINAKeyBindingChange")
}
@@ -1,8 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="14313.13.2" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="14460.31" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
<dependencies>
<deployment identifier="macosx"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="14313.13.2"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="14460.31"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
@@ -13,7 +13,8 @@
<outlet property="configHintLabel" destination="tP6-Ua-acA" id="bRT-AA-zL7"/>
<outlet property="deleteConfFileBtn" destination="EpF-t6-PtC" id="3NC-Xb-5kT"/>
<outlet property="duplicateConfigBtn" destination="5WK-s3-J9x" id="Ri8-b5-d3s"/>
<outlet property="kbTableView" destination="1Z4-NL-6P3" id="v4p-E7-gvv"/>
<outlet property="kbTableView" destination="1Z4-NL-6P3" id="OyE-OE-MSd"/>
<outlet property="mappingController" destination="xGz-Vh-hMb" id="hDG-Z5-OmL"/>
<outlet property="newConfigBtn" destination="iCp-ho-SlQ" id="LI0-TX-tNs"/>
<outlet property="removeKmBtn" destination="uFG-OF-DJ5" id="XWN-Lt-tmc"/>
<outlet property="revealConfFileBtn" destination="KZA-hu-vhZ" id="lVg-3j-Qgp"/>
@@ -67,6 +68,9 @@
<color key="backgroundColor" name="controlBackgroundColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
<tableColumnResizingMask key="resizingMask" resizeWithTable="YES" userResizable="YES"/>
<connections>
<binding destination="xGz-Vh-hMb" name="value" keyPath="arrangedObjects.keyForDisplay" id="FWk-cQ-DIx"/>
</connections>
</tableColumn>
<tableColumn identifier="Action" width="367" minWidth="40" maxWidth="1000" id="4Bn-MF-dfY">
<tableHeaderCell key="headerCell" lineBreakMode="truncatingTail" borderStyle="border" title="Action">
@@ -80,8 +84,15 @@
<color key="backgroundColor" name="controlBackgroundColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
<tableColumnResizingMask key="resizingMask" resizeWithTable="YES" userResizable="YES"/>
<connections>
<binding destination="xGz-Vh-hMb" name="value" keyPath="arrangedObjects.actionForDisplay" id="lft-aO-sfz"/>
</connections>
</tableColumn>
</tableColumns>
<connections>
<binding destination="xGz-Vh-hMb" name="content" keyPath="arrangedObjects" id="msx-K3-0J4"/>
<binding destination="xGz-Vh-hMb" name="selectionIndexes" keyPath="selectionIndexes" previousBinding="msx-K3-0J4" id="Bzi-wl-Zks"/>
</connections>
</tableView>
</subviews>
</clipView>
@@ -144,7 +155,7 @@
<font key="font" metaFont="system"/>
</buttonCell>
<connections>
<action selector="removeKeyMappingBtnAction:" target="-2" id="AMw-dz-4NC"/>
<action selector="removeKeyMappingBtnAction:" target="-2" id="aeN-fq-0zS"/>
</connections>
</button>
<button toolTip="Show the raw mpv key code and command." translatesAutoresizingMaskIntoConstraints="NO" id="l2M-TH-eCt">
@@ -155,6 +166,7 @@
</buttonCell>
<connections>
<action selector="displayRawValueAction:" target="-2" id="EX1-Ia-ua1"/>
<binding destination="XM5-Sj-lhw" name="value" keyPath="values.displayRawValue" id="cXv-OP-hZr"/>
</connections>
</button>
<box horizontalHuggingPriority="750" boxType="separator" translatesAutoresizingMaskIntoConstraints="NO" id="GnK-98-Zrg">
@@ -406,6 +418,7 @@
<point key="canvasLocation" x="121.5" y="248.5"/>
</customView>
<userDefaultsController representsSharedInstance="YES" id="XM5-Sj-lhw"/>
<arrayController objectClassName="KeyMapping" id="xGz-Vh-hMb"/>
</objects>
<resources>
<image name="NSAddTemplate" width="11" height="11"/>
@@ -102,7 +102,7 @@ class FontPickerWindowController: NSWindowController, NSTableViewDelegate, NSTab
faceTableView.reloadData()
} else {
isSearching = true
filteredFontNames = fontNames.filter { $0.localizedName.lowercased() .contains(str.lowercased()) }
filteredFontNames = fontNames.filter { $0.localizedName.lowercased().contains(str.lowercased()) }
chosenFontMembers = nil
familyTableView.reloadData()
faceTableView.reloadData()
@@ -8,7 +8,7 @@
import Foundation

class KeyMapping {
class KeyMapping: NSObject {

static private let modifierOrder: [String: Int] = [
"Ctrl": 0,
@@ -17,6 +17,26 @@ class KeyMapping {
"Meta": 3
]

@objc var keyForDisplay: String {
get {
return UserDefaults.standard.bool(forKey: "displayRawValue") ? key : prettyKey
}
set {
key = newValue
NotificationCenter.default.post(Notification(name: .iinaKeyBindingChange))
}
}

@objc var actionForDisplay: String {
get {
return UserDefaults.standard.bool(forKey: "displayRawValue") ? prettyCommand : readableAction
}
set {
rawAction = newValue
NotificationCenter.default.post(Notification(name: .iinaKeyBindingChange))
}
}

var isIINACommand: Bool

var key: String
@@ -37,12 +37,10 @@ class PrefKeyBindingViewController: NSViewController, PreferenceWindowEmbeddable
var userConfigs: [String: Any]!
var userConfigNames: [String] = []

var currentMapping: [KeyMapping] = []
var currentConfName: String!
var currentConfFilePath: String!

var shouldEnableEdit: Bool = true
var displayRawValues: Bool = false

// MARK: - Outlets
@@ -56,15 +54,13 @@ class PrefKeyBindingViewController: NSViewController, PreferenceWindowEmbeddable
@IBOutlet weak var newConfigBtn: NSButton!
@IBOutlet weak var duplicateConfigBtn: NSButton!
@IBOutlet weak var useMediaKeysButton: NSButton!

@IBOutlet var mappingController: NSArrayController!

override func viewDidLoad() {
super.viewDidLoad()

// tableview
kbTableView.dataSource = self
kbTableView.delegate = self
kbTableView.doubleAction = #selector(editRow)
kbTableView.doubleAction = UserDefaults.standard.bool(forKey: "displayRawValue") ? nil : #selector(editRow)
confTableView.dataSource = self
confTableView.delegate = self

@@ -106,6 +102,8 @@ class PrefKeyBindingViewController: NSViewController, PreferenceWindowEmbeddable
guard let path = getFilePath(forConfig: currentConf) else { return }
currentConfFilePath = path
loadConfigFile()

NotificationCenter.default.addObserver(forName: .iinaKeyBindingChange, object: nil, queue: .main, using: saveToConfFile)
}

private func confTableSelectRow(withTitle title: String) {
@@ -139,25 +137,21 @@ class PrefKeyBindingViewController: NSViewController, PreferenceWindowEmbeddable
guard !key.isEmpty && !action.isEmpty else { return }
if action.hasPrefix("@iina") {
let trimmedAction = action[action.index(action.startIndex, offsetBy: "@iina".count)...].trimmingCharacters(in: .whitespaces)
self.currentMapping.append(KeyMapping(key: key,
rawAction: trimmedAction,
isIINACommand: true))
self.mappingController.addObject(KeyMapping(key: key,
rawAction: trimmedAction,
isIINACommand: true))
} else {
self.currentMapping.append(KeyMapping(key: key, rawAction: action))
self.mappingController.addObject(KeyMapping(key: key, rawAction: action))
}

self.kbTableView.reloadData()
self.kbTableView.scrollRowToVisible(self.currentMapping.count - 1)
self.saveToConfFile()
self.kbTableView.scrollRowToVisible((self.mappingController.arrangedObjects as! [AnyObject]).count - 1)
NotificationCenter.default.post(Notification(name: .iinaKeyBindingChange))
}
}

@IBAction func removeKeyMappingBtnAction(_ sender: AnyObject) {
if kbTableView.selectedRow >= 0 {
currentMapping.remove(at: kbTableView.selectedRow)
kbTableView.reloadData()
}
saveToConfFile()
mappingController.remove(sender)
NotificationCenter.default.post(Notification(name: .iinaKeyBindingChange))
}

// FIXME: may combine with duplicate action?
@@ -307,8 +301,7 @@ class PrefKeyBindingViewController: NSViewController, PreferenceWindowEmbeddable
}

@IBAction func displayRawValueAction(_ sender: NSButton) {
displayRawValues = sender.state == .on
kbTableView.doubleAction = displayRawValues ? nil : #selector(editRow)
kbTableView.doubleAction = UserDefaults.standard.bool(forKey: "displayRawValue") ? nil : #selector(editRow)
kbTableView.reloadData()
}

@@ -327,10 +320,10 @@ class PrefKeyBindingViewController: NSViewController, PreferenceWindowEmbeddable
configHintLabel.stringValue = NSLocalizedString("preference.key_binding_hint_\(shouldEnableEdit ? "2" : "1")", comment: "preference.key_binding_hint")
}

func saveToConfFile() {
func saveToConfFile(_ sender: Notification) {
setKeybindingsForPlayerCore()
do {
try KeyMapping.generateConfData(from: currentMapping).write(toFile: currentConfFilePath, atomically: true, encoding: .utf8)
try KeyMapping.generateConfData(from: mappingController.arrangedObjects as! [KeyMapping]).write(toFile: currentConfFilePath, atomically: true, encoding: .utf8)
} catch {
Utility.showAlert("config.cannot_write", sheetWindow: view.window)
}
@@ -341,7 +334,9 @@ class PrefKeyBindingViewController: NSViewController, PreferenceWindowEmbeddable
private func loadConfigFile() {
if let mapping = KeyMapping.parseInputConf(at: currentConfFilePath) {
currentMapping = mapping
mappingController.content = nil
mappingController.add(contentsOf: mapping)
mappingController.setSelectionIndexes(IndexSet())
} else {
// on error
Utility.showAlert("keybinding_config.error", arguments: [currentConfName], sheetWindow: view.window)
@@ -354,7 +349,6 @@ class PrefKeyBindingViewController: NSViewController, PreferenceWindowEmbeddable
}
Preference.set(currentConfName, for: .currentInputConfigName)
setKeybindingsForPlayerCore()
kbTableView.reloadData()
changeButtonEnabledStatus()
}

@@ -377,7 +371,7 @@ class PrefKeyBindingViewController: NSViewController, PreferenceWindowEmbeddable
}

private func setKeybindingsForPlayerCore() {
PlayerCore.setKeyBindings(currentMapping)
PlayerCore.setKeyBindings(mappingController.arrangedObjects as! [KeyMapping])
}

private func tellUserToDuplicateConfig() {
@@ -391,48 +385,20 @@ class PrefKeyBindingViewController: NSViewController, PreferenceWindowEmbeddable
extension PrefKeyBindingViewController: NSTableViewDelegate, NSTableViewDataSource {

func numberOfRows(in tableView: NSTableView) -> Int {
if tableView == kbTableView {
return currentMapping.count
} else {
return userConfigNames.count
}
return userConfigNames.count
}

func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
if tableView == kbTableView {
guard let identifier = tableColumn?.identifier else { return nil }

guard let mapping = currentMapping[at: row] else { return nil }
if identifier == .key {
return displayRawValues ? mapping.key : mapping.prettyKey
} else if identifier == .action {
return displayRawValues ? mapping.readableAction : mapping.prettyCommand
}
return ""
} else {
let name = userConfigNames[row]
return [
"name": name,
"isHidden": !isDefaultConfig(name)
]
}
}

func tableView(_ tableView: NSTableView, setObjectValue object: Any?, for tableColumn: NSTableColumn?, row: Int) {
guard tableView == kbTableView else { return }
guard let value = object as? String,
let identifier = tableColumn?.identifier else { return }
if identifier == .key {
currentMapping[row].key = value
} else if identifier == .action {
currentMapping[row].rawAction = value
}
saveToConfFile()
let name = userConfigNames[row]
return [
"name": name,
"isHidden": !isDefaultConfig(name)
]
}

func tableView(_ tableView: NSTableView, shouldEdit tableColumn: NSTableColumn?, row: Int) -> Bool {
if tableView == kbTableView {
return displayRawValues
return UserDefaults.standard.bool(forKey: "displayRawValue")
} else {
return false
}
@@ -444,13 +410,13 @@ extension PrefKeyBindingViewController: NSTableViewDelegate, NSTableViewDataSour
return
}
guard kbTableView.selectedRow != -1 else { return }
let selectedData = currentMapping[kbTableView.selectedRow]
let selectedData = mappingController.selectedObjects[0] as! KeyMapping
showKeyBindingPanel(key: selectedData.key, action: selectedData.readableAction) { key, action in
guard !key.isEmpty && !action.isEmpty else { return }
selectedData.key = key
selectedData.rawAction = action
self.kbTableView.reloadData()
self.saveToConfFile()
NotificationCenter.default.post(Notification(name: .iinaKeyBindingChange))
}
}

@@ -461,6 +427,6 @@ extension PrefKeyBindingViewController: NSTableViewDelegate, NSTableViewDataSour
currentConfFilePath = getFilePath(forConfig: title)!
loadConfigFile()
}
removeKmBtn.isEnabled = shouldEnableEdit && (kbTableView.selectedRow != -1)
removeKmBtn.isEnabled = shouldEnableEdit && kbTableView.selectedRow != -1
}
}
@@ -254,6 +254,8 @@ struct Preference {
static let enableLogging = Key("enableLogging")
static let logLevel = Key("logLevel")

static let displayRawValue = Key("displayRawValue")

/** unused */
// static let resizeFrameBuffer = Key("resizeFrameBuffer")
@@ -765,6 +767,7 @@ struct Preference {
.useMpvOsd: false,
.enableLogging: false,
.logLevel: Logger.Level.debug.rawValue,
.displayRawValue: false,
.userOptions: [],
.useUserDefinedConfDir: false,
.userDefinedConfDir: "~/.config/mpv/",

0 comments on commit a2e9c6d

Please sign in to comment.
You can’t perform that action at this time.