<# 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()