// LogiSwitch for macOS - menu-bar app that moves Logitech keyboard + mouse to the PC // when the cursor is pushed against the screen edge facing the PC. // // Sends the Logitech HID++ 2.0 "Change Host" command (feature 0x1814) over the existing // Bluetooth HID link. Optional clipboard sync (text, off by default): this Mac listens on TCP 51888 // for the PC, encrypted with AES-256 + HMAC-SHA256 from a shared pairing code. No internet, no file sharing. // // Build: xcrun swiftc -O -o LogiSwitch LogiSwitch.swift -framework AppKit -framework IOKit // Modes: LogiSwitch menu-bar app + edge watcher (normally started by launchd) // LogiSwitch --dry-run same, but only logs instead of switching // LogiSwitch --list read-only: devices, channel count, active channel // LogiSwitch --switch N switch all devices to channel N now // LogiSwitch --configure [--edge Left|Right] [--channel N] [--source DIR] import AppKit import CommonCrypto import Darwin import IOKit import IOKit.hid // MARK: - Paths and logging let fm = FileManager.default let home = fm.homeDirectoryForCurrentUser let supportDir = home.appendingPathComponent("Library/Application Support/LogiSwitch") let settingsURL = supportDir.appendingPathComponent("settings.json") let devicesURL = supportDir.appendingPathComponent("devices.json") let logURL = supportDir.appendingPathComponent("watch.log") let binaryURL = supportDir.appendingPathComponent("LogiSwitch") let plistURL = home.appendingPathComponent("Library/LaunchAgents/com.logiswitch.agent.plist") let problemURL = supportDir.appendingPathComponent("last-problem-report.txt") // fixed path Claude Code can read directly let desktopReportURL = home.appendingPathComponent("Desktop/LogiSwitch-problem-report.txt") let markerURL = supportDir.appendingPathComponent(".running") // left behind = last run did not end cleanly let markerPathC: UnsafeMutablePointer = strdup(markerURL.path)! /// Set by the app; called (on the main thread) when a problem is detected, to create a report automatically. var problemHandler: ((String) -> Void)? let appVersion: String = (try? String(contentsOf: supportDir.appendingPathComponent("version.txt"), encoding: .utf8))? .trimmingCharacters(in: .whitespacesAndNewlines) ?? "?" func logLine(_ m: String) { let f = DateFormatter() f.dateFormat = "yyyy-MM-dd HH:mm:ss" let line = "\(f.string(from: Date())) \(m)\n" let data = line.data(using: .utf8)! FileHandle.standardOutput.write(data) try? fm.createDirectory(at: supportDir, withIntermediateDirectories: true) if let h = try? FileHandle(forWritingTo: logURL) { h.seekToEndOfFile(); h.write(data); h.closeFile() } else { try? data.write(to: logURL) } } // MARK: - Settings struct Settings: Codable { var edge = "Left" // side of THIS screen that faces the PC var channel = 1 // PC's Easy-Switch channel var active = true var sourceDir = "" // folder the install came from (for "Reinstall") var clipboardSync = false var clipPort = 51888 init() {} init(from d: Decoder) throws { let c = try d.container(keyedBy: CodingKeys.self) edge = try c.decodeIfPresent(String.self, forKey: .edge) ?? "Left" channel = try c.decodeIfPresent(Int.self, forKey: .channel) ?? 1 active = try c.decodeIfPresent(Bool.self, forKey: .active) ?? true sourceDir = try c.decodeIfPresent(String.self, forKey: .sourceDir) ?? "" clipboardSync = try c.decodeIfPresent(Bool.self, forKey: .clipboardSync) ?? false clipPort = try c.decodeIfPresent(Int.self, forKey: .clipPort) ?? 51888 } } func loadSettings() -> Settings { guard let d = try? Data(contentsOf: settingsURL), let s = try? JSONDecoder().decode(Settings.self, from: d) else { return Settings() } return s } func saveSettings(_ s: Settings) { try? fm.createDirectory(at: supportDir, withIntermediateDirectories: true) let e = JSONEncoder(); e.outputFormatting = .prettyPrinted try? e.encode(s).write(to: settingsURL) } // MARK: - Logitech HID++ over IOKit struct KnownDevice: Codable { var key: String // "-", e.g. "B020-255" (Bluetooth) or "C52B-2" (receiver slot 2) var name: String var devIndex: Int // 0xFF = Bluetooth direct, 1...6 = receiver slot var featureIndex: Int // index of feature 0x1814 on this device var hostCount: Int var currentHost: Int? } let hidQueue = DispatchQueue(label: "logiswitch.hid") var knownDevices: [KnownDevice] = [] // only touched on hidQueue func loadKnown() { if let d = try? Data(contentsOf: devicesURL), let k = try? JSONDecoder().decode([KnownDevice].self, from: d) { knownDevices = k } } func saveKnown() { let e = JSONEncoder(); e.outputFormatting = .prettyPrinted let clean = knownDevices.map { d -> KnownDevice in var x = d; x.currentHost = nil; return x } try? e.encode(clean).write(to: devicesURL) } func remember(_ list: [KnownDevice]) { guard !list.isEmpty else { return } for d in list { knownDevices.removeAll { $0.key == d.key } knownDevices.append(d) } saveKnown() } func hidProp(_ d: IOHIDDevice, _ key: String) -> Any? { IOHIDDeviceGetProperty(d, key as CFString) } func productID(_ d: IOHIDDevice) -> Int { (hidProp(d, kIOHIDProductIDKey) as? NSNumber)?.intValue ?? 0 } func productName(_ d: IOHIDDevice) -> String { (hidProp(d, kIOHIDProductKey) as? String) ?? String(format: "PID %04X", productID(d)) } func usagePage(_ d: IOHIDDevice) -> Int { (hidProp(d, kIOHIDPrimaryUsagePageKey) as? NSNumber)?.intValue ?? 0 } func locationID(_ d: IOHIDDevice) -> Int { (hidProp(d, kIOHIDLocationIDKey) as? NSNumber)?.intValue ?? 0 } func isUSB(_ d: IOHIDDevice) -> Bool { ((hidProp(d, kIOHIDTransportKey) as? String) ?? "").uppercased().contains("USB") } // On macOS a Bluetooth keyboard/mouse is one HID device whose PRIMARY usage is keyboard/mouse; the // Logitech HID++ collection (page 0xFF43) is a secondary usage, so match on any usage page, not primary. let bluetoothMatch: [String: Any] = [kIOHIDVendorIDKey: 0x046D, kIOHIDDeviceUsagePageKey: 0xFF43] let receiverMatch: [String: Any] = [kIOHIDVendorIDKey: 0x046D, kIOHIDDeviceUsagePageKey: 0xFF00] func isKeyboardName(_ n: String) -> Bool { n.range(of: "K\\d|Keys|Keyboard", options: [.regularExpression, .caseInsensitive]) != nil } /// A Logitech HID++ interface: a Bluetooth device (device index 0xFF) or a Unifying/Bolt receiver (slots 1-6). struct HidTarget { let dev: IOHIDDevice; let receiver: Bool } func deviceKey(_ t: HidTarget, _ devIdx: UInt8) -> String { String(format: "%04X-%d", productID(t.dev), Int(devIdx)) } /// One open HID++ connection. Use only on hidQueue. final class HidConn { let dev: IOHIDDevice var inbox: [[UInt8]] = [] let buf = UnsafeMutablePointer.allocate(capacity: 64) init?(_ d: IOHIDDevice) { dev = d let r = IOHIDDeviceOpen(d, IOOptionBits(kIOHIDOptionsTypeNone)) if r != kIOReturnSuccess { logLine("cannot open \(productName(d)) (IOReturn \(String(format: "0x%08X", r)))") buf.deallocate() return nil } IOHIDDeviceScheduleWithRunLoop(d, CFRunLoopGetCurrent(), CFRunLoopMode.defaultMode.rawValue) IOHIDDeviceRegisterInputReportCallback(d, buf, 64, { ctx, _, _, _, reportID, report, length in guard let ctx = ctx else { return } let me = Unmanaged.fromOpaque(ctx).takeUnretainedValue() var bytes = Array(UnsafeBufferPointer(start: report, count: length)) let rid = UInt8(truncatingIfNeeded: reportID) if rid != 0 && bytes.first != rid { bytes.insert(rid, at: 0) } me.inbox.append(bytes) }, Unmanaged.passUnretained(self).toOpaque()) } func close() { IOHIDDeviceRegisterInputReportCallback(dev, buf, 64, nil, nil) IOHIDDeviceUnscheduleFromRunLoop(dev, CFRunLoopGetCurrent(), CFRunLoopMode.defaultMode.rawValue) IOHIDDeviceClose(dev, IOOptionBits(kIOHIDOptionsTypeNone)) buf.deallocate() } /// Sends a full report (first byte = report ID 0x11). @discardableResult func send(_ msg: [UInt8]) -> Bool { let rid = CFIndex(msg[0]) let r = msg.withUnsafeBufferPointer { p in IOHIDDeviceSetReport(dev, kIOHIDReportTypeOutput, rid, p.baseAddress!, p.count) } return r == kIOReturnSuccess } /// Long HID++ 2.0 request. devIdx 0xFF = Bluetooth device, 1-6 = receiver slot. Returns 16 parameter bytes. func request(_ devIdx: UInt8, _ feat: UInt8, _ fn: UInt8, _ params: [UInt8] = [], timeout: TimeInterval = 1.5) -> [UInt8]? { var msg = [UInt8](repeating: 0, count: 20) msg[0] = 0x11; msg[1] = devIdx; msg[2] = feat; msg[3] = (fn << 4) | 0x0B for (i, b) in params.prefix(16).enumerated() { msg[4 + i] = b } inbox.removeAll() guard send(msg) else { return nil } let end = Date().addingTimeInterval(timeout) while Date() < end { _ = CFRunLoopRunInMode(CFRunLoopMode.defaultMode, 0.02, true) while !inbox.isEmpty { let b = inbox.removeFirst() guard b.count >= 4, b[1] == devIdx else { continue } if b[0] == 0x10 && b[2] == 0x8F { return nil } // receiver: device absent/asleep guard b[0] == 0x11, b.count >= 20 else { continue } if b[2] == 0xFF && b[3] == feat { return nil } // HID++ 2.0 error if b[2] == feat && b[3] == msg[3] { return Array(b[4..<20]) } } } return nil } /// Device name via feature 0x0005 (DeviceName), or nil. func deviceName(_ devIdx: UInt8) -> String? { guard let r = request(devIdx, 0x00, 0, [0x00, 0x05]), r[0] != 0 else { return nil } let idx = r[0] guard let cnt = request(devIdx, idx, 0) else { return nil } let len = Int(cnt[0]) var bytes: [UInt8] = [] while bytes.count < len { guard let chunk = request(devIdx, idx, 1, [UInt8(bytes.count)]) else { break } bytes.append(contentsOf: chunk.prefix(len - bytes.count)) } let s = String(decoding: bytes.filter { $0 != 0 }, as: UTF8.self) return s.isEmpty ? nil : s } } /// Runs body with the connected Logitech HID++ interfaces (Bluetooth devices and USB receivers). hidQueue only. func withLogitechDevices(_ body: ([HidTarget]) -> T) -> T { let mgr = IOHIDManagerCreate(kCFAllocatorDefault, IOOptionBits(kIOHIDOptionsTypeNone)) IOHIDManagerSetDeviceMatchingMultiple(mgr, [bluetoothMatch, receiverMatch] as CFArray) let r = IOHIDManagerOpen(mgr, IOOptionBits(kIOHIDOptionsTypeNone)) if r != kIOReturnSuccess { let msg = "IOHIDManagerOpen returned \(String(format: "0x%08X", r)) - if this is 0xE00002E2 (not permitted), allow LogiSwitch in System Settings > Privacy & Security > Input Monitoring" logLine(msg) DispatchQueue.main.async { problemHandler?(msg) } } let devs: [IOHIDDevice] = (IOHIDManagerCopyDevices(mgr) as? Set).map { Array($0) } ?? [] var targets: [HidTarget] = [] var seenReceivers = Set() for d in devs { if isUSB(d) { // Unifying/Bolt receiver (its HID++ interface) if seenReceivers.insert(locationID(d)).inserted { targets.append(HidTarget(dev: d, receiver: true)) } } else { // Bluetooth keyboard or mouse targets.append(HidTarget(dev: d, receiver: false)) } } let result = body(targets) IOHIDManagerClose(mgr, IOOptionBits(kIOHIDOptionsTypeNone)) return result } /// Read-only: finds every connected device that supports channel switching and remembers it. hidQueue only. func discover() -> [KnownDevice] { let found: [KnownDevice] = withLogitechDevices { targets in var out: [KnownDevice] = [] for t in targets { guard let c = HidConn(t.dev) else { continue } defer { c.close() } let slots: [UInt8] = t.receiver ? [1, 2, 3, 4, 5, 6] : [0xFF] for di in slots { guard let r = c.request(di, 0x00, 0, [0x18, 0x14], timeout: t.receiver ? 0.8 : 1.5), r[0] != 0, let info = c.request(di, r[0], 0) else { continue } let name = c.deviceName(di) ?? productName(t.dev) out.append(KnownDevice(key: deviceKey(t, di), name: name, devIndex: Int(di), featureIndex: Int(r[0]), hostCount: Int(info[0]), currentHost: Int(info[1]) + 1)) } } return out } remember(found) return found } /// Seconds since the last keyboard/mouse input on this Mac (no permission needed). func systemIdleSeconds() -> Double { let svc = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("IOHIDSystem")) guard svc != 0 else { return 0 } defer { IOObjectRelease(svc) } guard let v = IORegistryEntryCreateCFProperty(svc, "HIDIdleTime" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue() as? NSNumber else { return 0 } return v.doubleValue / 1_000_000_000 } /// "Whichever device you switch, the other follows": notices a Logitech Bluetooth keyboard or mouse /// disconnecting from this Mac (its own Easy-Switch button was pressed). Runs on the main run loop. final class KeyboardWatch { let mgr = IOHIDManagerCreate(kCFAllocatorDefault, IOOptionBits(kIOHIDOptionsTypeNone)) var keyboards: [String: String] = [:] // device key -> name, for connected Logitech devices var onKeyboardLeft: ((String) -> Void)? // called with the name of the device that left static func key(_ d: IOHIDDevice) -> String { "\(productID(d))-\(locationID(d))" } func start() { IOHIDManagerSetDeviceMatching(mgr, bluetoothMatch as CFDictionary) let ctx = Unmanaged.passUnretained(self).toOpaque() IOHIDManagerRegisterDeviceMatchingCallback(mgr, { ctx, _, _, dev in guard let ctx = ctx else { return } let me = Unmanaged.fromOpaque(ctx).takeUnretainedValue() me.keyboards[KeyboardWatch.key(dev)] = productName(dev) }, ctx) IOHIDManagerRegisterDeviceRemovalCallback(mgr, { ctx, _, _, dev in guard let ctx = ctx else { return } let me = Unmanaged.fromOpaque(ctx).takeUnretainedValue() if let n = me.keyboards.removeValue(forKey: KeyboardWatch.key(dev)) { me.onKeyboardLeft?(n) } }, ctx) IOHIDManagerScheduleWithRunLoop(mgr, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue) IOHIDManagerOpen(mgr, IOOptionBits(kIOHIDOptionsTypeNone)) } } /// Sends every connected device to `channel` (1-based), mice before keyboards. hidQueue only. func switchAll(to channel: Int, onlyMice: Bool = false) -> [String] { return withLogitechDevices { targets -> [String] in // Work out what to send where; unknown Bluetooth devices are identified on the fly. var plan: [(conn: HidConn, dev: KnownDevice)] = [] var conns: [HidConn] = [] for t in targets { guard let c = HidConn(t.dev) else { continue } conns.append(c) if t.receiver { let prefix = String(format: "%04X-", productID(t.dev)) var slots = knownDevices.filter { $0.key.hasPrefix(prefix) } if slots.isEmpty { // receiver never seen before: probe its slots once for di in UInt8(1)...UInt8(6) { guard let r = c.request(di, 0x00, 0, [0x18, 0x14], timeout: 0.8), r[0] != 0, let info = c.request(di, r[0], 0) else { continue } slots.append(KnownDevice(key: deviceKey(t, di), name: c.deviceName(di) ?? productName(t.dev), devIndex: Int(di), featureIndex: Int(r[0]), hostCount: Int(info[0]), currentHost: nil)) } remember(slots) } for k in slots { plan.append((c, k)) } } else { let key = deviceKey(t, 0xFF) if let k = knownDevices.first(where: { $0.key == key }) { plan.append((c, k)); continue } guard let r = c.request(0xFF, 0x00, 0, [0x18, 0x14]), r[0] != 0 else { continue } let hosts = c.request(0xFF, r[0], 0).map { Int($0[0]) } ?? 3 let k = KnownDevice(key: key, name: productName(t.dev), devIndex: 0xFF, featureIndex: Int(r[0]), hostCount: hosts, currentHost: nil) remember([k]); plan.append((c, k)) } } if onlyMice { plan = plan.filter { !isKeyboardName($0.dev.name) } } plan.sort { !isKeyboardName($0.dev.name) && isKeyboardName($1.dev.name) } func changeHost(_ d: KnownDevice) -> [UInt8] { var m = [UInt8](repeating: 0, count: 20) m[0] = 0x11; m[1] = UInt8(d.devIndex); m[2] = UInt8(d.featureIndex); m[3] = 0x1B; m[4] = UInt8(channel - 1) return m } func stillHere(_ p: (conn: HidConn, dev: KnownDevice)) -> Bool { p.conn.request(UInt8(p.dev.devIndex), 0x00, 0, [0x18, 0x14], timeout: 0.4) != nil } var out: [String] = [] var sent: [Int] = [] var attempts: [Int: Int] = [:] for (i, p) in plan.enumerated() { if channel > p.dev.hostCount { out.append("\(p.dev.name): has only \(p.dev.hostCount) channels, skipped"); continue } if p.conn.send(changeHost(p.dev)) { sent.append(i); attempts[i] = 1 } else { out.append("\(p.dev.name) -> channel \(channel): failed") } } // Confirm: a device that still answers here did not switch (command lost); re-send, up to 3 attempts. var waiting = sent for _ in 0..<2 { if waiting.isEmpty { break } Thread.sleep(forTimeInterval: 0.6) var again: [Int] = [] for i in waiting where stillHere(plan[i]) { _ = plan[i].conn.send(changeHost(plan[i].dev)) attempts[i, default: 1] += 1 again.append(i) } waiting = again } if !waiting.isEmpty { Thread.sleep(forTimeInterval: 0.6) } for i in sent { let n = attempts[i] ?? 1 let failed = waiting.contains(i) && stillHere(plan[i]) out.append("\(plan[i].dev.name) -> channel \(channel): " + (failed ? "FAILED after \(n) attempts (device still on this Mac)" : (n > 1 ? "sent (attempt \(n))" : "sent"))) } conns.forEach { $0.close() } if out.isEmpty { out.append("no Logitech device is connected to this Mac right now") } return out } } // MARK: - Clipboard sync (stage 1: plain text) // // This Mac listens; the PC dials out to it and keeps one connection open, so nothing ever has // to connect in to the PC (its firewall blocks that). Both directions use that one connection. // Every message: [4-byte length][16-byte IV][AES-256-CBC ciphertext][32-byte HMAC-SHA256]. // Plaintext: [1 type][8-byte unix ms][payload]. Keys come from the shared pairing code. // Payload for type 0x10: [1 byte format count] then [1 byte format][4-byte length][data] each, // format 1 = UTF-8 text (later stages add 2 = HTML, 3 = RTF, 4 = PNG). let clipCodeURL = supportDir.appendingPathComponent("clipboard-code.txt") let codeAlphabet = Array("0123456789ABCDEFGHJKMNPQRSTVWXYZ") // Crockford base32: no I, L, O or U func newPairingCode() -> String { var out = "" for i in 0..<16 { if i > 0 && i % 4 == 0 { out.append("-") } out.append(codeAlphabet[Int.random(in: 0..<32)]) } return out } func normalizeCode(_ s: String) -> String { var out = "" for raw in s.uppercased() { var c = raw if c == "I" || c == "L" { c = "1" } else if c == "O" { c = "0" } else if c == "U" { c = "V" } if codeAlphabet.contains(c) { out.append(c) } } return out } func readPairingCode() -> String { guard let t = try? String(contentsOf: clipCodeURL, encoding: .utf8) else { return "" } for line in t.split(separator: "\n") { let l = line.trimmingCharacters(in: .whitespaces) if !l.isEmpty && !l.hasPrefix("#") { return l } } return "" } func writePairingCode(_ code: String) { let body = """ # LogiSwitch clipboard pairing code. The SAME code must be set on the PC. # Anyone with this code and access to your network could read the shared clipboard. \(code) """ try? body.write(to: clipCodeURL, atomically: true, encoding: .utf8) } /// This Mac's address on the local network, for typing into the PC. func localIPv4() -> String { var best: String? var ifaddr: UnsafeMutablePointer? guard getifaddrs(&ifaddr) == 0, let first = ifaddr else { return "?" } defer { freeifaddrs(ifaddr) } var p: UnsafeMutablePointer? = first while let cur = p { let f = cur.pointee if let sa = f.ifa_addr, sa.pointee.sa_family == UInt8(AF_INET), (f.ifa_flags & UInt32(IFF_LOOPBACK)) == 0 { var host = [CChar](repeating: 0, count: Int(NI_MAXHOST)) if getnameinfo(sa, socklen_t(sa.pointee.sa_len), &host, socklen_t(host.count), nil, 0, NI_NUMERICHOST) == 0 { let ip = String(cString: host) let name = String(cString: f.ifa_name) if best == nil || name == "en0" { best = ip } } } p = f.ifa_next } return best ?? "?" } final class ClipServer { private var encKey = Data(), macKey = Data() private var listenFD: Int32 = -1 private var clientFD: Int32 = -1 private let wlock = NSLock() private var running = false var port: UInt16 = 51888 var onText: ((String) -> Void)? var onInfo: ((String) -> Void)? var onConnected: (() -> Void)? private var rejected = 0 // rejected connections in a row; only the first (then one every ~10 min) is logged var isConnected: Bool { wlock.lock(); defer { wlock.unlock() }; return clientFD >= 0 } // ---- crypto helpers (CommonCrypto) ---- private static func pbkdf2(_ password: String, _ salt: String, rounds: UInt32, length: Int) -> Data { var out = [UInt8](repeating: 0, count: length) let saltBytes = Array(salt.utf8) _ = password.withCString { pw in CCKeyDerivationPBKDF(CCPBKDFAlgorithm(kCCPBKDF2), pw, strlen(pw), saltBytes, saltBytes.count, CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256), rounds, &out, length) } return Data(out) } private static func hmac(_ key: Data, _ data: Data) -> Data { var out = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH)) let k = [UInt8](key), d = [UInt8](data) CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), k, k.count, d, d.count, &out) return Data(out) } private static func aes(_ op: Int, key: Data, iv: Data, input: Data) -> Data? { var out = [UInt8](repeating: 0, count: input.count + kCCBlockSizeAES128) var moved = 0 let k = [UInt8](key), v = [UInt8](iv), i = [UInt8](input) let status = CCCrypt(CCOperation(op), CCAlgorithm(kCCAlgorithmAES), CCOptions(kCCOptionPKCS7Padding), k, k.count, v, i, i.count, &out, out.count, &moved) guard status == CCCryptorStatus(kCCSuccess) else { return nil } return Data(out[0.. Data? { var plain = Data([type]) let ms = UInt64(Date().timeIntervalSince1970 * 1000) for i in 0..<8 { plain.append(UInt8(truncatingIfNeeded: ms >> (8 * (7 - UInt64(i))))) } plain.append(payload) var ivBytes = [UInt8](repeating: 0, count: 16) arc4random_buf(&ivBytes, 16) let iv = Data(ivBytes) guard let ct = ClipServer.aes(kCCEncrypt, key: encKey, iv: iv, input: plain) else { return nil } var body = iv body.append(ct) body.append(ClipServer.hmac(macKey, body)) let len = body.count var frame = Data([UInt8(truncatingIfNeeded: len >> 24), UInt8(truncatingIfNeeded: len >> 16), UInt8(truncatingIfNeeded: len >> 8), UInt8(truncatingIfNeeded: len)]) frame.append(body) return frame } private func open(_ body: Data) -> (UInt8, Data)? { guard body.count >= 64, (body.count - 48) % 16 == 0 else { return nil } let b = [UInt8](body) let ctLen = b.count - 48 let tag = ClipServer.hmac(macKey, Data(b[0..<(16 + ctLen)])) var diff: UInt8 = 0 let tagBytes = [UInt8](tag) for i in 0..<32 { diff |= tagBytes[i] ^ b[16 + ctLen + i] } guard diff == 0 else { return nil } guard let plain = ClipServer.aes(kCCDecrypt, key: encKey, iv: Data(b[0..<16]), input: Data(b[16..<(16 + ctLen)])), plain.count >= 9 else { return nil } let p = [UInt8](plain) var ms: UInt64 = 0 for i in 0..<8 { ms = (ms << 8) | UInt64(p[1 + i]) } let now = UInt64(Date().timeIntervalSince1970 * 1000) let delta = ms > now ? ms - now : now - ms guard delta <= 120_000 else { return nil } // replay return (p[0], Data(p[9...])) } // ---- payload ---- static func payload(text: String) -> Data { let b = Array(text.utf8) var d = Data([1, 1]) d.append(contentsOf: [UInt8(truncatingIfNeeded: b.count >> 24), UInt8(truncatingIfNeeded: b.count >> 16), UInt8(truncatingIfNeeded: b.count >> 8), UInt8(truncatingIfNeeded: b.count)]) d.append(contentsOf: b) return d } private func text(from payload: Data) -> String? { let b = [UInt8](payload) guard b.count >= 6 else { return nil } var i = 1 for _ in 0..= 0, i + len <= b.count else { return nil } if fmt == 1 { return String(decoding: b[i..<(i + len)], as: UTF8.self) } i += len } return nil } // ---- server ---- // On macOS, closing a socket from another thread does not wake a blocked accept()/recv(), so the // server thread owns its sockets and polls; stop() only bumps the generation and shuts the client down. private var gen = 0 private func alive(_ g: Int) -> Bool { wlock.lock(); defer { wlock.unlock() }; return running && gen == g } func start(code: String, port: UInt16) { stop() self.port = port setKeys(code) rejected = 0 wlock.lock(); running = true; gen += 1; let g = gen; wlock.unlock() let t = Thread { [weak self] in self?.listenLoop(g) } t.stackSize = 512 * 1024 t.start() } func stop() { wlock.lock() running = false gen += 1 if clientFD >= 0 { shutdown(clientFD, SHUT_RDWR) } // wakes the server thread, which closes it wlock.unlock() } private func listenLoop(_ g: Int) { let fd = socket(AF_INET, SOCK_STREAM, 0) guard fd >= 0 else { onInfo?("ERROR: clipboard sync could not open a socket"); return } var yes: Int32 = 1 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, socklen_t(MemoryLayout.size)) var addr = sockaddr_in() addr.sin_len = UInt8(MemoryLayout.size) addr.sin_family = sa_family_t(AF_INET) addr.sin_port = port.bigEndian addr.sin_addr.s_addr = INADDR_ANY // A previous server thread may still hold the port for up to half a second after a restart. var bound: Int32 = -1 for _ in 0..<15 { bound = withUnsafePointer(to: &addr) { p in p.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(fd, $0, socklen_t(MemoryLayout.size)) } } if bound == 0 || !alive(g) { break } Thread.sleep(forTimeInterval: 0.2) } guard alive(g) else { close(fd); return } guard bound == 0, listen(fd, 4) == 0 else { onInfo?("ERROR: clipboard sync could not listen on port \(port) (another program may be using it)") close(fd); return } wlock.lock(); listenFD = fd; wlock.unlock() onInfo?("clipboard sync: listening on \(localIPv4()):\(port) for the PC") while alive(g) { guard pending(fd, ms: 500) else { continue } let c = accept(fd, nil, nil) if c < 0 { if errno != EINTR { Thread.sleep(forTimeInterval: 0.5) }; continue } var one: Int32 = 1 setsockopt(c, Int32(IPPROTO_TCP), TCP_NODELAY, &one, socklen_t(MemoryLayout.size)) setsockopt(c, SOL_SOCKET, SO_NOSIGPIPE, &one, socklen_t(MemoryLayout.size)) var tv = timeval(tv_sec: 1, tv_usec: 0) // short, so a stale connection is noticed quickly setsockopt(c, SOL_SOCKET, SO_RCVTIMEO, &tv, socklen_t(MemoryLayout.size)) wlock.lock(); clientFD = c; wlock.unlock() let wasRejected = serve(c, listener: fd, gen: g) wlock.lock() if clientFD == c { clientFD = -1 } wlock.unlock() close(c) if alive(g) && !wasRejected { onInfo?("clipboard sync: the PC disconnected") } } wlock.lock(); if listenFD == fd { listenFD = -1 }; wlock.unlock() close(fd) } /// True if fd becomes readable (for a listening socket: a connection is waiting) within ms. private func pending(_ fd: Int32, ms: Int32) -> Bool { var p = pollfd(fd: fd, events: Int16(POLLIN), revents: 0) return poll(&p, 1, ms) > 0 && (p.revents & Int16(POLLIN)) != 0 } /// nil = closed or failed, empty = nothing arrived before the timeout. private func readExact(_ fd: Int32, _ n: Int) -> Data? { var buf = [UInt8](repeating: 0, count: n) var got = 0 while got < n { let r = buf.withUnsafeMutableBytes { p -> Int in recv(fd, p.baseAddress!.advanced(by: got), n - got, 0) } if r > 0 { got += r; continue } if r == 0 { return nil } if errno == EINTR { continue } if errno == EAGAIN || errno == EWOULDBLOCK { if got == 0 { return Data() } // idle, no message started continue // mid-message: keep waiting } return nil } return Data(buf) } /// Returns true if the connection was dropped because a message failed the security check. private func serve(_ fd: Int32, listener: Int32, gen g: Int) -> Bool { var lastHeard = Date() while alive(g) { guard let head = readExact(fd, 4) else { return false } if head.isEmpty { // The PC sends a keepalive every 20 s. Silence, or a new connection from the PC (it reconnected // after sleep or a network change), means this one is dead: drop it and accept the new one. if Date().timeIntervalSince(lastHeard) > 50 || pending(listener, ms: 0) { return false } continue } lastHeard = Date() let h = [UInt8](head) let len = Int(h[0]) << 24 | Int(h[1]) << 16 | Int(h[2]) << 8 | Int(h[3]) guard len >= 64, len <= 12 * 1024 * 1024 else { return false } guard let body = readExact(fd, len), body.count == len else { return false } guard let (type, payload) = open(body) else { // The PC retries every few seconds, so log the first rejection and then about every 10 minutes. rejected += 1 if rejected == 1 || rejected % 300 == 0 { onInfo?("ERROR: clipboard sync rejected a message (the two computers' pairing codes do not match, or a clock is more than 2 minutes off)" + (rejected > 1 ? " - \(rejected) attempts so far" : "; further rejections are not logged")) } return true } if rejected > 0 { onInfo?("clipboard sync: pairing codes now match (after \(rejected) rejected attempts)"); rejected = 0 } if type == 0x01 { onInfo?("clipboard sync: the PC connected"); onConnected?() } if type == 0x10, let t = text(from: payload) { onText?(t) } } return false } @discardableResult func sendText(_ s: String) -> Bool { guard let frame = seal(0x10, ClipServer.payload(text: s)) else { return false } wlock.lock(); defer { wlock.unlock() } guard clientFD >= 0 else { return false } let bytes = [UInt8](frame) var off = 0 while off < bytes.count { let w = bytes.withUnsafeBytes { p -> Int in send(clientFD, p.baseAddress!.advanced(by: off), bytes.count - off, 0) } if w <= 0 { shutdown(clientFD, SHUT_RDWR); return false } // the server thread closes it off += w } return true } } // MARK: - Edge detection final class EdgeWatcher { var since: Date? var armed = false // re-arms only after the cursor has left the edge var cooldownUntil = Date.distantPast var onHit: (() -> Void)? private func inside(_ f: NSRect, _ p: NSPoint) -> Bool { p.x >= f.minX && p.x <= f.maxX && p.y >= f.minY && p.y <= f.maxY } func tick(edge: String, dwell: TimeInterval) { let now = Date() if now < cooldownUntil || NSEvent.pressedMouseButtons != 0 { since = nil; return } let p = NSEvent.mouseLocation guard let screen = NSScreen.screens.first(where: { inside($0.frame, p) }) else { since = nil; return } let f = screen.frame let inMiddle = p.y >= f.minY + f.height * 0.1 && p.y <= f.maxY - f.height * 0.1 let atEdge: Bool let beyond: NSPoint if edge == "Right" { atEdge = p.x >= f.maxX - 1.5; beyond = NSPoint(x: f.maxX + 2, y: p.y) } else { atEdge = p.x <= f.minX + 0.5; beyond = NSPoint(x: f.minX - 2, y: p.y) } let outer = atEdge && inMiddle && !NSScreen.screens.contains(where: { inside($0.frame, beyond) }) if !outer { since = nil; armed = true; return } if !armed { return } guard let s = since else { since = now; return } if now.timeIntervalSince(s) < dwell { return } since = nil; armed = false; cooldownUntil = now.addingTimeInterval(1) onHit?() } } // MARK: - Launch agent func launchAgentPlist() -> String { return """ Labelcom.logiswitch.agent ProgramArguments\(binaryURL.path) RunAtLoad KeepAliveSuccessfulExit LimitLoadToSessionTypeAqua ProcessTypeInteractive AbandonProcessGroup StandardErrorPath\(supportDir.path)/stderr.log """ } func runDetached(_ script: String, _ args: [String]) { let p = Process() p.executableURL = URL(fileURLWithPath: "/bin/bash") p.arguments = [script] + args p.currentDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory()) do { try p.run() } catch { logLine("could not run \(script): \(error)") } } // MARK: - Menu-bar app final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation { var settings = loadSettings() let dryRun: Bool var statusItem: NSStatusItem! let watcher = EdgeWatcher() var tickTimer: Timer? var refreshTimer: Timer? let menu = NSMenu() var miStatus = NSMenuItem(), miActive = NSMenuItem(), miLeft = NSMenuItem(), miRight = NSMenuItem() var miLogin = NSMenuItem(), miUpdSrc = NSMenuItem(), miProblem = NSMenuItem() var miChannels: [NSMenuItem] = [] var hasProblem = false var lastAutoReport = Date.distantPast var lastSwitch = Date.distantPast let keyboardWatch = KeyboardWatch() let clipServer = ClipServer() var clipTimer: Timer? var lastClipChange = 0 var lastClipText: String? var pendingClip: String? // copied here while the PC was not connected; sent when it connects var miClip = NSMenuItem(), miClipOn = NSMenuItem(), miClipAddr = NSMenuItem(), miClipCode = NSMenuItem() init(dryRun: Bool) { self.dryRun = dryRun; super.init() } func applicationDidFinishLaunching(_ notification: Notification) { statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) buildMenu() statusItem.menu = menu refreshUI() problemHandler = { [weak self] reason in self?.autoReport(reason) } // Talking to a keyboard needs "Input Monitoring"; this shows macOS's own permission prompt once. let granted = IOHIDRequestAccess(kIOHIDRequestTypeListenEvent) logLine("Input Monitoring permission: \(granted ? "granted" : "NOT granted - allow LogiSwitch in System Settings > Privacy & Security > Input Monitoring, then quit and reopen it from the menu bar (or log out and in)")") if fm.fileExists(atPath: markerURL.path) { autoReport("LogiSwitch stopped unexpectedly last time (crash or forced quit); see stderr.log in the report") } fm.createFile(atPath: markerURL.path, contents: nil) watcher.onHit = { [weak self] in self?.edgeHit() } keyboardWatch.onKeyboardLeft = { [weak self] name in self?.keyboardLeft(name) } keyboardWatch.start() startClipboardSync() tickTimer = Timer.scheduledTimer(withTimeInterval: 0.02, repeats: true) { [weak self] _ in guard let s = self, s.settings.active else { return } s.watcher.tick(edge: s.settings.edge, dwell: 0.05) } refreshTimer = Timer.scheduledTimer(withTimeInterval: 180, repeats: true) { _ in hidQueue.async { _ = discover() } } let edge = settings.edge, ch = settings.channel, dry = dryRun hidQueue.async { loadKnown() let now = discover() let names = knownDevices.map { $0.name }.joined(separator: ", ") logLine("started v\(appVersion): PC on the \(edge.lowercased()) edge -> channel \(ch); devices: \(names) (connected now: \(now.count))\(dry ? " [DRY RUN]" : "")") } } func edgeHit() { let ch = settings.channel if dryRun { logLine("edge hit -> would switch to channel \(ch)"); return } switchAndCheck(ch) } /// A keyboard or mouse left this Mac (its own Easy-Switch button was pressed): the devices /// still connected here follow it. (The one that left is no longer connected, so it is skipped.) func keyboardLeft(_ name: String) { guard settings.active else { return } if Date().timeIntervalSince(lastSwitch) < 5 { logLine("\(name) left (part of our own switch)"); return } let idle = systemIdleSeconds() if idle > 60 { logLine("\(name) left while this Mac was idle for \(Int(idle)) s - treated as sleep/power-off, nothing follows"); return } logLine("\(name) switched away -> the other devices follow to channel \(settings.channel)") if dryRun { return } switchAndCheck(settings.channel) } /// Switches on the HID queue; if no device got the command, creates a problem report. func switchAndCheck(_ ch: Int, onlyMice: Bool = false) { lastSwitch = Date() hidQueue.async { let lines = switchAll(to: ch, onlyMice: onlyMice) lines.forEach { logLine($0) } if !lines.contains(where: { $0.contains(": sent") }) { let reason = "switch to channel \(ch) reached no device (\(lines.joined(separator: "; ")))" DispatchQueue.main.async { problemHandler?(reason) } } else if lines.contains(where: { $0.contains("FAILED") }) { let reason = "a device did not switch to channel \(ch) (\(lines.filter { $0.contains("FAILED") }.joined(separator: "; ")))" DispatchQueue.main.async { problemHandler?(reason) } } } } /// Creates a support report automatically (max one per 30 minutes) and notifies the user. func autoReport(_ reason: String) { logLine("ERROR: \(reason)") hasProblem = true miProblem.isHidden = false refreshUI() if Date().timeIntervalSince(lastAutoReport) < 1800 { logLine("problem noted, report skipped (one per 30 min)"); return } lastAutoReport = Date() logLine("creating automatic problem report") runDetached(supportDir.appendingPathComponent("report.sh").path, ["--auto", reason]) } func applicationWillTerminate(_ notification: Notification) { clipServer.stop() try? fm.removeItem(at: markerURL) } // ---- clipboard sync ---- func startClipboardSync() { clipTimer?.invalidate(); clipTimer = nil clipServer.stop() guard settings.clipboardSync else { return } var code = readPairingCode() if normalizeCode(code).count != 16 { code = newPairingCode(); writePairingCode(code) } clipServer.onInfo = { msg in DispatchQueue.main.async { logLine(msg) } } clipServer.onText = { [weak self] t in DispatchQueue.main.async { guard let s = self, !t.isEmpty, t != s.lastClipText else { return } s.lastClipText = t s.pendingClip = nil // the PC's newer text replaces what was waiting here let pb = NSPasteboard.general pb.clearContents() pb.setString(t, forType: .string) s.lastClipChange = pb.changeCount logLine("clipboard: received \(t.count) characters from the PC") } } // Text copied here while the PC was away is sent as soon as it connects, if it is still on the clipboard. clipServer.onConnected = { [weak self] in DispatchQueue.main.async { guard let s = self, let t = s.pendingClip else { return } s.pendingClip = nil guard NSPasteboard.general.string(forType: .string) == t, t != s.lastClipText else { return } if s.clipServer.sendText(t) { s.lastClipText = t; logLine("clipboard: sent \(t.count) characters to the PC (copied while it was not connected)") } else { s.pendingClip = t } } } clipServer.start(code: code, port: UInt16(settings.clipPort)) lastClipChange = NSPasteboard.general.changeCount clipTimer = Timer.scheduledTimer(withTimeInterval: 0.12, repeats: true) { [weak self] _ in self?.pollClipboard() } } func pollClipboard() { let pb = NSPasteboard.general guard pb.changeCount != lastClipChange else { return } lastClipChange = pb.changeCount guard let t = pb.string(forType: .string), !t.isEmpty, t != lastClipText else { return } if t.utf8.count > 1_048_576 { logLine("clipboard: \(t.utf8.count / 1024) KB copied here is too large to sync (limit 1024 KB)") return } // Only text that actually reached the PC counts as sent; anything else waits for the PC to connect. if clipServer.sendText(t) { lastClipText = t; pendingClip = nil; logLine("clipboard: sent \(t.count) characters to the PC") } else { pendingClip = t } } func askText(_ title: String, _ message: String, _ initial: String) -> String? { NSApp.activate(ignoringOtherApps: true) let a = NSAlert() a.messageText = title a.informativeText = message a.addButton(withTitle: "OK") a.addButton(withTitle: "Cancel") let tf = NSTextField(frame: NSRect(x: 0, y: 0, width: 280, height: 24)) tf.stringValue = initial a.accessoryView = tf a.window.initialFirstResponder = tf return a.runModal() == .alertFirstButtonReturn ? tf.stringValue : nil } @objc func toggleClipboard() { if settings.clipboardSync { settings.clipboardSync = false saveSettings(settings); startClipboardSync(); logLine("clipboard sync: off"); refreshUI() return } let warn = """ Anything you copy on either computer is then sent to the other over your local network \ (encrypted, and the PC only ever dials out - nothing connects in to it). That includes anything you copy from work applications on the PC. Only turn this on if you \ are comfortable with company text reaching this Mac. """ NSApp.activate(ignoringOtherApps: true) let a = NSAlert() a.messageText = "Share the text clipboard with the PC?" a.informativeText = warn a.alertStyle = .warning a.addButton(withTitle: "Share clipboard") a.addButton(withTitle: "Cancel") guard a.runModal() == .alertFirstButtonReturn else { return } var code = readPairingCode() if normalizeCode(code).count != 16 { code = newPairingCode() writePairingCode(code) let pb = NSPasteboard.general; pb.clearContents(); pb.setString(code, forType: .string) _ = alert("LogiSwitch pairing code", "Your pairing code is:\n\n\(code)\n\nIt has been copied to this clipboard and saved in clipboard-code.txt. Enter the SAME code on the PC (icon beside the clock > Clipboard sync > Pairing code).") } settings.clipboardSync = true saveSettings(settings); startClipboardSync() _ = alert("Clipboard sync is on", "On the PC, open the LogiSwitch icon beside the clock > Clipboard sync, set this Mac's address to \(localIPv4()), enter the same pairing code, and switch it on.") refreshUI() } @objc func showClipAddress() { let ip = localIPv4() let pb = NSPasteboard.general; pb.clearContents(); pb.setString(ip, forType: .string) _ = alert("This Mac's address", "\(ip) (port \(settings.clipPort))\n\nCopied to this clipboard. Enter it on the PC under Clipboard sync > Set the Mac's address.\n\nIf it stops working later, your router has probably given this Mac a different address; check here again.") } @objc func showClipCode() { var cur = readPairingCode() if normalizeCode(cur).count != 16 { cur = newPairingCode(); writePairingCode(cur) } let pb = NSPasteboard.general; pb.clearContents(); pb.setString(cur, forType: .string) guard let new = askText("LogiSwitch pairing code", "This Mac's code (copied to the clipboard). Enter the SAME code on the PC.\n\nTo use a code from the PC instead, type it here.", cur), !new.isEmpty else { return } guard normalizeCode(new).count == 16 else { _ = alert("LogiSwitch", "That code is not 16 characters long, so it was not saved.") return } writePairingCode(new.trimmingCharacters(in: .whitespaces)) startClipboardSync() refreshUI() } // Menu func item(_ title: String, _ action: Selector?) -> NSMenuItem { let i = NSMenuItem(title: title, action: action, keyEquivalent: "") i.target = self return i } func buildMenu() { miStatus = item("LogiSwitch", nil) menu.addItem(miStatus) menu.addItem(.separator()) miActive = item("Active - switch when cursor hits the edge", #selector(toggleActive)) menu.addItem(miActive) menu.addItem(item("Send keyboard + mouse to the PC now", #selector(sendNow))) menu.addItem(.separator()) let side = NSMenuItem(title: "Where is the PC?", action: nil, keyEquivalent: "") let sideMenu = NSMenu() miLeft = item("PC is to the LEFT of this Mac", #selector(setSide(_:))); miLeft.representedObject = "Left" miRight = item("PC is to the RIGHT of this Mac", #selector(setSide(_:))); miRight.representedObject = "Right" sideMenu.addItem(miLeft); sideMenu.addItem(miRight) side.submenu = sideMenu menu.addItem(side) let chan = NSMenuItem(title: "PC's Easy-Switch channel", action: nil, keyEquivalent: "") let chanMenu = NSMenu() for c in 1...3 { let i = item("Channel \(c)", #selector(setChannel(_:))); i.tag = c chanMenu.addItem(i); miChannels.append(i) } chan.submenu = chanMenu menu.addItem(chan) miClip = NSMenuItem(title: "Clipboard sync", action: nil, keyEquivalent: "") let clipMenu = NSMenu() miClipOn = item("Share the text clipboard with the PC", #selector(toggleClipboard)) miClipAddr = item("This Mac's address...", #selector(showClipAddress)) miClipCode = item("Pairing code...", #selector(showClipCode)) clipMenu.addItem(miClipOn); clipMenu.addItem(miClipAddr); clipMenu.addItem(miClipCode) miClip.submenu = clipMenu menu.addItem(miClip) miLogin = item("Start at login", #selector(toggleLogin)) menu.addItem(miLogin) menu.addItem(.separator()) menu.addItem(item("Show devices", #selector(showDevices))) menu.addItem(item("Re-detect devices", #selector(redetect))) menu.addItem(item("Open log", #selector(openLog))) menu.addItem(item("Create support report for Claude...", #selector(makeReport))) miProblem = item("Open automatic problem report (copies it for Claude)", #selector(openProblem)) miProblem.isHidden = !fm.fileExists(atPath: problemURL.path) menu.addItem(miProblem) menu.addItem(.separator()) let upd = NSMenuItem(title: "Update", action: nil, keyEquivalent: "") let updMenu = NSMenu() miUpdSrc = item("Reinstall from the original folder", #selector(updateFromSource)) updMenu.addItem(miUpdSrc) updMenu.addItem(item("Update from a folder...", #selector(updateFromFolder))) upd.submenu = updMenu menu.addItem(upd) menu.addItem(item("Uninstall...", #selector(uninstall))) menu.addItem(item("Quit (until next login)", #selector(quit))) } func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { if menuItem === miStatus { return false } if menuItem === miUpdSrc { return !settings.sourceDir.isEmpty && fm.fileExists(atPath: (settings.sourceDir as NSString).appendingPathComponent("install.sh")) } return true } func refreshUI() { let on = settings.active if let b = statusItem.button { let symbol = hasProblem ? "exclamationmark.triangle" : (on ? "arrow.left.arrow.right.circle.fill" : "pause.circle") let img = NSImage(systemSymbolName: symbol, accessibilityDescription: "LogiSwitch") img?.isTemplate = true b.image = img b.toolTip = "LogiSwitch: \(on ? "Active" : "Paused") (PC on the \(settings.edge.lowercased()), channel \(settings.channel))" } miStatus.title = "LogiSwitch \(appVersion) - \(on ? "Active" : "Paused")" miActive.state = on ? .on : .off miLeft.state = settings.edge == "Left" ? .on : .off miRight.state = settings.edge == "Right" ? .on : .off for i in miChannels { i.state = i.tag == settings.channel ? .on : .off } miLogin.state = fm.fileExists(atPath: plistURL.path) ? .on : .off miClipOn.state = settings.clipboardSync ? .on : .off miClip.title = "Clipboard sync" + (settings.clipboardSync ? (clipServer.isConnected ? " (on, PC connected)" : " (on, waiting for the PC)") : " (off)") miClipAddr.title = "This Mac's address... (\(localIPv4()))" } func apply(_ what: String) { saveSettings(settings) logLine(what) refreshUI() } func alert(_ title: String, _ text: String, confirm: Bool = false) -> Bool { NSApp.activate(ignoringOtherApps: true) let a = NSAlert() a.messageText = title a.informativeText = text a.addButton(withTitle: confirm ? "Uninstall" : "OK") if confirm { a.addButton(withTitle: "Cancel") } return a.runModal() == .alertFirstButtonReturn } @objc func toggleActive() { settings.active.toggle(); apply(settings.active ? "resumed" : "paused") } @objc func sendNow() { switchAndCheck(settings.channel) } @objc func openProblem() { guard let text = try? String(contentsOf: problemURL, encoding: .utf8) else { _ = alert("LogiSwitch", "The problem report is still being created. Try again in a minute.") return } NSPasteboard.general.clearContents() NSPasteboard.general.setString(text, forType: .string) NSWorkspace.shared.open(fm.fileExists(atPath: desktopReportURL.path) ? desktopReportURL : problemURL) hasProblem = false refreshUI() } @objc func setSide(_ sender: NSMenuItem) { settings.edge = (sender.representedObject as? String) ?? "Left"; apply("PC is now on the \(settings.edge.lowercased())") } @objc func setChannel(_ sender: NSMenuItem) { settings.channel = sender.tag; apply("PC channel is now \(settings.channel)") } @objc func toggleLogin() { if fm.fileExists(atPath: plistURL.path) { try? fm.removeItem(at: plistURL) logLine("start at login: off") } else { try? fm.createDirectory(at: plistURL.deletingLastPathComponent(), withIntermediateDirectories: true) try? launchAgentPlist().write(to: plistURL, atomically: true, encoding: .utf8) logLine("start at login: on") } refreshUI() } @objc func showDevices() { let list = hidQueue.sync { knownDevices.map { "- \($0.name) (\($0.hostCount) channels)" } } _ = alert("LogiSwitch devices", list.isEmpty ? "No devices known yet. Put the keyboard and mouse on this Mac, then choose Re-detect devices." : list.joined(separator: "\n")) } @objc func redetect() { hidQueue.async { let f = discover() logLine("re-detected: " + (f.isEmpty ? "no devices connected" : f.map { "\($0.name) (channel \($0.currentHost ?? 0))" }.joined(separator: ", "))) } } @objc func openLog() { NSWorkspace.shared.open(logURL) } @objc func makeReport() { runDetached(supportDir.appendingPathComponent("report.sh").path, []) } @objc func updateFromSource() { runInstaller(settings.sourceDir) } @objc func updateFromFolder() { NSApp.activate(ignoringOtherApps: true) let p = NSOpenPanel() p.canChooseDirectories = true; p.canChooseFiles = false; p.allowsMultipleSelection = false p.message = "Choose the folder that contains the new LogiSwitch files (install.sh)" if p.runModal() == .OK, let url = p.url { runInstaller(url.path) } } func runInstaller(_ dir: String) { let sh = (dir as NSString).appendingPathComponent("install.sh") guard fm.fileExists(atPath: sh) else { _ = alert("LogiSwitch", "No install.sh in:\n\(dir)"); return } logLine("updating from \(dir)") runDetached(sh, ["--quiet"]) // the installer restarts this app } @objc func uninstall() { guard alert("Uninstall LogiSwitch?", "This stops it, removes it from login items and deletes its files. Your Logitech devices and pairings are not affected.", confirm: true) else { return } logLine("uninstall requested") let src = supportDir.appendingPathComponent("uninstall.sh") let tmp = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("logiswitch-uninstall.sh") try? fm.removeItem(at: tmp) try? fm.copyItem(at: src, to: tmp) runDetached(tmp.path, []) } @objc func quit() { logLine("quit"); clipServer.stop(); NSApp.terminate(nil) } } // MARK: - Entry point let args = CommandLine.arguments func argValue(_ name: String) -> String? { guard let i = args.firstIndex(of: name), i + 1 < args.count else { return nil } return args[i + 1] } if args.contains("--configure") { var s = loadSettings() if let v = argValue("--edge")?.capitalized, ["Left", "Right"].contains(v) { s.edge = v } if let v = argValue("--channel"), let c = Int(v), (1...3).contains(c) { s.channel = c } if let v = argValue("--source"), URL(fileURLWithPath: v).standardizedFileURL.path != supportDir.standardizedFileURL.path { s.sourceDir = v } saveSettings(s) print("PC is to the \(s.edge.uppercased()) of this Mac; PC channel = \(s.channel)") exit(0) } if args.contains("--list") { print("Input Monitoring permission: \(IOHIDCheckAccess(kIOHIDRequestTypeListenEvent) == kIOHIDAccessTypeGranted ? "granted" : "not granted (needed for keyboards)")") let found = hidQueue.sync { () -> [KnownDevice] in loadKnown(); return discover() } if found.isEmpty { print("No connected Logitech device supports channel switching on this Mac.") } for d in found { let via = d.devIndex == 0xFF ? "Bluetooth" : "USB receiver slot \(d.devIndex)" print("\(d.name) | \(via) | channels \(d.hostCount) | active channel \(d.currentHost ?? 0)") } exit(0) } if let v = argValue("--switch"), let ch = Int(v) { let lines = hidQueue.sync { () -> [String] in loadKnown(); return switchAll(to: ch) } lines.forEach { print($0) } exit(0) } // Single instance. try? fm.createDirectory(at: supportDir, withIntermediateDirectories: true) let lockFD = open(supportDir.appendingPathComponent(".lock").path, O_CREAT | O_RDWR, 0o644) if lockFD < 0 || flock(lockFD, LOCK_EX | LOCK_NB) != 0 { print("LogiSwitch is already running.") exit(0) } // A normal stop (logout, update, uninstall) sends SIGTERM: remove the marker so it isn't reported as a crash. signal(SIGTERM) { _ in unlink(markerPathC); exit(0) } let app = NSApplication.shared let delegate = AppDelegate(dryRun: args.contains("--dry-run")) app.delegate = delegate app.setActivationPolicy(.accessory) // menu-bar only, no Dock icon app.run()