implementation of alias for the send special command entries

This commit is contained in:
True Zhuanjia committed 2024-07-24 12:36:01 +08:00
1 parent eb6adea47c
commit 916e9b65a6
5 files changed
+185 -177

No files matched your search

+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{