implementation of alias for the send special command entries

This commit is contained in:
True Zhuanjia
2024-07-24 12:36:01 +08:00
parent eb6adea47c
commit 916e9b65a6
5 changed files with 185 additions and 177 deletions
+121
View File
@@ -0,0 +1,121 @@
//
// KeyManager.swift
// Moonlight-ZWM
//
// Created by ZWM on 2024/7/23.
// Copyright © 2024 Moonlight Game Streaming Project. All rights reserved.
//
import Foundation
import UIKit
// Define the RemoteCommand class
@objc public class RemoteCommand: NSObject, NSCoding {
@objc public var keyboardCmdString: String
@objc public var alias: String
init(keyboardCmdString: String, alias: String) {
self.keyboardCmdString = keyboardCmdString
self.alias = alias
}
// MARK: - NSCoding
required public init?(coder: NSCoder) {
guard let keyboardCmdString = coder.decodeObject(forKey: "keyboardCmdString") as? String,
let alias = coder.decodeObject(forKey: "alias") as? String else {
return nil
}
self.keyboardCmdString = keyboardCmdString
self.alias = alias
}
public func encode(with coder: NSCoder) {
coder.encode(keyboardCmdString, forKey: "keyboardCmdString")
coder.encode(alias, forKey: "alias")
}
}
// Define the CommandManager class
@objc public class CommandManager: NSObject {
@objc public static let shared = CommandManager()
private var commands: [RemoteCommand] = []
private let keyMappings: [String: UInt16] = [
"CTRL": 0x11,
"ALT": 0x12,
"DEL": 0x2E,
"F1": 0x70,
"F2": 0x71
]
private weak var viewController: CommandManagerViewController?
private override init() {
super.init()
loadCommands()
}
@objc public func createTestKeyMappings() -> [String: UInt16] {
return keyMappings
}
@objc public func extractKeyStrings(from input: String) -> [String]? {
let keys = keyMappings.keys.joined(separator: "|")
let pattern = "^((?:\(keys))(?:\\+\(keys))*)$"
guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else {
return nil
}
let range = NSRange(location: 0, length: input.utf16.count)
guard let match = regex.firstMatch(in: input, options: [], range: range) else {
return nil
}
let matchedString = (input as NSString).substring(with: match.range(at: 1))
let keyStrings = matchedString.split(separator: "+").map { String($0) }
return keyStrings
}
@objc public func addCommand(_ command: RemoteCommand) {
commands.append(command)
saveCommands()
viewController?.reloadTableView()
}
@objc public func deleteCommand(at index: Int) {
guard index >= 0 && index < commands.count else {
return
}
commands.remove(at: index)
saveCommands()
}
@objc public func getAllCommands() -> [RemoteCommand] {
return commands
}
private func loadCommands() {
if let savedCommandsData = UserDefaults.standard.data(forKey: "savedCommands"),
let savedCommands = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(savedCommandsData) as? [RemoteCommand] {
commands = savedCommands
}
}
private func saveCommands() {
if let data = try? NSKeyedArchiver.archivedData(withRootObject: commands, requiringSecureCoding: false) {
UserDefaults.standard.set(data, forKey: "savedCommands")
}
}
@objc public func setupViewController(_ viewController: CommandManagerViewController) {
self.viewController = viewController
//let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(promptForNewCommand))
//viewController.navigationItem.rightBarButtonItem = addButton
//viewController.navigationItem.title = "Manage Commands"
//viewController.tableView.delegate = viewController
//viewController.tableView.dataSource = viewController
}
}
-126
View File
@@ -1,126 +0,0 @@
//
// KeyManager.swift
// Moonlight-ZWM
//
// Created by ZWM on 2024/7/23.
// Copyright © 2024 Moonlight Game Streaming Project. All rights reserved.
//
import Foundation
import UIKit
@objc public class KeyManager: NSObject {
@objc public static let shared = KeyManager()
private var strings: [String] = []
private let keyMappings: [String: UInt16] = [
"CTRL": 0x11,
"ALT": 0x12,
"DEL": 0x2E,
"F1": 0x70,
"F2": 0x71
]
private weak var viewController: KeyManagerViewController?
private override init() {
super.init()
loadStrings()
}
@objc public func createTestKeyMappings() -> [String: UInt16] {
return keyMappings
}
@objc public func extractKeyStrings(from input: String) -> [String]? {
let keys = keyMappings.keys.joined(separator: "|")
let pattern = "^((?:\(keys))(?:\\+\(keys))*)$"
guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else {
return nil
}
let range = NSRange(location: 0, length: input.utf16.count)
guard let match = regex.firstMatch(in: input, options: [], range: range) else {
return nil
}
let matchedString = (input as NSString).substring(with: match.range(at: 1))
let keyStrings = matchedString.split(separator: "+").map { String($0) }
return keyStrings
}
@objc public func addString(_ string: String) {
/* guard isValidString(string) else {
return
} */
strings.append(string)
saveStrings()
viewController?.reloadTableView()
}
@objc public func deleteString(at index: Int) {
guard index >= 0 && index < strings.count else {
return
}
strings.remove(at: index)
saveStrings()
viewController?.reloadTableView()
}
@objc public func getAllStrings() -> [String] {
return strings
}
private func isValidString(_ string: String) -> Bool {
let keys = keyMappings.keys.joined(separator: "|")
let pattern = "^((?:\(keys))(?:\\+\(keys))*)$"
guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else {
return false
}
let range = NSRange(location: 0, length: string.utf16.count)
return regex.firstMatch(in: string, options: [], range: range) != nil
}
private func loadStrings() {
if let savedStrings = UserDefaults.standard.array(forKey: "savedStrings") as? [String] {
strings = savedStrings
}
}
private func saveStrings() {
UserDefaults.standard.set(strings, forKey: "savedStrings")
}
@objc public func setupViewController(_ viewController: KeyManagerViewController) {
self.viewController = viewController
let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(promptForNewString))
viewController.navigationItem.rightBarButtonItem = addButton
viewController.navigationItem.title = "Manage Strings"
viewController.tableView.delegate = viewController
viewController.tableView.dataSource = viewController
//viewController.tableView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
}
@objc private func promptForNewString() {
guard let topController = UIApplication.shared.keyWindow?.rootViewController else {
return
}
let alert = UIAlertController(title: "New String", message: "Enter a new string", preferredStyle: .alert)
alert.addTextField()
let submitAction = UIAlertAction(title: "Add", style: .default) { [unowned alert] _ in
let newString = alert.textFields![0].text ?? ""
self.addString(newString)
}
alert.addAction(submitAction)
topController.present(alert, animated: true)
}
}
@@ -8,7 +8,7 @@
import UIKit
@objc public class KeyManagerViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@objc public class CommandManagerViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
public let tableView = UITableView()
private let addButton = UIButton(type: .system)
@@ -18,7 +18,7 @@ import UIKit
private let viewBackgroundColor = UIColor(white: 0.2, alpha: 1.0);
private let highlightColor = UIColor(white: 0.3, alpha: 1.0);
private let titleLabel = UILabel()
private var isEditingMode: Bool = false {
didSet {
updateEditingMode()
@@ -37,20 +37,20 @@ import UIKit
// Register the cell class
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
KeyManager.shared.setupViewController(self)
CommandManager.shared.setupViewController(self)
}
override public func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
setupConstraints()
}
private func setupViews() {
// Set corner radius
view.layer.cornerRadius = 20 // Adjust the corner radius
view.layer.masksToBounds = true
// Set up the title label
titleLabel.text = SwiftLocalizationHelper.localizedString(forKey: "Send Special Keys")
titleLabel.font = UIFont.boldSystemFont(ofSize: 24) // Adjust font size as needed
@@ -71,7 +71,7 @@ import UIKit
deleteButton.titleLabel?.font = UIFont.systemFont(ofSize: 20)
editButton.titleLabel?.font = UIFont.systemFont(ofSize: 20)
exitButton.titleLabel?.font = UIFont.systemFont(ofSize: 20)
// Add subviews
view.addSubview(tableView)
view.addSubview(addButton)
@@ -100,9 +100,9 @@ import UIKit
editButton.translatesAutoresizingMaskIntoConstraints = false
exitButton.translatesAutoresizingMaskIntoConstraints = false
titleLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
// Set the width and height of the view
view.widthAnchor.constraint(equalTo: view.superview!.widthAnchor, multiplier: 0.7),
view.heightAnchor.constraint(equalTo: view.superview!.heightAnchor, multiplier: 0.75),
@@ -115,8 +115,8 @@ import UIKit
titleLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20),
titleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
titleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10),
// TableView constraints
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10),
@@ -146,30 +146,44 @@ import UIKit
deleteButton.isEnabled = isEditingMode
if(isEditingMode){ editButton.setTitle(SwiftLocalizationHelper.localizedString(forKey: "Done"), for: .normal) }
else{ editButton.setTitle(SwiftLocalizationHelper.localizedString(forKey: "Edit"), for: .normal) }
}
@objc private func addButtonTapped() {
let alertController = UIAlertController(title: SwiftLocalizationHelper.localizedString(forKey: "Add String"), message: nil, preferredStyle: .alert)
alertController.addTextField()
//CommandManager.shared.promptForNewCommand()
let addAction = UIAlertAction(title: SwiftLocalizationHelper.localizedString(forKey: "Add"), style: .default) { [weak self] _ in
if let newString = alertController.textFields?.first?.text, !newString.isEmpty {
KeyManager.shared.addString(newString)
self?.reloadTableView()
}
let alert = UIAlertController(title: "New Command", message: "Enter a new command and alias", preferredStyle: .alert)
alert.addTextField { $0.placeholder = "Command" }
alert.addTextField { $0.placeholder = "Alias" }
let submitAction = UIAlertAction(title: "Add", style: .default) { [unowned alert] _ in
let keyboardCmdString = alert.textFields?[0].text ?? ""
let alias = alert.textFields?[1].text ?? keyboardCmdString
let newCommand = RemoteCommand(keyboardCmdString: keyboardCmdString, alias: alias)
CommandManager.shared.addCommand(newCommand)
//self.reloadTableView()
}
let cancelAction = UIAlertAction(title: SwiftLocalizationHelper.localizedString(forKey: "Cancel"), style: .cancel, handler: nil)
alertController.addAction(addAction)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
alert.addAction(submitAction)
alert.addAction(cancelAction)
if let selectedIndexPath = self.tableView.indexPathForSelectedRow {
let selectedCommand = CommandManager.shared.getAllCommands()[selectedIndexPath.row]
alert.textFields?[0].text = selectedCommand.keyboardCmdString
alert.textFields?[1].text = selectedCommand.alias
}
self.present(alert, animated: true)
}
@objc private func deleteButtonTapped() {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
KeyManager.shared.deleteString(at: selectedIndexPath.row)
reloadTableView()
guard let selectedIndexPath = tableView.indexPathForSelectedRow else {
return
}
CommandManager.shared.deleteCommand(at: selectedIndexPath.row)
reloadTableView()
}
@objc private func editButtonTapped() {
@@ -186,7 +200,7 @@ import UIKit
// UITableViewDataSource
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return KeyManager.shared.getAllStrings().count
return CommandManager.shared.getAllCommands().count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
@@ -194,22 +208,21 @@ import UIKit
// Configure cell appearance
cell.backgroundColor = viewBackgroundColor // Set background color of the cell
cell.textLabel?.textColor = UIColor.white // Set font color of the text
// Set selected background view
let selectedBackgroundView = UIView()
selectedBackgroundView.backgroundColor = highlightColor // Color for the selected state
cell.selectedBackgroundView = selectedBackgroundView
let keyStrings = KeyManager.shared.getAllStrings()
cell.textLabel?.text = keyStrings[indexPath.row]
let command = CommandManager.shared.getAllCommands()[indexPath.row]
cell.textLabel?.text = command.alias
return cell
}
// UITableViewDelegate
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
// Set the cell background color to the flashing color
// Animate the flash effect
@@ -222,7 +235,7 @@ import UIKit
}
}
}
if !isEditingMode {
// Call the dummy method for key-value sending implementation
dummyMethodForKeySending()
@@ -54,7 +54,7 @@
CGSize _keyboardSize;
#if !TARGET_OS_TV
CustomEdgeSwipeGestureRecognizer *_exitSwipeRecognizer;
CustomEdgeSwipeGestureRecognizer *_keyManagerSwipeRecognizer;
CustomEdgeSwipeGestureRecognizer *_commandManagerSwipeRecognizer;
CustomTapGestureRecognizer *_oscLayoutTapRecoginizer;
LayoutOnScreenControlsViewController *_layoutOnScreenControlsVC;
#endif
@@ -88,9 +88,9 @@
}
}
- (void)presentKeyManagerViewController{
KeyManagerViewController* keyManViewController = [[KeyManagerViewController alloc] init];
[self presentViewController:keyManViewController animated:YES completion:nil];
- (void)presentCommandManagerViewController{
CommandManagerViewController* cmdManViewController = [[CommandManagerViewController alloc] init];
[self presentViewController:cmdManViewController animated:YES completion:nil];
}
- (void)configSwipeGestures{
@@ -103,13 +103,13 @@
[self.view addGestureRecognizer:_exitSwipeRecognizer];
[self.view removeGestureRecognizer:_keyManagerSwipeRecognizer];
_keyManagerSwipeRecognizer = [[CustomEdgeSwipeGestureRecognizer alloc] initWithTarget:self action:@selector(presentKeyManagerViewController)];
_keyManagerSwipeRecognizer.edges = UIRectEdgeRight;
_keyManagerSwipeRecognizer.normalizedThresholdDistance = _settings.swipeToExitDistance.floatValue;
_keyManagerSwipeRecognizer.delaysTouchesBegan = NO;
_keyManagerSwipeRecognizer.delaysTouchesEnded = NO;
[self.view addGestureRecognizer:_keyManagerSwipeRecognizer];
[self.view removeGestureRecognizer:_commandManagerSwipeRecognizer];
_commandManagerSwipeRecognizer = [[CustomEdgeSwipeGestureRecognizer alloc] initWithTarget:self action:@selector(presentCommandManagerViewController)];
_commandManagerSwipeRecognizer.edges = UIRectEdgeRight;
_commandManagerSwipeRecognizer.normalizedThresholdDistance = _settings.swipeToExitDistance.floatValue;
_commandManagerSwipeRecognizer.delaysTouchesBegan = NO;
_commandManagerSwipeRecognizer.delaysTouchesEnded = NO;
[self.view addGestureRecognizer:_commandManagerSwipeRecognizer];
}
- (void)configZoomGesture{
+8 -8
View File
@@ -23,8 +23,8 @@
8454AC662C31907F00F0A302 /* iPad.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 8454AC682C31907F00F0A302 /* iPad.storyboard */; };
8454AC6A2C319BDA00F0A302 /* iPhone.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 8454AC6C2C319BDA00F0A302 /* iPhone.storyboard */; };
84591A512BE1625E006AAB10 /* CustomEdgeSwipeGestureRecognizer.m in Sources */ = {isa = PBXBuildFile; fileRef = 84591A502BE1625E006AAB10 /* CustomEdgeSwipeGestureRecognizer.m */; };
84E1CDEC2C4F67D300547904 /* KeyManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84E1CDEB2C4F67D300547904 /* KeyManager.swift */; };
84E1CDEF2C4F688E00547904 /* KeyManagerViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84E1CDEE2C4F688E00547904 /* KeyManagerViewController.swift */; };
84E1CDEC2C4F67D300547904 /* CommandManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84E1CDEB2C4F67D300547904 /* CommandManager.swift */; };
84E1CDEF2C4F688E00547904 /* CommandManagerViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84E1CDEE2C4F688E00547904 /* CommandManagerViewController.swift */; };
84E1CDFA2C4FE83400547904 /* SwiftLocalizationHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84E1CDF92C4FE83400547904 /* SwiftLocalizationHelper.swift */; };
84FD0B512C31338D006B5BE5 /* LocalizationHelper.m in Sources */ = {isa = PBXBuildFile; fileRef = 84FD0B502C31338D006B5BE5 /* LocalizationHelper.m */; };
84FD0B542C3134A6006B5BE5 /* Localizable.xcstrings in Resources */ = {isa = PBXBuildFile; fileRef = 84FD0B532C3134A6006B5BE5 /* Localizable.xcstrings */; };
@@ -153,8 +153,8 @@
8454AC6D2C319BDA00F0A302 /* mul */ = {isa = PBXFileReference; lastKnownFileType = text.json.xcstrings; name = mul; path = mul.lproj/iPhone.xcstrings; sourceTree = "<group>"; };
84591A4F2BE16240006AAB10 /* CustomEdgeSwipeGestureRecognizer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CustomEdgeSwipeGestureRecognizer.h; sourceTree = "<group>"; };
84591A502BE1625E006AAB10 /* CustomEdgeSwipeGestureRecognizer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CustomEdgeSwipeGestureRecognizer.m; sourceTree = "<group>"; };
84E1CDEB2C4F67D300547904 /* KeyManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyManager.swift; sourceTree = "<group>"; };
84E1CDEE2C4F688E00547904 /* KeyManagerViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyManagerViewController.swift; sourceTree = "<group>"; };
84E1CDEB2C4F67D300547904 /* CommandManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommandManager.swift; sourceTree = "<group>"; };
84E1CDEE2C4F688E00547904 /* CommandManagerViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommandManagerViewController.swift; sourceTree = "<group>"; };
84E1CDF92C4FE83400547904 /* SwiftLocalizationHelper.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwiftLocalizationHelper.swift; sourceTree = "<group>"; };
84FD0B4F2C313343006B5BE5 /* LocalizationHelper.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = LocalizationHelper.h; sourceTree = "<group>"; };
84FD0B502C31338D006B5BE5 /* LocalizationHelper.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = LocalizationHelper.m; sourceTree = "<group>"; };
@@ -622,7 +622,7 @@
9819CC21254F180F008A7C8E /* AbsoluteTouchHandler.m */,
988FCD3F293B091B003050E2 /* KeyboardInputField.h */,
988FCD40293B091B003050E2 /* KeyboardInputField.m */,
84E1CDEB2C4F67D300547904 /* KeyManager.swift */,
84E1CDEB2C4F67D300547904 /* CommandManager.swift */,
);
path = Input;
sourceTree = "<group>";
@@ -686,7 +686,7 @@
FBD3494F19FF2174002D2A60 /* SettingsViewController.m */,
FB4A23B61A9D3637004D2EF2 /* LoadingFrameViewController.h */,
FB4A23B71A9D3637004D2EF2 /* LoadingFrameViewController.m */,
84E1CDEE2C4F688E00547904 /* KeyManagerViewController.swift */,
84E1CDEE2C4F688E00547904 /* CommandManagerViewController.swift */,
);
path = ViewControllers;
sourceTree = "<group>";
@@ -1019,7 +1019,7 @@
FB9AFD321A7D867C00872C98 /* AppAssetRetriever.m in Sources */,
843E93BE2C41528700B1651F /* OrientationHelper.swift in Sources */,
FB4678FF1A565DAC00377732 /* WakeOnLanManager.m in Sources */,
84E1CDEC2C4F67D300547904 /* KeyManager.swift in Sources */,
84E1CDEC2C4F67D300547904 /* CommandManager.swift in Sources */,
FB53E1431BE5DC4400CD6ECE /* IdManager.m in Sources */,
9897B6A1221260EF00966419 /* Controller.m in Sources */,
84351B112C29ACCB00A77989 /* OSCProfilesManager.m in Sources */,
@@ -1045,7 +1045,7 @@
FB89463619F646E200339C8A /* StreamFrameViewController.m in Sources */,
9827E7A32514366900F25707 /* HapticContext.m in Sources */,
9832D1361BBCD5C50036EF48 /* TemporaryApp.m in Sources */,
84E1CDEF2C4F688E00547904 /* KeyManagerViewController.swift in Sources */,
84E1CDEF2C4F688E00547904 /* CommandManagerViewController.swift in Sources */,
84351B102C29ACCB00A77989 /* OSCProfile.m in Sources */,
84351B2C2C29AD6100A77989 /* OSCProfilesTableViewController.m in Sources */,
98D585701C0ED0E800F6CC00 /* TemporarySettings.m in Sources */,