-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMWBToggleApp.cs
More file actions
2334 lines (2079 loc) · 101 KB
/
MWBToggleApp.cs
File metadata and controls
2334 lines (2079 loc) · 101 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Microsoft.Win32;
namespace MWBToggle;
/// <summary>
/// Main application context — lives in the system tray, no visible window.
/// Port of MWBToggle.ahk with all features intact.
/// </summary>
internal sealed class MWBToggleApp : ApplicationContext
{
internal static readonly string Version = typeof(MWBToggleApp).Assembly.GetName().Version?.ToString(3) ?? "0.0.0";
// UTF-8 without BOM — matches AHK's "UTF-8-RAW"
private static readonly Encoding Utf8NoBom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
// P/Invoke for kernel32 Beep (Console.Beep may not work in WinExe)
[DllImport("kernel32.dll")]
private static extern bool Beep(uint dwFreq, uint dwDuration);
// P/Invoke for TaskbarCreated message (Explorer restart recovery)
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern uint RegisterWindowMessage(string lpString);
// P/Invoke for opening MWB settings (simulate tray icon click)
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
[DllImport("user32.dll")]
private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
[DllImport("user32.dll")]
private static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
// Win state isn't exposed in Keys.Modifiers (only Ctrl/Alt/Shift). Read directly.
[DllImport("user32.dll")]
private static extern short GetKeyState(int nVirtKey);
private const int VK_LWIN = 0x5B;
private const int VK_RWIN = 0x5C;
// ── Configuration (defaults, overridden by MWBToggle.ini) ──────────────
private string _hotkey = "#^+f"; // Win+Ctrl+Shift+F (fresh-install default)
private string _fileTransferHotkey = ""; // empty = unbound
private readonly string _settingsPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
@"Microsoft\PowerToys\MouseWithoutBorders\settings.json");
private readonly string _powerToysExe = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
@"PowerToys\PowerToys.exe");
private bool _confirmToggle;
private bool _soundFeedback;
private bool _middleClickOpensMwbSettings = true;
private bool _singleClickToggles = true;
private bool _disposed;
private bool _toggleInProgress;
// Window during which FileSystemWatcher events on settings.json are ours and should be ignored.
private DateTime _suppressWatcherUntilUtc;
// Absolute UTC time when a pause should auto-resume. null = no active timed pause
// (either no pause at all, or an unlimited "until resumed" pause).
// Using absolute time (instead of relying on WinForms Timer.Interval) makes pause
// survive OS sleep: PowerModeChanged.Resume recomputes the remaining interval.
private DateTime? _pauseResumeAtUtc;
// Snapshot of ShareClipboard / TransferFile captured at the moment pause began.
// Resume restores these exact values instead of forcing both ON — so a user who
// was running {clipboard:on, file:off} gets that state back, not {on, on}.
// Non-null snapshot ⇔ pause is active (timed or unlimited).
private bool? _pauseSnapshotClipboard;
private bool? _pauseSnapshotFile;
// ── UI ──────────────────────────────────────────────────────────────────
private readonly NotifyIcon _trayIcon;
private readonly ContextMenuStrip _menu;
private readonly ToolStripMenuItem _startupItem;
private readonly ToolStripMenuItem _pause5;
private readonly ToolStripMenuItem _pause30;
private readonly ToolStripMenuItem _pauseUnlimited;
private readonly ToolStripMenuItem _middleClickItem;
private readonly ToolStripMenuItem _clipboardItem;
private readonly ToolStripMenuItem _transferFileItem;
private readonly ToolStripMenuItem _singleClickItem;
// Both hotkeys are nullable — null means "unbound". Primary can be unbound since
// the app remains operable via the tray icon and menu items.
private GlobalHotkey? _globalHotkey;
private GlobalHotkey? _fileTransferGlobalHotkey;
// Hotkey submenu uses two rows per binding: a clickable title + a disabled
// greyed subtitle showing the current key combo. We hold the subtitles so
// RefreshHotkeyLabels can update them from anywhere the hotkey changes.
private ToolStripMenuItem? _primaryHotkeySubtitle;
private ToolStripMenuItem? _fileTransferHotkeySubtitle;
private readonly System.Windows.Forms.Timer _pauseTimer;
private readonly MessageWindow _messageWindow;
private FileSystemWatcher? _fileWatcher;
private System.Windows.Forms.Timer? _debounceTimer;
private AboutForm? _aboutForm;
// ── Embedded icons ─────────────────────────────────────────────────────
private readonly Icon _iconOn;
private readonly Icon _iconOff;
// ── Paths ────────────────────────────────────────────────────────────
private readonly string _exeDir = Path.GetDirectoryName(
Environment.ProcessPath ?? Application.ExecutablePath) ?? AppContext.BaseDirectory;
private readonly string _startupShortcut = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Startup),
"MWBToggle.lnk");
private string _configDir = null!; // Resolved in LoadConfig()
// ── OSD tooltip (discreet, pinned above the system tray) ──────────────
private readonly OsdForm _osd = new();
// ── SyncTray state cache (avoid allocations every 5s) ────────────────
private bool _lastSyncState;
private bool _lastTransferFileState;
private bool _lastSyncInitialized;
private string? _lastTooltip;
public MWBToggleApp()
{
// Icon loading priority: user's icons on disk > embedded in .exe > system fallback
// Users can drop on.ico / off.ico next to the .exe to override the built-in icons.
_iconOn = LoadIconFromDisk(Path.Combine(_exeDir, "on.ico"))
?? LoadEmbeddedIcon("MWBToggle.on.ico")
?? (Icon)SystemIcons.Application.Clone();
_iconOff = LoadIconFromDisk(Path.Combine(_exeDir, "off.ico"))
?? LoadEmbeddedIcon("MWBToggle.off.ico")
?? (Icon)SystemIcons.Shield.Clone();
// Load INI config (may override _hotkey, _confirmToggle, _soundFeedback)
LoadConfig();
// ── Build context menu ─────────────────────────────────────────────
_menu = new ContextMenuStrip();
// Title bar — click opens About
var titleItem = new ToolStripMenuItem($"MWBToggle v{Version}", null, (_, _) => ShowAbout());
titleItem.Font = new Font(titleItem.Font, FontStyle.Bold);
titleItem.ToolTipText = "About MWBToggle";
_menu.Items.Add(titleItem);
_menu.Items.Add(new ToolStripSeparator());
// Hotkey display — two rows per binding: clickable centered title above a
// disabled greyed subtitle showing the actual combo. Keeps the submenu narrow
// (width = max of title/subtitle) instead of title + ": " + subtitle on one line.
var hotkeysMenu = new ToolStripMenuItem("Hotkeys");
if (hotkeysMenu.DropDown is ToolStripDropDownMenu hd)
{
hd.ShowImageMargin = false;
// Keep the check margin visible even though no Hotkey item ever has a
// checkmark — this preserves the left-side padding rhythm that the
// rest of the context menu uses (Pause submenu, tray menu root etc.).
hd.ShowCheckMargin = true;
}
var primaryTitle = new ToolStripMenuItem("Clipboard + File Transfer")
{
TextAlign = ContentAlignment.MiddleCenter,
};
primaryTitle.Click += (_, _) => ChangeHotkey();
_primaryHotkeySubtitle = new ToolStripMenuItem
{
Enabled = false,
TextAlign = ContentAlignment.MiddleCenter,
};
hotkeysMenu.DropDownItems.Add(primaryTitle);
hotkeysMenu.DropDownItems.Add(_primaryHotkeySubtitle);
hotkeysMenu.DropDownItems.Add(new ToolStripSeparator());
var fileTransferTitle = new ToolStripMenuItem("File Transfer")
{
TextAlign = ContentAlignment.MiddleCenter,
};
fileTransferTitle.Click += (_, _) => ChangeFileTransferHotkey();
_fileTransferHotkeySubtitle = new ToolStripMenuItem
{
Enabled = false,
TextAlign = ContentAlignment.MiddleCenter,
};
hotkeysMenu.DropDownItems.Add(fileTransferTitle);
hotkeysMenu.DropDownItems.Add(_fileTransferHotkeySubtitle);
RefreshHotkeyLabels();
_menu.Items.Add(hotkeysMenu);
_menu.Items.Add(new ToolStripSeparator());
// Toggle action
_menu.Items.Add(new ToolStripMenuItem("Toggle Sharing", null, (_, _) => DoToggle()));
// Pause sharing submenu. Click-while-checked resumes; click-while-unchecked starts
// a pause of that duration. Matches the checkmark-as-toggle mental model users have
// when they see a checkmark next to a menu item.
_pause5 = new ToolStripMenuItem("5 minutes", null, (s, _) => TogglePause(s, 5));
_pause30 = new ToolStripMenuItem("30 minutes", null, (s, _) => TogglePause(s, 30));
_pauseUnlimited = new ToolStripMenuItem("Until resumed", null, (s, _) => TogglePause(s, 0));
var pauseItem = new ToolStripMenuItem("Pause Sharing");
pauseItem.DropDownItems.AddRange(new ToolStripItem[] { _pause5, _pause30, _pauseUnlimited });
_menu.Items.Add(pauseItem);
_menu.Items.Add(new ToolStripSeparator());
// PowerToys submenu — slim: kill the wide image margin, keep the check column
var powerToysMenu = new ToolStripMenuItem("PowerToys");
if (powerToysMenu.DropDown is ToolStripDropDownMenu pd)
{
pd.ShowImageMargin = false;
pd.ShowCheckMargin = true;
}
powerToysMenu.DropDownItems.Add(new ToolStripMenuItem("Open PowerToys", null, (_, _) => OpenPowerToys()));
powerToysMenu.DropDownItems.Add(new ToolStripMenuItem("MWB Settings", null, (_, _) => OpenMwbSettings()));
powerToysMenu.DropDownItems.Add(new ToolStripSeparator());
_startupItem = new ToolStripMenuItem("Run at Startup", null, (_, _) => ToggleStartup());
_startupItem.Checked = File.Exists(_startupShortcut);
powerToysMenu.DropDownItems.Add(_startupItem);
powerToysMenu.DropDownItems.Add(new ToolStripSeparator());
_singleClickItem = new ToolStripMenuItem("Single-click toggles sharing", null, (_, _) => ToggleSingleClick());
_singleClickItem.Checked = _singleClickToggles;
powerToysMenu.DropDownItems.Add(_singleClickItem);
_middleClickItem = new ToolStripMenuItem("Middle-click opens MWB Settings", null, (_, _) => ToggleMiddleClick());
_middleClickItem.Checked = _middleClickOpensMwbSettings;
powerToysMenu.DropDownItems.Add(_middleClickItem);
powerToysMenu.DropDownItems.Add(new ToolStripSeparator());
_clipboardItem = new ToolStripMenuItem("Clipboard Sharing", null, (_, _) => ToggleShareClipboard());
_clipboardItem.Checked = true; // SyncTray will set the real state
powerToysMenu.DropDownItems.Add(_clipboardItem);
_transferFileItem = new ToolStripMenuItem("File Transfer", null, (_, _) => ToggleTransferFile());
_transferFileItem.Checked = true; // SyncTray will set the real state
powerToysMenu.DropDownItems.Add(_transferFileItem);
_menu.Items.Add(powerToysMenu);
_menu.Items.Add(new ToolStripSeparator());
_menu.Items.Add(new ToolStripMenuItem("Exit", null, (_, _) => ExitApplication()));
// Snapshot existing NotifyIconSettings subkeys BEFORE our NIM_ADD so
// TrayIconPromoter can identify the one Explorer creates for us even
// when it ships without ExecutablePath populated.
var trayBaseline = TrayIconPromoter.CaptureBaseline();
// ── Tray icon ──────────────────────────────────────────────────────
// Seed a non-empty tooltip BEFORE Visible=true so Shell_NotifyIcon
// passes NIF_TIP on NIM_ADD. Without it Explorer's per-icon schema
// in the registry comes out sparse (IconSnapshot only — no
// ExecutablePath / InitialTooltip), which breaks both Settings-UI
// listing and our promotion logic. SyncTray overwrites it with the
// real state-driven tooltip shortly after startup.
_trayIcon = new NotifyIcon
{
ContextMenuStrip = _menu,
Text = "MWB Toggle",
Visible = true
};
_trayIcon.MouseClick += (_, e) =>
{
if (e.Button == MouseButtons.Left && _singleClickToggles)
DoToggle();
else if (e.Button == MouseButtons.Middle && _middleClickOpensMwbSettings)
OpenMwbSettings();
};
// Ensure our tray icon is visible in the taskbar rather than buried in
// Win11's overflow flyout. Explorer writes the per-icon registry key
// asynchronously after NIM_ADD, so we poll up to 10 s. See
// TrayIconPromoter for the two-phase identification rules.
StartTrayIconPromotion(trayBaseline);
// ── Global hotkey (may update _hotkey on fallback). Empty = user unbound it
// and we shouldn't silently rebind to the default on next launch.
if (!string.IsNullOrEmpty(_hotkey))
_globalHotkey = new GlobalHotkey(ref _hotkey, DoToggle, msg => ShowOSD(msg, 5000));
// File Transfer hotkey is optional — only register if the user configured one.
// allowFallback:false means a failed registration leaves IsRegistered=false rather
// than silently re-using the primary's ^!c combo.
if (!string.IsNullOrEmpty(_fileTransferHotkey))
{
_fileTransferGlobalHotkey = new GlobalHotkey(
ref _fileTransferHotkey, ToggleTransferFile,
msg => ShowOSD(msg, 5000),
allowFallback: false);
if (!_fileTransferGlobalHotkey.IsRegistered)
{
_fileTransferGlobalHotkey.Dispose();
_fileTransferGlobalHotkey = null;
_fileTransferHotkey = "";
}
}
// ── Message window for TaskbarCreated (Explorer restart recovery) ──
// Re-capture a fresh baseline before the re-add so the promoter can
// recover visibility if the subkey was externally cleaned up while
// we were running (e.g. Settings UI "Remove" on the entry).
_messageWindow = new MessageWindow(RegisterWindowMessage("TaskbarCreated"), () =>
{
var recoveryBaseline = TrayIconPromoter.CaptureBaseline();
_trayIcon.Visible = true;
SyncTray();
StartTrayIconPromotion(recoveryBaseline);
});
// ── File watcher — replaces 5s polling timer ──────────────────────
// Only reads settings.json when it actually changes on disk,
// instead of polling every 5s (~12,000 reads/day of wasted I/O).
StartFileWatcher();
// ── Pause resume timer (one-shot) ──────────────────────────────────
_pauseTimer = new System.Windows.Forms.Timer();
_pauseTimer.Tick += (_, _) =>
{
// Tick may fire earlier than expected if we recomputed the interval after
// wake — check absolute time and only fire if we've truly reached the deadline.
if (_pauseResumeAtUtc is DateTime due && DateTime.UtcNow >= due)
{
ResumeSharing();
}
else if (_pauseResumeAtUtc is DateTime pending)
{
_pauseTimer.Stop();
_pauseTimer.Interval = Math.Max(1000, (int)(pending - DateTime.UtcNow).TotalMilliseconds);
_pauseTimer.Start();
}
};
// Re-check pause deadline on wake-from-sleep. WinForms Timer.Interval is
// wall-clock-blind — without this, a 30 min pause through a 2 hr sleep would
// resume 30 min after wake instead of the moment we woke up.
SystemEvents.PowerModeChanged += OnPowerModeChanged;
// Validate startup shortcut target (self-healing after winget upgrades)
ValidateStartupShortcut();
// Initial tray sync
SyncTray();
// Re-attach any pause that was pending when we last exited (or reboot killed us).
// Deferred to the first message-loop tick so the OSD form has a chance to paint
// (showing it mid-constructor misses the first WM_PAINT cycle and the user sees
// nothing). Must also run after _pauseTimer + PowerModeChanged + SyncTray.
var restoreTimer = new System.Windows.Forms.Timer { Interval = 1 };
restoreTimer.Tick += (s, _) =>
{
restoreTimer.Stop();
restoreTimer.Dispose();
RestorePauseDeadlineOnStartup();
};
restoreTimer.Start();
// Tell the self-updater we reached running state — safe to drop .old rollback
// on the next launch. If we crashed before this, .old persists for recovery.
UpdateDialog.WriteStartupSentinel();
Logger.Info($"MWBToggle v{Version} started.");
}
// ╔══════════════════════════════════════════════════════════════════════╗
// ║ Core ║
// ╚══════════════════════════════════════════════════════════════════════╝
private void DoToggle(bool confirm = true)
{
// Reentrancy guard — WaitWithMessagePump pumps messages, which can dispatch
// another WM_HOTKEY (or tray click) into DoToggle before the current one completes.
if (_toggleInProgress) return;
_toggleInProgress = true;
try
{
var processes = Process.GetProcessesByName("PowerToys.MouseWithoutBorders");
bool mwbRunning = processes.Length > 0;
foreach (var p in processes) p.Dispose();
if (!mwbRunning)
{
ShowOSD("Mouse Without Borders doesn't appear to be running.", 5000);
return;
}
if (!File.Exists(_settingsPath))
{
ShowOSD("Settings file not found — check PowerToys MWB is configured.", 5000);
return;
}
// Reject files over 1MB — valid MWB settings.json is <5KB
var toggleFileInfo = new FileInfo(_settingsPath);
if (toggleFileInfo.Length > 1_000_000)
{
ShowOSD("Settings file is unexpectedly large — aborting.", 5000);
return;
}
string json;
try
{
json = File.ReadAllText(_settingsPath, Utf8NoBom);
}
catch (IOException ex)
{
Logger.Warn($"DoToggle read failed: {ex.Message}");
ShowOSD("Could not read settings.json — file may be locked. Try again.", 5000);
return;
}
var match = ShareClipboardRegex.Match(json);
if (!match.Success)
{
ShowOSD("ShareClipboard not found in settings.json — run MWB at least once.", 5000);
return;
}
bool currentlyOn = match.Groups[1].Value == "true";
// If a pause is active, the primary toggle means "resume". Routing through
// ResumeSharing preserves the pre-pause snapshot — the whole point of v2.5.5.
// Without this branch, a user with {clip:on, file:off} who paused and then
// hit the hotkey would end up at {on, on}, the exact bug this release fixes.
if (IsPauseActive)
{
if (_confirmToggle && confirm)
{
if (MessageBox.Show("Resume sharing now?", "MWBToggle",
MessageBoxButtons.YesNo, MessageBoxIcon.Question)
!= DialogResult.Yes)
return;
}
ResumeSharing();
return;
}
if (_confirmToggle && confirm)
{
string prompt = "Turn clipboard/file sharing " + (currentlyOn ? "OFF" : "ON") + "?";
if (MessageBox.Show(prompt, "MWBToggle", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
!= DialogResult.Yes)
return;
}
string newVal = currentlyOn ? "false" : "true";
json = ShareClipboardReplaceRegex.Replace(json, "$1" + newVal);
json = TransferFileReplaceRegex.Replace(json, "$1" + newVal);
// Verify BOTH replacements landed — guards against future MWB schema drift.
var verifyClip = ShareClipboardRegex.Match(json);
var verifyFile = TransferFileRegex.Match(json);
if (!verifyClip.Success || verifyClip.Groups[1].Value != newVal
|| !verifyFile.Success || verifyFile.Groups[1].Value != newVal)
{
Logger.Warn("DoToggle verify failed — regex replace did not update both fields.");
ShowOSD("Failed to update settings — JSON structure may have changed.", 5000);
return;
}
if (!WriteSettingsAtomic(json))
{
Logger.Warn("DoToggle aborted — WriteSettingsAtomic returned false.");
ShowOSD("Could not write settings.json — file locked. Try again.", 5000);
return;
}
bool nowOn = !currentlyOn;
// Breadcrumb on every successful toggle — on an LTR tray app, this is the
// single most useful line in the log when a user reports "the toggle
// doesn't work." Without it the only evidence is settings.json mtime, which
// support can't ask for easily. One line per toggle, negligible volume.
Logger.Info($"Toggled {(nowOn ? "ON" : "OFF")} — ShareClipboard={nowOn} TransferFile={nowOn}, wrote {_settingsPath}");
WaitWithMessagePump(300);
SyncTray();
ShowOSDState(nowOn ? "Clipboard + File · ON" : "Clipboard + File · OFF", nowOn);
if (_soundFeedback)
Beep(currentlyOn ? 400u : 800u, 150);
}
finally
{
_toggleInProgress = false;
}
}
// Overload so GlobalHotkey can call with no args
private void DoToggle() => DoToggle(confirm: true);
/// <summary>
/// Write settings.json atomically: write to .tmp, then NTFS-atomic Replace with
/// backup rotation into .bak. This avoids truncate-then-write data loss on power
/// cuts or AV quarantines, and gives us a recoverable prior-state rollback target.
/// </summary>
private bool WriteSettingsAtomic(string json)
{
string bakPath = _settingsPath + ".bak";
// Suppress our own FileSystemWatcher event — this is a self-write, not an external one.
_suppressWatcherUntilUtc = DateTime.UtcNow.AddMilliseconds(500);
for (int i = 0; i < 3; i++)
{
// Refresh the self-write window inside the loop — a contended 3-retry path
// can exceed 500 ms, at which point our own successful write would leak
// through as an external change and trigger a redundant SyncTray.
_suppressWatcherUntilUtc = DateTime.UtcNow.AddMilliseconds(500);
try
{
// ── The core-feature fix ──────────────────────────────────────
// PowerToys' Mouse Without Borders watches settings.json with a
// FileSystemWatcher that only reacts to `Changed` events. The
// previous port used `File.Replace(tmp, target, bak)` for atomic
// safety — elegant, but the NTFS ReplaceFile call invalidates the
// file's identity and PT's watcher never saw the change. The app
// would flip its own tray icon but MWB kept sharing on the old
// in-memory state.
//
// The AHK version worked because it wrote in-place with `FileOpen("w")`
// — same identity, LastWrite bumped, Changed event fires. We match
// that here: back up the current settings first (manual rollback),
// then truncate-and-write the target directly.
//
// We lose the "atomic against power-cut mid-write" property that
// File.Replace gave us. In exchange, the toggle actually takes
// effect. For a 2.5 KB settings.json on a tray-app path, that's
// a trade worth making — and the .bak from the previous toggle
// is still recoverable manually if anything does go wrong.
if (File.Exists(_settingsPath))
{
try { File.Copy(_settingsPath, bakPath, overwrite: true); }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Backup failed — warn and proceed. The write itself is
// the value here; losing the .bak is not a correctness issue.
Logger.Warn($"WriteSettingsAtomic backup failed: {ex.Message}");
}
}
File.WriteAllText(_settingsPath, json, Utf8NoBom);
return true;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// UnauthorizedAccessException covers AV quarantine / DACL denial mid-retry,
// which otherwise escapes and crashes the toggle path.
Logger.Warn($"WriteSettingsAtomic attempt {i + 1} failed: {ex.Message}");
WaitWithMessagePump(200);
}
}
return false;
}
/// <summary>
/// Wait for the specified duration while pumping the WinForms message loop,
/// so the UI stays responsive (tray icon, hotkeys, timers all keep working).
/// Replaces Thread.Sleep which would freeze the UI.
/// </summary>
private static void WaitWithMessagePump(int milliseconds)
{
var sw = Stopwatch.StartNew();
while (sw.ElapsedMilliseconds < milliseconds)
{
Application.DoEvents();
Thread.Sleep(10); // Small yield to avoid spinning CPU
}
}
// ╔══════════════════════════════════════════════════════════════════════╗
// ║ Tray sync ║
// ╚══════════════════════════════════════════════════════════════════════╝
// Pre-compiled regexes — parsed once at startup, JIT-compiled to IL.
private static readonly Regex ShareClipboardRegex = new(
@"""ShareClipboard""\s*:\s*\{\s*""value""\s*:\s*(true|false)",
RegexOptions.Compiled);
private static readonly Regex ShareClipboardReplaceRegex = new(
@"(""ShareClipboard""\s*:\s*\{\s*""value""\s*:\s*)(true|false)",
RegexOptions.Compiled);
private static readonly Regex TransferFileRegex = new(
@"""TransferFile""\s*:\s*\{\s*""value""\s*:\s*(true|false)",
RegexOptions.Compiled);
private static readonly Regex TransferFileReplaceRegex = new(
@"(""TransferFile""\s*:\s*\{\s*""value""\s*:\s*)(true|false)",
RegexOptions.Compiled);
// Pre-built version prefix — zero allocation per sync.
private static readonly string TrayTextVersionPrefix = $"MWBToggle v{Version}";
// Compose the tray tooltip from the last-synced state + any active pause.
// Clipboard and File Transfer are independent, so the tooltip shows each channel
// explicitly — "Clipboard ON · Files OFF" — instead of a single combined ON/OFF.
// Shell clamps NotifyIcon.Text at 127 chars; all formats below fit comfortably.
private string BuildTrayTooltip()
{
if (IsPauseActive)
{
if (_pauseResumeAtUtc is DateTime due)
{
string local = due.ToLocalTime().ToString("HH:mm", CultureInfo.InvariantCulture);
return $"{TrayTextVersionPrefix} — Paused (resumes {local})";
}
return $"{TrayTextVersionPrefix} — Paused";
}
string clip = _lastSyncState ? "ON" : "OFF";
string file = _lastTransferFileState ? "ON" : "OFF";
return $"{TrayTextVersionPrefix} — Clipboard {clip} · Files {file}";
}
/// <summary>
/// Watch settings.json for changes instead of polling every 5s.
/// FileSystemWatcher uses OS-level notifications (ReadDirectoryChangesW)
/// — zero CPU/memory when idle, fires only when MWB actually writes.
/// </summary>
private void StartFileWatcher()
{
string? dir = Path.GetDirectoryName(_settingsPath);
string file = Path.GetFileName(_settingsPath);
if (dir == null) return;
// MWB settings dir doesn't exist yet — watch nearest existing ancestor
// for the subdir to appear, then re-initialize. Covers install-before-PowerToys
// and PowerToys-reinstall cases without polling.
if (!Directory.Exists(dir))
{
WatchForSettingsDir(dir);
return;
}
// Create debounce timer — on FSW error-recovery re-entry, the previous
// timer must be disposed first or each recovery cycle leaks a WinForms
// Timer + Tick subscription.
if (_debounceTimer is not null)
{
_debounceTimer.Stop();
_debounceTimer.Dispose();
}
_debounceTimer = new System.Windows.Forms.Timer { Interval = 300 };
_debounceTimer.Tick += (_, _) =>
{
_debounceTimer.Stop();
// Ignore our own writes — WriteSettingsAtomic sets a short suppression window.
if (DateTime.UtcNow < _suppressWatcherUntilUtc) return;
SyncTray();
};
_fileWatcher = new FileSystemWatcher(dir, file)
{
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size,
EnableRaisingEvents = true
};
// FileSystemWatcher fires on a threadpool thread — marshal to UI thread
_fileWatcher.Changed += (_, _) =>
{
try
{
_menu.BeginInvoke(() =>
{
_debounceTimer?.Stop();
_debounceTimer?.Start();
});
}
catch { }
};
// If the watcher errors (network drive disconnect, settings dir removed, etc.),
// attempt to restart it in-place. If that fails (common case: the dir is gone
// entirely), tear down and fall back to the bootstrap watcher so the tray
// recovers when MWB reappears. Without the fallback, a vanished settings dir
// leaves the app silently blind to future state changes.
_fileWatcher.Error += (_, errArgs) =>
{
try
{
_fileWatcher!.EnableRaisingEvents = false;
_fileWatcher.EnableRaisingEvents = true;
}
catch (Exception ex)
{
Logger.Warn($"FileSystemWatcher Error — in-place restart failed ({ex.Message}); falling back to bootstrap watcher.");
try
{
_menu.BeginInvoke(() =>
{
if (_disposed) return;
try { _fileWatcher?.Dispose(); } catch { }
_fileWatcher = null;
string? settingsDir = Path.GetDirectoryName(_settingsPath);
if (!string.IsNullOrEmpty(settingsDir))
WatchForSettingsDir(settingsDir);
});
}
catch (Exception ex2) { Logger.Warn($"FileSystemWatcher Error — bootstrap re-init marshal failed: {ex2.Message}"); }
}
};
}
// Single-shot guard for the bootstrap watcher: IncludeSubdirectories means we can get
// several `Created` events in quick succession as PowerToys builds out its dir tree.
// Without this flag, multiple in-flight BeginInvokes would each call StartFileWatcher
// and orphan the previous _fileWatcher with EnableRaisingEvents still true.
private bool _watcherBootstrapped;
/// <summary>
/// Watch the nearest existing ancestor of the settings dir. When the target dir
/// finally appears (MWB first launch after install), tear this down and re-init
/// the real watcher + refresh the tray.
/// </summary>
private void WatchForSettingsDir(string targetDir)
{
string? ancestor = Path.GetDirectoryName(targetDir);
while (!string.IsNullOrEmpty(ancestor) && !Directory.Exists(ancestor))
ancestor = Path.GetDirectoryName(ancestor);
if (string.IsNullOrEmpty(ancestor))
{
Logger.Warn($"No existing ancestor for {targetDir} — watcher not started.");
return;
}
var bootstrap = new FileSystemWatcher(ancestor)
{
IncludeSubdirectories = true,
NotifyFilter = NotifyFilters.DirectoryName,
EnableRaisingEvents = true
};
_fileWatcher = bootstrap;
_watcherBootstrapped = false;
bootstrap.Created += (_, _) =>
{
if (!Directory.Exists(targetDir)) return;
try
{
_menu.BeginInvoke(() =>
{
if (_disposed || _watcherBootstrapped) return;
_watcherBootstrapped = true;
bootstrap.EnableRaisingEvents = false;
bootstrap.Dispose();
_fileWatcher = null;
StartFileWatcher();
SyncTray();
});
}
catch (Exception ex) { Logger.Warn($"watcher bootstrap marshal: {ex.Message}"); }
};
}
private void SyncTray()
{
bool clipOn = false;
bool fileOn = false;
try
{
if (File.Exists(_settingsPath))
{
// Reject files over 1MB — valid MWB settings.json is <5KB
var fileInfo = new FileInfo(_settingsPath);
if (fileInfo.Length > 1_000_000) return;
string json = File.ReadAllText(_settingsPath, Utf8NoBom);
var cm = ShareClipboardRegex.Match(json);
if (cm.Success)
clipOn = cm.Groups[1].Value == "true";
var fm = TransferFileRegex.Match(json);
if (fm.Success)
fileOn = fm.Groups[1].Value == "true";
}
}
catch
{
return; // File locked — watcher will fire again on next write
}
// Only update tray icon when state actually changes
if (!_lastSyncInitialized || clipOn != _lastSyncState)
{
_lastSyncState = clipOn;
_lastSyncInitialized = true;
_trayIcon.Icon = clipOn ? _iconOn : _iconOff;
_clipboardItem.Checked = clipOn;
}
// Update file-state BEFORE tooltip so BuildTrayTooltip sees the current value
// for both channels. Previously the tooltip read a stale _lastTransferFileState.
if (fileOn != _lastTransferFileState)
{
_lastTransferFileState = fileOn;
_transferFileItem.Checked = fileOn;
}
// Tooltip depends on clip + file + pause. BuildTrayTooltip composes all three;
// _lastTooltip gates the shell update so NotifyIcon.Text only fires on change.
string tooltip = BuildTrayTooltip();
if (tooltip != _lastTooltip)
{
_lastTooltip = tooltip;
_trayIcon.Text = tooltip;
}
// File Transfer depends on clipboard — grey it out when clipboard is OFF,
// EXCEPT during an active pause, where the CHANGELOG promises clicking
// either toggle cancels the pause. Re-evaluated on every SyncTray so that
// pause-enter and pause-exit both refresh the gate (pause-exit may leave
// clipOn unchanged, which would otherwise skip the change-detection above).
_transferFileItem.Enabled = clipOn || IsPauseActive;
}
// ╔══════════════════════════════════════════════════════════════════════╗
// ║ Pause / Resume ║
// ╚══════════════════════════════════════════════════════════════════════╝
// True when a pause is active (timed or unlimited). A non-null snapshot is the
// single source of truth; _pauseResumeAtUtc is additionally non-null for timed
// pauses but null for unlimited.
private bool IsPauseActive => _pauseSnapshotClipboard is not null;
// Menu-click dispatcher. If the item is already checked (pause is active in that mode),
// resume instead of re-firing the pause — matches the checkmark-as-toggle UI contract.
private void TogglePause(object? sender, int minutes)
{
if (sender is ToolStripMenuItem item && item.Checked)
ResumeSharing();
else
PauseSharing(minutes);
}
/// <summary>
/// Enter (or re-arm) pause. On first entry this snapshots the current
/// ShareClipboard + TransferFile states so Resume can restore the user's
/// actual configuration instead of forcing both ON. Re-entering pause while
/// already paused (e.g. switching 5min → 30min) preserves the existing
/// snapshot and just updates the deadline.
/// </summary>
private void PauseSharing(int minutes)
{
if (!File.Exists(_settingsPath)) return;
if (new FileInfo(_settingsPath).Length > 1_000_000) return;
string json;
try { json = File.ReadAllText(_settingsPath, Utf8NoBom); }
catch (Exception ex) { Logger.Warn($"PauseSharing read: {ex.Message}"); return; }
var clipMatch = ShareClipboardRegex.Match(json);
var fileMatch = TransferFileRegex.Match(json);
if (!clipMatch.Success || !fileMatch.Success)
{
ShowOSD("ShareClipboard/TransferFile not found in settings.json — run MWB at least once.", 5000);
return;
}
bool currentClip = clipMatch.Groups[1].Value == "true";
bool currentFile = fileMatch.Groups[1].Value == "true";
// Snapshot only on first entry. Re-arming an active pause must preserve the
// ORIGINAL pre-pause state, not the current paused {off,off} state — otherwise
// clicking 5min then 30min would snapshot {off,off} and resume would leave the
// user with sharing disabled.
bool freshSnapshot = !IsPauseActive;
if (freshSnapshot)
{
_pauseSnapshotClipboard = currentClip;
_pauseSnapshotFile = currentFile;
}
// Remember prior timer/menu state so we can roll back cleanly on settings-write
// failure without leaving the app showing "paused" when pause didn't take.
DateTime? priorResumeAt = _pauseResumeAtUtc;
bool priorCheck5 = _pause5.Checked;
bool priorCheck30 = _pause30.Checked;
bool priorCheckUnlimited = _pauseUnlimited.Checked;
// Set menu + timer + sidecar BEFORE mutating settings.json. The invariant is:
// "snapshot persisted ⇒ ResumeSharing will restore the exact pre-pause state."
// If a crash or kill interrupts us between the pause.dat write and the
// settings.json write, the next startup reads pause.dat with snapshot matching
// current on-disk settings — ResumeSharing becomes a no-op. That's strictly
// better than the reverse order, where a crash leaves sharing stuck OFF with
// no sidecar and no way to auto-resume.
_pause5.Checked = minutes == 5;
_pause30.Checked = minutes == 30;
_pauseUnlimited.Checked = minutes == 0;
_pauseTimer.Stop();
if (minutes > 0)
{
_pauseResumeAtUtc = DateTime.UtcNow.AddMinutes(minutes);
_pauseTimer.Interval = minutes * 60_000;
_pauseTimer.Start();
}
else
{
_pauseResumeAtUtc = null;
}
PersistPauseDeadline();
// Force both fields to false. Skip the write if they're already off to avoid a
// spurious FileSystemWatcher event and an unnecessary backup rotation.
if (currentClip || currentFile)
{
string paused = ShareClipboardReplaceRegex.Replace(json, "$1false");
paused = TransferFileReplaceRegex.Replace(paused, "$1false");
var verifyClip = ShareClipboardRegex.Match(paused);
var verifyFile = TransferFileRegex.Match(paused);
if (!verifyClip.Success || verifyClip.Groups[1].Value != "false"
|| !verifyFile.Success || verifyFile.Groups[1].Value != "false")
{
Logger.Warn("PauseSharing verify failed — regex replace did not update both fields.");
RollbackPauseState(freshSnapshot, priorResumeAt, priorCheck5, priorCheck30, priorCheckUnlimited);
ShowOSD("Failed to update settings — JSON structure may have changed.", 5000);
return;
}
if (!WriteSettingsAtomic(paused))
{
RollbackPauseState(freshSnapshot, priorResumeAt, priorCheck5, priorCheck30, priorCheckUnlimited);
ShowOSD("Could not pause — settings.json is locked. Try again.", 5000);
return;
}
}
WaitWithMessagePump(300);
SyncTray();
string msg = minutes > 0 ? $"Paused · {minutes} min" : "Paused";
ShowOSDState(msg, on: false);
}
/// <summary>
/// Restore pause state to what it was before a failed PauseSharing attempt so the
/// user doesn't see a "paused" UI while sharing is still active. If the pause was
/// pre-existing (not a fresh entry), the snapshot stays — we only rolled back the
/// timer/menu updates that would have been wrong on failure.
/// </summary>
private void RollbackPauseState(bool clearSnapshot, DateTime? priorResumeAt,
bool priorCheck5, bool priorCheck30, bool priorCheckUnlimited)
{
_pauseTimer.Stop();
_pauseResumeAtUtc = priorResumeAt;
if (priorResumeAt is DateTime due)
{
_pauseTimer.Interval = Math.Max(1000, (int)(due - DateTime.UtcNow).TotalMilliseconds);
_pauseTimer.Start();
}
_pause5.Checked = priorCheck5;
_pause30.Checked = priorCheck30;
_pauseUnlimited.Checked = priorCheckUnlimited;
if (clearSnapshot)
{
_pauseSnapshotClipboard = null;
_pauseSnapshotFile = null;
}
PersistPauseDeadline();
}
/// <summary>
/// Exit pause by restoring the pre-pause ShareClipboard + TransferFile states.
/// Also called by the timer tick and by the startup path when the pause window
/// has already elapsed.
/// </summary>
private void ResumeSharing()
{
// Capture snapshot before we clear pause state — the write below needs it.
bool restoreClip = _pauseSnapshotClipboard ?? true;
bool restoreFile = _pauseSnapshotFile ?? true;
_pauseTimer.Stop();
_pauseResumeAtUtc = null;
_pauseSnapshotClipboard = null;
_pauseSnapshotFile = null;
PersistPauseDeadline();
_pause5.Checked = false;
_pause30.Checked = false;
_pauseUnlimited.Checked = false;
if (!File.Exists(_settingsPath)) return;
if (new FileInfo(_settingsPath).Length > 1_000_000) return;
string json;
try { json = File.ReadAllText(_settingsPath, Utf8NoBom); }
catch (Exception ex)
{
Logger.Warn($"ResumeSharing read: {ex.Message}");
ShowOSD("Resume aborted — could not read settings.json.", 5000);
return;
}
var clipMatch = ShareClipboardRegex.Match(json);
var fileMatch = TransferFileRegex.Match(json);
if (!clipMatch.Success || !fileMatch.Success) return;