Repository navigation
Expand file tree
/
Copy pathMainWindow.cs
More file actions
2465 lines (2181 loc) · 100 KB
/
Copy pathMainWindow.cs
File metadata and controls
2465 lines (2181 loc) · 100 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.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace VozWindows;
public sealed class MainWindow : Window
{
private const int HOTKEY_ID_F8 = 9001;
private const int HOTKEY_ID_CTRL_SHIFT_SPACE = 9002;
private const int HOTKEY_ID_SPEED_0 = 9100;
private const int HOTKEY_ID_SPEED_1 = 9101;
private const int HOTKEY_ID_SPEED_2 = 9102;
private const int HOTKEY_ID_SPEED_3 = 9103;
private readonly NativeMicrophoneCapture _mic = new();
private readonly GeminiLiveClient _gemini = new();
private readonly GeminiRewriteClient _rewriter = new();
private readonly RewriteDeckView _rewriteDeck = new();
// Integrated Module 2: CursorLoop (Touchpad Booster + Infinite Monitor Edges + Head Motion Monitor Switcher)
private readonly CursorWrapEngine _cursorEngine = new();
private readonly HeadMonitorTracker _headTracker = new();
private readonly CursorLoopSettings _cursorSettings;
private readonly System.Windows.Forms.Timer _cursorTimer = new() { Interval = 8 };
// IPC Events for single-instance activation
private readonly System.Threading.EventWaitHandle? _showUiEvent;
private readonly System.Threading.EventWaitHandle? _cursorLoopEvent;
private readonly System.Threading.EventWaitHandle? _legacyLoopEvent;
private volatile bool _isClosingApp;
private readonly Border _outerBorder;
private readonly Grid _middleVisorGrid;
private readonly StackPanel _wavePanel;
private readonly StackPanel _textStack;
private readonly Button _micButton;
private readonly TextBlock _micButtonLabel;
private readonly Ellipse _statusDot;
private readonly TextBlock _statusText;
private readonly TextBlock _livePreviewText;
private readonly Button _rewriteToggleButton;
private readonly Button _listenPcAudioButton;
private readonly Button _pcTypingModeButton;
private readonly Button _headTrackerButton;
private readonly Button _headRealtimeMouseButton;
private readonly Button _headConfigButton;
private readonly Button _cursorLoopButton;
private readonly Button _cursorSpeedButton;
private readonly Button _minButton;
private readonly Rectangle[] _bars = new Rectangle[10];
private readonly Random _rng = new();
private HwndSource? _hwndSource;
private System.Windows.Forms.NotifyIcon? _trayIcon;
private HeadTrackerConfigWindow? _headConfigWindow;
private volatile bool _isListening;
private volatile bool _isCompact = false;
private bool _rewriteTooltipEnabled = false; // Starts hidden in System Tray (without sidebar)
private bool _liveCursorMode = true;
private double _expandedLeft;
private double _expandedTop;
private string _cachedApiKey = string.Empty;
private string _activeCursorInterim = string.Empty;
private string _lastAutoSealedText = string.Empty;
private DateTime _lastAutoSealedUtc = DateTime.MinValue;
private string _currentBlockCommittedText = string.Empty;
private IntPtr _lastTargetWindowHwnd = IntPtr.Zero;
private DateTime _lastInterimUiUtc = DateTime.UtcNow;
private DateTime _lastInterimRewriteUtc = DateTime.MinValue;
private DateTime _lastWaveformUiUtc = DateTime.MinValue;
private DateTime _ignoreSpeechUntilUtc = DateTime.MinValue;
private bool _needsLeadingSpace;
private bool _isApplyingVariation;
private bool _hasAppliedInCurrentCycle;
private DateTime _lastAppliedUtc = DateTime.MinValue;
private RewriteVariations? _latestVariationsSnapshot;
private RewriteVariations? _previousArchivedVariations;
private UpdateReleaseInfo? _pendingUpdateRelease;
private volatile bool _isUpdatingApp;
private string _sessionTranscript = string.Empty;
private int _wordsTypedCount;
private static readonly SolidColorBrush BrushRedLive = CreateFrozenBrush(239, 68, 68);
private static readonly SolidColorBrush BrushSkyBlue = CreateFrozenBrush(212, 212, 216); // #D4D4D8 Neutral Silver
private static readonly SolidColorBrush BrushDarkBorder = CreateFrozenBrush(36, 36, 40); // #242428 Dark Graphite Border
private static readonly SolidColorBrush BrushGreenReady = CreateFrozenBrush(34, 197, 94);
private static readonly SolidColorBrush BrushAmberWarn = CreateFrozenBrush(245, 158, 11);
private static readonly SolidColorBrush BrushMutedGray = CreateFrozenBrush(161, 161, 170); // #A1A1AA
private static readonly SolidColorBrush BrushWhiteText = CreateFrozenBrush(244, 244, 245); // #F4F4F5
private static SolidColorBrush CreateFrozenBrush(byte r, byte g, byte b)
{
var brush = new SolidColorBrush(Color.FromRgb(r, g, b));
brush.Freeze();
return brush;
}
public MainWindow(
System.Threading.EventWaitHandle? showUiEvent = null,
System.Threading.EventWaitHandle? cursorLoopEvent = null,
System.Threading.EventWaitHandle? legacyLoopEvent = null,
bool openCursorLoopOnStart = false)
{
_showUiEvent = showUiEvent;
_cursorLoopEvent = cursorLoopEvent;
_legacyLoopEvent = legacyLoopEvent;
_cursorSettings = CursorLoopSettings.Load();
_cursorEngine.SpeedMultiplier = _cursorSettings.GetEffectiveMultiplier();
_cursorEngine.SmartPrecision = _cursorSettings.SmartPrecision;
_headTracker.WrapEngine = _cursorEngine;
_headTracker.Settings = _cursorSettings;
if (!string.IsNullOrEmpty(Environment.ProcessPath))
{
CursorLoopSettings.EnsureUnifiedStartup(Environment.ProcessPath);
}
Title = "VozWindows — Ditado por Voz + CursorLoop";
SizeToContent = SizeToContent.Manual;
WindowStyle = WindowStyle.None;
// Hardware-accelerated native DWM surface (Zero WS_EX_LAYERED / Zero CPU DropShadow lag!)
AllowsTransparency = false;
Background = new SolidColorBrush(Color.FromRgb(11, 11, 13)); // #0B0B0D True Dark
Topmost = true;
ShowInTaskbar = false;
ShowActivated = false;
Focusable = false;
ResizeMode = ResizeMode.NoResize;
TryLoadWindowIcon();
Rect workArea = SystemParameters.WorkArea;
_expandedLeft = workArea.Left + (workArea.Width - 920) / 2;
_expandedTop = workArea.Bottom - 92 - 16;
_outerBorder = new Border
{
CornerRadius = new CornerRadius(0),
Background = new SolidColorBrush(Color.FromRgb(11, 11, 13)), // #0B0B0D True Dark
BorderBrush = BrushDarkBorder,
BorderThickness = new Thickness(1, 0, 0, 0),
Padding = new Thickness(12, 8, 12, 8),
Margin = new Thickness(0),
ClipToBounds = true
};
// Unified 2-row Grid inside the single native sidebar window:
// Row 0 (*): _rewriteDeck (6 Live Options — always visible in Sidebar mode)
// Row 1 (Auto): mainGrid (Bottom Voice/Suite Control Bar)
var rootMorphGrid = new Grid { ClipToBounds = true };
rootMorphGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
rootMorphGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
_rewriteDeck.Visibility = Visibility.Visible;
Grid.SetRow(_rewriteDeck, 0);
rootMorphGrid.Children.Add(_rewriteDeck);
var mainGrid = new Grid
{
VerticalAlignment = VerticalAlignment.Bottom,
MinHeight = 46
};
mainGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); // Row 0: Mic button + Status Visor + Minimize button
mainGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); // Row 1: Wrapped Quick-Action Pills (never clips in Sidebar!)
mainGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); // Col 0: Mic button
mainGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); // Col 1: Status Visor
mainGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); // Col 2: Minimize to Tray
// 1. Mic Toggle Button (F8)
_micButton = new Button
{
Cursor = Cursors.Hand,
Focusable = false,
Background = new SolidColorBrush(Color.FromRgb(37, 99, 235)), // #2563EB
Foreground = Brushes.White,
BorderThickness = new Thickness(0),
Padding = new Thickness(12, 7, 12, 7),
Margin = new Thickness(0, 0, 8, 0),
VerticalAlignment = VerticalAlignment.Center,
ToolTip = "Ativar/Parar ditado por voz em qualquer janela (Atalho: F8 ou Ctrl+Shift+Espaço)"
};
_micButtonLabel = new TextBlock
{
Text = "🎙️ F8",
FontWeight = FontWeights.Bold,
FontSize = 13,
Foreground = Brushes.White
};
_micButton.Content = _micButtonLabel;
ApplyRoundedButtonTemplate(_micButton, 10);
_micButton.Click += async (_, _) => await ToggleDictationAsync();
Grid.SetRow(_micButton, 0);
Grid.SetColumn(_micButton, 0);
mainGrid.Children.Add(_micButton);
// 2. Middle Visor Grid (Status + Live Preview inside Sidebar Footer)
_middleVisorGrid = new Grid
{
ClipToBounds = true,
MinWidth = 0,
VerticalAlignment = VerticalAlignment.Center
};
_middleVisorGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
_middleVisorGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
_wavePanel = new StackPanel
{
Orientation = Orientation.Horizontal,
VerticalAlignment = VerticalAlignment.Center,
Visibility = Visibility.Collapsed
};
for (int i = 0; i < _bars.Length; i++)
{
_bars[i] = new Rectangle { Width = 3, Height = 6 };
}
Grid.SetColumn(_wavePanel, 0);
_middleVisorGrid.Children.Add(_wavePanel);
_textStack = new StackPanel
{
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(0, 0, 6, 0)
};
var statusRow = new StackPanel
{
Orientation = Orientation.Horizontal,
Margin = new Thickness(0, 0, 0, 1)
};
_statusDot = new Ellipse
{
Width = 7,
Height = 7,
Fill = BrushGreenReady,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(0, 0, 5, 0)
};
_statusText = new TextBlock
{
Text = "MICROFONE DESLIGADO • Aperte F8 para falar",
FontSize = 10,
FontWeight = FontWeights.SemiBold,
Foreground = BrushMutedGray,
TextTrimming = TextTrimming.CharacterEllipsis
};
statusRow.Children.Add(_statusDot);
statusRow.Children.Add(_statusText);
_livePreviewText = new TextBlock
{
Text = "Pronto na bandeja (F8 para ativar voz)...",
FontSize = 11.5,
FontWeight = FontWeights.Medium,
Foreground = BrushWhiteText,
TextWrapping = TextWrapping.NoWrap,
TextTrimming = TextTrimming.CharacterEllipsis
};
_textStack.Children.Add(statusRow);
_textStack.Children.Add(_livePreviewText);
Grid.SetColumn(_textStack, 1);
_middleVisorGrid.Children.Add(_textStack);
Grid.SetRow(_middleVisorGrid, 0);
Grid.SetColumn(_middleVisorGrid, 1);
mainGrid.Children.Add(_middleVisorGrid);
// 3. Wrapped Quick-Action Controls (Row 1: automatically wraps into 2 neat rows in Sidebar without ever cutting off!)
var actionsPanel = new WrapPanel
{
Orientation = Orientation.Horizontal,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(0, 7, 0, 0)
};
_rewriteToggleButton = CreateSmallActionButton(
_cursorSettings.GetRewriteModePillText(),
"Alternar entre Modo Nativo Direto (sem correção e sem 6 opções, máxima velocidade) e Modo 6 Opções de Escrita");
_rewriteToggleButton.Foreground = _cursorSettings.RealtimeRewriteEnabled ? BrushGreenReady : BrushSkyBlue;
_rewriteToggleButton.Click += (_, _) => ToggleRealtimeRewriteMode();
_rewriteDeck.SetRealtimeRewriteMode(_cursorSettings.RealtimeRewriteEnabled);
_listenPcAudioButton = CreateSmallActionButton(
_cursorSettings.GetSystemAudioLoopbackPillText(),
"Ouvir o Computador (WASAPI Loopback): escuta o áudio reproduzido pelo Windows (vídeos, reuniões, áudios) e resume/transcreve em tempo real (Clique direito alterna entre Só Resumo e Digitar no Cursor)");
_listenPcAudioButton.Foreground = _cursorSettings.SystemAudioLoopbackEnabled ? BrushGreenReady : BrushMutedGray;
_listenPcAudioButton.Click += async (_, _) => await ToggleSystemAudioLoopbackAsync();
_listenPcAudioButton.MouseRightButtonUp += (_, _) => ToggleSystemAudioLoopbackTypeMode();
_pcTypingModeButton = CreateSmallActionButton(
_cursorSettings.GetSystemAudioLoopbackTypePillText(),
"Tipo do Ouvir PC: '📋 PC: Só Resumo' (escuta e monta a Linha do Tempo sem digitar no seu cursor) vs. '⌨️ PC: Digitar' (digita o áudio onde o cursor estiver)");
_pcTypingModeButton.Foreground = _cursorSettings.SystemAudioLoopbackTypeInCursor ? BrushAmberWarn : BrushSkyBlue;
_pcTypingModeButton.Click += (_, _) => ToggleSystemAudioLoopbackTypeMode();
_rewriteDeck.SetPcTypingModeVisual(_cursorSettings.SystemAudioLoopbackTypeInCursor);
_headTrackerButton = CreateSmallActionButton(
_cursorSettings.GetHeadTrackerPillText(),
"Alternar Head Motion Detection: move o mouse para o centro do 2º monitor quando o rosto vira para a direita em tempo real (Clique direito abre a tela de Teste e Sensibilidade)");
_headTrackerButton.Foreground = _cursorSettings.HeadTrackerEnabled ? BrushGreenReady : BrushMutedGray;
_headTrackerButton.Click += async (_, _) => await ToggleHeadTrackerOnBarAsync();
_headTrackerButton.MouseRightButtonUp += (_, _) => OpenHeadTrackerConfigWindow();
_headRealtimeMouseButton = CreateSmallActionButton(
_cursorSettings.GetHeadRealtimeMousePillText(),
"Modo Função Realtime para controlar o mouse pelo rosto (X e Y contínuo • Começa Desativado • Clique direito abre Config)");
_headRealtimeMouseButton.Foreground = _cursorSettings.HeadRealtimeMouseEnabled ? BrushGreenReady : BrushMutedGray;
_headRealtimeMouseButton.Click += async (_, _) => await ToggleHeadRealtimeMouseOnBarAsync();
_headRealtimeMouseButton.MouseRightButtonUp += (_, _) => OpenHeadTrackerConfigWindow();
_headConfigButton = CreateSmallActionButton(
"🎯 Config",
"Abrir Tela de Teste ao Vivo e Configuração de Sensibilidade / Longa Distância / Mouse Realtime do Head Motion Monitor");
_headConfigButton.Foreground = BrushSkyBlue;
_headConfigButton.Click += (_, _) => OpenHeadTrackerConfigWindow();
_cursorLoopButton = CreateSmallActionButton(
_cursorSettings.GetLoopPillText(),
"Alternar repetição de borda (Loop ON / OFF) de forma independente da velocidade");
_cursorLoopButton.Foreground = _cursorSettings.Enabled ? BrushGreenReady : BrushMutedGray;
_cursorLoopButton.Click += (_, _) => ToggleCursorLoopOnlyOnBar();
_cursorSpeedButton = CreateSmallActionButton(
_cursorSettings.GetSpeedPillText(),
"Alternar velocidade do cursor (1.8x ➔ 2.8x ➔ 4.5x ➔ 1.0x) de forma independente do Loop • Atalhos: Ctrl+Alt+1/2/3/0");
_cursorSpeedButton.Foreground = _cursorSettings.GetEffectiveMultiplier() > 1.001 ? BrushSkyBlue : BrushMutedGray;
_cursorSpeedButton.Click += (_, _) => CycleCursorSpeedOnlyOnBar();
if (!CursorLoopSettings.IsCursorLoopSupported)
{
_headTrackerButton.Visibility = Visibility.Collapsed;
_headRealtimeMouseButton.Visibility = Visibility.Collapsed;
_headConfigButton.Visibility = Visibility.Collapsed;
_cursorLoopButton.Visibility = Visibility.Collapsed;
_cursorSpeedButton.Visibility = Visibility.Collapsed;
}
_minButton = CreateSmallActionButton("—", "Minimizar para a bandeja");
_minButton.Visibility = Visibility.Collapsed;
var closeButton = CreateSmallActionButton("—", "Minimizar a barra lateral para o ícone da bandeja do relógio (clique no ícone da bandeja para restaurar)");
closeButton.Margin = new Thickness(4, 0, 0, 0);
closeButton.Click += (_, _) => MinimizeToTray();
Grid.SetRow(closeButton, 0);
Grid.SetColumn(closeButton, 2);
mainGrid.Children.Add(closeButton);
actionsPanel.Children.Add(_rewriteToggleButton);
actionsPanel.Children.Add(_listenPcAudioButton);
actionsPanel.Children.Add(_pcTypingModeButton);
actionsPanel.Children.Add(_headTrackerButton);
actionsPanel.Children.Add(_headRealtimeMouseButton);
actionsPanel.Children.Add(_headConfigButton);
actionsPanel.Children.Add(_cursorLoopButton);
actionsPanel.Children.Add(_cursorSpeedButton);
Grid.SetRow(actionsPanel, 1);
Grid.SetColumn(actionsPanel, 0);
Grid.SetColumnSpan(actionsPanel, 3);
mainGrid.Children.Add(actionsPanel);
Grid.SetRow(mainGrid, 1);
rootMorphGrid.Children.Add(mainGrid);
_outerBorder.Child = rootMorphGrid;
Content = _outerBorder;
// 8ms (~120 FPS) Engine Timer: CursorLoop detecta movimento físico do Touchpad + Head Realtime Espacial + Active Target Tracker
_cursorTimer.Tick += (_, _) =>
{
if (CursorLoopSettings.IsCursorLoopSupported)
{
_cursorEngine.Tick(_cursorSettings.Enabled, _cursorSettings.HorizontalLoop, _cursorSettings.VerticalLoop);
_headTracker.TickRealtimeCursor(_cursorEngine.LastTickHadPhysicalMove);
}
TrackActiveExternalWindow();
};
_cursorTimer.Start();
// Start background listener for IPC events (--cursorloop, Start Menu click)
StartIpcSignalListener();
_headTracker.OnStateUpdated += (statusMsg, lookingRight, _) =>
{
Dispatcher.BeginInvoke(() =>
{
if (!_isListening)
{
_statusDot.Fill = lookingRight ? BrushGreenReady : BrushSkyBlue;
_statusText.Text = statusMsg;
}
});
};
// Wire embedded RewriteDeckView callbacks
_rewriter.OnVariationsUpdated += variations =>
{
_latestVariationsSnapshot = variations;
if (variations.IsAiRefined)
{
_ = Task.Run(() => SaveConversationState(variations));
}
Dispatcher.BeginInvoke(() =>
{
_rewriteDeck.UpdateVariations(variations);
_rewriteDeck.SetPreviousBackupAvailable(_previousArchivedVariations != null);
});
};
_rewriter.OnTimelineEntryUpdated += (entry, isNew) =>
{
Dispatcher.BeginInvoke(() =>
{
_rewriteDeck.AddOrUpdateTimelineEntry(entry, isNew);
});
};
_rewriter.OnCurrentLiveTopicPreview += (themeTitle, liveSnippet) =>
{
Dispatcher.BeginInvoke(() =>
{
_rewriteDeck.UpdateLiveTopicPreview(themeTitle, liveSnippet);
});
};
_rewriteDeck.OnUserDisabled += () =>
{
Dispatcher.BeginInvoke(MinimizeToTray);
};
_rewriteDeck.OnOptionClicked += (chosenText, label) =>
{
_ = ApplyChosenVariationToCursorAsync(chosenText, label);
};
_rewriteDeck.OnToggleRewriteModeRequested += ToggleRealtimeRewriteMode;
_rewriteDeck.OnTogglePcTypingModeRequested += ToggleSystemAudioLoopbackTypeMode;
_rewriteDeck.OnRestorePreviousRequested += () =>
{
RestorePreviousArchivedConversation();
};
_rewriteDeck.OnResetBlockRequested += () =>
{
ArchiveAndAutoClearForNewConversation(updateDeckImmediately: false);
_rewriteDeck.ResetDisplay();
_rewriteDeck.SetPreviousBackupAvailable(_previousArchivedVariations != null);
};
_rewriteDeck.OnUpdateRequested += () =>
{
_ = TriggerOneClickUpdateAsync();
};
// Wire audio & Gemini callbacks
_mic.OnPcmFrame += (pcm, rms) =>
{
_gemini.EnqueueAudioPcm16k(pcm, rms);
};
_gemini.OnStatusChanged += status =>
{
Dispatcher.BeginInvoke(() =>
{
_statusText.Text = status.ToUpperInvariant();
if (_isListening)
{
_statusDot.Fill = _gemini.IsStandby ? BrushSkyBlue : BrushRedLive;
}
});
};
_gemini.OnInterimTranscript += interim =>
{
Dispatcher.BeginInvoke(() => HandleInterimTranscript(interim));
};
_gemini.OnFinalTranscript += finalText =>
{
Dispatcher.BeginInvoke(() => HandleFinalTranscript(finalText));
};
_gemini.OnError += err =>
{
Dispatcher.BeginInvoke(() =>
{
_statusDot.Fill = BrushAmberWarn;
_statusText.Text = "RECUPERANDO AUTOMATICAMENTE: " + err;
});
};
// Fast watchdog
var watchdog = new DispatcherTimer
{
Interval = TimeSpan.FromMilliseconds(500)
};
watchdog.Tick += (_, _) =>
{
if (!_isListening)
return;
DateTime now = DateTime.UtcNow;
double silenceSecs = (now - _lastInterimUiUtc).TotalSeconds;
// 1. Auto-seal any hanging interim phrase after 2.8s of silence and lock in the server turn prefix
// so the server never re-emits those words when the user resumes speaking.
if (!string.IsNullOrEmpty(_activeCursorInterim) && silenceSecs >= 2.8)
{
string sealedChunk = _activeCursorInterim.Trim();
_lastAutoSealedText = _activeCursorInterim;
_lastAutoSealedUtc = now;
_needsLeadingSpace = !_activeCursorInterim.EndsWith(' ') && !_activeCursorInterim.EndsWith('\n');
_activeCursorInterim = string.Empty;
_gemini.ClearInterimState();
if (!string.IsNullOrEmpty(sealedChunk))
{
_currentBlockCommittedText = CombineBlockText(_currentBlockCommittedText, sealedChunk);
_rewriter.FlushPendingTimelineSegment(_cachedApiKey, _cursorSettings.SystemAudioLoopbackEnabled);
if (_cursorSettings.RealtimeRewriteEnabled)
{
_rewriter.RequestRealtimeRewrite(_cachedApiKey, _currentBlockCommittedText, isFinalCommit: true);
}
else
{
_rewriteDeck.UpdateNativeLivePreview(_currentBlockCommittedText, isFinal: true);
}
}
}
// 2. Automatic 10-Second Silence Cut-Off ("Ponto de Corte de Silêncio"):
// After ~9.5s of silence, automatically archive the current conversation into '⏪ Anterior'
// and clear the 6 cards + memory so the next speech starts 100% clean without residue!
// (If the user's mouse is hovering over the sidebar reading the options, wait until the mouse leaves.)
if (!string.IsNullOrEmpty(_currentBlockCommittedText) &&
silenceSecs >= 9.5 &&
!_rewriteDeck.IsMouseOver &&
!_isApplyingVariation)
{
ArchiveAndAutoClearForNewConversation(
updateDeckImmediately: true,
customReason: "✂️ PONTO DE CORTE (10s DE SILÊNCIO) • Limpo p/ nova fala (salvo em '⏪ Anterior')");
}
// 3. Revive Windows microphone if audio driver stopped delivering frames
if ((now - _mic.LastFrameUtc).TotalSeconds > 3.2)
{
try
{
_mic.Stop();
_mic.Start(chunkMs: 40);
}
catch { }
}
// 4. Ensure WebSocket reconnects if dropped
if (!_gemini.IsStandby && !_gemini.IsConnected)
{
_ = _gemini.TriggerReconnectAsync("Watchdog de sessão");
}
};
watchdog.Start();
SetupSystemTray();
}
/// <summary>
/// Initializes the hidden Win32 handle (for global hotkeys F8 / Ctrl+Alt+0..3) and background services
/// while keeping the sidebar CLOSED and the microphone DISABLED (only showing the System Tray icon).
/// </summary>
public void InitializeTrayOnlyStartup(bool openCursorLoopOnStart = false)
{
_rewriteTooltipEnabled = false;
_isListening = false;
_ = new WindowInteropHelper(this).EnsureHandle();
AutoUpdateService.CleanupOldExecutableOnStartup();
TryRestoreLastConversationState();
if (CursorLoopSettings.IsCursorLoopSupported)
{
_cursorSettings.Enabled = true;
_cursorSettings.HeadRealtimeMouseEnabled = false; // Always starts disabled on startup
_cursorSettings.SystemAudioLoopbackEnabled = false; // Always starts disabled on startup
_mic.UseSystemLoopback = false;
_cursorSettings.Save();
ApplyCursorLoopToBar();
if (_cursorSettings.HeadTrackerEnabled || _cursorSettings.HeadRealtimeMouseEnabled)
{
_ = _headTracker.StartAsync();
}
}
RefreshTrayIconVisual();
StartAutoUpdateChecker();
}
/// <summary>
/// Mode 1: Maximized in the Native Windows Sidebar on the right edge of the screen.
/// </summary>
public void MaximizeToSidebar(bool ensureListening = false)
{
_rewriteTooltipEnabled = true;
_isCompact = false;
if (!IsVisible)
{
Show();
}
UpdateControlBarLabels();
ApplyNativeLayout();
string currentText = CombineBlockText(_currentBlockCommittedText, _activeCursorInterim);
if (!string.IsNullOrWhiteSpace(currentText) && _cursorSettings.RealtimeRewriteEnabled)
{
string apiKey = !string.IsNullOrWhiteSpace(_cachedApiKey)
? _cachedApiKey
: (NativeInterop.ReadApiKeyFromVault() ?? string.Empty);
_rewriter.RequestRealtimeRewrite(apiKey, currentText, isFinalCommit: true);
}
if (ensureListening && !_isListening)
{
_ = StartDictationAsync();
}
}
/// <summary>
/// Mode 2: Minimized to the System Tray (releases the sidebar reservation and hides the window).
/// </summary>
public void MinimizeToTray()
{
_rewriteTooltipEnabled = false;
NativeInterop.UndockNativeSidebarAppBar();
Hide();
}
public void ToggleSidebarOrTray()
{
if (IsVisible && _rewriteTooltipEnabled)
{
MinimizeToTray();
}
else
{
MaximizeToSidebar(ensureListening: false);
}
}
private void UpdateControlBarLabels()
{
_micButtonLabel.Text = _isListening ? "⏹️ F8" : "🎙️ F8";
_outerBorder.BorderBrush = BrushDarkBorder;
}
/// <summary>
/// Two-Mode Native Layout Engine:
/// - When visible: Docked as Native Windows Sidebar AppBar on the right edge (dividing the screen with zero overlap).
/// - When minimized: Undocked and hidden in the System Tray.
/// </summary>
private void ApplyNativeLayout()
{
_rewriteDeck.Visibility = Visibility.Visible;
_middleVisorGrid.Visibility = Visibility.Visible;
IntPtr myHwnd = new WindowInteropHelper(this).Handle;
if (myHwnd == IntPtr.Zero)
return;
if (_rewriteTooltipEnabled)
{
DpiScale dpi = VisualTreeHelper.GetDpi(this);
_outerBorder.CornerRadius = new CornerRadius(0);
_outerBorder.BorderThickness = new Thickness(1, 0, 0, 0);
_outerBorder.BorderBrush = BrushDarkBorder;
int desiredWidthPx = (int)Math.Round(_rewriteDeck.PreferredSlotWidthDip * dpi.DpiScaleX);
NativeInterop.DockNativeSidebarAppBar(myHwnd, desiredWidthPx);
}
else
{
NativeInterop.UndockNativeSidebarAppBar();
}
}
private static Button CreateSmallActionButton(string text, string tooltip)
{
var btn = new Button
{
Content = text,
ToolTip = tooltip,
Cursor = Cursors.Hand,
Focusable = false,
Background = new SolidColorBrush(Color.FromRgb(22, 22, 26)), // #16161A True Dark Card
Foreground = new SolidColorBrush(Color.FromRgb(228, 228, 231)), // #E4E4E7
BorderThickness = new Thickness(0),
FontSize = 11,
FontWeight = FontWeights.SemiBold,
Padding = new Thickness(8, 5, 8, 5),
Margin = new Thickness(0, 0, 5, 5),
VerticalAlignment = VerticalAlignment.Center
};
ApplyRoundedButtonTemplate(btn, 8);
return btn;
}
private static void ApplyRoundedButtonTemplate(Button button, double radius)
{
var template = new ControlTemplate(typeof(Button));
var borderFactory = new FrameworkElementFactory(typeof(Border));
borderFactory.SetValue(Border.CornerRadiusProperty, new CornerRadius(radius));
borderFactory.SetValue(Border.BackgroundProperty, new TemplateBindingExtension(Control.BackgroundProperty));
borderFactory.SetValue(Border.PaddingProperty, new TemplateBindingExtension(Control.PaddingProperty));
var contentFactory = new FrameworkElementFactory(typeof(ContentPresenter));
contentFactory.SetValue(HorizontalAlignmentProperty, HorizontalAlignment.Center);
contentFactory.SetValue(VerticalAlignmentProperty, VerticalAlignment.Center);
borderFactory.AppendChild(contentFactory);
template.VisualTree = borderFactory;
button.Template = template;
}
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
IntPtr hwnd = new WindowInteropHelper(this).Handle;
// Make window non-activating and toolwindow so it NEVER steals focus and NEVER appears in Taskbar/Alt+Tab!
int exStyle = NativeInterop.GetWindowLong(hwnd, NativeInterop.GWL_EXSTYLE);
NativeInterop.SetWindowLong(
hwnd,
NativeInterop.GWL_EXSTYLE,
(exStyle | NativeInterop.WS_EX_TOOLWINDOW | NativeInterop.WS_EX_NOACTIVATE | NativeInterop.WS_EX_TOPMOST));
// Configure pure hardware-accelerated DWM rendering (zero WS_EX_LAYERED lag)
NativeInterop.ConfigureNativeHardwareWindow(hwnd, roundedCorners: true, borderColorRef: 0x00282424);
_hwndSource = HwndSource.FromHwnd(hwnd);
_hwndSource?.AddHook(WndProc);
ApplyNativeLayout();
// Register F8 and Ctrl+Shift+Space globally for Voice Dictation
NativeInterop.RegisterHotKey(hwnd, HOTKEY_ID_F8, NativeInterop.MOD_NOREPEAT, NativeInterop.VK_F8);
NativeInterop.RegisterHotKey(
hwnd,
HOTKEY_ID_CTRL_SHIFT_SPACE,
NativeInterop.MOD_CONTROL | NativeInterop.MOD_SHIFT | NativeInterop.MOD_NOREPEAT,
NativeInterop.VK_SPACE);
if (CursorLoopSettings.IsCursorLoopSupported)
{
// Register Ctrl+Alt+0/1/2/3 globally for CursorLoop Touchpad Speed Levels
uint ctrlAlt = NativeInterop.MOD_CONTROL | NativeInterop.MOD_ALT | NativeInterop.MOD_NOREPEAT;
NativeInterop.RegisterHotKey(hwnd, HOTKEY_ID_SPEED_0, ctrlAlt, 0x30); // D0
NativeInterop.RegisterHotKey(hwnd, HOTKEY_ID_SPEED_1, ctrlAlt, 0x31); // D1
NativeInterop.RegisterHotKey(hwnd, HOTKEY_ID_SPEED_2, ctrlAlt, 0x32); // D2
NativeInterop.RegisterHotKey(hwnd, HOTKEY_ID_SPEED_3, ctrlAlt, 0x33); // D3
}
}
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == NativeInterop.WM_NCCALCSIZE && wParam != IntPtr.Zero)
{
handled = true;
return IntPtr.Zero;
}
if (msg == NativeInterop.WM_MOUSEACTIVATE)
{
handled = true;
return new IntPtr(NativeInterop.MA_NOACTIVATE);
}
if (msg == NativeInterop.APPBAR_CALLBACK_MSG && wParam.ToInt32() == NativeInterop.ABN_POSCHANGED)
{
if (_rewriteTooltipEnabled)
{
NativeInterop.HandleAppBarPosChanged(hwnd);
}
handled = true;
return IntPtr.Zero;
}
if (msg == NativeInterop.WM_HOTKEY)
{
int id = wParam.ToInt32();
if (id == HOTKEY_ID_F8 || id == HOTKEY_ID_CTRL_SHIFT_SPACE)
{
handled = true;
_ = ToggleDictationAsync();
}
else if (id is >= HOTKEY_ID_SPEED_0 and <= HOTKEY_ID_SPEED_3)
{
handled = true;
int level = id - HOTKEY_ID_SPEED_0;
SetCursorLoopLevelOnBar(level);
}
}
return IntPtr.Zero;
}
public async Task ToggleDictationAsync()
{
if (_isListening)
{
await StopDictationAsync();
}
else
{
await StartDictationAsync();
}
}
public async Task StartDictationAsync()
{
if (_isListening)
return;
string? apiKey = NativeInterop.ReadApiKeyFromVault();
if (string.IsNullOrWhiteSpace(apiKey))
{
_statusDot.Fill = BrushRedLive;
_statusText.Text = "CHAVE AUSENTE NO COFRE • Copie a chave (Ctrl+C) e importe pelo ícone da bandeja";
return;
}
_cachedApiKey = apiKey;
_isListening = true;
_activeCursorInterim = string.Empty;
_lastAutoSealedText = string.Empty;
_needsLeadingSpace = false;
if (_rewriteTooltipEnabled && !IsVisible)
Show();
// Update UI to active listening state (True Dark border without blue frame)
bool pcLoopback = _cursorSettings.SystemAudioLoopbackEnabled;
bool pcTypeCursor = _cursorSettings.SystemAudioLoopbackTypeInCursor;
_mic.UseSystemLoopback = pcLoopback;
_micButton.Background = new SolidColorBrush(Color.FromRgb(220, 38, 38)); // #DC2626
_micButtonLabel.Text = (_isCompact || _rewriteTooltipEnabled) ? "⏹️ F8" : "⏹️ Parar (F8)";
_outerBorder.BorderBrush = BrushDarkBorder;
_statusDot.Fill = BrushRedLive;
_statusText.Text = pcLoopback
? (pcTypeCursor
? "🎧 OUVINDO PC (DIGITANDO NO CURSOR + RESUMO) • Transcrevendo som do PC..."
: "🎧 OUVINDO PC (SÓ RESUMO • SEM DIGITAR NO CURSOR) • Montando Linha do Tempo...")
: "OUVINDO AO VIVO • Qualidade máxima sem reescrita (gemini-3.5-transcribe-live)";
_livePreviewText.Text = pcLoopback
? "🎧 Escutando o som do Windows... reproduza um áudio ou vídeo."
: "Estou ouvindo... fale agora.";
_livePreviewText.Foreground = BrushWhiteText;
RefreshTrayIconVisual();
try
{
// Start microphone immediately with 40ms frames for clean acoustic context
_mic.Start(chunkMs: 40);
await _gemini.StartSessionAsync(apiKey, "pt-BR");
}
catch (Exception ex)
{
_isListening = false;
_mic.Stop();
ResetIdleVisuals($"Erro ao iniciar: {ex.Message}");
}
}
public async Task StopDictationAsync()
{
if (!_isListening)
return;
_isListening = false;
_statusText.Text = "FINALIZANDO ÚLTIMAS PALAVRAS...";
// Capture a brief 180ms tail so final syllable is never clipped
await Task.Delay(180);
_mic.Stop();
ResetWaveformBars();
await _gemini.StopAndFlushAsync();
_rewriter.FlushPendingTimelineSegment(_cachedApiKey, _cursorSettings.SystemAudioLoopbackEnabled);
ResetIdleVisuals($"PRONTO • {_wordsTypedCount} palavras digitadas • Aperte F8 para falar");
}
private static string GetConversationStatePath()
{
string dir = System.IO.Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"PROJETOS_RUNTIME",
"voz-windows");
Directory.CreateDirectory(dir);
return System.IO.Path.Combine(dir, "last_conversation_state.json");
}
private void SaveConversationState(RewriteVariations v)
{
try
{
if (string.IsNullOrWhiteSpace(v.RawOriginal))
return;
string json = System.Text.Json.JsonSerializer.Serialize(v);
File.WriteAllText(GetConversationStatePath(), json, Encoding.UTF8);
}
catch { }
}
private void TryRestoreLastConversationState()
{
try
{
string path = GetConversationStatePath();
if (!File.Exists(path))
return;
string json = File.ReadAllText(path, Encoding.UTF8);
var restored = System.Text.Json.JsonSerializer.Deserialize<RewriteVariations>(json);
if (restored != null && !string.IsNullOrWhiteSpace(restored.RawOriginal))
{
if (string.Equals(restored.DiretaCoesa, restored.FormalPolida, StringComparison.OrdinalIgnoreCase))
{
restored = GeminiRewriteClient.BuildLocalSixVariations(
restored.RawOriginal,
isAiRefined: true);
}
// Store the last session's message inside '⏪ Anterior' so the active panel starts 100% clean without residue!
_previousArchivedVariations = restored;
_rewriteDeck.ResetDisplay();
_rewriteDeck.SetPreviousBackupAvailable(true);
}
}
catch { }
}
private void ArchiveAndAutoClearForNewConversation(
bool updateDeckImmediately,
string? customReason = null,
bool cutOffServerTurn = true)
{
if (_latestVariationsSnapshot != null && !string.IsNullOrWhiteSpace(_latestVariationsSnapshot.RawOriginal))
{
_previousArchivedVariations = _latestVariationsSnapshot;
}
else if (!string.IsNullOrWhiteSpace(_currentBlockCommittedText))
{
_previousArchivedVariations = GeminiRewriteClient.BuildLocalSixVariations(
_currentBlockCommittedText,
isAiRefined: true);
}
_latestVariationsSnapshot = null;
_hasAppliedInCurrentCycle = false;
_lastAppliedUtc = DateTime.MinValue;
_currentBlockCommittedText = string.Empty;
_activeCursorInterim = string.Empty;
_lastAutoSealedText = string.Empty;
_needsLeadingSpace = false;
if (cutOffServerTurn)
{
_gemini.CutOffServerTurn();
}
_rewriter.ResetMemoryCache();
DeleteSavedConversationState();
bool hasBackup = _previousArchivedVariations != null;
if (updateDeckImmediately)
{
_rewriteDeck.ShowAutoClearedReadyForNewSpeech(hasBackup, customReason);
_livePreviewText.Text = customReason ?? "✨ Conversa limpa automaticamente • Fale a próxima mensagem";
_livePreviewText.Foreground = BrushGreenReady;
_statusText.Text = "✨ PAINEL LIMPO AUTOMATICAMENTE • PRONTO PARA NOVA CONVERSA";
}
else
{
_rewriteDeck.ResetDisplay();
_rewriteDeck.SetPreviousBackupAvailable(hasBackup);
}
}
private void RestorePreviousArchivedConversation()