App · project 15 of 37
PairSwitch.
Push the cursor against the screen edge, or press Easy-Switch on either device, and a keyboard and mouse move together between a Mac and a PC. Works with Logitech keyboards and mice. Copied text can follow, encrypted.
BeforeA keyboard on the PC and a mouse on the Mac, two channel buttons to press every time you turn to the other screen, and a link emailed to yourself to get it across.
AfterPush the cursor against the edge and the keyboard and mouse both cross; press one device's button and the other follows; copy on one computer, paste on the other.
What it is worthOne keyboard and mouse that move together in a fraction of a second, with no admin rights, no Logitech software and no connection into the PC. Instead of pressing two Easy-Switch buttons and emailing yourself text between two computers on the same desk.
How to use it
- Open the page and press Show me how for the six-step tour, or press the buttons yourself: push against the edge, press Easy-Switch on the keyboard or the mouse, copy on either side, and untick Pairing codes match to see a rejected message.
- Pair your Logitech keyboard and mouse with both computers, each on its own Easy-Switch channel (by default the PC on 1 and the Mac on 2), then download PairSwitch (the download still uses its old file name, LogiSwitch).
- On Windows, unzip and double-click Install.cmd; set where the Mac is and its channel from the arrows icon beside the clock.
- On the Mac, run bash ~/Downloads/LogiSwitch/install.sh in Terminal, allow LogiSwitch under Privacy & Security, Input Monitoring, then quit it from the menu bar and run the installer again.
- To share the clipboard, turn it on in the Mac's menu (note the pairing code and the Mac's address), then on the PC set the same address and code and turn it on there.
Where it helps most
- Anyone with a Logitech Easy-Switch keyboard and mouse and two computers on one desk who is tired of pressing two channel buttons every time.
- A work PC where you cannot install software as admin or accept incoming connections: it needs neither.
- Copying a link, an address or a line of text from one computer to the other in under a second, without email, chat or a cloud clipboard.
The idea
I work with a Windows PC and a Mac side by side and one ERGO K860 keyboard and MX Vertical mouse. Pressing a channel button on the keyboard, then another on the mouse, every time I turned to the other screen got old fast, and the mouse always ended up on one computer and the keyboard on the other. I wanted the cursor to just carry both across the edge, like one big desk, without installing Logitech's software or asking for admin rights, and with a PC whose firewall blocks incoming connections. Later I wanted copy on one and paste on the other, kept on my own network.
The build
Claude wrote it with me in two halves. The Windows side came first: PowerShell with embedded C# that finds the Logitech HID++ collections through hid.dll and setupapi.dll, a tray icon and a watcher. The Mac side is one Swift file (AppKit and IOKit) that was written blind on Windows and compiled for the first time on the Mac in the session that put it here: it built at once, and Claude then read it line by line and fixed what would have failed in use. A dead connection after the PC slept blocked every reconnect; restarting the clipboard listener failed because macOS does not wake a blocked socket when another thread closes it; a send to a PC that had just left could kill the app. Live tests then found two more: the Windows installer erased the clipboard settings on every update, and text copied while the computers were not connected was never sent, so both were fixed, and a wrong pairing code now writes one log line instead of two every 2 seconds. Switching uses Logitech's HID++ 2.0 feature 0x1814 (Change Host); the clipboard uses AES-256-CBC with an HMAC-SHA256 tag, keys from PBKDF2-SHA256 (200,000 rounds) of a 16-character pairing code, and a 2-minute timestamp window against replays. Tested with an ERGO K860 and an MX Vertical over Bluetooth on an Apple-silicon Mac and a Windows PC: the screen edge, the keyboard's and the mouse's own buttons (the other follows), and the clipboard both ways, plus a stand-in PC on the Mac for wrong codes. Limits, honestly: the Mac app is not signed with a developer certificate, so macOS asks for Input Monitoring again after every rebuild; the saved app runs only on Apple silicon; text only, up to 1 MB; one Mac and one PC; no automatic discovery, so after a router restart you may have to type the Mac's new address on the PC; the USB-receiver path is in the code but was not tested this round. Not affiliated with Logitech.
Free to take
Build your own.
Copy the skill, paste it into your own AI, and say what you want different. How to use a skill, step by step ›
Get the skillThe instructions your AI follows. Works in Claude, ChatGPT, Gemini or any other
# Master prompt: PairSwitch (formerly LogiSwitch)
You are a macOS and Windows systems programmer who knows Logitech's HID++ 2.0 protocol. Build "PairSwitch": a free tool that moves one Logitech Easy-Switch keyboard and mouse between a Mac and a Windows PC together, with optional encrypted sharing of the text clipboard. No admin rights, no internet, no third-party services, no Logitech software.
WHAT IT DOES
- Edge: watch the cursor 50 times a second. When it is held for 50 ms against the screen edge that faces the other computer (not in the top or bottom 10%, and only on an outer edge with no other screen beyond it), switch. Re-arm only after the cursor has left the edge; ignore it while a mouse button is down; 1 s cooldown.
- Follow: when a Logitech keyboard or mouse disappears from this computer (its own Easy-Switch button was pressed), send the devices still here to the same channel. Skip it if the computer has been idle over 60 s (the device went to sleep) or within 5 s of our own switch.
- Switching: HID++ 2.0 long report 0x11, 20 bytes: [0x11][device index: 0xFF over Bluetooth, 1-6 on a Unifying/Bolt receiver][feature index of 0x1814 Change Host][0x1B = function 1 setCurrentHost, software id 0xB][host, 0-based]. Find the feature index with root feature 0x0000 getFeature(0x1814) and the channel count with function 0. Mice before keyboards. After 0.6 s, ask each device again; one that still answers did not switch: re-send, up to 3 attempts, and report FAILED if it is still here.
- Remember devices (name, interface, feature index, channels) in devices.json; re-detect every 3 minutes, so a different set at work is picked up.
MAC SIDE (one Swift file, built with xcrun swiftc, AppKit + IOKit)
- Menu-bar app (accessory policy) started by a user LaunchAgent (KeepAlive on crash). Menu: Active, Send now, Where is the PC (left/right), PC's channel 1-3, Clipboard sync, Start at login, Show devices, Re-detect, Open log, Create support report, Update, Uninstall, Quit.
- IOHIDManager matching vendor 0x046D and DeviceUsagePage 0xFF43 (Bluetooth HID++ collection, a secondary usage) or 0xFF00 (receivers). Input reports via a registered callback on the HID queue's run loop. IOHIDRequestAccess(kIOHIDRequestTypeListenEvent) for Input Monitoring.
- Modes: --list (read-only), --switch N, --configure --edge --channel --source, --dry-run. A .running marker detects crashes; problems create a support report automatically (once per 30 min).
WINDOWS SIDE (PowerShell 5.1 with embedded C#, no admin)
- hid.dll + setupapi.dll to find Logitech HID++ collections, overlapped reads; a tray icon (WinForms) with the same menu, a watcher process run with -STA, a Startup-folder shortcut; settings in %LOCALAPPDATA%\LogiSwitch\settings.json. The installer must keep every saved setting on update.
CLIPBOARD SYNC (text only, off until the person turns it on and accepts a warning)
- The Mac listens on TCP 51888; the PC dials out (its firewall blocks incoming), keeps one connection, sends a keepalive every 20 s and backs off 2 to 30 s. The Mac drops a connection silent for 50 s or when a newer one is waiting.
- Frame: [4-byte length][16-byte IV][AES-256-CBC + PKCS7][32-byte HMAC-SHA256 of IV + ciphertext]. Plaintext: [type: 0x01 hello, 0x02 keepalive, 0x10 clipboard][8-byte unix ms, refuse if more than 2 min off][payload]. Payload: [format count] then [format 1 = UTF-8][4-byte length][bytes]. Max message 12 MB, text 1 MB.
- Keys: master = PBKDF2-SHA256(normalised code, "logiswitch-clipboard-v1", 200000, 32); enc = HMAC(master, "enc"), mac = HMAC(master, "mac"). The code is 16 Crockford base32 characters shown as 4 groups; accept lower case, missing dashes, O for 0, I or L for 1.
- Poll the clipboard about 8 times a second; never echo back what just arrived; count text as sent only when it was written; send what was copied while disconnected as soon as the other side connects, if it is still on the clipboard; compare text case-sensitively.
- Log a wrong code once (then about every 10 min), not on every retry.
MAC PITFALLS TO HANDLE
- Closing a socket from another thread does not wake accept() or recv() on macOS: the server thread owns its sockets and polls; stop() bumps a generation and shuts the client down; retry bind for a moment after a restart. Set SO_NOSIGPIPE.
- The app is ad-hoc signed, so each rebuild needs Input Monitoring again: save the first build in mac-bin/ so later installs reuse it; tell the person to remove and re-allow LogiSwitch after a rebuild.
INSTALL, SUPPORT, EXPLAINER
- install.sh: build (universal if possible, else native), save mac-bin/, keep settings, write the LaunchAgent, log everything to the Desktop, and on failure write a ready-to-paste fix request for Claude. Install.cmd does the same on Windows.
- report.sh / Get-LogiSwitchReport.ps1: a support report with how it works, diagnostics, logs and the full source, with usernames and hardware addresses removed.
- A web explainer page with a simulated Mac and PC: buttons for the edge push, Easy-Switch on each device, copy on each side, sharing on/off and codes match/don't; the exact bytes on the wire; a simulated watch.log; a six-step "Show me how" tour; the source download.
STRESS TEST
- Edge on every side and screen layout, corners ignored, no bounce back; Easy-Switch on each device with the other following; idle 60 s then switch a device off (nothing follows); 40 fast edge hits.
- Clipboard: both ways, Unicode, 1 MB limit, wrong code (one log line), PC asleep and back (reconnects without restarting the Mac), sharing off then on (waiting text goes), restart of either side, router gives the Mac a new address.
Get the code19 files, exactly as they run on this site · free under the MIT license
SKILL.md (Claude skill: install, test, fix and update LogiSwitch)45 lines
---
name: logiswitch
description: Install, test, fix or update LogiSwitch, the tool that moves one Logitech keyboard and mouse between a Mac and a Windows PC (screen edge or Easy-Switch, the other device follows) with optional encrypted clipboard sync. Use when someone says LogiSwitch, wants their Logitech keyboard and mouse to switch together between a Mac and a PC, or pastes a LogiSwitch report.
---
# LogiSwitch: install, test, fix, update
LogiSwitch is a small Swift menu-bar app on the Mac (`LogiSwitch.swift`, built by `install.sh`) and a PowerShell tray app on Windows (`LogiSwitch.ps1`, `LogiSwitchTray.ps1`, installed by `Install.cmd`). It sends Logitech's HID++ 2.0 Change Host command (feature 0x1814) to move Easy-Switch devices, and optionally shares the text clipboard: the Mac listens on TCP 51888, the PC dials out, AES-256-CBC + HMAC-SHA256 with keys from PBKDF2-SHA256 (200,000 rounds) of a 16-character pairing code. Source and a live demo: https://sghadimi.com/tools/logiswitch/
## Rules
- No admin password, unless macOS itself asks to install the Command Line Tools.
- No internet, no third-party services. Clipboard sync stays off until the person turns it on, and they accept its warning themselves.
- Ask before any macOS permission (Input Monitoring, incoming connections, Local Network). Never click Allow for them.
- Keep the behaviour: 50 ms edge hold away from the corners, mice before keyboards, confirm the device left and re-send up to 3 times, the other device follows, nothing follows after a minute idle.
## Install
1. Mac: `bash ~/Downloads/LogiSwitch/install.sh`. It builds with `xcrun swiftc`; if the Command Line Tools are missing it opens Apple's installer and exits with code 3 (not a failure). On Apple silicon the Intel half of the universal build fails to link with some toolchains; the installer falls back to a native build, so `link command failed ... x86_64` is harmless.
2. The person allows LogiSwitch under Privacy & Security > Input Monitoring. The running app only picks it up after a restart: `launchctl kickstart -k gui/$(id -u)/com.logiswitch.agent`, or run install.sh again.
3. Check `"$HOME/Library/Application Support/LogiSwitch/LogiSwitch" --list`. Run from Claude's shell, its "permission: granted" line reflects Claude's own permission, not the app's. The truth is the `Input Monitoring permission:` line in watch.log after a restart.
4. Windows: unzip, double-click Install.cmd. Defaults: Mac on the right of the PC, Mac on channel 2.
## Test with the person (read watch.log after each)
- a) cursor against the edge facing the other computer: both devices go.
- b) Easy-Switch on the keyboard: the mouse follows. c) channel button on the mouse: the keyboard follows.
- Leave about 10 s between tests and bring both devices back first. Nothing at all in the log usually means there was no time, not a bug. To check whether reconnects are seen, run a separate IOHIDManager watcher (vendor 0x046D, usage page 0xFF43) that logs arrivals and removals; never rebuild the app just to add logging.
## Clipboard sync
- Mac: icon > Clipboard sync > Share the text clipboard with the PC. The pairing code and address dialogs are modal: until the person clicks OK, nothing listens on 51888 (`lsof -nP -iTCP:51888`).
- PC: icon > Clipboard sync > Set the Mac's address, Pairing code (the same code), Share the text clipboard with the Mac.
- Before involving the PC, test the Mac alone with a stand-in client that speaks the same protocol on 127.0.0.1 (hello 0x01, text 0x10, payload [count][format 1][4-byte length][UTF-8]). Restore the person's clipboard afterwards.
- No "the PC connected" in the Mac's log means the PC never got through: wrong address, other network, or sync off on the PC. "rejected a message" means the codes differ, or a clock is more than 2 minutes off. The Mac's firewall asks once; after that `socketfilterfw --listapps` lists LogiSwitch as allowed.
- Text copied while disconnected is sent when the other side connects, if it is still on the clipboard.
## Known traps
- The Mac app is ad-hoc signed, so every rebuild is a new app to macOS: Input Monitoring must be removed (minus) and allowed again, then the app restarted. An install that reuses the ready-built `mac-bin/LogiSwitch` of the same version keeps it. Bump `version.txt` only when the Mac code changes.
- On macOS, closing a socket from another thread does not wake accept() or recv(): the server thread owns its sockets, polls, and stop() only shuts the client down. Set SO_NOSIGPIPE on accepted sockets.
- PowerShell `-eq` / `-ne` ignore case; compare clipboard text with `-ceq` / `-cne`.
- The PC installer must keep every key of settings.json (ClipboardSync, PeerHost, PeerPort), or an update silently turns clipboard sync off.
- Getting text between the computers while clipboard sync is down: write files into a folder both computers sync (for example OneDrive) or give the person one ready-made file to download. Do not ask them to retype long commands.
## Update
- Mac: menu > Update (reinstall from the original folder, or pick a folder), or run install.sh from the new folder. Settings are kept.
- PC: Install.cmd from the new folder, or tray menu > Update. Settings and the pairing code are kept.
- Logs: Mac `~/Library/Application Support/LogiSwitch/watch.log` (also stderr.log, install.log, Desktop/LogiSwitch-install-log.txt); PC `%LOCALAPPDATA%\LogiSwitch\watch.log`. Problem reports go to the Desktop.
LogiSwitch.swift (the Mac menu-bar app: devices, edge, follow, clipboard server)1,218 lines
// 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<CChar> = 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 // "<interface product ID>-<device index>", 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<UInt8>.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<HidConn>.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<T>(_ 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<IOHIDDevice>).map { Array($0) } ?? []
var targets: [HidTarget] = []
var seenReceivers = Set<Int>()
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<KeyboardWatch>.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<KeyboardWatch>.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<ifaddrs>?
guard getifaddrs(&ifaddr) == 0, let first = ifaddr else { return "?" }
defer { freeifaddrs(ifaddr) }
var p: UnsafeMutablePointer<ifaddrs>? = 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..<moved])
}
private func setKeys(_ code: String) {
let master = ClipServer.pbkdf2(normalizeCode(code), "logiswitch-clipboard-v1", rounds: 200_000, length: 32)
encKey = ClipServer.hmac(master, Data("enc".utf8))
macKey = ClipServer.hmac(master, Data("mac".utf8))
}
private func seal(_ type: UInt8, _ payload: Data) -> 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..<Int(b[0]) {
guard i + 5 <= b.count else { return nil }
let fmt = b[i]; i += 1
let len = Int(b[i]) << 24 | Int(b[i+1]) << 16 | Int(b[i+2]) << 8 | Int(b[i+3]); i += 4
guard len >= 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<Int32>.size))
var addr = sockaddr_in()
addr.sin_len = UInt8(MemoryLayout<sockaddr_in>.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<sockaddr_in>.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<Int32>.size))
setsockopt(c, SOL_SOCKET, SO_NOSIGPIPE, &one, socklen_t(MemoryLayout<Int32>.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<timeval>.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 """
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key><string>com.logiswitch.agent</string>
<key>ProgramArguments</key><array><string>\(binaryURL.path)</string></array>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
<key>LimitLoadToSessionType</key><string>Aqua</string>
<key>ProcessType</key><string>Interactive</string>
<key>AbandonProcessGroup</key><true/>
<key>StandardErrorPath</key><string>\(supportDir.path)/stderr.log</string>
</dict>
</plist>
"""
}
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()
install.sh (Mac installer: build, start at login, fix request on failure)166 lines
#!/bin/bash
# LogiSwitch for macOS - install or update for the current user (no admin password needed).
# bash install.sh install / update, keep existing settings
# bash install.sh --edge Left --channel 1 also set where the PC is and the PC's Easy-Switch channel
set -euo pipefail
SRC="$(cd "$(dirname "$0")" && pwd)"
DIR="$HOME/Library/Application Support/LogiSwitch"
PLIST="$HOME/Library/LaunchAgents/com.logiswitch.agent.plist"
LABEL="com.logiswitch.agent"
EDGE=""; CHANNEL=""; QUIET=0
while [ $# -gt 0 ]; do
case "$1" in
--edge) EDGE="$2"; shift 2 ;;
--channel) CHANNEL="$2"; shift 2 ;;
--quiet) QUIET=1; shift ;;
*) echo "Unknown option: $1"; exit 2 ;;
esac
done
# Everything below is logged from the first line: to the Desktop (always easy to find) and to the
# install folder. Paste LogiSwitch-install-log.txt into Claude if anything goes wrong.
DESKTOP_LOG="$HOME/Desktop/LogiSwitch-install-log.txt"
mkdir -p "$DIR" "$HOME/Library/LaunchAgents"
: > "$DESKTOP_LOG" 2>/dev/null || DESKTOP_LOG="/dev/null"
exec > >(tee -a "$DIR/install.log" "$DESKTOP_LOG") 2>&1
echo "== LogiSwitch install $(date '+%Y-%m-%d %H:%M:%S') from $SRC"
echo "macOS $(sw_vers -productVersion 2>/dev/null) on $(uname -m)"
if [ "$(uname)" != "Darwin" ]; then
echo "This installer is for macOS. On Windows, double-click Install.cmd instead."
exit 1
fi
# If anything fails: write a ready-to-paste request for Claude (prompt + error + source),
# copy it to the clipboard and open it, so one paste into any Claude chat gets the fix.
make_fix_request() {
local out="$HOME/Desktop/LogiSwitch-fix-request.txt"
{
cat "$SRC/ASK-CLAUDE.txt" 2>/dev/null | sed -n '/^=== MAC: INSTALL FAILED/,/^=== END MAC: INSTALL FAILED/p'
echo
echo "===== macOS ====="
sw_vers 2>/dev/null; echo "Architecture: $(uname -m)"
echo "Swift compiler: $(xcrun swiftc --version 2>&1 | head -1)"
echo
echo "===== INSTALL OUTPUT (last 120 lines) ====="
tail -n 120 "$DIR/install.log" 2>/dev/null
for f in LogiSwitch.swift install.sh; do
echo; echo "===== SOURCE: $f ====="; cat "$SRC/$f" 2>/dev/null
done
} | sed -e "s/$(id -un | sed 's/[]\/$*.^[]/\\&/g')/<user>/g" > "$out"
pbcopy < "$out" 2>/dev/null || true
open -e "$out" 2>/dev/null || true
echo
echo "Install FAILED. A fix request was saved to your Desktop (LogiSwitch-fix-request.txt)"
echo "and copied to the clipboard: paste it into any Claude chat and follow the answer."
}
# Any failure (not just command errors) produces the fix request. Exit code 3 = waiting for
# Apple's Command Line Tools, which is not a failure.
INSTALL_OK=0
on_exit() {
local rc=$?
if [ "$INSTALL_OK" != 1 ] && [ "$rc" != 0 ] && [ "$rc" != 3 ]; then
echo "Failed with exit code $rc."
sleep 1; make_fix_request
fi
}
trap on_exit EXIT
# 1. Ready-built app in the package? (Saved there by the first successful build, so later
# installs on any Mac need no compiler.) Otherwise Apple's Command Line Tools are needed.
VERSION="$(cat "$SRC/version.txt" 2>/dev/null || echo '?')"
PREBUILT="$SRC/mac-bin/LogiSwitch"
USE_PREBUILT=0
if [ -f "$PREBUILT" ] && [ "$(cat "$SRC/mac-bin/version.txt" 2>/dev/null)" = "$VERSION" ]; then USE_PREBUILT=1; fi
if [ "$USE_PREBUILT" = 0 ] && ! xcrun --find swiftc >/dev/null 2>&1; then
echo "Apple's Command Line Tools are needed to build LogiSwitch (one-time, free, from Apple)."
xcode-select --install 2>/dev/null || true
echo "Click Install in the window that appears, wait for it to finish, then run this installer again."
exit 3
fi
# 2. Stop a running copy.
launchctl bootout "gui/$(id -u)/$LABEL" 2>/dev/null || true
pkill -f "Application Support/LogiSwitch/LogiSwitch$" 2>/dev/null || true
rm -f "$DIR/.running" # this stop was intentional, not a crash
# 3. Copy files (only the Mac ones are needed; the folder is shared with the Windows version).
for f in LogiSwitch.swift install.sh uninstall.sh report.sh README.txt version.txt ASK-CLAUDE.txt; do
if [ -f "$SRC/$f" ] && [ "$SRC" != "$DIR" ]; then cp -f "$SRC/$f" "$DIR/"; fi
done
chmod +x "$DIR"/*.sh
xattr -dr com.apple.quarantine "$DIR" 2>/dev/null || true
# 4. Build (or reuse the ready-built app).
if [ "$USE_PREBUILT" = 1 ]; then
[ "$QUIET" = 1 ] || echo "Using the ready-built app from mac-bin/ (no compiler needed)."
cp -f "$PREBUILT" "$DIR/LogiSwitch.new"
xattr -d com.apple.quarantine "$DIR/LogiSwitch.new" 2>/dev/null || true
chmod +x "$DIR/LogiSwitch.new"
codesign --force --sign - "$DIR/LogiSwitch.new" 2>/dev/null || true # local ad-hoc signature
else
[ "$QUIET" = 1 ] || echo "Building (about a minute)..."
B="$DIR/build"; rm -rf "$B"; mkdir -p "$B"
# Universal app (Apple silicon + Intel) so the saved copy works on any Mac; fall back to this Mac only.
if xcrun swiftc -O -target arm64-apple-macos12 -o "$B/arm64" "$DIR/LogiSwitch.swift" -framework AppKit -framework IOKit \
&& xcrun swiftc -O -target x86_64-apple-macos12 -o "$B/x86_64" "$DIR/LogiSwitch.swift" -framework AppKit -framework IOKit \
&& lipo -create -output "$DIR/LogiSwitch.new" "$B/arm64" "$B/x86_64"; then
[ "$QUIET" = 1 ] || echo "Built for Apple silicon and Intel Macs."
else
xcrun swiftc -O -o "$DIR/LogiSwitch.new" "$DIR/LogiSwitch.swift" -framework AppKit -framework IOKit
fi
rm -rf "$B"
# Save the built app into the package, so the next Mac installs without a compiler.
if mkdir -p "$SRC/mac-bin" 2>/dev/null && cp -f "$DIR/LogiSwitch.new" "$SRC/mac-bin/LogiSwitch" 2>/dev/null; then
echo "$VERSION" > "$SRC/mac-bin/version.txt"
[ "$QUIET" = 1 ] || echo "Saved the built app to $SRC/mac-bin (re-zip this folder to share it)."
fi
fi
mv -f "$DIR/LogiSwitch.new" "$DIR/LogiSwitch"
# 5. Settings (keeps existing ones; remembers this folder for "Update > Reinstall").
ARGS=(--configure --source "$SRC")
if [ -n "$EDGE" ]; then ARGS+=(--edge "$EDGE"); fi
if [ -n "$CHANNEL" ]; then ARGS+=(--channel "$CHANNEL"); fi
"$DIR/LogiSwitch" "${ARGS[@]}"
# 6. Start at login (user LaunchAgent) and start now.
cat > "$PLIST" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key><string>$LABEL</string>
<key>ProgramArguments</key><array><string>$DIR/LogiSwitch</string></array>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
<key>LimitLoadToSessionType</key><string>Aqua</string>
<key>ProcessType</key><string>Interactive</string>
<key>AbandonProcessGroup</key><true/>
<key>StandardErrorPath</key><string>$DIR/stderr.log</string>
</dict>
</plist>
EOF
# macOS sometimes refuses to re-register right after the old copy was stopped: retry, then fall back.
if ! launchctl bootstrap "gui/$(id -u)" "$PLIST" 2>/dev/null; then
echo "launchctl bootstrap refused; retrying..."
sleep 2
launchctl bootout "gui/$(id -u)/$LABEL" 2>/dev/null || true
sleep 1
if ! launchctl bootstrap "gui/$(id -u)" "$PLIST"; then
echo "launchctl still refused; starting LogiSwitch directly (it will start at login next time)."
nohup "$DIR/LogiSwitch" >/dev/null 2>&1 &
fi
fi
sleep 2
if pgrep -f "Application Support/LogiSwitch/LogiSwitch$" >/dev/null; then echo "LogiSwitch is running."
else echo "WARNING: LogiSwitch did not stay running. See $DIR/stderr.log and watch.log."; fi
INSTALL_OK=1
if [ "$QUIET" != 1 ]; then
echo
echo "LogiSwitch $(cat "$DIR/version.txt" 2>/dev/null) installed."
echo "Look for the arrows icon in the menu bar (top right). Click it for options."
echo "Default: the PC is to the LEFT of this Mac and is on Easy-Switch channel 1."
fi
uninstall.sh (Mac)14 lines
#!/bin/bash
# LogiSwitch for macOS - remove for the current user.
# Stops the menu-bar app, removes it from login, deletes its files.
# Logitech software, devices and pairings are not touched.
DIR="$HOME/Library/Application Support/LogiSwitch"
PLIST="$HOME/Library/LaunchAgents/com.logiswitch.agent.plist"
LABEL="com.logiswitch.agent"
launchctl bootout "gui/$(id -u)/$LABEL" 2>/dev/null || true
pkill -f "Application Support/LogiSwitch/LogiSwitch$" 2>/dev/null || true
rm -f "$PLIST"
rm -rf "$DIR"
echo "LogiSwitch removed."
report.sh (Mac support report for Claude)146 lines
#!/bin/bash
# LogiSwitch for macOS - build a support report to paste into any Claude chat.
# Starts with instructions for Claude, then diagnostics, log and full source.
# Removes: macOS username, computer/host name, hardware addresses.
# Saves to the Desktop, copies to the clipboard, opens it in TextEdit.
DIR="$HOME/Library/Application Support/LogiSwitch"
PLIST="$HOME/Library/LaunchAgents/com.logiswitch.agent.plist"
SRC="$(cd "$(dirname "$0")" && pwd)"
TMP="$(mktemp -t logiswitch)"
# bash report.sh -> asks for a description, saves to Desktop, copies, opens
# bash report.sh --auto "reason" -> used by the app itself when it detects a problem: no
# questions; saves to the fixed path last-problem-report.txt
# (Claude Code can read it directly) and to the Desktop, then notifies
AUTO=0
if [ "${1:-}" = "--auto" ]; then
AUTO=1
PROBLEM="AUTOMATIC REPORT (created by LogiSwitch itself, no user description). Detected problem: ${2:-unknown}"
OUT="$DIR/last-problem-report.txt"
else
PROBLEM="${1:-}"
OUT="$HOME/Desktop/LogiSwitch-mac-report-$(date +%Y%m%d-%H%M).txt"
fi
mkdir -p "$DIR"
if [ "$AUTO" = 0 ] && [ -z "$PROBLEM" ]; then
PROBLEM="$(osascript -e 'try' -e 'text returned of (display dialog "Briefly describe the problem (what you did, what happened, what you expected):" default answer "" with title "LogiSwitch support report")' -e 'end try' 2>/dev/null)"
fi
esc() { printf '%s' "$1" | sed -e 's/[]\/$*.^[]/\\&/g'; }
USER_RE="$(esc "$(id -un)")"
COMP_RE="$(esc "$(scutil --get ComputerName 2>/dev/null)")"
HOST_RE="$(esc "$(hostname -s 2>/dev/null)")"
SED_ARGS=(-e "s/$USER_RE/<user>/g")
if [ -n "$COMP_RE" ]; then SED_ARGS+=(-e "s/$COMP_RE/<computer>/g"); fi
if [ -n "$HOST_RE" ]; then SED_ARGS+=(-e "s/$HOST_RE/<host>/g"); fi
redact() {
sed "${SED_ARGS[@]}" | sed -E 's/([0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F]{2}/<hwaddr>/g'
}
# Live device check (read-only), max 40 s.
LIVE="(LogiSwitch binary not found)"
if [ -x "$DIR/LogiSwitch" ]; then
( "$DIR/LogiSwitch" --list > "$TMP" 2>&1 ) & pid=$!
for _ in $(seq 1 40); do kill -0 "$pid" 2>/dev/null || break; sleep 1; done
kill "$pid" 2>/dev/null && echo "(timed out)" >> "$TMP"
LIVE="$(cat "$TMP")"
fi
{
cat <<'EOF'
===== INSTRUCTIONS FOR CLAUDE =====
You are helping me fix "LogiSwitch", a small tool that switches my Logitech keyboard and mouse
between my Windows PC and my Mac. This report is from the MAC side (Swift menu-bar app).
How it works:
- It sends the Logitech HID++ 2.0 "Change Host" command (feature 0x1814, function 1
setCurrentHost, host index 0-based) to every connected Logitech device that supports it.
Local HID (IOKit). The only network use is the optional clipboard sync (see below).
- Bluetooth devices: HID interface with primary usage page 0xFF43, long report ID 0x11
(20 bytes, report ID included in the buffer), device index 0xFF.
Unifying/Bolt receivers: primary usage page 0xFF00, device index 1-6, errors arrive as short
report 0x10 with sub-id 0x8F.
- The app polls NSEvent.mouseLocation; when the cursor is held against the outer screen edge
facing the PC (middle 80% of the height, no button held) for 300 ms, it switches all devices
to the PC's channel. The cursor stays on the edge; it re-arms only after leaving the edge.
- Devices are remembered in devices.json and re-detected every 3 minutes, so a new keyboard/mouse
set (e.g. at work) is picked up automatically.
- Installed per user to ~/Library/Application Support/LogiSwitch, built with
`xcrun swiftc -O -o LogiSwitch LogiSwitch.swift -framework AppKit -framework IOKit`,
started by the user LaunchAgent ~/Library/LaunchAgents/com.logiswitch.agent.plist.
- The Windows side is a separate PowerShell tool in the same package (Install.cmd).
Constraints (must keep): no admin password, no internet or third-party services, and network only for the optional clipboard sync (off until turned on; the Mac listens on TCP 51888, the PC dials out, AES-256 + HMAC with a shared pairing code), no file sharing.
Ask me before granting any macOS permission.
What I need from you:
1. Read my problem, the diagnostics and logs below, and identify the root cause.
2. Give me the fix: exact Terminal commands, or the complete corrected file(s) (full content,
ready to save over the old one), then how to reinstall (bash install.sh in the folder with
the corrected files, or menu bar icon > Update).
3. Tell me how to confirm it is fixed.
If you can run commands on this Mac (for example Claude Code), apply the fix yourself instead:
the installed files are in ~/Library/Application Support/LogiSwitch (it is also a complete
install package); after editing, run bash ~/Library/Application\ Support/LogiSwitch/install.sh
and verify with ".../LogiSwitch --list" and watch.log. The latest automatic report is always
at ~/Library/Application Support/LogiSwitch/last-problem-report.txt.
EOF
echo
echo "===== MY PROBLEM ====="
echo "${PROBLEM:-(not described)}"
echo
echo "===== SYSTEM ====="
echo "Report created : $(date '+%Y-%m-%d %H:%M:%S')"
echo "LogiSwitch : $(cat "$DIR/version.txt" 2>/dev/null || echo 'not installed')"
sw_vers 2>/dev/null
echo "Architecture : $(uname -m)"
echo "Swift compiler : $(xcrun swiftc --version 2>&1 | head -1)"
echo
echo "===== AGENT STATUS ====="
echo "LaunchAgent plist present: $([ -f "$PLIST" ] && echo yes || echo no)"
launchctl print "gui/$(id -u)/com.logiswitch.agent" 2>&1 | grep -E '^\s*(state|pid|last exit code|runs) ' || echo "(agent not loaded)"
pgrep -fl "Application Support/LogiSwitch/LogiSwitch$" || echo "(app process not running)"
echo
echo "===== SETTINGS (settings.json) ====="
cat "$DIR/settings.json" 2>/dev/null || echo "(none)"
echo
echo "===== REMEMBERED DEVICES (devices.json) ====="
cat "$DIR/devices.json" 2>/dev/null || echo "(none)"
echo
echo "===== LIVE DEVICE CHECK (LogiSwitch --list, read-only) ====="
echo "$LIVE"
echo
echo "===== DISPLAYS ====="
system_profiler SPDisplaysDataType 2>/dev/null | grep -E 'Resolution|Main Display|Mirror|Online|Display Type' || echo "?"
echo
echo "===== LOGITECH BLUETOOTH DEVICES ====="
system_profiler SPBluetoothDataType 2>/dev/null | grep -iE -A4 'logi|mx |ergo|k[0-9]{3}|m[0-9]{3}|lift|pebble|signature' | grep -vE 'Address|Serial' || echo "(none found)"
echo
echo "===== LOG (last 150 lines of watch.log) ====="
tail -n 150 "$DIR/watch.log" 2>/dev/null || echo "(none)"
echo
echo "===== STDERR (last 50 lines) ====="
tail -n 50 "$DIR/stderr.log" 2>/dev/null || echo "(none)"
echo
echo "===== INSTALL LOG (last 60 lines) ====="
tail -n 60 "$DIR/install.log" 2>/dev/null || echo "(none)"
} | redact > "$OUT"
# Source code (not redacted; contains no personal data).
for f in LogiSwitch.swift install.sh uninstall.sh report.sh; do
p="$DIR/$f"; [ -f "$p" ] || p="$SRC/$f"
{ echo; echo "===== SOURCE: $f ====="; cat "$p" 2>/dev/null || echo "(missing)"; } >> "$OUT"
done
echo; echo "===== END OF REPORT =====" >> "$OUT"
rm -f "$TMP"
if [ "$AUTO" = 1 ]; then
cp -f "$OUT" "$HOME/Desktop/LogiSwitch-problem-report.txt" 2>/dev/null || true
osascript -e 'display notification "A report for Claude was saved to your Desktop (LogiSwitch-problem-report.txt). Menu bar icon > Open automatic problem report copies it; then paste it into any Claude chat." with title "LogiSwitch found a problem"' 2>/dev/null || true
echo "Automatic report saved to $OUT and the Desktop."
else
pbcopy < "$OUT"
open -e "$OUT"
echo "Report saved to $OUT (also copied to the clipboard)."
fi
LogiSwitch.ps1 (Windows: HID++ over hid.dll, edge watcher, follow, clipboard client)903 lines
<#
LogiSwitch.ps1 - switch Logitech keyboard + mouse to another Easy-Switch channel at once.
Uses the HID++ 2.0 "Change Host" feature (0x1814), the same command Logi Flow sends.
Works over Bluetooth and Unifying/Bolt receivers. No admin rights, no internet, no file sharing.
Optional clipboard sync (text, off by default): this PC dials out to the Mac on TCP 51888, encrypted.
.\LogiSwitch.ps1 -List # read-only: devices, channel count, active channel
.\LogiSwitch.ps1 -Channel 2 # send all supported devices to channel 2 (1-based)
.\LogiSwitch.ps1 -Channel 2 -Name K860,"MX Vertical" # only devices whose name matches
.\LogiSwitch.ps1 -Watch -Edge Right -Channel 2 # background: push cursor against right edge -> switch
.\LogiSwitch.ps1 -Watch -Edge Right -Channel 2 -DryRun # test edge detection without switching
#>
param(
[switch]$List,
[int]$Channel = 0,
[string[]]$Name,
[switch]$Watch,
[ValidateSet('Right','Left')][string]$Edge = 'Right',
[int]$DwellMs = 50,
[switch]$DryRun,
[int]$MaxSeconds = 0,
[double]$RefreshMinutes = 3,
[switch]$Fast, # with -Channel: use remembered devices instead of the slow search
# Clipboard sync (off unless asked for). This PC only ever dials OUT to the Mac, so no
# firewall change is needed. Everything is encrypted with the shared pairing code.
[switch]$ClipboardSync,
[string]$PeerHost = '',
[int]$PeerPort = 51888
)
$cs = @'
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
public class LogiDev {
public string LongPath; public string ShortPath; public string Name; public byte DevIdx; public byte ChangeHostIdx;
public int HostCount; public int CurrentHost; public string Transport;
}
class Conn : IDisposable {
public FileStream L, S; List<FileStream> streams = new List<FileStream>();
List<Task<int>> tasks = new List<Task<int>>(); List<byte[]> bufs = new List<byte[]>();
public Conn(FileStream l, FileStream s) { L = l; S = s; Add(l); if (s != null) Add(s); }
void Add(FileStream f) { streams.Add(f); bufs.Add(null); tasks.Add(null); Arm(streams.Count - 1); }
void Arm(int i) { bufs[i] = new byte[streams[i] == S ? 7 : 20]; tasks[i] = streams[i].ReadAsync(bufs[i], 0, bufs[i].Length); }
// Returns next incoming report from any collection, or null on timeout. Pending reads stay armed.
public byte[] Next(int ms) {
int i = Task.WaitAny(tasks.ToArray(), Math.Max(1, ms));
if (i < 0) return null;
var b = bufs[i]; Arm(i); return b;
}
public void Dispose() { foreach (var f in streams) f.Dispose(); }
}
public static class LogiHid {
[StructLayout(LayoutKind.Sequential)] struct HIDD_ATTRIBUTES { public int Size; public ushort VendorID; public ushort ProductID; public ushort Version; }
[StructLayout(LayoutKind.Sequential)] struct HIDP_CAPS {
public ushort Usage, UsagePage, InputReportByteLength, OutputReportByteLength, FeatureReportByteLength;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 27)] public ushort[] Reserved;
}
[StructLayout(LayoutKind.Sequential)] struct SP_DEVICE_INTERFACE_DATA { public int cbSize; public Guid InterfaceClassGuid; public int Flags; public IntPtr Reserved; }
[DllImport("hid.dll")] static extern void HidD_GetHidGuid(out Guid g);
[DllImport("hid.dll")] static extern bool HidD_GetAttributes(SafeFileHandle h, ref HIDD_ATTRIBUTES a);
[DllImport("hid.dll")] static extern bool HidD_GetPreparsedData(SafeFileHandle h, out IntPtr p);
[DllImport("hid.dll")] static extern bool HidD_FreePreparsedData(IntPtr p);
[DllImport("hid.dll")] static extern int HidP_GetCaps(IntPtr p, out HIDP_CAPS c);
[DllImport("setupapi.dll", CharSet = CharSet.Unicode)] static extern IntPtr SetupDiGetClassDevs(ref Guid g, IntPtr e, IntPtr w, int f);
[DllImport("setupapi.dll")] static extern bool SetupDiEnumDeviceInterfaces(IntPtr s, IntPtr i, ref Guid g, int idx, ref SP_DEVICE_INTERFACE_DATA d);
[DllImport("setupapi.dll", CharSet = CharSet.Unicode)] static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr s, ref SP_DEVICE_INTERFACE_DATA d, IntPtr det, int size, out int req, IntPtr info);
[DllImport("setupapi.dll")] static extern bool SetupDiDestroyDeviceInfoList(IntPtr s);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern SafeFileHandle CreateFile(string n, uint acc, uint share, IntPtr sec, uint disp, uint flags, IntPtr t);
const byte SW = 0x0B;
public static List<string> Log = new List<string>();
class Iface { public string Path; public ushort Pid, Page, Usage; }
static List<Iface> Enumerate() {
var res = new List<Iface>();
Guid g; HidD_GetHidGuid(out g);
IntPtr set = SetupDiGetClassDevs(ref g, IntPtr.Zero, IntPtr.Zero, 0x12);
var d = new SP_DEVICE_INTERFACE_DATA(); d.cbSize = Marshal.SizeOf(d);
for (int i = 0; SetupDiEnumDeviceInterfaces(set, IntPtr.Zero, ref g, i, ref d); i++) {
int req; SetupDiGetDeviceInterfaceDetail(set, ref d, IntPtr.Zero, 0, out req, IntPtr.Zero);
IntPtr buf = Marshal.AllocHGlobal(req);
Marshal.WriteInt32(buf, IntPtr.Size == 8 ? 8 : 6);
if (SetupDiGetDeviceInterfaceDetail(set, ref d, buf, req, out req, IntPtr.Zero)) {
string path = Marshal.PtrToStringUni(new IntPtr(buf.ToInt64() + 4));
if (path.ToLowerInvariant().Contains("046d")) {
using (var h = CreateFile(path, 0, 3, IntPtr.Zero, 3, 0, IntPtr.Zero)) {
if (!h.IsInvalid) {
var a = new HIDD_ATTRIBUTES(); a.Size = Marshal.SizeOf(a);
IntPtr pp; HIDP_CAPS c;
if (HidD_GetAttributes(h, ref a) && a.VendorID == 0x046D && HidD_GetPreparsedData(h, out pp)) {
HidP_GetCaps(pp, out c); HidD_FreePreparsedData(pp);
res.Add(new Iface { Path = path, Pid = a.ProductID, Page = c.UsagePage, Usage = c.Usage });
}
}
}
}
}
Marshal.FreeHGlobal(buf);
}
SetupDiDestroyDeviceInfoList(set);
return res;
}
internal static FileStream OpenStream(string path, int len) {
if (path == null) return null;
var h = CreateFile(path, 0xC0000000, 3, IntPtr.Zero, 3, 0x40000000, IntPtr.Zero);
if (h.IsInvalid) return null;
return new FileStream(h, FileAccess.ReadWrite, len, true);
}
static Conn Open(string longPath, string shortPath) {
var l = OpenStream(longPath, 20); if (l == null) return null;
return new Conn(l, OpenStream(shortPath, 7));
}
// Long HID++ 2.0 request; returns 16 param bytes, or null on error/timeout.
static byte[] Request(Conn c, byte dev, byte feat, byte fn, byte[] p, int timeoutMs) {
var msg = new byte[20]; msg[0] = 0x11; msg[1] = dev; msg[2] = feat; msg[3] = (byte)((fn << 4) | SW);
if (p != null) Array.Copy(p, 0, msg, 4, Math.Min(p.Length, 16));
c.L.Write(msg, 0, 20); c.L.Flush();
var deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs);
while (DateTime.UtcNow < deadline) {
var rb = c.Next((int)(deadline - DateTime.UtcNow).TotalMilliseconds);
if (rb == null) return null;
if (rb[1] != dev) continue;
if (rb[2] == 0x8F || (rb[0] == 0x11 && rb[2] == 0xFF && rb[3] == feat)) return null; // device absent / error
if (rb[0] == 0x11 && rb[2] == feat && rb[3] == msg[3]) { var r = new byte[16]; Array.Copy(rb, 4, r, 0, 16); return r; }
}
return null;
}
static byte GetFeatureIndex(Conn c, byte dev, ushort id) {
var r = Request(c, dev, 0x00, 0, new byte[] { (byte)(id >> 8), (byte)id }, 1500);
return r == null ? (byte)0 : r[0];
}
static string GetName(Conn c, byte dev) {
byte idx = GetFeatureIndex(c, dev, 0x0005);
if (idx == 0) return null;
var r = Request(c, dev, idx, 0, null, 1000); if (r == null) return null;
int len = r[0]; var sb = new StringBuilder();
while (sb.Length < len) {
var ch = Request(c, dev, idx, 1, new byte[] { (byte)sb.Length }, 1000); if (ch == null) break;
for (int i = 0; i < 16 && sb.Length < len; i++) sb.Append((char)ch[i]);
}
return sb.ToString().TrimEnd('\0');
}
public static List<LogiDev> Discover() {
var found = new List<LogiDev>();
var all = Enumerate();
foreach (var e in all) {
bool ble = e.Page == 0xFF43 && e.Usage == 0x0202;
bool rcv = e.Page == 0xFF00 && e.Usage == 0x0002;
if (!ble && !rcv) continue;
string shortPath = null;
if (rcv) {
shortPath = FindShortPath(e.Path, all);
}
Conn c = null;
try {
c = Open(e.Path, shortPath);
if (c == null) { Log.Add("cannot open " + e.Pid.ToString("X4")); continue; }
var idxs = ble ? new byte[] { 0xFF } : new byte[] { 1, 2, 3, 4, 5, 6 };
foreach (var dev in idxs) {
byte ch = GetFeatureIndex(c, dev, 0x1814);
if (ch == 0) continue;
var info = Request(c, dev, ch, 0, null, 1500);
if (info == null) continue;
found.Add(new LogiDev { LongPath = e.Path, ShortPath = shortPath, DevIdx = dev, ChangeHostIdx = ch, HostCount = info[0],
CurrentHost = info[1] + 1, Name = GetName(c, dev) ?? ("PID " + e.Pid.ToString("X4")),
Transport = ble ? "Bluetooth" : "USB receiver " + e.Pid.ToString("X4") + " slot " + dev });
}
} catch (Exception ex) { Log.Add(e.Pid.ToString("X4") + ": " + ex.Message); }
finally { if (c != null) c.Dispose(); }
}
return found;
}
public static string Switch(LogiDev d, int channel) {
FileStream l = null;
try {
l = OpenStream(d.LongPath, 20);
if (l == null) return "not connected";
var msg = new byte[20]; msg[0] = 0x11; msg[1] = d.DevIdx; msg[2] = d.ChangeHostIdx; msg[3] = (byte)(0x10 | SW); msg[4] = (byte)(channel - 1);
var t = l.WriteAsync(msg, 0, 20);
if (!t.Wait(400)) return "no response (not connected?)";
return "sent";
} catch (Exception) { return "not connected"; }
finally { if (l != null) l.Dispose(); }
}
// The receiver's short-report collection (where receiver errors and connect/disconnect notices arrive)
// is a sibling interface of the long one: same path up to "&col", page 0xFF00 usage 0x0001.
static readonly Dictionary<string, string> shortPaths = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
static string FindShortPath(string longPath, List<Iface> all) {
int i = longPath.IndexOf("&col", StringComparison.OrdinalIgnoreCase);
if (i < 0) return null;
string prefix = longPath.Substring(0, i);
foreach (var s in all ?? Enumerate())
if (s.Page == 0xFF00 && s.Usage == 0x0001 && s.Path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) return s.Path;
return null;
}
internal static string ShortPathFor(LogiDev d) {
if (d.DevIdx == 0xFF) return null; // Bluetooth: no short collection needed
if (!string.IsNullOrEmpty(d.ShortPath)) return d.ShortPath;
string sp;
lock (shortPaths) { if (shortPaths.TryGetValue(d.LongPath, out sp)) return sp; }
sp = FindShortPath(d.LongPath, null);
lock (shortPaths) { shortPaths[d.LongPath] = sp; }
return sp;
}
static string Ok(int attempt) { return attempt > 1 ? "sent (attempt " + attempt + ")" : "sent"; }
// Sends Change Host, then confirms the device really left (it no longer answers here).
// A lost or undeliverable command is re-sent, up to 3 attempts.
public static string SwitchConfirmed(LogiDev d, int channel) {
string last = "";
for (int attempt = 1; attempt <= 3; attempt++) {
Conn c = null;
try {
c = Open(d.LongPath, ShortPathFor(d));
if (c == null) return attempt == 1 ? "not connected" : Ok(attempt - 1);
var msg = new byte[20]; msg[0] = 0x11; msg[1] = d.DevIdx; msg[2] = d.ChangeHostIdx; msg[3] = (byte)(0x10 | SW); msg[4] = (byte)(channel - 1);
var t = c.L.WriteAsync(msg, 0, 20);
if (!t.Wait(400)) return attempt == 1 ? "no response (not connected?)" : Ok(attempt - 1);
// A receiver answers at once if it could not deliver the command (device asleep / out of range).
bool rejected = false;
var end = DateTime.UtcNow.AddMilliseconds(250);
while (DateTime.UtcNow < end) {
var rb = c.Next((int)(end - DateTime.UtcNow).TotalMilliseconds);
if (rb == null) break;
if (rb[1] != d.DevIdx) continue;
if (rb[2] == 0x8F || (rb[0] == 0x11 && rb[2] == 0xFF)) { rejected = true; break; }
}
c.Dispose(); c = null;
if (rejected) { last = "receiver could not deliver"; System.Threading.Thread.Sleep(300); continue; }
// Confirm: if the device still answers on this PC, the switch did not happen.
System.Threading.Thread.Sleep(600);
c = Open(d.LongPath, ShortPathFor(d));
if (c == null) return Ok(attempt);
var cc = c;
var probe = Task.Run(() => Request(cc, d.DevIdx, 0x00, 0, new byte[] { 0x18, 0x14 }, 400));
bool stillHere = probe.Wait(900) && probe.Result != null;
if (!stillHere) return Ok(attempt);
last = "device still on this PC";
} catch (Exception ex) { last = ex.Message; }
finally { if (c != null) c.Dispose(); }
}
return "FAILED after 3 attempts (" + last + ")";
}
// Switch all devices at once, so a remembered device that is not here (e.g. home vs. work setup) adds no delay.
public static string[] SwitchAll(LogiDev[] devs, int channel) {
var tasks = new Task<string>[devs.Length];
for (int i = 0; i < devs.Length; i++) {
var d = devs[i];
tasks[i] = Task.Run(() => d.Name + " -> channel " + channel + ": " +
(d.HostCount > 0 && channel > d.HostCount ? "skipped (only " + d.HostCount + " channels)" : SwitchConfirmed(d, channel)));
}
try { Task.WaitAll(tasks, 8000); } catch (AggregateException) { }
var r = new string[devs.Length];
for (int i = 0; i < devs.Length; i++) r[i] = tasks[i].Status == TaskStatus.RanToCompletion ? tasks[i].Result : devs[i].Name + ": timed out";
return r;
}
public static LogiDev Make(string longPath, string name, byte devIdx, byte chIdx, int hosts, string transport) {
return new LogiDev { LongPath = longPath, Name = name, DevIdx = devIdx, ChangeHostIdx = chIdx, HostCount = hosts, Transport = transport };
}
}
// "Keyboard leads, mouse follows": listens to the USB receiver of each keyboard. When the keyboard
// leaves this PC (its Easy-Switch key was pressed), the receiver sends HID++ 1.0 notification 0x41
// with the "link not established" bit, and an event is queued for the watcher loop.
public static class KeyboardFollow {
static readonly System.Collections.Concurrent.ConcurrentQueue<string> events = new System.Collections.Concurrent.ConcurrentQueue<string>();
static readonly HashSet<string> watching = new HashSet<string>();
public static bool IsKeyboard(string name) { return Regex.IsMatch(name ?? "", "K\\d|Keys|Keyboard", RegexOptions.IgnoreCase); }
public static string Take() { string e; return events.TryDequeue(out e) ? e : null; }
public static void Watch(LogiDev[] devs) {
foreach (var d in devs) {
if (d == null || d.DevIdx == 0xFF || !IsKeyboard(d.Name)) continue; // Bluetooth keyboards: no disconnect signal on Windows
string sp = LogiHid.ShortPathFor(d);
if (sp == null) continue;
string key = sp.ToLowerInvariant() + "|" + d.DevIdx;
lock (watching) { if (!watching.Add(key)) continue; }
var dev = d;
var t = new System.Threading.Thread(() => Listen(sp, dev.DevIdx, dev.Name, key));
t.IsBackground = true;
t.Start();
}
}
// The receiver reports the current link state as soon as we start listening; those first
// notifications are not a key press, so they are ignored.
static void Handle(byte[] r, byte devIdx, string name, DateTime started) {
if (r == null || r.Length < 5 || r[0] != 0x10 || r[1] != devIdx || r[2] != 0x41) return;
if ((DateTime.UtcNow - started).TotalMilliseconds < 3000) return;
events.Enqueue(((r[4] & 0x40) != 0 ? "left:" : "back:") + name);
}
static void Listen(string shortPath, byte devIdx, string name, string key) {
FileStream s = null;
var started = DateTime.UtcNow;
try {
s = LogiHid.OpenStream(shortPath, 7);
if (s == null) { events.Enqueue("info:cannot open the receiver for " + name); return; }
events.Enqueue("info:mouse will follow keyboard " + name + " (receiver slot " + devIdx + ")");
Task<int> pending = null; byte[] buf = null;
Func<int, byte[]> next = ms => {
if (pending == null) { buf = new byte[7]; pending = s.ReadAsync(buf, 0, 7); }
if (!pending.Wait(ms)) return null;
var r = buf; pending = null; return r;
};
// Make sure the receiver reports connect/disconnect: HID++ 1.0 register 0x00, "wireless" flag (0x000100).
s.Write(new byte[] { 0x10, 0xFF, 0x81, 0x00, 0, 0, 0 }, 0, 7);
var end = DateTime.UtcNow.AddMilliseconds(1000);
byte[] reg = null;
while (DateTime.UtcNow < end) {
var r = next((int)Math.Max(1, (end - DateTime.UtcNow).TotalMilliseconds));
if (r == null) break;
if (r[1] == 0xFF && r[2] == 0x81 && r[3] == 0x00) { reg = r; break; }
Handle(r, devIdx, name, started);
}
if (reg != null && (reg[5] & 0x01) == 0) {
s.Write(new byte[] { 0x10, 0xFF, 0x80, 0x00, reg[4], (byte)(reg[5] | 0x01), reg[6] }, 0, 7);
events.Enqueue("info:enabled connect/disconnect notifications on the receiver");
}
while (true) { var r = next(-1); if (r == null) break; Handle(r, devIdx, name, started); }
} catch (Exception ex) {
events.Enqueue("info:stopped following " + name + " (" + ex.Message + ")");
} finally {
if (s != null) s.Dispose();
lock (watching) { watching.Remove(key); }
}
}
}
'@
if (-not ('LogiHid' -as [type])) { Add-Type -TypeDefinition $cs -Language CSharp }
if ($Watch) {
if ($Channel -lt 1) { $Channel = 2 }
Add-Type -AssemblyName System.Windows.Forms, System.Drawing
if (-not ('LogiCursor' -as [type])) {
Add-Type -TypeDefinition @'
using System; using System.Runtime.InteropServices;
public static class LogiCursor {
[StructLayout(LayoutKind.Sequential)] public struct POINT { public int X, Y; }
[DllImport("user32.dll")] public static extern bool GetCursorPos(out POINT p);
[DllImport("user32.dll")] public static extern bool SetCursorPos(int x, int y);
[DllImport("user32.dll")] public static extern short GetAsyncKeyState(int vk);
public static bool AnyButtonDown() { return (GetAsyncKeyState(1) & 0x8000) != 0 || (GetAsyncKeyState(2) & 0x8000) != 0 || (GetAsyncKeyState(4) & 0x8000) != 0; }
[StructLayout(LayoutKind.Sequential)] struct LASTINPUTINFO { public uint cbSize; public uint dwTime; }
[DllImport("user32.dll")] static extern bool GetLastInputInfo(ref LASTINPUTINFO i);
// Seconds since the last keyboard/mouse input on this PC.
public static double IdleSeconds() {
var i = new LASTINPUTINFO(); i.cbSize = (uint)Marshal.SizeOf(i);
if (!GetLastInputInfo(ref i)) return 0;
return unchecked((uint)Environment.TickCount - i.dwTime) / 1000.0;
}
// Changes every time anything puts something new on the clipboard. Cheap to read.
[DllImport("user32.dll")] public static extern uint GetClipboardSequenceNumber();
}
'@
}
if (-not ('ClipSync' -as [type])) {
Add-Type -TypeDefinition @'
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
// Clipboard sync client. This PC dials OUT to the Mac and keeps one connection open; the Mac
// replies down the same socket, so nothing ever has to connect IN to this PC.
// 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.
public static class ClipSync {
const int MaxMessage = 12 * 1024 * 1024;
static Thread worker;
static volatile bool running;
static string host; static int port;
static byte[] encKey, macKey;
static NetworkStream stream;
static readonly object sendLock = new object();
static readonly ConcurrentQueue<byte[]> incoming = new ConcurrentQueue<byte[]>();
static readonly ConcurrentQueue<string> info = new ConcurrentQueue<string>();
public static volatile string Status = "off";
public static volatile int Connects = 0; // counts successful connections, so the script can send what waited
static long connectedTicks;
// Seconds the current connection has been up (0 if none). The Mac drops a connection with a wrong
// pairing code at once, so one that has lasted a couple of seconds was accepted.
public static double ConnectedSeconds() {
return Status == "connected" ? (DateTime.UtcNow.Ticks - Interlocked.Read(ref connectedTicks)) / 1e7 : 0;
}
static bool rejectLogged;
// ---- pairing code (Crockford base32, 16 characters, shown in groups of 4) ----
const string Alphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
public static string NewCode() {
var b = new byte[16];
using (var r = RandomNumberGenerator.Create()) r.GetBytes(b);
var sb = new StringBuilder();
for (int i = 0; i < 16; i++) { if (i > 0 && i % 4 == 0) sb.Append('-'); sb.Append(Alphabet[b[i] % 32]); }
return sb.ToString();
}
// Accepts the code however it was typed: lower case, no dashes, O/0 and I/1 mixed up.
public static string Normalize(string code) {
var sb = new StringBuilder();
foreach (char raw in (code ?? "").ToUpperInvariant()) {
char c = raw;
if (c == 'I' || c == 'L') c = '1';
else if (c == 'O') c = '0';
else if (c == 'U') c = 'V';
if (Alphabet.IndexOf(c) >= 0) sb.Append(c);
}
return sb.ToString();
}
public static bool CodeLooksValid(string code) { return Normalize(code).Length == 16; }
static void SetKeys(string code) {
byte[] master;
using (var k = new Rfc2898DeriveBytes(Normalize(code), Encoding.ASCII.GetBytes("logiswitch-clipboard-v1"), 200000, HashAlgorithmName.SHA256))
master = k.GetBytes(32);
using (var m = new HMACSHA256(master)) encKey = m.ComputeHash(Encoding.ASCII.GetBytes("enc"));
using (var m = new HMACSHA256(master)) macKey = m.ComputeHash(Encoding.ASCII.GetBytes("mac"));
}
// ---- framing ----
static void PutInt32(byte[] dst, int offset, int value) {
dst[offset] = (byte)(value >> 24); dst[offset + 1] = (byte)(value >> 16);
dst[offset + 2] = (byte)(value >> 8); dst[offset + 3] = (byte)value;
}
static byte[] Seal(byte type, byte[] payload) {
var plain = new byte[9 + payload.Length];
plain[0] = type;
long ms = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
for (int i = 0; i < 8; i++) plain[1 + i] = (byte)(ms >> (8 * (7 - i)));
Buffer.BlockCopy(payload, 0, plain, 9, payload.Length);
var iv = new byte[16];
using (var r = RandomNumberGenerator.Create()) r.GetBytes(iv);
byte[] ct;
using (var aes = new AesCryptoServiceProvider()) {
aes.KeySize = 256; aes.Key = encKey; aes.IV = iv; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7;
using (var e = aes.CreateEncryptor()) ct = e.TransformFinalBlock(plain, 0, plain.Length);
}
var body = new byte[16 + ct.Length + 32];
Buffer.BlockCopy(iv, 0, body, 0, 16);
Buffer.BlockCopy(ct, 0, body, 16, ct.Length);
using (var h = new HMACSHA256(macKey)) {
var tag = h.ComputeHash(body, 0, 16 + ct.Length);
Buffer.BlockCopy(tag, 0, body, 16 + ct.Length, 32);
}
var frame = new byte[4 + body.Length];
PutInt32(frame, 0, body.Length);
Buffer.BlockCopy(body, 0, frame, 4, body.Length);
return frame;
}
static bool Open(byte[] body, out byte type, out byte[] payload) {
type = 0; payload = null;
if (body.Length < 16 + 16 + 32 || (body.Length - 48) % 16 != 0) return false;
int ctLen = body.Length - 16 - 32;
byte[] tag;
using (var h = new HMACSHA256(macKey)) tag = h.ComputeHash(body, 0, 16 + ctLen);
int diff = 0;
for (int i = 0; i < 32; i++) diff |= tag[i] ^ body[16 + ctLen + i];
if (diff != 0) return false; // wrong code, or tampered with
var iv = new byte[16]; Buffer.BlockCopy(body, 0, iv, 0, 16);
byte[] plain;
try {
using (var aes = new AesCryptoServiceProvider()) {
aes.KeySize = 256; aes.Key = encKey; aes.IV = iv; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7;
using (var d = aes.CreateDecryptor()) plain = d.TransformFinalBlock(body, 16, ctLen);
}
} catch { return false; }
if (plain.Length < 9) return false;
long ms = 0;
for (int i = 0; i < 8; i++) ms = (ms << 8) | plain[1 + i];
if (Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - ms) > 120000) return false; // replay
type = plain[0];
payload = new byte[plain.Length - 9];
Buffer.BlockCopy(plain, 9, payload, 0, payload.Length);
return true;
}
// ---- connection ----
public static void Start(string h, int p, string code) {
Stop();
host = h; port = p;
SetKeys(code);
running = true;
worker = new Thread(Run); worker.IsBackground = true; worker.Start();
}
public static void Stop() {
running = false;
lock (sendLock) { try { if (stream != null) stream.Close(); } catch { } stream = null; }
Status = "off";
}
public static byte[] TakeIncoming() { byte[] b; return incoming.TryDequeue(out b) ? b : null; }
public static string TakeInfo() { string s; return info.TryDequeue(out s) ? s : null; }
static void SendRaw(byte[] data) {
lock (sendLock) {
var s = stream;
if (s == null) throw new IOException("not connected");
s.Write(data, 0, data.Length); s.Flush();
}
}
public static bool SendClipboard(byte[] payload) {
try { SendRaw(Seal(0x10, payload)); return true; } catch { return false; }
}
static bool ReadExact(NetworkStream s, byte[] buf, int n) {
int got = 0;
while (got < n) {
int r;
try { r = s.Read(buf, got, n - got); }
catch (IOException) { if (got == 0) return false; throw; } // idle timeout between messages
if (r <= 0) throw new IOException("the Mac closed the connection");
got += r;
}
return true;
}
static void Run() {
int backoff = 2000;
bool announced = false;
bool flapping = false; // connections keep being dropped at once (e.g. the pairing codes differ)
while (running) {
TcpClient c = null;
DateTime connectedAt = DateTime.MinValue;
try {
c = new TcpClient();
var ar = c.BeginConnect(host, port, null, null);
if (!ar.AsyncWaitHandle.WaitOne(4000)) throw new IOException("no answer from " + host + ":" + port);
c.EndConnect(ar);
c.NoDelay = true;
var s = c.GetStream();
s.ReadTimeout = 20000;
lock (sendLock) { stream = s; }
SendRaw(Seal(0x01, Encoding.UTF8.GetBytes("windows"))); // no computer name is sent
connectedAt = DateTime.UtcNow;
Interlocked.Exchange(ref connectedTicks, connectedAt.Ticks);
Status = "connected";
Connects++;
if (!flapping) info.Enqueue("clipboard sync: connected to " + host + ":" + port);
var head = new byte[4];
while (running) {
if (!ReadExact(s, head, 4)) { // quiet for 20 s: send a keepalive
SendRaw(Seal(0x02, new byte[0]));
if (flapping) { flapping = false; info.Enqueue("clipboard sync: connected to " + host + ":" + port + " (the Mac accepted the pairing code)"); }
continue;
}
int len = (head[0] << 24) | (head[1] << 16) | (head[2] << 8) | head[3];
if (len < 48 || len > MaxMessage) throw new IOException("unexpected data on the connection");
var body = new byte[len];
if (!ReadExact(s, body, len)) throw new IOException("message cut short");
byte type; byte[] payload;
if (!Open(body, out type, out payload)) {
if (!rejectLogged) info.Enqueue("ERROR: clipboard sync rejected a message (the two computers' pairing codes do not match, or a clock is more than 2 minutes off)");
rejectLogged = true;
throw new IOException("security check failed");
}
rejectLogged = false;
if (flapping) { flapping = false; info.Enqueue("clipboard sync: connected to " + host + ":" + port + " (the Mac accepted the pairing code)"); }
if (type == 0x10) incoming.Enqueue(payload);
}
} catch (Exception ex) {
// A connection that lasted a while ended: start over. One dropped within seconds: keep backing
// off (up to 30 s) and stay quiet, so a code mismatch does not fill the log.
if (connectedAt != DateTime.MinValue) {
if ((DateTime.UtcNow - connectedAt).TotalSeconds >= 10) { backoff = 2000; announced = false; flapping = false; }
else flapping = true;
}
if (running) {
Status = "waiting for the Mac";
if (!announced) { info.Enqueue("clipboard sync: " + ex.Message + " - retrying in the background"); announced = true; }
}
} finally {
lock (sendLock) { stream = null; }
try { if (c != null) c.Close(); } catch { }
}
for (int i = 0; i < backoff && running; i += 100) Thread.Sleep(100);
if (backoff < 30000) backoff *= 2;
}
Status = "off";
}
}
'@
}
$logDir = Join-Path $env:LOCALAPPDATA 'LogiSwitch'
New-Item -ItemType Directory -Force $logDir | Out-Null
$logFile = Join-Path $logDir 'watch.log'
function Write-WatchLog($m) { $line = "{0:yyyy-MM-dd HH:mm:ss} {1}" -f (Get-Date), $m; $line; try { Add-Content -Path $logFile -Value $line } catch {} }
$mutex = New-Object System.Threading.Mutex($false, 'Local\LogiSwitchEdgeWatcher')
if (-not $mutex.WaitOne(0)) { "Another LogiSwitch watcher is already running."; return }
# Device cache: remembered across runs so a switch never waits for discovery.
$cacheFile = Join-Path $logDir 'devices.json'
$cache = @()
try {
$saved = Get-Content $cacheFile -Raw -ErrorAction Stop | ConvertFrom-Json # PS 5.1 emits JSON arrays as one object; the variable lets foreach enumerate it
foreach ($e in $saved) {
$cache += [LogiHid]::Make($e.LongPath, $e.Name, [byte]$e.DevIdx, [byte]$e.ChangeHostIdx, [int]$e.HostCount, $e.Transport)
}
} catch {}
foreach ($d in @([LogiHid]::Discover())) {
$cache = @($cache | Where-Object { -not ($_.LongPath -eq $d.LongPath -and $_.DevIdx -eq $d.DevIdx) }) + $d
}
if ($Name) { $cache = @($cache | Where-Object { $n = $_.Name; @($Name | Where-Object { $n -like "*$_*" }).Count -gt 0 }) }
$cache = @($cache | Sort-Object { $_.Name -match 'K\d|Keys|Keyboard' })
try { $cache | Select-Object LongPath, Name, DevIdx, ChangeHostIdx, HostCount, Transport | ConvertTo-Json -AsArray -ErrorAction Stop | Set-Content $cacheFile -Encoding utf8 }
catch { ConvertTo-Json @($cache | Select-Object LongPath, Name, DevIdx, ChangeHostIdx, HostCount, Transport) | Set-Content $cacheFile -Encoding utf8 }
Write-WatchLog ("watching {0} edge -> channel {1}; devices: {2}{3}" -f $Edge, $Channel, (($cache | ForEach-Object Name) -join ', '), $(if ($DryRun) { ' [DRY RUN]' } else { '' }))
function Save-DeviceCache { try { ConvertTo-Json @($cache | Select-Object LongPath, Name, DevIdx, ChangeHostIdx, HostCount, Transport) | Set-Content $cacheFile -Encoding utf8 } catch {} }
# Background re-discovery (separate runspace, so edge detection never pauses).
$refreshEvery = [TimeSpan]::FromMinutes($RefreshMinutes); $nextRefresh = (Get-Date).Add($refreshEvery); $refresh = $null; $refreshHandle = $null
$script:lastSwitch = [DateTime]::MinValue
function Invoke-LogiSwitch([string]$why, [LogiDev[]]$devices = @($cache)) {
if ($DryRun) { Write-WatchLog "$why -> would switch to channel $Channel"; return }
if (-not $devices) { Write-WatchLog "ERROR: $why, but no Logitech devices are known yet (none detected on this PC since start-up)"; return }
$script:lastSwitch = Get-Date
Write-WatchLog "$why -> switching to channel $Channel"
$results = @([LogiHid]::SwitchAll([LogiDev[]]@($devices), $Channel))
foreach ($line in $results) { Write-WatchLog $line }
if (-not @($results | Where-Object { $_ -like '*: sent*' }).Count) {
Write-WatchLog ("ERROR: switch to channel {0} reached no device ({1})" -f $Channel, ($results -join '; '))
} elseif (@($results | Where-Object { $_ -like '*FAILED*' }).Count) {
Write-WatchLog ("ERROR: a device did not switch to channel {0} ({1})" -f $Channel, (($results | Where-Object { $_ -like '*FAILED*' }) -join '; '))
}
}
# "Whichever device you switch, the other follows": a device left this PC because its own
# Easy-Switch button was pressed -> send the devices still here to the other computer.
function Test-StillHere($d) {
if ($d.DevIdx -ne 255) { return $true }
$b = @($script:ble | Where-Object { $_.Name -eq $d.Name }) | Select-Object -First 1
if ($b) { return [bool]$b.Up } else { return $true }
}
function Invoke-Follow([string]$who) {
if (((Get-Date) - $script:lastSwitch).TotalSeconds -lt 5) { Write-WatchLog "$who left (part of our own switch)"; return }
$idle = [LogiCursor]::IdleSeconds()
if ($idle -gt 60) { Write-WatchLog ("$who left while this PC was idle for {0:N0} s - treated as sleep/power-off, nothing follows" -f $idle); return }
$others = @($cache | Where-Object { $_.Name -ne $who -and (Test-StillHere $_) })
if (-not $others) { Write-WatchLog "$who left; no other device here to follow it"; return }
Invoke-LogiSwitch ("$who switched away -> {0} follow" -f (($others | ForEach-Object Name) -join ' + ')) $others
}
# Bluetooth devices: Windows reports their live connection state (WinRT), so a mouse or keyboard
# switched away with its own Easy-Switch button is noticed within ~0.25 s.
$script:ble = @(); $script:bleNames = ''; $script:asTask = $null; $script:lastBlePoll = [DateTime]::MinValue
function Update-BleWatch {
try {
if (-not $script:asTask) {
$null = [Windows.Devices.Enumeration.DeviceInformation, Windows.Devices.Enumeration, ContentType = WindowsRuntime]
$null = [Windows.Devices.Bluetooth.BluetoothLEDevice, Windows.Devices.Bluetooth, ContentType = WindowsRuntime]
Add-Type -AssemblyName System.Runtime.WindowsRuntime
$script:asTask = ([System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object {
$_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' })[0]
}
$await = { param($op, $t) $task = $script:asTask.MakeGenericMethod($t).Invoke($null, @($op)); [void]$task.Wait(5000); $task.Result }
$sel = [Windows.Devices.Bluetooth.BluetoothLEDevice]::GetDeviceSelectorFromPairingState($true)
$infos = & $await ([Windows.Devices.Enumeration.DeviceInformation]::FindAllAsync($sel)) ([Windows.Devices.Enumeration.DeviceInformationCollection])
$les = @(foreach ($di in $infos) { & $await ([Windows.Devices.Bluetooth.BluetoothLEDevice]::FromIdAsync($di.Id)) ([Windows.Devices.Bluetooth.BluetoothLEDevice]) })
$list = @()
foreach ($d in @($cache | Where-Object { $_.DevIdx -eq 255 })) {
$m = [regex]::Match($d.LongPath, '_([0-9a-f]{12})&col', 'IgnoreCase')
if (-not $m.Success) { continue }
$le = $les | Where-Object { $_ -and ('{0:x12}' -f $_.BluetoothAddress) -eq $m.Groups[1].Value.ToLower() } | Select-Object -First 1
if ($le) { $list += [pscustomobject]@{ Name = $d.Name; Le = $le; Up = ($le.ConnectionStatus -eq 'Connected') } }
}
$script:ble = $list
$names = ($list | ForEach-Object Name) -join ', '
if ($names -ne $script:bleNames) { $script:bleNames = $names; if ($names) { Write-WatchLog "following Bluetooth devices: $names" } }
} catch { Write-WatchLog "Bluetooth connection tracking unavailable: $($_.Exception.Message)" }
}
[KeyboardFollow]::Watch([LogiDev[]]@($cache))
Update-BleWatch
# ---------------- clipboard sync (stage 1: plain text) ----------------
# Payload: [1 byte: number of formats] then, per format, [1 byte format][4-byte big-endian length][data].
# Format 1 = UTF-8 text. Later stages add 2 = HTML, 3 = RTF, 4 = PNG.
$script:clipOn = $false; $script:clipSeq = 0; $script:lastClipPoll = [DateTime]::MinValue
$script:lastClipText = $null # last text that went either way, so nothing is sent twice or echoed back
$script:clipPending = $null # copied here while the Mac was unreachable; sent on the next connection
$script:clipConnects = 0
$clipMaxBytes = 1MB
function New-ClipPayload([string]$text) {
$b = [Text.Encoding]::UTF8.GetBytes($text)
$p = New-Object byte[] (6 + $b.Length)
$p[0] = 1; $p[1] = 1
$p[2] = [byte](($b.Length -shr 24) -band 0xFF); $p[3] = [byte](($b.Length -shr 16) -band 0xFF)
$p[4] = [byte](($b.Length -shr 8) -band 0xFF); $p[5] = [byte]($b.Length -band 0xFF)
[Array]::Copy($b, 0, $p, 6, $b.Length)
, $p
}
function Read-ClipPayload([byte[]]$p) {
$out = @{}
try {
$i = 0; $count = $p[$i]; $i++
for ($n = 0; $n -lt $count; $n++) {
$fmt = $p[$i]; $i++
$len = ([int]$p[$i] -shl 24) -bor ([int]$p[$i+1] -shl 16) -bor ([int]$p[$i+2] -shl 8) -bor [int]$p[$i+3]; $i += 4
if ($len -lt 0 -or ($i + $len) -gt $p.Length) { break }
$d = New-Object byte[] $len; [Array]::Copy($p, $i, $d, 0, $len); $i += $len
$out[[int]$fmt] = $d
}
} catch {}
$out
}
# The clipboard can be locked by whatever app is using it, so every access gets a few tries.
function Get-ClipText {
for ($i = 0; $i -lt 6; $i++) {
try { if ([System.Windows.Forms.Clipboard]::ContainsText()) { return [System.Windows.Forms.Clipboard]::GetText() } else { return $null } }
catch { Start-Sleep -Milliseconds 25 }
}
$null
}
function Set-ClipText([string]$t) {
for ($i = 0; $i -lt 6; $i++) {
try { [System.Windows.Forms.Clipboard]::SetText($t); return $true } catch { Start-Sleep -Milliseconds 25 }
}
$false
}
if ($ClipboardSync -and [Threading.Thread]::CurrentThread.GetApartmentState() -ne 'STA') {
Write-WatchLog 'ERROR: clipboard sync needs the watcher to run with -STA; it is off for this run'
$ClipboardSync = $false
}
if ($ClipboardSync) {
$codeFile = Join-Path $logDir 'clipboard-code.txt'
$code = try { (Get-Content $codeFile -ErrorAction Stop | Where-Object { $_ -and -not $_.StartsWith('#') } | Select-Object -First 1).Trim() } catch { '' }
if (-not $PeerHost) {
Write-WatchLog 'ERROR: clipboard sync is on but no Mac address is set (icon menu > Clipboard sync > Set the Mac address)'
} elseif (-not [ClipSync]::CodeLooksValid($code)) {
Write-WatchLog 'ERROR: clipboard sync is on but the pairing code is missing or malformed (icon menu > Clipboard sync > Pairing code)'
} else {
[ClipSync]::Start($PeerHost, $PeerPort, $code)
$script:clipOn = $true
$script:clipSeq = [LogiCursor]::GetClipboardSequenceNumber()
Write-WatchLog "clipboard sync: text, dialling out to ${PeerHost}:${PeerPort} (nothing connects in to this PC)"
}
}
$since = $null; $armed = $false; $cooldownUntil = [DateTime]::MinValue; $start = Get-Date
# Lines starting with "ERROR:" make the tray icon create a support report automatically.
try {
while ($true) {
Start-Sleep -Milliseconds 20
if ($null -eq $refresh -and (Get-Date) -ge $nextRefresh) {
$refresh = [powershell]::Create().AddScript({ [LogiHid]::Discover() }); $refreshHandle = $refresh.BeginInvoke()
}
if ($null -ne $refresh -and $refreshHandle.IsCompleted) {
try {
$known = @($cache | ForEach-Object Name)
foreach ($d in @($refresh.EndInvoke($refreshHandle))) {
if ($Name -and -not @($Name | Where-Object { $d.Name -like "*$_*" }).Count) { continue }
$cache = @($cache | Where-Object { -not ($_.LongPath -eq $d.LongPath -and $_.DevIdx -eq $d.DevIdx) }) + $d
if ($known -notcontains $d.Name) { Write-WatchLog "learned device: $($d.Name) ($($d.Transport))" }
}
$cache = @($cache | Sort-Object { $_.Name -match 'K\d|Keys|Keyboard' }); Save-DeviceCache
[KeyboardFollow]::Watch([LogiDev[]]@($cache)) # follow keyboards that appeared since start-up
Update-BleWatch
} catch {}
$refresh.Dispose(); $refresh = $null; $nextRefresh = (Get-Date).Add($refreshEvery)
}
if ($MaxSeconds -gt 0 -and ((Get-Date) - $start).TotalSeconds -ge $MaxSeconds) { break }
for ($ev = [KeyboardFollow]::Take(); $ev; $ev = [KeyboardFollow]::Take()) {
if ($ev -like 'left:*') { Invoke-Follow $ev.Substring(5) }
elseif ($ev -like 'back:*') { Write-WatchLog "$($ev.Substring(5)) is back on this PC" }
elseif ($ev -like 'info:*') { Write-WatchLog $ev.Substring(5) }
}
if ($script:clipOn -and ((Get-Date) - $script:lastClipPoll).TotalMilliseconds -ge 120) {
$script:lastClipPoll = Get-Date
for ($m = [ClipSync]::TakeInfo(); $m; $m = [ClipSync]::TakeInfo()) { Write-WatchLog $m }
# Something arrived from the Mac: put it on this clipboard, and remember the resulting
# sequence number so it is not immediately sent straight back.
for ($inb = [ClipSync]::TakeIncoming(); $inb; $inb = [ClipSync]::TakeIncoming()) {
$parts = Read-ClipPayload $inb
if ($parts.ContainsKey(1)) {
$txt = [Text.Encoding]::UTF8.GetString($parts[1])
if ($txt.Length -gt 0 -and $txt -cne $script:lastClipText -and (Set-ClipText $txt)) {
$script:lastClipText = $txt
$script:clipPending = $null # the Mac's newer text replaces what was waiting here
$script:clipSeq = [LogiCursor]::GetClipboardSequenceNumber()
Write-WatchLog ("clipboard: received {0} characters from the Mac" -f $txt.Length)
}
}
}
# Something was copied here: send it over.
$seq = [LogiCursor]::GetClipboardSequenceNumber()
if ($seq -ne $script:clipSeq) {
$script:clipSeq = $seq
$txt = Get-ClipText
if ($txt -and $txt -cne $script:lastClipText) {
$bytes = [Text.Encoding]::UTF8.GetByteCount($txt)
if ($bytes -gt $clipMaxBytes) { $script:lastClipText = $txt; Write-WatchLog ("clipboard: {0:N0} KB copied here is too large to sync (limit {1:N0} KB)" -f ($bytes/1KB), ($clipMaxBytes/1KB)) }
elseif ([ClipSync]::SendClipboard((New-ClipPayload $txt))) { $script:lastClipText = $txt; $script:clipPending = $null; Write-WatchLog ("clipboard: sent {0} characters to the Mac" -f $txt.Length) }
else { $script:clipPending = $txt } # not connected: send it when the Mac is reachable again
}
}
# Just (re)connected: send what was copied here while the Mac could not be reached, if it is still on the clipboard.
$conn = [ClipSync]::Connects
if ($conn -ne $script:clipConnects -and [ClipSync]::ConnectedSeconds() -ge 2) {
$script:clipConnects = $conn
$p = $script:clipPending
if ($p) {
$script:clipPending = $null
if ($p -cne $script:lastClipText -and (Get-ClipText) -ceq $p) {
if ([ClipSync]::SendClipboard((New-ClipPayload $p))) { $script:lastClipText = $p; Write-WatchLog ("clipboard: sent {0} characters to the Mac (copied while it was not reachable)" -f $p.Length) }
else { $script:clipPending = $p }
}
}
}
}
if ($script:ble -and ((Get-Date) - $script:lastBlePoll).TotalMilliseconds -ge 250) {
$script:lastBlePoll = Get-Date
foreach ($b in $script:ble) {
$up = ($b.Le.ConnectionStatus -eq 'Connected')
if ($b.Up -and -not $up) { $b.Up = $false; Invoke-Follow $b.Name }
elseif ($up -and -not $b.Up) { $b.Up = $true; Write-WatchLog "$($b.Name) is back on this PC" }
}
}
$now = Get-Date
if ($now -lt $cooldownUntil -or [LogiCursor]::AnyButtonDown()) { $since = $null; continue }
$p = New-Object LogiCursor+POINT; [void][LogiCursor]::GetCursorPos([ref]$p)
$pt = New-Object System.Drawing.Point($p.X, $p.Y)
$b = [System.Windows.Forms.Screen]::FromPoint($pt).Bounds
$margin = [int]($b.Height * 0.1)
$inMiddle = $p.Y -ge ($b.Top + $margin) -and $p.Y -le ($b.Bottom - $margin)
if ($Edge -eq 'Right') { $atEdge = $p.X -ge ($b.Right - 1); $beyond = New-Object System.Drawing.Point(($b.Right + 1), $p.Y); $inward = $p.X - 150 }
else { $atEdge = $p.X -le $b.Left; $beyond = New-Object System.Drawing.Point(($b.Left - 2), $p.Y); $inward = $p.X + 150 }
$outer = $atEdge -and $inMiddle -and -not ([System.Windows.Forms.Screen]::AllScreens | Where-Object { $_.Bounds.Contains($beyond) })
# The cursor stays on the edge after a switch; re-arm only once it has left the edge,
# so coming back to this computer never bounces the devices straight back.
if (-not $outer) { $since = $null; $armed = $true; continue }
if (-not $armed) { continue }
if ($null -eq $since) { $since = $now; continue }
if (($now - $since).TotalMilliseconds -lt $DwellMs) { continue }
$since = $null; $armed = $false; $cooldownUntil = $now.AddSeconds(1)
Invoke-LogiSwitch "edge hit at ($($p.X),$($p.Y))"
}
} catch {
Write-WatchLog ("ERROR: watcher crashed: {0} (script line {1})" -f $_.Exception.Message, $_.InvocationInfo.ScriptLineNumber)
[ClipSync]::Stop()
exit 1
}
[ClipSync]::Stop()
$mutex.ReleaseMutex()
return
}
$knownFile = Join-Path (Join-Path $env:LOCALAPPDATA 'LogiSwitch') 'devices.json'
if ($Fast -and $Channel -gt 0 -and (Test-Path $knownFile)) {
$saved = Get-Content $knownFile -Raw | ConvertFrom-Json
$devs = @($saved | ForEach-Object {
[LogiHid]::Make($_.LongPath, $_.Name, [byte]$_.DevIdx, [byte]$_.ChangeHostIdx, [int]$_.HostCount, $_.Transport) })
} else {
$devs = [LogiHid]::Discover()
}
if ($Name) { $devs = @($devs | Where-Object { $n = $_.Name; @($Name | Where-Object { $n -like "*$_*" }).Count -gt 0 }) }
if ($List -or $Channel -eq 0) {
if (-not $devs) { "No connected Logitech device supports channel switching on this computer." }
$devs | Select-Object Name, Transport, @{n='Channels';e={$_.HostCount}}, @{n='ActiveChannel';e={$_.CurrentHost}} | Format-Table -AutoSize
[LogiHid]::Log | ForEach-Object { "note: $_" }
return
}
if (-not $devs) { "No connected Logitech device answered; nothing switched. Move the mouse / press a key to wake them and retry."; [LogiHid]::Log | ForEach-Object { "note: $_" }; return }
$already = @($devs | Where-Object { $_.CurrentHost -eq $Channel })
$already | ForEach-Object { "$($_.Name): already on channel $Channel" }
$todo = @($devs | Where-Object { $_.CurrentHost -ne $Channel })
if ($todo) { [LogiHid]::SwitchAll([LogiDev[]]$todo, $Channel) }
LogiSwitchTray.ps1 (Windows tray icon and menu)339 lines
<#
LogiSwitchTray.ps1 - icon beside the clock that controls the LogiSwitch edge watcher.
Right-click the icon for the menu; double-click to pause/resume.
#>
$ErrorActionPreference = 'Continue'
Add-Type -AssemblyName System.Windows.Forms, System.Drawing
[System.Windows.Forms.Application]::EnableVisualStyles()
$Here = Split-Path -Parent $MyInvocation.MyCommand.Path
$DataDir = Join-Path $env:LOCALAPPDATA 'LogiSwitch'
$SettingsFile = Join-Path $DataDir 'settings.json'
$DevicesFile = Join-Path $DataDir 'devices.json'
$LogFile = Join-Path $DataDir 'watch.log'
$ProblemFile = Join-Path $DataDir 'last-problem-report.txt' # fixed path Claude Code can read directly
$DesktopReport = Join-Path ([Environment]::GetFolderPath('Desktop')) 'LogiSwitch-problem-report.txt'
$ReportPs1 = Join-Path $Here 'Get-LogiSwitchReport.ps1'
$SwitchPs1 = Join-Path $Here 'LogiSwitch.ps1'
$UninstallPs1 = Join-Path $Here 'Uninstall-LogiSwitch.ps1'
$PsExe = Join-Path $env:WINDIR 'System32\WindowsPowerShell\v1.0\powershell.exe'
$StartupLnk = Join-Path ([Environment]::GetFolderPath('Startup')) 'LogiSwitch.lnk'
$Version = try { (Get-Content (Join-Path $Here 'version.txt') -ErrorAction Stop | Select-Object -First 1).Trim() } catch { '?' }
Set-Location $env:TEMP # never hold the install folder open (lets uninstall/update replace it)
New-Item -ItemType Directory -Force $DataDir | Out-Null
$Mutex = New-Object System.Threading.Mutex($false, 'Local\LogiSwitchTray')
if (-not $Mutex.WaitOne(0)) {
[void][System.Windows.Forms.MessageBox]::Show('LogiSwitch is already running. Look for its icon beside the clock (you may need to click the ^ arrow).', 'LogiSwitch')
exit
}
function Write-TrayLog($m) { try { Add-Content $LogFile ("{0:yyyy-MM-dd HH:mm:ss} [tray] {1}" -f (Get-Date), $m) } catch {} }
# ---------- settings ----------
$script:S = [ordered]@{ Edge = 'Right'; Channel = 2; Active = $true; SourceDir = ''; ClipboardSync = $false; PeerHost = ''; PeerPort = 51888 }
try {
$j = Get-Content $SettingsFile -Raw -ErrorAction Stop | ConvertFrom-Json
foreach ($k in @($script:S.Keys)) { if ($null -ne $j.$k) { $script:S[$k] = $j.$k } }
} catch {}
function Save-Settings { try { [pscustomobject]$script:S | ConvertTo-Json | Set-Content $SettingsFile -Encoding utf8 } catch {} }
# ---------- watcher process ----------
$script:Child = $null
function Get-WatcherProcs { @(Get-CimInstance Win32_Process -Filter "Name='powershell.exe'" | Where-Object { $_.CommandLine -match '\\LogiSwitch\.ps1.+-Watch' }) }
function Stop-Watcher { foreach ($p in Get-WatcherProcs) { try { Stop-Process -Id $p.ProcessId -Force -ErrorAction Stop } catch {} }; $script:Child = $null }
function Start-Watcher {
Stop-Watcher
# -STA is required for clipboard access (OLE), and is the default only by convention.
$a = "-NoProfile -ExecutionPolicy Bypass -STA -WindowStyle Hidden -File `"$SwitchPs1`" -Watch -Edge $($script:S.Edge) -Channel $($script:S.Channel)"
if ($script:S.ClipboardSync) { $a += " -ClipboardSync -PeerHost `"$($script:S.PeerHost)`" -PeerPort $($script:S.PeerPort)" }
$script:Child = Start-Process -FilePath $PsExe -ArgumentList $a -WindowStyle Hidden -PassThru
$null = $script:Child.Handle # keep a handle so the exit code can be read later
Write-TrayLog "watcher started (Mac on the $($script:S.Edge), channel $($script:S.Channel))"
}
# ---------- startup shortcut ----------
function Set-StartAtLogin([bool]$on) {
if ($on) {
$sc = (New-Object -ComObject WScript.Shell).CreateShortcut($StartupLnk)
$sc.TargetPath = $PsExe
$sc.Arguments = "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$(Join-Path $Here 'LogiSwitchTray.ps1')`""
$sc.WorkingDirectory = $env:LOCALAPPDATA; $sc.WindowStyle = 7; $sc.Description = 'LogiSwitch tray icon'
$sc.Save()
} else { Remove-Item $StartupLnk -ErrorAction SilentlyContinue }
}
# ---------- icon ----------
function New-StatusIcon([bool]$active) {
$bmp = New-Object System.Drawing.Bitmap 32, 32
$g = [System.Drawing.Graphics]::FromImage($bmp)
$g.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
$col = if ($active) { [System.Drawing.Color]::FromArgb(46, 125, 50) } else { [System.Drawing.Color]::FromArgb(128, 128, 128) }
$g.FillEllipse((New-Object System.Drawing.SolidBrush $col), 1, 1, 30, 30)
$pen = New-Object System.Drawing.Pen ([System.Drawing.Color]::White), 3
$pen.CustomEndCap = New-Object System.Drawing.Drawing2D.AdjustableArrowCap 2, 2
$g.DrawLine($pen, 7, 11, 23, 11)
$g.DrawLine($pen, 25, 21, 9, 21)
$g.Dispose()
[System.Drawing.Icon]::FromHandle($bmp.GetHicon())
}
$IconOn = New-StatusIcon $true
$IconOff = New-StatusIcon $false
# ---------- menu ----------
function New-Item2($text) { New-Object System.Windows.Forms.ToolStripMenuItem $text }
$Menu = New-Object System.Windows.Forms.ContextMenuStrip
$miStatus = New-Item2 'LogiSwitch'; $miStatus.Enabled = $false
$miActive = New-Item2 'Active - switch when cursor hits the edge'
$miNow = New-Item2 'Send keyboard + mouse to the Mac now'
$miSide = New-Item2 'Where is the Mac?'
$miRight = New-Item2 'Mac is to the RIGHT of this PC'; $miRight.Tag = 'Right'
$miLeft = New-Item2 'Mac is to the LEFT of this PC'; $miLeft.Tag = 'Left'
[void]$miSide.DropDownItems.Add($miRight); [void]$miSide.DropDownItems.Add($miLeft)
$miChan = New-Item2 "Mac's Easy-Switch channel"
$miCh = @(1, 2, 3 | ForEach-Object { $i = New-Item2 "Channel $_"; $i.Tag = $_; [void]$miChan.DropDownItems.Add($i); $i })
$miClip = New-Item2 'Clipboard sync'
$miClipOn = New-Item2 'Share the text clipboard with the Mac'
$miClipHost = New-Item2 "Set the Mac's address..."
$miClipCode = New-Item2 'Pairing code...'
foreach ($x in @($miClipOn, $miClipHost, $miClipCode)) { [void]$miClip.DropDownItems.Add($x) }
$miLogin = New-Item2 'Start at login'
$miDev = New-Item2 'Show devices'
$miRedet = New-Item2 'Re-detect devices'
$miLog = New-Item2 'Open log'
$miReport = New-Item2 'Create support report for Claude...'
$miProblem = New-Item2 'Open automatic problem report (copies it for Claude)'
$miProblem.Visible = Test-Path $ProblemFile
$miUpd = New-Item2 'Update'
$miUpdSrc = New-Item2 'Reinstall from the original folder'
$miUpdNew = New-Item2 'Update from a folder...'
[void]$miUpd.DropDownItems.Add($miUpdSrc); [void]$miUpd.DropDownItems.Add($miUpdNew)
$miUninst = New-Item2 'Uninstall...'
$miExit = New-Item2 'Exit (until next login)'
foreach ($x in @($miStatus, '-', $miActive, $miNow, '-', $miSide, $miChan, $miClip, $miLogin, '-', $miDev, $miRedet, $miLog, $miReport, $miProblem, '-', $miUpd, $miUninst, $miExit)) {
if ($x -eq '-') { [void]$Menu.Items.Add((New-Object System.Windows.Forms.ToolStripSeparator)) } else { [void]$Menu.Items.Add($x) }
}
$Tray = New-Object System.Windows.Forms.NotifyIcon
$Tray.ContextMenuStrip = $Menu
function Update-Ui {
$on = [bool]$script:S.Active
$Tray.Icon = if ($on) { $IconOn } else { $IconOff }
$state = if ($on) { 'Active' } else { 'Paused' }
$Tray.Text = "LogiSwitch: $state (Mac on the $($script:S.Edge.ToLower()), ch $($script:S.Channel))"
$miStatus.Text = "LogiSwitch $Version - $state"
$miActive.Checked = $on
$miRight.Checked = $script:S.Edge -eq 'Right'
$miLeft.Checked = $script:S.Edge -eq 'Left'
foreach ($m in $miCh) { $m.Checked = ([int]$m.Tag -eq [int]$script:S.Channel) }
$miLogin.Checked = Test-Path $StartupLnk
$miClipOn.Checked = [bool]$script:S.ClipboardSync
$miClip.Text = 'Clipboard sync' + $(if ($script:S.ClipboardSync) { " (on, Mac at $($script:S.PeerHost))" } else { ' (off)' })
$miClipHost.Text = "Set the Mac's address..." + $(if ($script:S.PeerHost) { " ($($script:S.PeerHost))" } else { '' })
$src = [string]$script:S.SourceDir
$miUpdSrc.Enabled = $src -and (Test-Path (Join-Path $src 'Install-LogiSwitch.ps1'))
$miUpdSrc.ToolTipText = $src
}
function Apply-Settings {
Save-Settings
if ($script:S.Active) { Start-Watcher } else { Stop-Watcher; Write-TrayLog 'paused' }
Update-Ui
}
function Invoke-Installer([string]$dir) {
$inst = Join-Path $dir 'Install-LogiSwitch.ps1'
if (-not (Test-Path $inst)) { [void][System.Windows.Forms.MessageBox]::Show("No Install-LogiSwitch.ps1 in:`n$dir", 'LogiSwitch'); return }
Write-TrayLog "updating from $dir"
$Tray.Visible = $false
Start-Process -FilePath $PsExe -ArgumentList "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$inst`" -Quiet" -WindowStyle Hidden
Stop-Watcher
[System.Windows.Forms.Application]::Exit()
}
$miActive.add_Click({ $script:S.Active = -not [bool]$script:S.Active; Apply-Settings })
$Tray.add_DoubleClick({ $script:S.Active = -not [bool]$script:S.Active; Apply-Settings })
$miNow.add_Click({
Start-Process -FilePath $PsExe -ArgumentList "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$SwitchPs1`" -Channel $($script:S.Channel) -Fast" -WindowStyle Hidden
})
# ---------- clipboard sync ----------
$CodeFile = Join-Path $DataDir 'clipboard-code.txt'
$CodeAlphabet = '0123456789ABCDEFGHJKMNPQRSTVWXYZ' # Crockford base32: no I, L, O or U to mistype
function New-PairingCode {
$b = New-Object byte[] 16
([System.Security.Cryptography.RandomNumberGenerator]::Create()).GetBytes($b)
$s = ''
for ($i = 0; $i -lt 16; $i++) { if ($i -gt 0 -and $i % 4 -eq 0) { $s += '-' }; $s += $CodeAlphabet[$b[$i] % 32] }
$s
}
function Get-NormalizedCode([string]$c) {
$o = ''
foreach ($ch in ([string]$c).ToUpperInvariant().ToCharArray()) {
$x = $ch
if ($x -eq 'I' -or $x -eq 'L') { $x = '1' } elseif ($x -eq 'O') { $x = '0' } elseif ($x -eq 'U') { $x = 'V' }
if ($CodeAlphabet.IndexOf($x) -ge 0) { $o += $x }
}
$o
}
function Get-PairingCode { try { (Get-Content $CodeFile -ErrorAction Stop | Where-Object { $_ -and -not $_.StartsWith('#') } | Select-Object -First 1).Trim() } catch { '' } }
function Set-PairingCode([string]$c) {
@('# LogiSwitch clipboard pairing code. The SAME code must be set on the Mac.', '# Anyone with this code and access to your network could read the shared clipboard.', $c) |
Set-Content $CodeFile -Encoding utf8
}
function Read-Line([string]$prompt, [string]$title, [string]$default) {
Add-Type -AssemblyName Microsoft.VisualBasic
[Microsoft.VisualBasic.Interaction]::InputBox($prompt, $title, $default)
}
$miClipOn.add_Click({
if ($script:S.ClipboardSync) { $script:S.ClipboardSync = $false; Apply-Settings; return }
$warn = @"
Share the text clipboard with the Mac?
Anything you copy on this PC is then sent to your Mac over your local network
(encrypted, and this PC only ever dials out - nothing connects in to it).
That includes anything you copy from work applications. Only turn this on if
you are comfortable with company text reaching your personal Mac.
"@
if ([System.Windows.Forms.MessageBox]::Show($warn, 'LogiSwitch clipboard sync', 'OKCancel', 'Warning') -ne [System.Windows.Forms.DialogResult]::OK) { return }
$code = Get-PairingCode
if ((Get-NormalizedCode $code).Length -ne 16) {
$code = New-PairingCode
Set-PairingCode $code
try { Set-Clipboard -Value $code } catch {}
[void][System.Windows.Forms.MessageBox]::Show("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 Mac (menu bar icon > Clipboard sync > Pairing code).", 'LogiSwitch pairing code')
}
if (-not $script:S.PeerHost) {
$h = Read-Line "The Mac's address on your network (its IP address, or its name ending in .local). The Mac's menu bar icon shows it under Clipboard sync." 'Address of the Mac' ''
if (-not $h) { return }
$script:S.PeerHost = $h.Trim()
}
$script:S.ClipboardSync = $true
Apply-Settings
})
$miClipHost.add_Click({
$h = Read-Line "The Mac's address on your network (its IP address, or its name ending in .local). The Mac's menu bar icon shows it under Clipboard sync." 'Address of the Mac' ([string]$script:S.PeerHost)
if ($null -eq $h -or $h -eq '') { return }
$script:S.PeerHost = $h.Trim()
Apply-Settings
})
$miClipCode.add_Click({
$cur = Get-PairingCode
if ((Get-NormalizedCode $cur).Length -ne 16) { $cur = New-PairingCode; Set-PairingCode $cur }
try { Set-Clipboard -Value $cur } catch {}
$new = Read-Line "This PC's pairing code (copied to the clipboard). Enter the SAME code on the Mac.`n`nTo use a code from the Mac instead, paste it here. Leave it as it is to keep this one." 'LogiSwitch pairing code' $cur
if ($null -eq $new -or $new -eq '') { return }
if ((Get-NormalizedCode $new).Length -ne 16) {
[void][System.Windows.Forms.MessageBox]::Show('That code is not 16 characters long, so it was not saved.', 'LogiSwitch')
return
}
Set-PairingCode $new.Trim()
Apply-Settings
})
foreach ($m in @($miRight, $miLeft)) { $m.add_Click({ param($sender, $e) $script:S.Edge = [string]$sender.Tag; Apply-Settings }) }
foreach ($m in $miCh) { $m.add_Click({ param($sender, $e) $script:S.Channel = [int]$sender.Tag; Apply-Settings }) }
$miLogin.add_Click({ Set-StartAtLogin (-not (Test-Path $StartupLnk)); Update-Ui })
$miDev.add_Click({
$names = try { $saved = Get-Content $DevicesFile -Raw -ErrorAction Stop | ConvertFrom-Json; @($saved | ForEach-Object { "- $($_.Name) ($($_.Transport))" }) } catch { @() }
$txt = if ($names) { $names -join "`n" } else { 'No devices known yet. Make sure the keyboard and mouse are on this PC, then use "Re-detect devices".' }
[void][System.Windows.Forms.MessageBox]::Show($txt, 'LogiSwitch devices')
})
$miRedet.add_Click({ if ($script:S.Active) { Start-Watcher } else { [void][System.Windows.Forms.MessageBox]::Show('Resume LogiSwitch first; devices are detected when it starts.', 'LogiSwitch') } })
$miLog.add_Click({ if (Test-Path $LogFile) { Start-Process notepad.exe -ArgumentList "`"$LogFile`"" } })
$miReport.add_Click({
$rep = Join-Path $Here 'Get-LogiSwitchReport.ps1'
if (Test-Path $rep) { Start-Process -FilePath $PsExe -ArgumentList "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$rep`"" -WindowStyle Hidden }
})
$miUpdSrc.add_Click({ Invoke-Installer ([string]$script:S.SourceDir) })
$miUpdNew.add_Click({
$dlg = New-Object System.Windows.Forms.FolderBrowserDialog
$dlg.Description = 'Choose the folder that contains the new LogiSwitch files (Install-LogiSwitch.ps1)'
if ($dlg.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { Invoke-Installer $dlg.SelectedPath }
})
$miUninst.add_Click({
$r = [System.Windows.Forms.MessageBox]::Show("Remove LogiSwitch from this PC?`n`nThis stops it, removes it from startup and deletes its files. Your Logitech devices and pairings are not affected.", 'Uninstall LogiSwitch', 'YesNo', 'Question')
if ($r -ne [System.Windows.Forms.DialogResult]::Yes) { return }
Write-TrayLog 'uninstall requested'
$Tray.Visible = $false
Stop-Watcher
Start-Process -FilePath $PsExe -ArgumentList "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$UninstallPs1`" -Quiet" -WindowStyle Hidden
[System.Windows.Forms.Application]::Exit()
})
$miExit.add_Click({ Write-TrayLog 'exit'; Stop-Watcher; $Tray.Visible = $false; [System.Windows.Forms.Application]::Exit() })
# ---------- automatic problem reports ----------
# Problems (watcher crash/unexpected stop, "ERROR:" lines in the log) produce a support report
# automatically: saved to the Desktop and to a fixed path, plus a notification. Max one per 30 min.
$script:LogPos = try { (Get-Item $LogFile -ErrorAction Stop).Length } catch { 0 }
$script:LastAuto = [DateTime]::MinValue
$script:ReportProc = $null
function Get-NewLogErrors {
try {
$fs = [System.IO.File]::Open($LogFile, 'Open', 'Read', 'ReadWrite')
try {
if ($fs.Length -lt $script:LogPos) { $script:LogPos = 0 }
$fs.Position = $script:LogPos
$text = (New-Object System.IO.StreamReader($fs)).ReadToEnd()
$script:LogPos = $fs.Length
} finally { $fs.Dispose() }
@($text -split "`r?`n" | Where-Object { $_ -match 'ERROR:' -and $_ -notmatch '\[tray\]' })
} catch { @() }
}
function Start-AutoReport([string]$reason) {
if ($null -ne $script:ReportProc) { return }
if (((Get-Date) - $script:LastAuto).TotalMinutes -lt 30) { Write-TrayLog "problem noted, report skipped (one per 30 min): $reason"; return }
$script:LastAuto = Get-Date
Write-TrayLog "creating automatic problem report: $reason"
$problem = "AUTOMATIC REPORT (created by LogiSwitch itself, no user description). Detected problem: $reason"
$a = "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$ReportPs1`" -Problem `"$($problem -replace '"', "'")`" -NoOpen -NoClipboard -OutFile `"$ProblemFile`""
$script:ReportProc = Start-Process -FilePath $PsExe -ArgumentList $a -WindowStyle Hidden -PassThru
}
function Open-ProblemReport {
if (-not (Test-Path $ProblemFile)) { return }
try { Set-Clipboard -Value (Get-Content $ProblemFile -Raw) } catch {}
$f = if (Test-Path $DesktopReport) { $DesktopReport } else { $ProblemFile }
Start-Process notepad.exe -ArgumentList "`"$f`""
}
$miProblem.add_Click({ Open-ProblemReport })
$Tray.add_BalloonTipClicked({ Open-ProblemReport })
# Supervisor: restart the watcher if it stops, and turn problems into reports.
$Timer = New-Object System.Windows.Forms.Timer
$Timer.Interval = 5000
$Timer.add_Tick({
if ($script:S.Active) {
if ($null -eq $script:Child) { Start-Watcher }
elseif ($script:Child.HasExited) {
$code = $script:Child.ExitCode
if ($code -ne 0) { Start-AutoReport "the background watcher stopped unexpectedly (exit code $code)" }
Write-TrayLog "watcher not running (exit code $code); restarting"
Start-Watcher
}
}
$errs = @(Get-NewLogErrors) # @() keeps a single line as a list (PowerShell unrolls one-item arrays)
if ($errs.Count) { Start-AutoReport (($errs[-1] -replace '^\S+ \S+ ', '') -replace '^ERROR:\s*', '') }
if ($null -ne $script:ReportProc -and $script:ReportProc.HasExited) {
$script:ReportProc = $null
if (Test-Path $ProblemFile) {
try { Copy-Item $ProblemFile $DesktopReport -Force } catch {}
$miProblem.Visible = $true
$Tray.ShowBalloonTip(20000, 'LogiSwitch found a problem',
'A report for Claude was saved to your Desktop (LogiSwitch-problem-report.txt). Click here to open it and copy it, then paste it into any Claude chat.',
[System.Windows.Forms.ToolTipIcon]::Warning)
Write-TrayLog "automatic problem report ready: $ProblemFile"
}
}
})
Write-TrayLog "tray started (version $Version)"
if ($script:S.Active) { Start-Watcher } else { Stop-Watcher }
Update-Ui
$Tray.Visible = $true
$Timer.Start()
[System.Windows.Forms.Application]::Run()
$Timer.Stop(); $Tray.Visible = $false; $Tray.Dispose()
Install-LogiSwitch.ps1 (Windows installer)64 lines
<#
Install-LogiSwitch.ps1 - install or update LogiSwitch for the current Windows user (no admin rights).
.\Install-LogiSwitch.ps1 # install / update, keep existing settings
.\Install-LogiSwitch.ps1 -Edge Left -Channel 3 # also set where the Mac is and its channel
#>
param(
[ValidateSet('Right', 'Left')][string]$Edge,
[ValidateRange(1, 3)][int]$Channel,
[switch]$NoStart,
[switch]$Quiet
)
$ErrorActionPreference = 'Stop'
$src = Split-Path -Parent $MyInvocation.MyCommand.Path
$dst = Join-Path $env:LOCALAPPDATA 'LogiSwitch'
$psExe = Join-Path $env:WINDIR 'System32\WindowsPowerShell\v1.0\powershell.exe'
$files = 'LogiSwitch.ps1', 'LogiSwitchTray.ps1', 'Install-LogiSwitch.ps1', 'Uninstall-LogiSwitch.ps1', 'Get-LogiSwitchReport.ps1', 'Report.cmd', 'Install.cmd', 'Uninstall.cmd', 'README.txt', 'version.txt', 'ASK-CLAUDE.txt'
# 1. Stop any running copy (tray and watcher), but not this installer.
Get-CimInstance Win32_Process -Filter "Name='powershell.exe'" |
Where-Object { $_.CommandLine -match '\\LogiSwitch(Tray)?\.ps1' -and $_.ProcessId -ne $PID } |
ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }
Start-Sleep -Milliseconds 500
# 2. Copy program files.
New-Item -ItemType Directory -Force $dst | Out-Null
foreach ($f in $files) {
$p = Join-Path $src $f
if (-not (Test-Path $p)) { continue }
if ((Resolve-Path $src).Path -ne (Resolve-Path $dst).Path) { Copy-Item $p $dst -Force }
Unblock-File (Join-Path $dst $f) -ErrorAction SilentlyContinue
}
# 3. Settings: keep existing ones, apply any given on the command line, remember the source folder for updates.
$settingsFile = Join-Path $dst 'settings.json'
$s = [ordered]@{ Edge = 'Right'; Channel = 2; Active = $true; SourceDir = '' }
# Keep EVERY saved setting (also clipboard sync, the Mac's address and port), not only the four above.
try { $j = Get-Content $settingsFile -Raw -ErrorAction Stop | ConvertFrom-Json; foreach ($p in $j.PSObject.Properties) { if ($null -ne $p.Value) { $s[$p.Name] = $p.Value } } } catch {}
if ($PSBoundParameters.ContainsKey('Edge')) { $s.Edge = $Edge }
if ($PSBoundParameters.ContainsKey('Channel')) { $s.Channel = $Channel }
if ((Resolve-Path $src).Path -ne (Resolve-Path $dst).Path) { $s.SourceDir = (Resolve-Path $src).Path }
[pscustomobject]$s | ConvertTo-Json | Set-Content $settingsFile -Encoding utf8
# 4. Start at login (replaces the older watcher-only shortcut).
$startup = [Environment]::GetFolderPath('Startup')
Remove-Item (Join-Path $startup 'LogiSwitch edge watcher.lnk') -ErrorAction SilentlyContinue
$sc = (New-Object -ComObject WScript.Shell).CreateShortcut((Join-Path $startup 'LogiSwitch.lnk'))
$sc.TargetPath = $psExe
$sc.Arguments = "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$(Join-Path $dst 'LogiSwitchTray.ps1')`""
$sc.WorkingDirectory = $env:LOCALAPPDATA; $sc.WindowStyle = 7; $sc.Description = 'LogiSwitch tray icon'
$sc.Save()
# 5. Start the tray icon now.
if (-not $NoStart) {
Start-Process -FilePath $psExe -ArgumentList $sc.Arguments -WorkingDirectory $env:LOCALAPPDATA -WindowStyle Hidden
}
$ver = try { (Get-Content (Join-Path $dst 'version.txt') | Select-Object -First 1).Trim() } catch { '?' }
if (-not $Quiet) {
"LogiSwitch $ver installed to $dst"
"Mac is to the $($s.Edge.ToUpper()) of this PC; Mac channel = $($s.Channel)."
"Look for the green icon beside the clock (click ^ if hidden). Right-click it for options."
}
Uninstall-LogiSwitch.ps1 (Windows)21 lines
<#
Uninstall-LogiSwitch.ps1 - remove LogiSwitch for the current Windows user.
Stops the tray icon and watcher, removes the startup entry, deletes the installed files.
Logitech software, devices and pairings are not touched.
#>
param([switch]$Quiet)
$dst = Join-Path $env:LOCALAPPDATA 'LogiSwitch'
Get-CimInstance Win32_Process -Filter "Name='powershell.exe'" |
Where-Object { $_.CommandLine -match '\\LogiSwitch(Tray)?\.ps1' -and $_.ProcessId -ne $PID } |
ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }
$startup = [Environment]::GetFolderPath('Startup')
Remove-Item (Join-Path $startup 'LogiSwitch.lnk'), (Join-Path $startup 'LogiSwitch edge watcher.lnk') -ErrorAction SilentlyContinue
# Delete the folder a moment after this script exits (it may be running from inside it).
if (Test-Path $dst) {
Start-Process -FilePath "$env:WINDIR\System32\cmd.exe" -ArgumentList "/c timeout /t 2 /nobreak >nul & rmdir /s /q `"$dst`"" -WindowStyle Hidden -WorkingDirectory $env:TEMP
}
if (-not $Quiet) { "LogiSwitch removed. (Installed files in $dst are deleted in a few seconds.)" }
Get-LogiSwitchReport.ps1 (Windows support report for Claude)132 lines
<#
Get-LogiSwitchReport.ps1 - build a support report you can paste into any Claude chat.
The report starts with instructions for Claude, then diagnostics, then the full source code.
Removes: Windows username, computer name, Bluetooth/hardware addresses and device serials.
Saves to the Desktop, copies to the clipboard and opens it in Notepad.
#>
param([string]$Problem = '', [switch]$NoOpen, [switch]$NoClipboard, [string]$OutFile)
$ErrorActionPreference = 'Continue'
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$dataDir = Join-Path $env:LOCALAPPDATA 'LogiSwitch'
$psExe = Join-Path $env:WINDIR 'System32\WindowsPowerShell\v1.0\powershell.exe'
function Protect-Text([string]$t) {
if (-not $t) { return $t }
$t = $t -replace [regex]::Escape($env:USERNAME), '<user>'
$t = $t -replace [regex]::Escape($env:COMPUTERNAME), '<computer>'
if ($env:USERDOMAIN) { $t = $t -replace ('\b' + [regex]::Escape($env:USERDOMAIN) + '\b'), '<domain>' }
$t = $t -replace '(?i)(?<![0-9a-f])[0-9a-f]{12}(?![0-9a-f])', '<hwaddr>' # Bluetooth addresses in device paths
$t = $t -replace '(?i)\b([0-9a-f]{2}[:-]){5}[0-9a-f]{2}\b', '<hwaddr>' # MAC-style addresses
$t = $t -replace '(?i)(serial\w*\s*[=:]\s*"?)[^",\s]+', '$1<serial>'
$t
}
function Section($title, $body, [switch]$Raw) {
$b = [string]$body; if (-not $Raw) { $b = Protect-Text $b }
"`n===== $title =====`n" + $b.TrimEnd()
}
if (-not $Problem) {
try {
Add-Type -AssemblyName Microsoft.VisualBasic
$Problem = [Microsoft.VisualBasic.Interaction]::InputBox('Briefly describe the problem (what you did, what happened, what you expected):', 'LogiSwitch support report', '')
} catch {}
}
$ver = try { (Get-Content (Join-Path $here 'version.txt') -ErrorAction Stop | Select-Object -First 1).Trim() } catch { '?' }
$os = Get-CimInstance Win32_OperatingSystem
$sb = New-Object System.Text.StringBuilder
[void]$sb.AppendLine(@"
===== INSTRUCTIONS FOR CLAUDE =====
You are helping me fix "LogiSwitch", a small Windows tool (PowerShell 5.1 + embedded C#) that
switches my Logitech keyboard and mouse between my Windows PC and my Mac.
How it works:
- It sends the Logitech HID++ 2.0 "Change Host" command (feature 0x1814, function 1 setCurrentHost,
host index 0-based) over the existing USB receiver or Bluetooth HID link. The only network use is
the optional clipboard sync (see below).
- Bluetooth devices: vendor HID collection usage page 0xFF43 / usage 0x0202, 20-byte long report 0x11,
device index 0xFF. Unifying/Bolt receiver: usage page 0xFF00, usage 0x0002 (long) and 0x0001 (short,
where receiver errors 0x8F arrive), device index 1-6.
- LogiSwitch.ps1 -Watch polls the cursor; when it is held against the outer screen edge facing the Mac
(middle 80% of the height, no button held) for ~300 ms it switches all remembered devices to the
Mac's channel. The cursor stays on the edge; it re-arms only after the cursor leaves the edge.
- Devices are remembered in devices.json; a background runspace re-detects them every 3 minutes.
- LogiSwitchTray.ps1 is the icon beside the clock (pause/resume, Mac position, channel, start at
login, update, uninstall) and runs the watcher as a hidden child process.
- Install-LogiSwitch.ps1 installs per user to %LOCALAPPDATA%\LogiSwitch with a Startup-folder
shortcut. No admin rights are available on this PC.
Constraints (must keep):
- No admin rights, no firewall/security/Group Policy changes, no internet or third-party services, and network only for the optional clipboard sync (off until turned on; the Mac listens on TCP 51888, the PC dials out, AES-256 + HMAC with a shared pairing code), no file sharing.
What I need from you:
1. Read my problem description, the diagnostics and the log below, and identify the root cause.
2. Give me the fix: either exact PowerShell commands to run, or the complete corrected file(s)
(full file content, ready to save over the old one), then how to reinstall
(run Install.cmd from the folder containing the corrected files, or icon menu > Update).
3. Tell me how to confirm it is fixed.
If you can run commands on this PC (for example Claude Code), apply the fix yourself instead:
the installed files are in %LOCALAPPDATA%\LogiSwitch (it is also a complete install package),
reinstall with powershell -NoProfile -ExecutionPolicy Bypass -File "%LOCALAPPDATA%\LogiSwitch\Install-LogiSwitch.ps1"
after editing, then verify with ...\LogiSwitch.ps1 -List and the log. The latest automatic
report is always at %LOCALAPPDATA%\LogiSwitch\last-problem-report.txt.
"@)
[void]$sb.AppendLine((Section 'MY PROBLEM' $(if ($Problem) { $Problem } else { '(not described)' })))
$diag = @(
"Report created : $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
"LogiSwitch : $ver (installed in %LOCALAPPDATA%\LogiSwitch: $(Test-Path (Join-Path $dataDir 'LogiSwitchTray.ps1')))"
"Windows : $($os.Caption) $($os.Version)"
"PowerShell : $($PSVersionTable.PSVersion) language mode: $($ExecutionContext.SessionState.LanguageMode)"
"Exec policy : " + ((Get-ExecutionPolicy -List | ForEach-Object { "$($_.Scope)=$($_.ExecutionPolicy)" }) -join ', ')
"Startup entry : $(Test-Path (Join-Path ([Environment]::GetFolderPath('Startup')) 'LogiSwitch.lnk'))"
) -join "`n"
[void]$sb.AppendLine((Section 'SYSTEM' $diag))
$procs = Get-CimInstance Win32_Process -Filter "Name='powershell.exe'" | Where-Object { $_.CommandLine -match '\\LogiSwitch(Tray)?\.ps1' } |
ForEach-Object { "pid $($_.ProcessId) started $($_.CreationDate): " + ($_.CommandLine -replace '^.*?-File\s+', '-File ') }
[void]$sb.AppendLine((Section 'RUNNING PROCESSES' $(if ($procs) { $procs -join "`n" } else { 'none (tray and watcher are not running)' })))
$settings = try { Get-Content (Join-Path $dataDir 'settings.json') -Raw -ErrorAction Stop } catch { '(no settings.json)' }
[void]$sb.AppendLine((Section 'SETTINGS (settings.json)' $settings))
$devs = try { $saved = Get-Content (Join-Path $dataDir 'devices.json') -Raw -ErrorAction Stop | ConvertFrom-Json
$saved | ForEach-Object { "$($_.Name) | $($_.Transport) | devIdx $($_.DevIdx) | featureIdx $($_.ChangeHostIdx) | channels $($_.HostCount)" } } catch { @('(no devices.json)') }
[void]$sb.AppendLine((Section 'REMEMBERED DEVICES (devices.json)' ($devs -join "`n")))
$screens = try { Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.Screen]::AllScreens | ForEach-Object { "$($_.DeviceName -replace '^\\\\\.\\','') primary=$($_.Primary) bounds=$($_.Bounds)" } } catch { @('?') }
[void]$sb.AppendLine((Section 'DISPLAYS' ($screens -join "`n")))
# Live detection (read-only; takes ~10 s). Runs in a separate process so a hang cannot block the report.
$live = '(skipped: LogiSwitch.ps1 not found)'
$switchPs1 = Join-Path $here 'LogiSwitch.ps1'
if (Test-Path $switchPs1) {
$tmp = Join-Path $env:TEMP 'logiswitch-list.txt'
$p = Start-Process -FilePath $psExe -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File `"$switchPs1`" -List" -RedirectStandardOutput $tmp -WindowStyle Hidden -PassThru
if ($p.WaitForExit(45000)) { $live = Get-Content $tmp -Raw } else { try { $p.Kill() } catch {}; $live = '(timed out after 45 s)' }
Remove-Item $tmp -ErrorAction SilentlyContinue
}
[void]$sb.AppendLine((Section 'LIVE DEVICE CHECK (LogiSwitch.ps1 -List, read-only)' $live))
$logi = Get-PnpDevice -PresentOnly -ErrorAction SilentlyContinue | Where-Object { $_.FriendlyName -match 'Logi|MX |ERGO|K860|Bolt|Unifying' -or $_.InstanceId -match 'VID_046D|VID&02046D' } |
Sort-Object FriendlyName -Unique | ForEach-Object { "$($_.Status) $($_.Class) $($_.FriendlyName)" }
[void]$sb.AppendLine((Section 'LOGITECH DEVICES SEEN BY WINDOWS' ($logi -join "`n")))
$log = try { (Get-Content (Join-Path $dataDir 'watch.log') -Tail 150 -ErrorAction Stop) -join "`n" } catch { '(no watch.log)' }
[void]$sb.AppendLine((Section 'LOG (last 150 lines of watch.log)' $log))
foreach ($f in 'LogiSwitch.ps1', 'LogiSwitchTray.ps1', 'Install-LogiSwitch.ps1', 'Uninstall-LogiSwitch.ps1') {
$path = Join-Path $here $f
$body = if (Test-Path $path) { Get-Content $path -Raw } else { '(missing)' }
[void]$sb.AppendLine((Section "SOURCE: $f" $body -Raw))
}
[void]$sb.AppendLine("`n===== END OF REPORT =====")
$out = if ($OutFile) { $OutFile } else { Join-Path ([Environment]::GetFolderPath('Desktop')) ("LogiSwitch-report-{0:yyyyMMdd-HHmm}.txt" -f (Get-Date)) }
$sb.ToString() | Set-Content -Path $out -Encoding utf8
if (-not $NoClipboard) { try { Set-Clipboard -Value $sb.ToString() } catch {} }
if (-not $NoOpen) { Start-Process notepad.exe -ArgumentList "`"$out`"" }
"Report saved to $out" + $(if ($NoClipboard) { '.' } else { ' (also copied to the clipboard).' })
Install.cmd6 lines
@echo off
rem Install or update LogiSwitch for this Windows user (no admin rights needed).
rem Optional: Install.cmd -Edge Left -Channel 3
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0Install-LogiSwitch.ps1" %*
pause
Uninstall.cmd6 lines
@echo off
rem Remove LogiSwitch for this Windows user. Copies itself to TEMP first so it can delete the install folder.
copy /y "%~dp0Uninstall-LogiSwitch.ps1" "%TEMP%\Uninstall-LogiSwitch.ps1" >nul
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%TEMP%\Uninstall-LogiSwitch.ps1"
pause
Report.cmd4 lines
@echo off
rem Create a LogiSwitch support report (saved to Desktop, copied to clipboard) to paste into any Claude chat.
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0Get-LogiSwitchReport.ps1" %*
README.txt108 lines
LogiSwitch (Windows + macOS)
=============================
Two ways to move your Logitech keyboard AND mouse to the other computer together:
1. Push the cursor against the screen edge that faces the other computer.
2. Press the Easy-Switch button on EITHER the keyboard or the mouse - the other
one follows automatically within about a second.
(Follow is skipped when the computer has been idle for over a minute, so a device
that merely goes to sleep or is switched off does not drag the other one away.)
It sends Logitech's own Easy-Switch "change channel" command over the existing
Bluetooth or USB-receiver (Unifying / Bolt) connection.
- No network, no admin rights, no firewall or security changes.
- No clipboard or file sharing between the computers.
- Works with ANY Logitech keyboard/mouse that has Easy-Switch channels. It finds
whatever is connected (at start-up and every 3 minutes), so a different set at
work is picked up automatically. Tested: ERGO K860, MX Vertical.
ONE-TIME SETUP OF THE DEVICES
Pair each keyboard and mouse with both computers, each computer on its own
Easy-Switch channel. Default assumption: Windows PC = channel 1, Mac = channel 2.
(Hold a channel button ~3 s until it blinks fast, then connect from the computer.)
INSTALL ON WINDOWS
Copy this folder to the PC and double-click Install.cmd.
Optional (command prompt): Install.cmd -Edge Right -Channel 2
-Edge = side of the PC screen where the Mac is (default Right)
-Channel = the Mac's Easy-Switch channel (default 2)
A green arrows icon appears beside the clock (click ^ if hidden).
INSTALL ON macOS
Copy this folder to the Mac, open Terminal and run:
bash ~/Downloads/LogiSwitch/install.sh
(use the real path of the folder; you can type "bash " and drag install.sh in).
Every run writes LogiSwitch-install-log.txt to the Desktop. If it fails, it also
writes LogiSwitch-fix-request.txt (copied to the clipboard): paste into Claude.
macOS will ask to allow LogiSwitch under Input Monitoring (needed to switch a
keyboard): allow it, then click the menu bar icon > Quit and run install.sh again.
The first time, macOS may ask to install Apple's free Command Line Tools: accept,
wait, then run the same command again. The first build saves a ready-built app
in the folder's mac-bin/ subfolder; zip the folder again and every later Mac
installs from it in seconds, with no Command Line Tools needed.
Optional: bash install.sh --edge Left --channel 1
--edge = side of the Mac screen where the PC is (default Left)
--channel = the PC's Easy-Switch channel (default 1)
An arrows icon appears in the menu bar (top right).
CLIPBOARD SYNC (optional, OFF until you turn it on; text only for now)
Copy on one computer, paste on the other, usually in well under a second.
The Mac listens and the PC dials out to it, so nothing connects IN to the PC and
no firewall change is needed. Traffic stays on your own network - no internet, no
third-party service. Encrypted with AES-256 and a 16-character pairing code that
must match on both computers.
Turn it on:
1. Mac: icon > Clipboard sync > Share the text clipboard with the PC.
Note the pairing code it shows, and the Mac's address.
2. Windows: icon > Clipboard sync > Set the Mac's address..., then Pairing code...
(enter the same one), then Share the text clipboard with the Mac.
If it stops working, your router has probably given the Mac a new address: check
the Mac's icon > Clipboard sync > This Mac's address, and set it again on the PC.
WARNING: anything you copy on a work computer is then sent to the other computer.
Think about your employer's rules before turning this on.
ICON MENU (same on both)
Active ............................ pause / resume (remembered)
Send keyboard + mouse ... now ..... manual switch
Where is the Mac / PC? ............ LEFT or RIGHT (fixes the edge direction)
... Easy-Switch channel ........... 1 / 2 / 3 of the OTHER computer
Clipboard sync .................... share the text clipboard (see above)
Start at login .................... on / off
Show devices / Re-detect devices / Open log
Create support report for Claude... see below
Update ............................ reinstall from the original folder, or pick a
folder with a newer copy (settings are kept)
Uninstall... ...................... stop, remove from login, delete files
Exit / Quit ....................... until next login
(Windows: double-click the icon to pause/resume.)
NEED CLAUDE? (normally not)
ASK-CLAUDE.txt has ready-made prompts: first Mac install with Claude, a failed Mac
install, and a new Windows PC. If install.sh fails on a Mac it writes
LogiSwitch-fix-request.txt to the Desktop (prompt + error + source) and copies it
to the clipboard: paste it into any Claude chat, apply the answer, run install.sh again.
SOMETHING WRONG?
Usually you don't have to do anything: when LogiSwitch detects a problem itself
(crash, a switch that reached no device, blocked device access) it creates the
report automatically, saves it as LogiSwitch-problem-report.txt on the Desktop
and shows a notification. Click it (or icon menu > Open automatic problem
report) to copy it, then paste into any Claude chat. Max one report per 30 min.
For anything else:
Icon menu > Create support report for Claude...
(or Windows: Report.cmd, Mac: bash report.sh)
Describe the problem. A text file is saved to the Desktop and copied to the
clipboard. Paste it into any Claude chat (any account): it tells Claude how the
tool works and includes diagnostics, logs and the full source, so Claude can
find the cause and give you corrected files. Username, computer name and
hardware addresses are removed automatically.
UNINSTALL
Icon menu > Uninstall... or Windows: Uninstall.cmd, Mac: bash uninstall.sh
FILES
Windows: Install.cmd, Uninstall.cmd, Report.cmd and the .ps1 files
installs to %LOCALAPPDATA%\LogiSwitch (+ Startup-folder shortcut)
macOS: install.sh, uninstall.sh, report.sh, LogiSwitch.swift
installs to ~/Library/Application Support/LogiSwitch
(+ ~/Library/LaunchAgents/com.logiswitch.agent.plist)
MAC-START-HERE.txt (first Mac install with Claude)69 lines
LogiSwitch on the Mac - start here
==================================
1. Unzip LogiSwitch-1.4.0.zip in Downloads (double-click it).
2. Open Claude on this Mac (Claude Code or the Claude desktop app works best, because it
can run the commands itself; a normal Claude chat also works, one command at a time).
3. Copy everything between the lines below and paste it into Claude.
----------------------------------------------------------------------------------------
Help me install and get working "LogiSwitch", my own small tool, on this Mac. The Windows
side already works; only the Mac side is missing. The files are in ~/Downloads/LogiSwitch
(find the folder if it is somewhere else). Read README.txt there first.
My setup: Logitech ERGO K860 keyboard and MX Vertical mouse, paired with this Mac over
Bluetooth on Easy-Switch channel 2. My Windows PC is channel 1 and sits to the LEFT of
this Mac.
What the tool does:
- Switches both devices to the PC when I push the cursor against the Mac's LEFT edge
(50 ms hold), or when I press the Easy-Switch button on either device (the other
follows). It sends the Logitech HID++ 2.0 "Change Host" command (feature 0x1814) over
IOKit HID, confirms the device actually left, and re-sends up to 3 times if not.
- Optionally shares the plain-text clipboard with the PC. This Mac LISTENS on TCP 51888
and the PC dials out to it (the PC's firewall blocks incoming connections, so it must
be this way round). Both directions then use that one connection. Everything is
encrypted: AES-256-CBC plus HMAC-SHA256, keys from PBKDF2-SHA256 (200000 rounds) of a
shared 16-character pairing code. Clipboard sync is OFF until I turn it on.
If you can run commands on this Mac, do the steps yourself. If you cannot, give me one
command at a time and ask me to paste the output back.
Steps:
1. Run: bash ~/Downloads/LogiSwitch/install.sh
It builds LogiSwitch.swift with xcrun swiftc. If Apple's Command Line Tools are
missing, tell me to click Install in the pop-up, wait, then run it again.
2. LogiSwitch.swift was written on Windows and has NEVER been compiled. If the build
fails, fix LogiSwitch.swift with the smallest change that keeps its behaviour, save it
in ~/Downloads/LogiSwitch, and run install.sh again until it builds and prints
"LogiSwitch is running." Likely trouble spots, since they were written blind:
the CommonCrypto calls (CCCrypt, CCHmac, CCKeyDerivationPBKDF), the BSD socket code in
ClipServer, getifaddrs in localIPv4(), and the IOHIDManager matching dictionaries.
3. When macOS asks to allow LogiSwitch under Privacy & Security > Input Monitoring, I will
allow it. Then restart it: menu bar arrows icon > Quit, then run install.sh again.
4. Check: "$HOME/Library/Application Support/LogiSwitch/LogiSwitch" --list
It must list my keyboard and mouse and say "Input Monitoring permission: granted".
5. Test the switching with me, reading
~/Library/Application Support/LogiSwitch/watch.log after each step:
a) cursor pushed against the Mac's LEFT edge -> keyboard and mouse go to the PC
b) Easy-Switch key 1 on the keyboard -> the mouse follows to the PC
c) channel button 1 on the mouse -> the keyboard follows to the PC
Fix anything that does not work.
6. Then set up the clipboard, which has NEVER been tested between the two computers
(only Windows-to-Windows against a stand-in server):
a) Menu bar icon > Clipboard sync > Share the text clipboard with the PC. Accept the
warning. Note the pairing code it shows and this Mac's address.
b) If macOS asks to allow incoming network connections, or for Local Network access,
tell me and I will allow it.
c) I will then enter the same address and pairing code on the PC and switch it on
there (icon beside the clock > Clipboard sync).
d) Test both directions with me: copy text on the Mac, paste on the PC, and the other
way round. Expect it to arrive in well under a second. Check watch.log on this side
for "clipboard: sent ..." / "clipboard: received ...". If messages are rejected,
the two pairing codes do not match.
7. At the end tell me briefly: how to update later, and where the logs are.
Rules: no admin password unless macOS itself asks for the Command Line Tools, no traffic
outside my own local network, no third-party services, and ask me before granting any
macOS permission.
----------------------------------------------------------------------------------------
ASK-CLAUDE.txt (ready-made prompts)102 lines
LogiSwitch - ready-made prompts for Claude
==========================================
Copy everything between the === lines of the section you need and paste it into
any Claude chat (any account). If the install fails on a Mac, you don't need to
copy anything: install.sh writes LogiSwitch-fix-request.txt to your Desktop and
copies it to the clipboard automatically - just paste.
AUTOMATIC PROBLEM REPORTS
When LogiSwitch detects a problem by itself (watcher crash, a switch that reached no
device, macOS blocking device access) it writes a complete report for Claude
automatically and shows a notification:
Desktop: LogiSwitch-problem-report.txt
Windows: %LOCALAPPDATA%\LogiSwitch\last-problem-report.txt
Mac: ~/Library/Application Support/LogiSwitch/last-problem-report.txt
Click the notification (or icon menu > Open automatic problem report) to copy it, and
paste it into any Claude chat. The report starts with its own instructions for Claude.
With Claude Code on that computer, just say:
"Read the LogiSwitch problem report at <path above> and fix it."
=== MAC: FIRST INSTALL WITH CLAUDE (Claude Code / Claude with terminal access) ===
I have a folder named LogiSwitch on this Mac (probably ~/Downloads/LogiSwitch; find it).
It is my own tool that switches my Logitech keyboard and mouse between this Mac and my
Windows PC when I push the cursor against the screen edge, or when I press the Easy-Switch
button on either device (the other follows). Read its README.txt first.
A previous install attempt failed and left no useful log; LogiSwitch-install-log.txt and
LogiSwitch-fix-request.txt on my Desktop (if present) show what happened.
Please install the macOS part:
1. Run: bash install.sh inside that folder. It builds LogiSwitch.swift with xcrun swiftc.
If Apple's Command Line Tools are missing, tell me to click Install in the pop-up,
wait until it finishes, then run install.sh again.
2. This Swift code was written on Windows and has never been compiled. If the build fails,
fix LogiSwitch.swift with the smallest change that keeps its behavior (HID++ 2.0 feature
0x1814 "Change Host" over IOKit for Bluetooth usage page 0xFF43 and Unifying/Bolt receivers
usage page 0xFF00; edge watcher; menu-bar menu; settings/devices JSON), then run install.sh
again until it succeeds.
3. Verify, with my Logitech keyboard and mouse connected to this Mac:
- macOS asks to allow LogiSwitch under Privacy & Security > Input Monitoring: I allow it,
then restart the app (menu bar icon > Quit, then bash install.sh again)
- "$HOME/Library/Application Support/LogiSwitch/LogiSwitch" --list shows them
(and says Input Monitoring is granted)
- pressing the Easy-Switch button on the keyboard OR the mouse makes the other follow
to the PC (check watch.log)
- the arrows icon is in the menu bar; its menu says "PC is to the LEFT" and PC channel 1
(change them in the menu if my setup differs)
- when I push the cursor against the Mac's left edge, both devices go to my PC
(check ~/Library/Application Support/LogiSwitch/watch.log)
4. If you changed any file, keep the corrected files in the LogiSwitch folder and tell me,
so the folder (with the new mac-bin/ subfolder) becomes my working package for other Macs.
5. Finally tell me in 3 lines: how to UPDATE later (bash install.sh from the newer folder,
or menu bar icon > Update), and where the LOGS are:
~/Library/Application Support/LogiSwitch/watch.log, stderr.log, install.log, and
~/Desktop/LogiSwitch-install-log.txt.
Rules: no admin password unless macOS itself asks for the Command Line Tools, no internet or
third-party services (clipboard sync stays off unless I turn it on), and ask me before granting any
macOS permission (for example Input Monitoring).
=== END MAC: FIRST INSTALL WITH CLAUDE ===
=== MAC: INSTALL FAILED - PLEASE FIX ===
The LogiSwitch installer failed on my Mac. LogiSwitch is my own small tool that switches my
Logitech keyboard and mouse between this Mac and my Windows PC: a Swift menu-bar app
(LogiSwitch.swift) that sends the Logitech HID++ 2.0 "Change Host" command (feature 0x1814,
function 1 setCurrentHost, 0-based host index) over IOKit HID when the cursor is pushed
against the screen edge facing the PC. Bluetooth devices: primary usage page 0xFF43, long
report ID 0x11 (20 bytes, report ID included in the buffer), device index 0xFF.
Unifying/Bolt receivers: usage page 0xFF00, device index 1-6, errors as short report 0x10/0x8F.
install.sh builds it with:
xcrun swiftc -O -o LogiSwitch LogiSwitch.swift -framework AppKit -framework IOKit
The code was written on Windows and had never been compiled before.
The installer output, my macOS version and the full source are below.
Please:
1. Find the cause of the failure.
2. Give me the COMPLETE corrected file(s), full content ready to save over the old ones
in my LogiSwitch folder (smallest change, keep the behavior), or exact Terminal commands.
3. Tell me to run bash install.sh in the LogiSwitch folder again, and how to check it
works: "$HOME/Library/Application Support/LogiSwitch/LogiSwitch" --list
Rules: no internet or third-party services, keep clipboard sync as it is (off by default), no admin password,
ask before any macOS permission.
=== END MAC: INSTALL FAILED - PLEASE FIX ===
=== WINDOWS: INSTALL OR PROBLEM ON A NEW PC ===
I have a folder named LogiSwitch on this Windows PC. It is my own tool (PowerShell 5.1 +
embedded C#) that switches my Logitech keyboard and mouse to my Mac when I push the cursor
against the screen edge, using the Logitech HID++ 2.0 "Change Host" command (feature 0x1814)
over Bluetooth or a Unifying/Bolt receiver. Read its README.txt first.
Please:
1. Install it by running Install.cmd in that folder (no admin rights are available).
2. Check that %LOCALAPPDATA%\LogiSwitch\LogiSwitch.ps1 -List shows my Logitech devices and
that the green icon is beside the clock (menu: where the Mac is, Mac's channel).
3. If anything fails, find the cause and fix the scripts with the smallest change.
Rules: no admin rights, no firewall/security/Group Policy changes, no internet or
third-party services, keep clipboard sync as it is (off by default).
=== END WINDOWS ===
index.html (this explainer page)160 lines
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>PairSwitch: one keyboard and mouse for a Mac and a PC</title>
<meta name="description" content="Free tool: push the cursor against the screen edge, or press Easy-Switch, and a Logitech keyboard and mouse move together between a Mac and a Windows PC.">
<link rel="icon" href="../../favicon.svg" type="image/svg+xml">
<link rel="stylesheet" href="./ls.css">
</head>
<body>
<div class="wrap">
<header class="mast">
<div>
<p class="kick">Free tool · macOS + Windows · works with Logitech Easy-Switch</p>
<h1>PairSwitch</h1>
<p class="lede">One keyboard and mouse for two computers. Works with Logitech keyboards and mice. Push the cursor against the screen edge, or press Easy-Switch on either device, and both move to the other computer together. Text you copy can follow, encrypted, over your own network.</p>
</div>
<div class="mastbtns">
<button type="button" class="btn pri" id="tourBtn">Show me how</button>
<a class="btn" href="/all/">Free tools ›</a>
</div>
</header>
<section class="demo" id="demo" aria-label="Try it: a Mac and a PC sharing one keyboard and mouse">
<div class="desk" id="desk">
<div class="screen pc" id="scrPC">
<div class="bar"><span class="dot"></span><span class="dot"></span><span class="dot"></span><b><span class="wide">Windows </span>PC</b><span class="ch">channel 1</span></div>
<div class="glass">
<svg class="cursor pcc" id="cursorPC" viewBox="0 0 20 28" aria-hidden="true"><path d="M2 2 L2 23 L7.5 17.5 L11 26 L14.5 24.5 L11 16 L18 16 Z"/></svg>
<div class="clip" id="clipPC"><span class="cliplbl">Clipboard</span><span class="cliptxt" id="clipPCtxt">(empty)</span></div>
</div>
</div>
<div class="screen mac" id="scrMac">
<div class="bar"><span class="dot"></span><span class="dot"></span><span class="dot"></span><b>Mac</b><span class="ch">channel 2</span></div>
<div class="glass" id="macGlass">
<div class="edge" id="edge" aria-hidden="true"></div>
<svg class="cursor" id="cursor" viewBox="0 0 20 28" aria-hidden="true"><path d="M2 2 L2 23 L7.5 17.5 L11 26 L14.5 24.5 L11 16 L18 16 Z"/></svg>
<div class="clip" id="clipMac"><span class="cliplbl">Clipboard</span><span class="cliptxt" id="clipMactxt">(empty)</span></div>
</div>
</div>
<div class="packet" id="packet" aria-hidden="true"></div>
<div class="devs">
<div class="dev kb" id="devKb" data-host="mac">
<svg viewBox="0 0 120 44" aria-hidden="true"><rect x="2" y="6" width="116" height="34" rx="9"/><g class="keys"><rect x="12" y="13" width="10" height="7" rx="2"/><rect x="25" y="13" width="10" height="7" rx="2"/><rect x="38" y="13" width="10" height="7" rx="2"/><rect x="72" y="13" width="10" height="7" rx="2"/><rect x="85" y="13" width="10" height="7" rx="2"/><rect x="98" y="13" width="10" height="7" rx="2"/><rect x="18" y="24" width="30" height="8" rx="2"/><rect x="72" y="24" width="30" height="8" rx="2"/></g></svg>
<span class="devname">Keyboard</span><span class="devhost" id="kbHost">on the Mac</span>
</div>
<div class="dev ms" id="devMs" data-host="mac">
<svg viewBox="0 0 40 52" aria-hidden="true"><path d="M20 3 C32 3 37 14 37 27 C37 42 30 49 20 49 C10 49 3 42 3 27 C3 14 8 3 20 3 Z"/><line x1="20" y1="4" x2="20" y2="20"/></svg>
<span class="devname">Mouse</span><span class="devhost" id="msHost">on the Mac</span>
</div>
</div>
</div>
<div class="controls" id="controls">
<div class="row" id="rowSwitch">
<span class="rowlbl">Switch</span>
<button type="button" class="btn act" id="bEdge">Push the cursor against the left edge</button>
<button type="button" class="btn act" id="bKey">Press Easy-Switch 1 on the keyboard</button>
<button type="button" class="btn act" id="bMouse">Press button 1 on the mouse</button>
<button type="button" class="btn" id="bBack">Bring both back to the Mac</button>
</div>
<div class="row" id="rowClip">
<span class="rowlbl">Clipboard</span>
<button type="button" class="btn act" id="bCopyMac">Copy text on the Mac</button>
<button type="button" class="btn act" id="bCopyPC">Copy text on the PC</button>
<label class="tog"><input type="checkbox" id="cSync" checked> Sharing on</label>
<label class="tog"><input type="checkbox" id="cMatch" checked> Pairing codes match</label>
</div>
</div>
<div class="panes">
<div class="pane" id="paneWire">
<h2>What goes over the wire</h2>
<div class="bytes" id="bytes" aria-live="polite"><p class="hint">Press any button above to see the exact message PairSwitch sends.</p></div>
</div>
<div class="pane" id="paneLog">
<h2>watch.log <span class="mute">(the tool's own log, simulated)</span></h2>
<ol class="log" id="log" aria-live="polite"></ol>
</div>
</div>
</section>
<section class="how" id="how">
<h2>How it works</h2>
<div class="cards">
<article class="card">
<h3>1. The screen edge</h3>
<p>A small menu-bar app (Mac) or tray app (Windows) watches the cursor 50 times a second. Hold it against the edge that faces the other computer for 50 ms, away from the corners, and it switches. It only re-arms after the cursor has left the edge, so arriving back never bounces you straight away again.</p>
</article>
<article class="card">
<h3>2. Logitech's own command</h3>
<p>It talks to the devices over the Bluetooth or receiver link they already use, with Logitech's HID++ 2.0 <i>Change Host</i> command (feature 0x1814): mouse first, then keyboard. It then checks that each device really left and re-sends up to three times if one did not.</p>
</article>
<article class="card">
<h3>3. The other one follows</h3>
<p>Press Easy-Switch on the keyboard or a channel button on the mouse, and the device disappears from this computer. PairSwitch notices and sends the other one after it. If the computer was idle for over a minute, it assumes the device just went to sleep and does nothing.</p>
</article>
<article class="card">
<h3>4. Clipboard, optional and off by default</h3>
<p>The Mac listens on TCP port 51888 and the PC dials out to it, so nothing ever connects in to the PC. Every message is AES-256-CBC with an HMAC-SHA256 tag and a timestamp, under keys made from a shared 16-character pairing code (PBKDF2-SHA256, 200,000 rounds). Text only, up to 1 MB. No internet, no account, no third party.</p>
</article>
</div>
</section>
<section class="get" id="get">
<h2>Get it</h2>
<p><a class="btn pri" id="dl" href="./LogiSwitch-1.4.1-source.zip" download>Download PairSwitch 1.4.1 (source, 60 KB)</a></p>
<p class="hint">PairSwitch was called LogiSwitch until November 2026. The download, its folder and the installed app still use the old file name, so copies already installed keep updating.</p>
<div class="cols">
<div>
<h3>Before you start</h3>
<ul>
<li>A Logitech keyboard and mouse with Easy-Switch (tested with an ERGO K860 and an MX Vertical).</li>
<li>Pair each device with both computers, each computer on its own channel. Default: PC on 1, Mac on 2.</li>
<li>No admin rights needed on either computer.</li>
</ul>
</div>
<div>
<h3>Windows</h3>
<ol>
<li>Unzip, open the LogiSwitch folder and double-click <b>Install.cmd</b>.</li>
<li>An arrows icon appears beside the clock. Set where the Mac is and its channel there.</li>
</ol>
</div>
<div>
<h3>Mac</h3>
<ol>
<li>Unzip into Downloads and run <code>bash ~/Downloads/LogiSwitch/install.sh</code> in Terminal. It builds the app with Apple's free Command Line Tools.</li>
<li>Allow LogiSwitch under Privacy & Security › Input Monitoring, then Quit it from the menu bar and run the installer again.</li>
</ol>
</div>
</div>
<h3>Good to know</h3>
<ul class="notes">
<li>The Mac app is not signed with a developer certificate, so macOS ties the Input Monitoring permission to each build. After an update that rebuilds it, remove LogiSwitch from that list and allow it again.</li>
<li>Clipboard sharing sends anything you copy to the other computer. On a work computer, check your employer's rules first.</li>
<li>If the clipboard stops after a router restart, the Mac probably has a new address: the Mac's menu shows it under Clipboard sync.</li>
<li>Something wrong? The menu's <i>Create support report for Claude</i> saves a text file with the logs and the full source; paste it into any Claude chat.</li>
</ul>
</section>
<footer class="foot">PairSwitch 1.4.1 · November 2026 · made with Claude · Logitech is a trademark of Logitech International S.A.; this project is not affiliated with Logitech.</footer>
</div>
<div class="tour" id="tour" role="dialog" aria-modal="false" aria-labelledby="tourTitle" hidden>
<p class="tstep" id="tourStep"></p>
<h2 id="tourTitle"></h2>
<p id="tourText"></p>
<div class="tbtns">
<button type="button" class="btn" id="tourPrev">Back</button>
<button type="button" class="btn pri" id="tourNext">Next</button>
<button type="button" class="btn" id="tourClose">Close</button>
</div>
</div>
<script src="./ls.js"></script>
</body>
</html>
ls.js (the simulation and the tour)300 lines
/* PairSwitch (formerly LogiSwitch) explainer: a simulated Mac + PC sharing one keyboard and mouse.
Nothing here talks to real devices or the network; it mirrors what the real tool does and logs. */
(function () {
'use strict';
var $ = function (id) { return document.getElementById(id); };
var reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
var T = function (ms) { return reduce ? Math.min(ms, 60) : ms; };
var sleep = function (ms) { return new Promise(function (r) { setTimeout(r, T(ms)); }); };
var st = { kb: 'mac', ms: 'mac', busy: false, pending: null, rejected: 0, connected: true, clipMac: '', clipPC: '' };
var phrases = ['Meeting moved to 3:30', 'https://example.com/report', 'Invoice 2026-114: $1,240.00', 'Grocery list: eggs, lemons, rice', 'café ☕ – naïve résumé', 'git commit -m "fix edge"'];
var phraseAt = 0;
var actBtns = ['bEdge', 'bKey', 'bMouse', 'bCopyMac', 'bCopyPC'].map($);
/* ---------- log ---------- */
function stamp() {
var d = new Date(), p = function (n) { return (n < 10 ? '0' : '') + n; };
return p(d.getHours()) + ':' + p(d.getMinutes()) + ':' + p(d.getSeconds());
}
function log(msg, cls) {
var li = document.createElement('li');
if (cls) li.className = cls;
var t = document.createElement('span'); t.className = 't'; t.textContent = stamp();
li.appendChild(t); li.appendChild(document.createTextNode(msg));
var ol = $('log'); ol.appendChild(li);
while (ol.children.length > 60) ol.removeChild(ol.firstChild);
ol.scrollTop = ol.scrollHeight;
}
/* ---------- wire pane ---------- */
function hex(n) { return (n < 16 ? '0' : '') + n.toString(16).toUpperCase(); }
function rnd(n) { var a = []; for (var i = 0; i < n; i++) a.push(hex(Math.floor(Math.random() * 256))); return a.join(' '); }
function box(v, lbl, key) {
var b = document.createElement('span'); b.className = 'b' + (key ? ' k' : '');
b.appendChild(document.createTextNode(v));
var i = document.createElement('i'); i.textContent = lbl; b.appendChild(i);
return b;
}
function wireHid(dev) {
var w = $('bytes'); w.textContent = '';
var cap = document.createElement('p'); cap.className = 'cap';
cap.textContent = 'HID++ 2.0 "Change Host" to the ' + dev + ' (20 bytes, over Bluetooth):';
var g = document.createElement('div'); g.className = 'grid';
g.appendChild(box('11', 'long report'));
g.appendChild(box('FF', 'Bluetooth'));
g.appendChild(box('0A', 'feature index', true));
g.appendChild(box('1B', 'set host', true));
g.appendChild(box('00', 'channel 1', true));
g.appendChild(box('00 ×15', 'padding'));
var n = document.createElement('p'); n.className = 'wire';
n.textContent = 'The feature index is looked up once per device (where it keeps feature 0x1814); 0A is an example. The host byte counts from 0, so 00 means channel 1.';
w.appendChild(cap); w.appendChild(g); w.appendChild(n);
}
function wireClip(text, from) {
var bytes = new TextEncoder().encode(text).length;
var plain = 1 + 8 + 2 + 4 + bytes; // type, timestamp, format count + format, length, text
var ct = (Math.floor(plain / 16) + 1) * 16; // AES-CBC with PKCS#7 padding
var body = 16 + ct + 32;
var w = $('bytes'); w.textContent = '';
var cap = document.createElement('p'); cap.className = 'cap';
cap.textContent = 'One encrypted message, ' + from + ' (' + (4 + body) + ' bytes for ' + bytes + ' bytes of text):';
var g = document.createElement('div'); g.className = 'grid';
g.appendChild(box(hex(body >> 24 & 255) + ' ' + hex(body >> 16 & 255) + ' ' + hex(body >> 8 & 255) + ' ' + hex(body & 255), 'length'));
g.appendChild(box(rnd(3) + ' …', 'IV, 16 random bytes'));
g.appendChild(box(rnd(3) + ' …', 'AES-256 ciphertext, ' + ct, true));
g.appendChild(box(rnd(3) + ' …', 'HMAC-SHA256 tag, 32', true));
var n = document.createElement('p'); n.className = 'wire';
n.textContent = 'Inside the ciphertext: type 0x10, the time in ms (anything over 2 minutes old is refused), then the text as UTF-8. A wrong pairing code fails the tag check, so the message is dropped unread. (Illustration: the bytes shown are random.)';
w.appendChild(cap); w.appendChild(g); w.appendChild(n);
}
/* ---------- drawing ---------- */
function setHost(which, host) {
st[which] = host;
var el = which === 'kb' ? $('devKb') : $('devMs');
el.setAttribute('data-host', host);
$(which === 'kb' ? 'kbHost' : 'msHost').textContent = host === 'pc' ? 'on the PC' : 'on the Mac';
if (which === 'ms') {
$('cursor').classList.toggle('off', host === 'pc');
$('cursorPC').classList.toggle('on', host === 'pc');
}
}
function flashDev(which) {
var el = which === 'kb' ? $('devKb') : $('devMs');
el.classList.add('moving');
setTimeout(function () { el.classList.remove('moving'); }, T(900));
}
async function flyPacket(label, to, hid) {
var p = $('packet');
p.classList.remove('at-pc', 'at-mac', 'show', 'hid');
if (hid) p.classList.add('hid');
p.classList.add(to === 'pc' ? 'at-mac' : 'at-pc');
p.textContent = label;
void p.offsetWidth; // restart the transition from the sender
p.classList.add('show');
await sleep(60);
p.classList.remove('at-mac', 'at-pc');
p.classList.add(to === 'pc' ? 'at-pc' : 'at-mac');
await sleep(950);
p.classList.remove('show');
}
function setClip(side, text, cls) {
var box = $(side === 'mac' ? 'clipMac' : 'clipPC');
$(side === 'mac' ? 'clipMactxt' : 'clipPCtxt').textContent = text;
st[side === 'mac' ? 'clipMac' : 'clipPC'] = text;
if (cls) { box.classList.add(cls); setTimeout(function () { box.classList.remove(cls); }, T(900)); }
}
/* ---------- buttons ---------- */
function refresh() {
var home = st.kb === 'mac' && st.ms === 'mac';
$('bEdge').disabled = st.busy || !home;
$('bKey').disabled = st.busy || !home;
$('bMouse').disabled = st.busy || !home;
$('bBack').disabled = st.busy || home;
$('bCopyMac').disabled = st.busy;
$('bCopyPC').disabled = st.busy;
$('bEdge').title = home ? '' : 'The mouse is on the PC now: bring both back first.';
}
function run(fn) {
return async function () {
if (st.busy) return;
st.busy = true; refresh();
try { await fn(); } finally { st.busy = false; refresh(); }
};
}
async function sendBoth(reason) {
// mouse first, then keyboard, as the real tool does
var order = ['ms', 'kb'].filter(function (w) { return st[w] === 'mac'; });
for (var i = 0; i < order.length; i++) {
var w = order[i], name = w === 'kb' ? 'Keyboard' : 'Mouse';
wireHid(w === 'kb' ? 'keyboard' : 'mouse');
flashDev(w);
await flyPacket('Change Host → 1', 'pc', true);
setHost(w, 'pc');
log(name + ' left (part of our own switch)');
log(name + ' -> channel 1: sent', 'ok');
}
if (reason) log(reason);
}
var doEdge = run(async function () {
var c = $('cursor'), e = $('edge');
c.classList.add('atedge');
await sleep(600);
e.classList.add('hot');
await sleep(250);
log('cursor held against the left edge for 50 ms -> the PC is on the left, channel 1');
await sendBoth();
e.classList.remove('hot');
c.classList.remove('atedge');
});
async function follow(first) {
var other = first === 'kb' ? 'ms' : 'kb';
var n1 = first === 'kb' ? 'Keyboard' : 'Mouse', n2 = other === 'kb' ? 'Keyboard' : 'Mouse';
var w = $('bytes'); w.textContent = '';
var p = document.createElement('p'); p.className = 'cap';
p.textContent = 'You pressed the ' + n1.toLowerCase() + "'s own button, so the device sent nothing through PairSwitch: it simply dropped off this Mac. PairSwitch saw it disappear.";
w.appendChild(p);
flashDev(first);
setHost(first, 'pc');
log(n1 + ' switched away -> the other devices follow to channel 1');
await sleep(700);
wireHid(other === 'kb' ? 'keyboard' : 'mouse');
flashDev(other);
await flyPacket('Change Host → 1', 'pc', true);
setHost(other, 'pc');
log(n2 + ' left (part of our own switch)');
log(n2 + ' -> channel 1: sent', 'ok');
}
var doKey = run(function () { return follow('kb'); });
var doMouse = run(function () { return follow('ms'); });
var doBack = run(async function () {
if (st.kb === 'mac' && st.ms === 'mac') return;
var w = $('bytes'); w.textContent = '';
var p = document.createElement('p'); p.className = 'cap';
p.textContent = 'On the PC side, the same tool does the same thing the other way: push against its right edge, or press button 2 on either device.';
w.appendChild(p);
['kb', 'ms'].forEach(function (k) { if (st[k] === 'pc') flashDev(k); });
await sleep(300);
setHost('kb', 'mac'); setHost('ms', 'mac');
await sleep(500);
log('Keyboard and mouse are back on this Mac');
});
function nextPhrase() { var t = phrases[phraseAt % phrases.length]; phraseAt++; return t; }
function linkUp() { return $('cSync').checked && $('cMatch').checked; }
var doCopyMac = run(async function () {
var t = nextPhrase();
setClip('mac', t, 'new');
if (!linkUp()) {
st.pending = t;
log('(not sent: the PC is not connected; it goes as soon as the PC connects)');
$('bytes').textContent = '';
var p = document.createElement('p'); p.className = 'cap';
p.textContent = $('cSync').checked ? 'The codes differ, so the Mac never accepted the PC and there is no connection to send on. The text waits.' : 'Sharing is off, so nothing leaves this Mac. The text waits in case you turn it on.';
$('bytes').appendChild(p);
return;
}
wireClip(t, 'Mac to PC');
await flyPacket('encrypted · ' + t.length + ' chars', 'pc');
setClip('pc', t, 'new');
st.pending = null;
log('clipboard: sent ' + t.length + ' characters to the PC', 'ok');
});
var doCopyPC = run(async function () {
var t = nextPhrase();
setClip('pc', t, 'new');
if (!$('cSync').checked) {
log('(sharing is off: the PC keeps it to itself)');
return;
}
wireClip(t, 'PC to Mac');
await flyPacket('encrypted · ' + t.length + ' chars', 'mac');
if (!$('cMatch').checked) {
st.rejected++;
$('clipMac').classList.add('bad'); setTimeout(function () { $('clipMac').classList.remove('bad'); }, T(900));
if (st.rejected === 1) log('ERROR: clipboard sync rejected a message (the two computers’ pairing codes do not match, or a clock is more than 2 minutes off); further rejections are not logged', 'err');
return;
}
setClip('mac', t, 'new');
log('clipboard: received ' + t.length + ' characters from the PC', 'ok');
});
async function relink() {
if (!linkUp()) {
if (!$('cSync').checked) log('clipboard sync: off');
else log('(the PC keeps dialling in every few seconds; the Mac refuses it)');
return;
}
if (st.rejected > 0) { log('clipboard sync: pairing codes now match (after ' + st.rejected + ' rejected attempts)', 'ok'); st.rejected = 0; }
log('clipboard sync: the PC connected');
if (st.pending) {
var t = st.pending; st.pending = null;
st.busy = true; refresh();
try {
wireClip(t, 'Mac to PC');
await flyPacket('encrypted · ' + t.length + ' chars', 'pc');
setClip('pc', t, 'new');
log('clipboard: sent ' + t.length + ' characters to the PC (copied while it was not connected)', 'ok');
} finally { st.busy = false; refresh(); }
}
}
$('bEdge').addEventListener('click', doEdge);
$('bKey').addEventListener('click', doKey);
$('bMouse').addEventListener('click', doMouse);
$('bBack').addEventListener('click', doBack);
$('bCopyMac').addEventListener('click', doCopyMac);
$('bCopyPC').addEventListener('click', doCopyPC);
$('cSync').addEventListener('change', relink);
$('cMatch').addEventListener('change', relink);
/* ---------- tour ---------- */
var steps = [
{ el: 'desk', title: 'Two computers, one set of devices', text: 'The keyboard and mouse are paired with both: the PC on channel 1, the Mac on channel 2. Right now they are on the Mac.', go: function () { return st.kb === 'pc' || st.ms === 'pc' ? doBack() : null; } },
{ el: 'rowSwitch', title: 'Push against the edge', text: 'The PC sits to the left, so holding the cursor against the Mac’s left edge for 50 ms sends both devices there. Watch them move.', go: function () { return doEdge(); } },
{ el: 'paneWire', title: 'The exact command', text: 'This is the 20-byte HID++ 2.0 message PairSwitch writes to each device: mouse first, then keyboard. It then checks that each one really left.' },
{ el: 'rowSwitch', title: 'The other one follows', text: 'Press Easy-Switch on the keyboard instead. It drops off the Mac by itself, and PairSwitch sends the mouse after it.', go: async function () { await doBack(); await doKey(); } },
{ el: 'rowClip', title: 'Copy here, paste there', text: 'With sharing on, text you copy goes to the other computer in one encrypted message, usually in well under a second. Try the two checkboxes to see what happens when it cannot connect.', go: async function () { if (!linkUp()) { $('cSync').checked = true; $('cMatch').checked = true; await relink(); } return doCopyMac(); } },
{ el: 'paneLog', title: 'Everything is written down', text: 'The real tool keeps this log on each computer. When something goes wrong, it builds a report you can paste into Claude. Scroll down to download it.' }
];
var at = -1;
function lit(id, on) { var e = $(id); if (e) e.classList.toggle('lit', on); }
function showStep(i) {
if (at >= 0) lit(steps[at].el, false);
at = Math.max(0, Math.min(steps.length - 1, i));
var s = steps[at];
$('tour').hidden = false;
$('tourStep').textContent = 'Step ' + (at + 1) + ' of ' + steps.length;
$('tourTitle').textContent = s.title;
$('tourText').textContent = s.text;
$('tourPrev').disabled = at === 0;
$('tourNext').textContent = at === steps.length - 1 ? 'Done' : 'Next';
lit(s.el, true);
var e = $(s.el);
if (e && e.scrollIntoView) e.scrollIntoView({ block: window.innerHeight < 760 ? 'start' : 'center', behavior: reduce ? 'auto' : 'smooth' });
if (s.go) {
var wait = function () { if (st.busy) { setTimeout(wait, 120); } else { s.go(); } };
setTimeout(wait, T(450));
}
}
function closeTour() { if (at >= 0) lit(steps[at].el, false); at = -1; $('tour').hidden = true; $('tourBtn').focus(); }
$('tourBtn').addEventListener('click', function () { showStep(0); $('tourNext').focus(); });
$('tourNext').addEventListener('click', function () { if (at >= steps.length - 1) closeTour(); else showStep(at + 1); });
$('tourPrev').addEventListener('click', function () { showStep(at - 1); });
$('tourClose').addEventListener('click', closeTour);
document.addEventListener('keydown', function (e) { if (e.key === 'Escape' && at >= 0) closeTour(); });
refresh();
log('started: PC on the left edge -> channel 1; devices: Keyboard, Mouse (connected now: 2)');
log('clipboard sync: the PC connected');
if (/[?&]tour=1\b/.test(location.search)) showStep(0);
})();
ls.css (look and layout)146 lines
:root {
--bg: #f4f1ea; --ink: #1d232b; --mute: #5d6672; --card: #ffffff; --line: #d9d3c6;
--acc: #1f6feb; --acc-ink: #ffffff; --pc: #2b6cb0; --mac: #4a5568; --hot: #e8590c; --ok: #2f855a; --bad: #c53030;
--glass-pc: #dbe7f6; --glass-mac: #e6e3ef; --dev: #2d3748;
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #14171c; --ink: #e8ebef; --mute: #9aa4b1; --card: #1d2229; --line: #2e3540;
--acc: #5b9bff; --acc-ink: #0b1220; --pc: #6aa7e8; --mac: #a0aec0; --hot: #ff8a3d; --ok: #68d391; --bad: #fc8181;
--glass-pc: #1c2a3b; --glass-mac: #272335; --dev: #cbd5e0;
}
}
* { box-sizing: border-box; }
html { -webkit-text-size-adjust: 100%; }
body { margin: 0; background: var(--bg); color: var(--ink); font: 16px/1.55 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
.wrap { max-width: 1080px; margin: 0 auto; padding: 18px clamp(12px, 4vw, 28px) 40px; }
h1 { font-size: clamp(2rem, 6vw, 3rem); line-height: 1.05; margin: .1em 0 .2em; letter-spacing: -.01em; }
h2 { font-size: 1.2rem; margin: 0 0 .6em; }
h3 { font-size: 1.02rem; margin: .2em 0 .4em; }
p, li { overflow-wrap: anywhere; }
code { font-family: var(--mono); font-size: .88em; background: var(--card); border: 1px solid var(--line); border-radius: 4px; padding: 0 .3em; }
.mute { color: var(--mute); font-weight: 400; font-size: .85em; }
.kick { color: var(--mute); margin: 0; font-size: .9rem; }
.lede { max-width: 62ch; margin: 0; }
.mast { display: flex; flex-wrap: wrap; gap: 14px 24px; align-items: flex-end; justify-content: space-between; margin-bottom: 18px; }
.mastbtns { display: flex; gap: 8px; flex-wrap: wrap; }
.btn { font: inherit; font-size: .92rem; line-height: 1.25; display: inline-block; text-decoration: none; color: var(--ink); background: var(--card); border: 1px solid var(--line); border-radius: 9px; padding: .55em .9em; cursor: pointer; }
.btn:hover { border-color: var(--acc); }
.btn:focus-visible, .tog input:focus-visible { outline: 3px solid var(--acc); outline-offset: 2px; }
.btn.pri { background: var(--acc); color: var(--acc-ink); border-color: var(--acc); font-weight: 600; }
.btn:disabled { opacity: .45; cursor: default; border-color: var(--line); }
/* ---------- demo ---------- */
.demo { background: var(--card); border: 1px solid var(--line); border-radius: 14px; padding: clamp(10px, 2.5vw, 20px); }
.desk { position: relative; display: grid; grid-template-columns: 1fr 1fr; gap: clamp(8px, 3vw, 28px); padding-bottom: clamp(70px, 14vw, 96px); }
.screen { border: 2px solid var(--line); border-radius: 10px; overflow: hidden; background: var(--bg); min-width: 0; }
.screen .bar { display: flex; align-items: center; gap: 5px; padding: 5px 8px; font-size: .78rem; border-bottom: 1px solid var(--line); white-space: nowrap; overflow: hidden; }
.screen .bar b { margin-left: 4px; overflow: hidden; text-overflow: ellipsis; }
.screen .ch { margin-left: auto; color: var(--mute); }
.dot { width: 8px; height: 8px; border-radius: 50%; background: var(--line); flex: none; }
.glass { position: relative; height: clamp(120px, 26vw, 230px); }
.pc .glass { background: var(--glass-pc); }
.mac .glass { background: var(--glass-mac); }
.screen.lit { border-color: var(--acc); }
.edge { position: absolute; left: 0; top: 10%; bottom: 10%; width: 5px; border-radius: 0 4px 4px 0; background: transparent; transition: background .2s, box-shadow .2s; }
.edge.hot { background: var(--hot); box-shadow: 0 0 14px var(--hot); }
.cursor { position: absolute; width: 18px; height: 25px; left: 62%; top: 42%; fill: var(--ink); stroke: var(--bg); stroke-width: 1.4; transition: left .55s ease-in, top .55s, opacity .25s; }
.cursor.atedge { left: 0; }
.cursor.off { opacity: 0; }
.cursor.pcc { left: 82%; opacity: 0; }
.cursor.pcc.on { left: 55%; opacity: 1; }
.clip { position: absolute; left: 8%; right: 8%; bottom: 8%; background: var(--card); border: 1px solid var(--line); border-radius: 7px; padding: 4px 8px; font-size: .78rem; display: flex; flex-direction: column; min-height: 2.8em; transition: border-color .3s, box-shadow .3s; }
.cliplbl { color: var(--mute); font-size: .7rem; }
.cliptxt { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.clip.new { border-color: var(--ok); box-shadow: 0 0 0 2px var(--ok); }
.clip.bad { border-color: var(--bad); box-shadow: 0 0 0 2px var(--bad); }
.packet { position: absolute; top: 34%; left: 75%; transform: translateX(-50%); background: var(--ink); color: var(--bg); font: 600 .72rem/1.2 var(--mono); padding: 5px 8px; border-radius: 6px; opacity: 0; pointer-events: none; white-space: nowrap; transition: left .9s cubic-bezier(.5,0,.3,1), opacity .2s; z-index: 2; }
.packet.show { opacity: 1; }
.packet.at-pc { left: 25%; }
.packet.at-mac { left: 75%; }
.packet.hid { top: auto; bottom: clamp(56px, 11vw, 78px); }
.devs { position: absolute; left: 0; right: 0; bottom: 0; height: clamp(60px, 12vw, 84px); }
.dev { position: absolute; bottom: 0; display: flex; flex-direction: column; align-items: center; transition: left .7s cubic-bezier(.5,0,.3,1); text-align: center; }
.dev svg { fill: none; stroke: var(--dev); stroke-width: 2.2; }
.dev .keys rect { stroke-width: 1.4; }
.kb svg { width: clamp(70px, 14vw, 120px); height: auto; }
.ms svg { width: clamp(22px, 4.2vw, 36px); height: auto; }
.devname { font-size: .72rem; font-weight: 600; }
.devhost { font-size: .68rem; color: var(--mute); white-space: nowrap; }
.kb[data-host="mac"] { left: calc(75% - clamp(60px, 11vw, 100px)); }
.ms[data-host="mac"] { left: calc(75% + clamp(16px, 4vw, 40px)); }
.kb[data-host="pc"] { left: calc(25% - clamp(60px, 11vw, 100px)); }
.ms[data-host="pc"] { left: calc(25% + clamp(16px, 4vw, 40px)); }
.dev.moving svg { stroke: var(--hot); }
.dev[data-host="pc"] .devhost { color: var(--pc); }
.controls { margin-top: 14px; display: grid; gap: 8px; }
.row { display: flex; flex-wrap: wrap; gap: 6px 8px; align-items: center; }
.rowlbl { font-size: .78rem; font-weight: 700; color: var(--mute); min-width: 5.5em; }
.tog { font-size: .85rem; display: inline-flex; align-items: center; gap: 5px; padding: .3em .2em; cursor: pointer; }
.tog input { width: 1.05em; height: 1.05em; accent-color: var(--acc); }
.row.lit, .pane.lit, .card.lit { outline: 3px solid var(--acc); outline-offset: 4px; border-radius: 8px; }
.panes { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; margin-top: 16px; }
.pane { min-width: 0; border-top: 1px solid var(--line); padding-top: 10px; }
.pane h2 { font-size: .95rem; }
.bytes { font: .8rem/1.5 var(--mono); }
.bytes .hint { font: .85rem/1.5 system-ui, sans-serif; color: var(--mute); margin: 0; }
.bytes .cap { font: 600 .82rem/1.4 system-ui, sans-serif; margin: 0 0 6px; }
.bytes .grid { display: flex; flex-wrap: wrap; gap: 4px; margin-bottom: 6px; }
.bytes .b { display: inline-flex; flex-direction: column; align-items: center; border: 1px solid var(--line); border-radius: 5px; padding: 2px 5px; min-width: 2.4em; }
.bytes .b i { font-style: normal; font-size: .62rem; color: var(--mute); font-family: system-ui, sans-serif; white-space: nowrap; }
.bytes .b.k { border-color: var(--hot); }
.bytes .wire { font: .8rem/1.5 system-ui, sans-serif; color: var(--mute); margin: 0; }
.log { list-style: none; margin: 0; padding: 0; font: .76rem/1.45 var(--mono); max-height: 15em; overflow-y: auto; overflow-x: hidden; }
.log li { padding: 1px 0; overflow-wrap: anywhere; }
.log li.err { color: var(--bad); }
.log li.ok { color: var(--ok); }
.log .t { color: var(--mute); margin-right: .5em; }
/* ---------- text sections ---------- */
section.how, section.get { margin-top: 34px; }
.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); gap: 12px; }
.card { background: var(--card); border: 1px solid var(--line); border-radius: 12px; padding: 14px 16px; }
.card p { margin: 0; font-size: .93rem; }
.cols { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 6px 22px; }
.cols ul, .cols ol, .notes { padding-left: 1.2em; margin: .2em 0 .8em; }
.cols li, .notes li { margin-bottom: .35em; font-size: .94rem; }
.foot { margin-top: 36px; padding-top: 12px; border-top: 1px solid var(--line); color: var(--mute); font-size: .82rem; }
/* ---------- tour ---------- */
.tour { position: fixed; left: 50%; bottom: 14px; transform: translateX(-50%); width: min(440px, calc(100vw - 20px)); background: var(--card); border: 2px solid var(--acc); border-radius: 12px; padding: 12px 16px; box-shadow: 0 10px 34px rgba(0,0,0,.28); z-index: 10; }
.tour[hidden] { display: none; }
.tour h2 { font-size: 1.05rem; margin: 0 0 .3em; }
.tour p { margin: 0 0 .6em; font-size: .92rem; }
.tstep { color: var(--mute); font-size: .78rem !important; margin: 0 !important; }
.tbtns { display: flex; gap: 6px; flex-wrap: wrap; }
.tbtns #tourClose { margin-left: auto; }
@media (max-width: 640px) {
.panes { grid-template-columns: 1fr; }
.screen .bar { gap: 4px; padding: 5px 6px; font-size: .72rem; }
.screen .bar .dot { display: none; }
.screen .bar b { margin-left: 0; }
.rowlbl { min-width: 100%; }
.row .btn { flex: 1 1 calc(50% - 8px); }
.tour { bottom: 8px; }
}
@media (max-width: 400px) {
.wide { display: none; }
}
@media (max-height: 420px) {
.glass { height: 110px; }
.tour { padding: 8px 12px; }
.tour p { margin-bottom: .3em; }
}
@media (prefers-reduced-motion: reduce) {
.cursor, .dev, .packet, .edge, .clip { transition-duration: .01s !important; }
}
Need a tool like this, built for your own work?
Take this one free. If you need your own version, with your lists, your rules and your name on it, I build it and hand it over. Fixed price agreed up front, and the first call is free.