-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
966 lines (881 loc) · 40.7 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
966 lines (881 loc) · 40.7 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
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using AndroidWidget.Models;
using AndroidWidget.Presentation.Media;
using AndroidWidget.Presentation.Notifications;
using AndroidWidget.Presentation.Screenshots;
using AndroidWidget.Presentation.Transfers;
using AndroidWidget.Services;
using Microsoft.Win32;
namespace AndroidWidget;
public partial class MainWindow : Window
{
public event EventHandler<IReadOnlyList<AndroidDevice>>? DevicesUpdated;
private const double CompactWidth = 258;
private const double CompactHeight = 392;
private const double CompactMinWidth = 230;
private readonly IAndroidDeviceService _devicesService;
private readonly ISettingsService _settings;
private readonly IDesktopIntegration _desktop;
private readonly IAppLogger _logger;
private readonly ScreenshotStorage _screenshots;
private readonly RecordingStorage _recordings;
private readonly TransferQueueService _transfers;
private readonly PhotoImportService _photoImport;
private readonly ICompanionService _companion;
private readonly CompanionCoordinator _companionCoordinator;
private readonly DispatcherTimer _refreshTimer;
private readonly DispatcherTimer _recordingTimer;
private readonly DispatcherTimer _operationBubbleTimer;
private readonly NotificationBubbleStack _smsBubbles = new();
private readonly CancellationTokenSource _lifetime = new();
private IReadOnlyList<AndroidDevice> _devices = Array.Empty<AndroidDevice>();
private AndroidDevice? _activeDevice;
private string? _boundSerial;
private bool _refreshing;
private bool _menuOpen;
private bool _operationInProgress;
private bool _recordingWasActive;
private string? _recordingSerial;
private string? _recordingPath;
private string? _operationBubblePath;
public MainWindow(IAndroidDeviceService devicesService, ISettingsService settings,
IDesktopIntegration desktop, IAppLogger logger, ScreenshotStorage screenshots,
RecordingStorage recordings, TransferQueueService transfers, PhotoImportService photoImport,
ICompanionService companion, CompanionCoordinator companionCoordinator)
{
_devicesService = devicesService;
_settings = settings;
_desktop = desktop;
_logger = logger;
_screenshots = screenshots;
_recordings = recordings;
_transfers = transfers;
_photoImport = photoImport;
_companion = companion;
_companionCoordinator = companionCoordinator;
_companionCoordinator.LinkChanged += CompanionLinkChanged;
_companionCoordinator.MessageReceived += CompanionMessageReceived;
_logger.Write("MainWindow constructor begin");
InitializeComponent();
_logger.Write("MainWindow XAML initialized");
_refreshTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(3) };
_refreshTimer.Tick += async (_, _) => await RefreshDevicesAsync();
_recordingTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(400) };
_recordingTimer.Tick += (_, _) => MonitorRecording();
_operationBubbleTimer = new DispatcherTimer();
_operationBubbleTimer.Tick += (_, _) => HideOperationBubble();
SmsBubbleItems.ItemsSource = _smsBubbles.Items;
_smsBubbles.Changed += SmsBubblesChanged;
_settings.Changed += SettingsChanged;
_transfers.Changed += TransfersChanged;
_photoImport.PhotoDetected += PhotoDetected;
IsVisibleChanged += (_, _) =>
{
if (!IsVisible)
{
ToggleActionPanel(false);
ClearSmsBubbles();
HideOperationBubble();
}
else
RefreshSmsBubbleVisibility();
};
}
private async void Window_Loaded(object sender, RoutedEventArgs e)
{
_logger.Write("MainWindow loaded");
RestoreSettings();
var companionHost = await _companionCoordinator.StartAsync(_lifetime.Token);
if (!companionHost.IsSuccess)
SetOperationStatus($"Не удалось запустить Companion Host: {companionHost.BestMessage}", true);
await RefreshDevicesAsync();
_refreshTimer.Start();
_recordingTimer.Start();
}
private void Window_Closing(object? sender, System.ComponentModel.CancelEventArgs e)
{
if (System.Windows.Application.Current is App app && !app.IsExiting)
{
e.Cancel = true;
app.HideToTray();
return;
}
_refreshTimer.Stop();
_recordingTimer.Stop();
_operationBubbleTimer.Stop();
_smsBubbles.Changed -= SmsBubblesChanged;
_smsBubbles.Dispose();
_settings.Changed -= SettingsChanged;
_transfers.Changed -= TransfersChanged;
_photoImport.PhotoDetected -= PhotoDetected;
_lifetime.Cancel();
_lifetime.Dispose();
_companionCoordinator.LinkChanged -= CompanionLinkChanged;
_companionCoordinator.MessageReceived -= CompanionMessageReceived;
SaveSettings();
}
private async Task RefreshDevicesAsync(bool force = false)
{
if (_refreshing || (_operationInProgress && !force))
return;
_refreshing = true;
try
{
var discovered = await _devicesService.GetDevicesAsync(_lifetime.Token);
_companionCoordinator.RetainAdbRoutes(discovered.Select(device => device.Serial));
foreach (var installedDevice in discovered.Where(device =>
device.State == DeviceConnectionState.Online &&
device.CompanionState.IsInstalled()))
await _companionCoordinator.EnsureAdbRouteAsync(installedDevice.Serial, _lifetime.Token);
var devices = discovered.Select(device =>
{
var link = _companionCoordinator.GetLinkState(device.Serial);
return device with
{
IsCompanionConnected = link.IsConnected,
CompanionNotificationAccess = link.HasNotificationAccess
};
}).ToList();
_devices = devices;
var selected = _boundSerial is not null
? devices.FirstOrDefault(device => device.Serial == _boundSerial)
: devices.FirstOrDefault(device => device.State == DeviceConnectionState.Online)
?? devices.FirstOrDefault();
SetActiveDevice(selected);
DevicesUpdated?.Invoke(this, devices);
_ = _photoImport.ScanAsync(devices, _lifetime.Token);
}
catch (OperationCanceledException) { }
catch (Exception ex)
{
_devices = Array.Empty<AndroidDevice>();
SetActiveDevice(null, ex.Message);
DevicesUpdated?.Invoke(this, _devices);
}
finally
{
_refreshing = false;
}
}
private void CompanionLinkChanged(object? sender, CompanionLinkState state) => Dispatcher.BeginInvoke(() =>
{
var changed = false;
_devices = _devices.Select(device =>
{
if (device.Serial != state.Serial)
return device;
changed = true;
return device with
{
IsCompanionConnected = state.IsConnected,
CompanionNotificationAccess = state.HasNotificationAccess
};
}).ToList();
if (!changed)
return;
if (_activeDevice?.Serial == state.Serial)
SetActiveDevice(_devices.First(device => device.Serial == state.Serial));
DevicesUpdated?.Invoke(this, _devices);
});
private void CompanionMessageReceived(object? sender, CompanionPhoneMessage received) =>
Dispatcher.BeginInvoke(() =>
{
if (!_settings.Current.ShowSmsBubbles)
return;
var changed = false;
_devices = _devices.Select(device =>
{
if (device.Serial != received.Serial)
return device;
changed = true;
return device with { LatestMessage = received.Message };
}).ToList();
if (!changed)
return;
if (_activeDevice?.Serial == received.Serial)
SetActiveDevice(_devices.First(device => device.Serial == received.Serial));
DevicesUpdated?.Invoke(this, _devices);
});
private void SetActiveDevice(AndroidDevice? device, string? error = null)
{
_activeDevice = device;
if (device is null)
{
ClearSmsBubbles();
PowerStateOverlay.Visibility = Visibility.Collapsed;
AuthorizationOverlay.Visibility = Visibility.Collapsed;
DeviceNameText.Text = "Устройство не найдено";
ConnectionText.Text = "Подключите USB и разрешите отладку";
BatteryText.Text = "—";
BatteryBar.Value = 0;
DropHintText.Text = "Ожидаю Android по ADB";
StatusText.Text = error ?? "Проверьте USB debugging или Wi-Fi ADB";
PanelStatusText.Text = error ?? "Нет подключённых устройств";
UpdateCompanionUi(null);
return;
}
ApplyDeviceSkin(device);
var authorizationRequired = device.State == DeviceConnectionState.Unauthorized;
AuthorizationOverlay.Visibility = authorizationRequired ? Visibility.Visible : Visibility.Collapsed;
if (authorizationRequired)
PhoneShell.BorderBrush = new SolidColorBrush(Color.FromRgb(255, 184, 77));
DeviceNameText.Text = device.DisplayName;
ConnectionText.Text = $"{device.ConnectionLabel} · Android {device.AndroidVersion}";
BatteryText.Text = device.BatteryPercent is int battery ? $"{battery}%" : "—";
BatteryBar.Value = device.BatteryPercent ?? 0;
BatteryBar.Foreground = new SolidColorBrush(device.BatteryPercent switch
{
< 20 => Color.FromRgb(255, 105, 105),
< 45 => Color.FromRgb(255, 190, 92),
_ => Color.FromRgb(114, 216, 162)
});
var sleepingOrLocked = device.State == DeviceConnectionState.Online && (!device.IsScreenOn || device.IsLocked);
PowerStateOverlay.Visibility = sleepingOrLocked ? Visibility.Visible : Visibility.Collapsed;
MainLockIcon.Visibility = sleepingOrLocked && device.IsLocked ? Visibility.Visible : Visibility.Collapsed;
MainPowerIcon.Visibility = sleepingOrLocked && !device.IsLocked ? Visibility.Visible : Visibility.Collapsed;
PowerStateText.Text = device.IsLocked ? "Телефон заблокирован" : "Экран выключен";
switch (device.State)
{
case DeviceConnectionState.Online:
DropHintText.Text = "Перетащите файл или APK";
StatusText.Text = _operationInProgress ? StatusText.Text : "Нажмите, чтобы открыть действия";
PanelStatusText.Text = _operationInProgress ? PanelStatusText.Text : $"Подключено: {device.Serial}";
break;
case DeviceConnectionState.Unauthorized:
DropHintText.Text = "Подтвердите RSA-ключ на телефоне";
StatusText.Text = "ADB ожидает разрешение отладки";
PanelStatusText.Text = "Устройство не авторизовано";
break;
default:
DropHintText.Text = "Устройство недоступно";
StatusText.Text = "Переподключите кабель или Wi-Fi ADB";
PanelStatusText.Text = "ADB: устройство offline";
break;
}
UpdateCompanionUi(device);
if (!_settings.Current.ShowSmsBubbles)
ClearSmsBubbles();
else if (CanShowMessageBubble && device.LatestMessage is not null)
ShowSmsBubble(device.LatestMessage);
}
private AndroidDevice? RequireOnlineDevice()
{
if (_activeDevice?.State == DeviceConnectionState.Online)
return _activeDevice;
SetOperationStatus("Сначала подключите и авторизуйте Android-устройство", true);
return null;
}
private void ApplyDeviceSkin(AndroidDevice device)
{
var skin = PhoneSkinResolver.Resolve(device);
var accent = new SolidColorBrush(skin.Accent);
PhoneShell.CornerRadius = new CornerRadius(skin.ShellRadius);
PhoneShell.Background = new SolidColorBrush(skin.Body);
PhoneShell.BorderBrush = accent;
PhoneBezelGrid.Margin = skin.Bezel;
PhoneScreen.CornerRadius = new CornerRadius(skin.ScreenRadius);
SkinDeviceBadge.BorderBrush = accent;
SkinAndroidFace.Fill = accent;
SkinAntennaLeft.Fill = accent;
SkinAntennaRight.Fill = accent;
SkinPowerButton.Background = accent;
SkinVolumeButton.Background = accent;
SkinPowerButton.Visibility = skin.HasSideButtons ? Visibility.Visible : Visibility.Collapsed;
SkinVolumeButton.Visibility = skin.HasSideButtons ? Visibility.Visible : Visibility.Collapsed;
ApplyCameraCutout(skin.Camera);
PhoneShell.ToolTip = $"Скин: {skin.Family}\n{device.Manufacturer} {device.Model}";
}
private void ApplyCameraCutout(CameraCutout camera)
{
SkinCameraCutout.Visibility = camera == CameraCutout.None ? Visibility.Collapsed : Visibility.Visible;
SkinCameraCutout.Width = camera == CameraCutout.Pill ? 22 : 7;
SkinCameraCutout.Height = 7;
SkinCameraCutout.CornerRadius = new CornerRadius(4);
SkinCameraCutout.HorizontalAlignment = camera == CameraCutout.LeftPunch
? HorizontalAlignment.Left
: HorizontalAlignment.Center;
SkinCameraCutout.Margin = camera == CameraCutout.LeftPunch
? new Thickness(28, 6, 0, 0)
: new Thickness(0, 6, 0, 0);
}
private void Phone_DragEnter(object sender, DragEventArgs e)
{
var valid = e.Data.GetDataPresent(DataFormats.FileDrop) && _activeDevice?.State == DeviceConnectionState.Online;
e.Effects = valid ? DragDropEffects.Copy : DragDropEffects.None;
DropOverlay.Visibility = valid ? Visibility.Visible : Visibility.Collapsed;
e.Handled = true;
}
private void Phone_DragLeave(object sender, DragEventArgs e) => DropOverlay.Visibility = Visibility.Collapsed;
private void Phone_Drop(object sender, DragEventArgs e)
{
DropOverlay.Visibility = Visibility.Collapsed;
var device = RequireOnlineDevice();
if (device is null || !e.Data.GetDataPresent(DataFormats.FileDrop))
return;
var paths = (string[]?)e.Data.GetData(DataFormats.FileDrop) ?? Array.Empty<string>();
paths = paths.Where(path => File.Exists(path) || Directory.Exists(path)).ToArray();
if (paths.Length == 0)
return;
foreach (var path in paths)
_transfers.EnqueueUpload(device.Serial, path);
SetOperationStatus(paths.Length == 1
? "Передача добавлена в очередь"
: $"В очередь добавлено: {paths.Length}");
}
private void DragHandle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (e.ButtonState == MouseButtonState.Pressed && e.OriginalSource is not Button)
DragMove();
}
private void ResizeGrip_DragDelta(object sender, DragDeltaEventArgs e)
{
var workArea = SystemParameters.WorkArea;
var maximumWidth = Math.Min(MaxWidth, workArea.Right - Left);
var maximumHeight = Math.Min(MaxHeight, workArea.Bottom - Top);
Width = Math.Clamp(Width + e.HorizontalChange, MinWidth, Math.Max(MinWidth, maximumWidth));
Height = Math.Clamp(Height + e.VerticalChange, MinHeight, Math.Max(MinHeight, maximumHeight));
}
private void ResizeGrip_DragCompleted(object sender, DragCompletedEventArgs e) => SaveSettings();
private void PhoneScreen_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (e.OriginalSource is Button)
return;
ToggleActionPanel();
}
private void MiniModeButton_Click(object sender, RoutedEventArgs e)
{
SaveSettings();
((App)System.Windows.Application.Current).EnterMiniMode();
}
private void SettingsButton_Click(object sender, RoutedEventArgs e) =>
((App)System.Windows.Application.Current).ShowSettings();
private void ToggleActionPanel(bool? open = null)
{
var nextOpen = open ?? !_menuOpen;
if (nextOpen == _menuOpen)
return;
_menuOpen = nextOpen;
ActionPopup.IsOpen = _menuOpen;
}
private void CollapsePanel_Click(object sender, RoutedEventArgs e) => ToggleActionPanel(false);
private void CloseButton_Click(object sender, RoutedEventArgs e) =>
((App)System.Windows.Application.Current).HideToTray();
private void PinButton_Click(object sender, RoutedEventArgs e)
{
Topmost = !Topmost;
_settings.Update(settings => settings with { Topmost = Topmost });
PinButton.Foreground = new SolidColorBrush(Topmost ? Color.FromRgb(138, 115, 255) : Color.FromRgb(120, 132, 163));
SetOperationStatus(Topmost ? "Виджет закреплён поверх окон" : "Режим «поверх окон» выключен");
}
public void SelectDevice(string serial)
{
_boundSerial = serial;
var selected = _devices.FirstOrDefault(device => device.Serial == serial);
if (selected is null)
{
SetActiveDevice(null);
return;
}
SetActiveDevice(selected);
}
private void ScreenButton_Click(object sender, RoutedEventArgs e)
{
var device = RequireOnlineDevice();
if (device is null)
return;
var result = _devicesService.StartScreenMirroring(device.Serial, _settings.Current.ScrcpyPreset);
if (result.IsSuccess)
SetOperationStatus("scrcpy запущен ✓");
else
SetOperationStatus(result.BestMessage, true);
}
private void SmsBubble_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (sender is FrameworkElement { DataContext: NotificationBubbleItem item })
_smsBubbles.Remove(item);
e.Handled = true;
}
private void ShowSmsBubble(PhoneMessage message)
{
// A WPF Popup can remain visible even when its owning window is hidden.
// In mini mode the per-device mini window owns notifications, so the
// background main window must never open a duplicate popup.
if (!CanShowMessageBubble)
{
ClearSmsBubbles();
return;
}
_smsBubbles.Add(message);
RefreshSmsBubbleVisibility();
}
private bool CanShowMessageBubble => IsVisible && WindowState != WindowState.Minimized;
private TimeSpan NotificationDisplayDuration => TimeSpan.FromSeconds(
Math.Clamp(_settings.Current.NotificationDisplaySeconds, 5, 60));
private void SmsBubblesChanged(object? sender, EventArgs e) => RefreshSmsBubbleVisibility();
private void RefreshSmsBubbleVisibility()
{
var show = CanShowMessageBubble && !OperationBubblePopup.IsOpen &&
_settings.Current.ShowSmsBubbles && _smsBubbles.Items.Count > 0;
SmsBubblePopup.IsOpen = show;
if (show)
_smsBubbles.Start(NotificationDisplayDuration);
else
_smsBubbles.Pause();
}
private void ClearSmsBubbles()
{
SmsBubblePopup.IsOpen = false;
_smsBubbles.Clear();
}
private void SettingsChanged(object? sender, EventArgs e) => Dispatcher.BeginInvoke(() =>
{
if (!_settings.Current.ShowSmsBubbles)
{
ClearSmsBubbles();
return;
}
_smsBubbles.Restart(NotificationDisplayDuration);
RefreshSmsBubbleVisibility();
});
private void TransfersChanged(object? sender, EventArgs e) => Dispatcher.BeginInvoke(() =>
{
if (_activeDevice is null)
return;
var job = _transfers.Snapshot.FirstOrDefault(item => item.DeviceSerial == _activeDevice.Serial);
if (job is null)
return;
var message = job.State switch
{
TransferJobState.Queued => $"В очереди: {job.Name}",
TransferJobState.Running when job.Progress is double progress =>
$"{job.Name}: {progress:P0}",
TransferJobState.Running => $"Выполняется: {job.Name}",
TransferJobState.Completed => $"Готово: {job.Name} ✓",
TransferJobState.Cancelled => $"Отменено: {job.Name}",
_ => $"Ошибка {job.Name}: {job.Message}"
};
SetOperationStatus(message, job.State == TransferJobState.Failed);
});
private void PhotoDetected(object? sender, PhotoImportEvent e) => Dispatcher.BeginInvoke(() =>
{
if (_activeDevice?.Serial != e.DeviceSerial)
return;
SetOperationStatus(e.Message, e.Message.StartsWith("Не удалось", StringComparison.Ordinal));
});
private void FilesButton_Click(object sender, RoutedEventArgs e)
{
var device = RequireOnlineDevice();
if (device is null)
return;
new RemoteFilesWindow(_devicesService, _desktop, _transfers, device) { Owner = this }.Show();
SetOperationStatus("Открыт ADB-браузер файлов");
}
private async void ScreenshotButton_Click(object sender, RoutedEventArgs e)
{
var device = RequireOnlineDevice();
if (device is null)
return;
await RunOperationAsync(async token =>
{
SetOperationStatus("Делаю снимок экрана…");
var file = _screenshots.CreateFilePath(device);
var result = await _devicesService.TakeScreenshotAsync(device.Serial, file, token);
if (!result.IsSuccess)
throw new InvalidOperationException(result.BestMessage);
SetOperationStatus($"Сохранено: {Path.GetFileName(file)} ✓");
var reveal = _desktop.RevealFile(file);
if (!reveal.IsSuccess)
throw new InvalidOperationException(reveal.BestMessage);
});
}
private void InstallButton_Click(object sender, RoutedEventArgs e)
{
var device = RequireOnlineDevice();
if (device is null)
return;
var dialog = new OpenFileDialog { Filter = "Android package (*.apk)|*.apk", Multiselect = true };
if (dialog.ShowDialog(this) != true)
return;
foreach (var path in dialog.FileNames)
_transfers.EnqueueUpload(device.Serial, path);
SetOperationStatus(dialog.FileNames.Length == 1
? "APK добавлен в очередь установки"
: $"APK добавлены в очередь: {dialog.FileNames.Length}");
}
private async void CompanionButton_Click(object sender, RoutedEventArgs e)
{
var device = RequireOnlineDevice();
if (device is null)
return;
var updateAvailable = device.CompanionState == CompanionInstallationState.UpdateAvailable;
if (device.CompanionState.IsInstalled() && !updateAvailable)
{
if (device.IsCompanionConnected)
{
var open = await _companionCoordinator.OpenCompanionAsync(device.Serial, _lifetime.Token);
SetOperationStatus(open.IsSuccess
? "Компаньон открыт на телефоне"
: open.BestMessage, !open.IsSuccess);
return;
}
await ShowPairingAsync(device);
return;
}
if (!_companion.IsInstallerAvailable)
{
SetOperationStatus("APK компаньона не входит в эту desktop-сборку", true);
return;
}
var consent = MessageBox.Show(this, updateAvailable
? $"Обновить Device Widget Companion на «{device.DisplayName}»?\n\n" +
"Новая версия заменит установленную, сохранив сопряжение и выданные разрешения. " +
"Android может попросить подтвердить обновление на телефоне."
: $"Установить Device Widget Companion на «{device.DisplayName}»?\n\n" +
"Установка начнётся только после вашего подтверждения. Доступ к уведомлениям приложение " +
"попросит отдельно на телефоне — автоматически он не выдаётся.",
updateAvailable ? "Обновление компаньона" : "Установка компаньона",
MessageBoxButton.YesNo, MessageBoxImage.Question,
MessageBoxResult.No);
if (consent != MessageBoxResult.Yes)
{
SetOperationStatus(updateAvailable
? "Обновление компаньона отменено"
: "Установка компаньона отменена");
return;
}
await RunOperationAsync(async token =>
{
SetOperationStatus(updateAvailable
? "Обновляю Device Widget Companion…"
: "Устанавливаю Device Widget Companion…");
var result = await _companion.InstallAsync(device.Serial, token);
if (result.FailureKind == CompanionInstallFailureKind.SignatureMismatch)
{
var reinstallConsent = MessageBox.Show(this,
"Android отклонил обновление: старая тестовая версия подписана другим ключом.\n\n" +
"Переустановить companion? Его локальное сопряжение и доступ к уведомлениям будут сброшены, " +
"после установки их потребуется включить снова.",
"Требуется переустановка companion", MessageBoxButton.YesNo,
MessageBoxImage.Warning, MessageBoxResult.No);
if (reinstallConsent != MessageBoxResult.Yes)
{
SetOperationStatus("Обновление отменено: подписи APK различаются", true);
return;
}
SetOperationStatus("Переустанавливаю companion с новым ключом подписи…");
var reinstall = await _companion.ReinstallAsync(device.Serial, token);
if (!reinstall.IsSuccess)
throw new InvalidOperationException(reinstall.BestMessage);
SetOperationStatus("Компаньон переустановлен · выполните сопряжение и разрешите уведомления заново");
await RefreshDevicesAsync(force: true);
return;
}
if (!result.IsSuccess)
throw new InvalidOperationException(result.BestMessage);
SetOperationStatus(updateAvailable
? "Компаньон обновлён и открыт на телефоне"
: "Компаньон установлен и открыт на телефоне · нажмите «Сопрячь»");
await RefreshDevicesAsync(force: true);
});
}
private async Task ShowPairingAsync(AndroidDevice device)
{
SetOperationStatus("Создаю защищённую ссылку сопряжения…");
var pairing = await _companionCoordinator.CreateAndOpenPairingAsync(device.Serial, _lifetime.Token);
if (pairing.Session is null)
{
SetOperationStatus(pairing.LaunchResult.BestMessage, true);
return;
}
var window = new CompanionPairingWindow(device.Serial, device.DisplayName, pairing,
_companionCoordinator)
{
Owner = this
};
window.Show();
SetOperationStatus(pairing.LaunchResult.IsSuccess
? "Ссылка сопряжения создана и открыта на телефоне"
: "Ссылка создана · откройте или скопируйте её из окна сопряжения",
!pairing.LaunchResult.IsSuccess);
}
private async void RecordButton_Click(object sender, RoutedEventArgs e)
{
var device = RequireOnlineDevice();
if (device is null)
return;
if (_devicesService.IsScreenRecording(device.Serial))
{
await StopRecordingAsync(device.Serial);
return;
}
var file = _recordings.CreateFilePath(device);
if (_settings.Current.ShowScreenRecordingGuide)
{
var guide = new ScreenRecordingWindow(device, _settings, file) { Owner = this };
if (guide.ShowDialog() != true)
return;
}
var result = _devicesService.StartScreenRecording(device.Serial, file, _settings.Current.ScrcpyPreset);
if (!result.IsSuccess)
{
SetOperationStatus(result.BestMessage, true);
return;
}
_recordingSerial = device.Serial;
_recordingPath = file;
_recordingWasActive = true;
UpdateRecordingUi();
SetOperationStatus("Идёт запись экрана · нажмите «Остановить» для сохранения");
}
private async Task StopRecordingAsync(string serial)
{
var path = _recordingPath ?? _devicesService.GetScreenRecordingPath(serial);
_recordingWasActive = false;
RecordButton.IsEnabled = false;
SetOperationStatus("Завершаю запись…");
var result = await Task.Run(() => _devicesService.StopScreenRecording(serial));
RecordButton.IsEnabled = true;
if (!result.IsSuccess && _devicesService.IsScreenRecording(serial))
{
_recordingWasActive = true;
SetOperationStatus(result.BestMessage, true);
return;
}
_recordingSerial = null;
_recordingPath = null;
UpdateRecordingUi();
CompleteRecording(path);
}
private void MonitorRecording()
{
if (_recordingSerial is null && _activeDevice is { } current &&
_devicesService.IsScreenRecording(current.Serial))
{
_recordingSerial = current.Serial;
_recordingPath = _devicesService.GetScreenRecordingPath(current.Serial);
_recordingWasActive = true;
}
if (_recordingSerial is { } serial && _recordingWasActive &&
!_devicesService.IsScreenRecording(serial))
{
var path = _recordingPath;
_recordingSerial = null;
_recordingPath = null;
_recordingWasActive = false;
CompleteRecording(path);
}
UpdateRecordingUi();
}
private void UpdateRecordingUi()
{
var recording = _activeDevice is { } device && _devicesService.IsScreenRecording(device.Serial);
RecordButtonText.Text = recording ? "Остановить" : "Запись";
RecordTileIcon.Background = new SolidColorBrush(recording
? Color.FromRgb(213, 75, 67)
: Color.FromRgb(195, 71, 85));
RecordButton.ToolTip = recording
? "Остановить запись экрана и сохранить MKV"
: "Настроить и запустить запись экрана в MKV";
}
private void CompleteRecording(string? path)
{
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
{
SetOperationStatus("Запись завершена, но видеофайл не найден", true);
return;
}
SetOperationStatus($"Видео сохранено: {Path.GetFileName(path)}");
ShowOperationBubble(path);
}
private void ShowOperationBubble(string path)
{
if (!CanShowMessageBubble)
return;
_operationBubblePath = path;
OperationBubbleMessageText.Text = Path.GetFileName(path);
SmsBubblePopup.IsOpen = false;
_smsBubbles.Pause();
OperationBubblePopup.IsOpen = true;
_operationBubbleTimer.Stop();
_operationBubbleTimer.Interval = NotificationDisplayDuration;
_operationBubbleTimer.Start();
}
private void OperationBubble_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (_operationBubblePath is { } path)
{
var result = _desktop.RevealFile(path);
if (!result.IsSuccess)
SetOperationStatus(result.BestMessage, true);
}
HideOperationBubble();
e.Handled = true;
}
private void HideOperationBubble()
{
_operationBubbleTimer.Stop();
OperationBubblePopup.IsOpen = false;
_operationBubblePath = null;
RefreshSmsBubbleVisibility();
}
private void TransfersButton_Click(object sender, RoutedEventArgs e) =>
new TransferQueueWindow(_transfers) { Owner = this }.Show();
private void WirelessButton_Click(object sender, RoutedEventArgs e) =>
new WirelessPairingWindow(_devicesService) { Owner = this }.Show();
private void ShellButton_Click(object sender, RoutedEventArgs e)
{
var device = RequireOnlineDevice();
if (device is null)
return;
try
{
var result = _devicesService.StartShell(device.Serial);
SetOperationStatus(result.IsSuccess ? "ADB shell открыт" : result.BestMessage, !result.IsSuccess);
}
catch (Exception ex) { SetOperationStatus(ex.Message, true); }
}
private async void ClipboardButton_Click(object sender, RoutedEventArgs e)
{
var device = RequireOnlineDevice();
if (device is null)
return;
if (!Clipboard.ContainsText())
{
SetOperationStatus("В буфере обмена нет текста", true);
return;
}
var text = Clipboard.GetText();
if (text.Length > 1000)
text = text[..1000];
await RunOperationAsync(async token =>
{
SetOperationStatus("Отправляю текст в активное поле телефона…");
var result = await _devicesService.SendTextAsync(device.Serial, text, token);
if (!result.IsSuccess)
throw new InvalidOperationException(result.BestMessage);
SetOperationStatus("Текст отправлен ✓");
});
}
private async void PowerButton_Click(object sender, RoutedEventArgs e)
{
var device = RequireOnlineDevice();
if (device is null)
return;
await RunOperationAsync(async token =>
{
var result = await _devicesService.TogglePowerAsync(device.Serial, token);
if (!result.IsSuccess)
throw new InvalidOperationException(result.BestMessage);
SetOperationStatus("Команда экрана отправлена ✓");
});
}
private void MtpButton_Click(object sender, RoutedEventArgs e)
{
var device = RequireOnlineDevice();
if (device is null)
return;
var result = _desktop.OpenMtpDevice(device);
SetOperationStatus(result.BestMessage, !result.IsSuccess);
}
private async Task RunOperationAsync(Func<CancellationToken, Task> operation)
{
if (_operationInProgress)
{
SetOperationStatus("Дождитесь завершения текущей операции", true);
return;
}
_operationInProgress = true;
try
{
await operation(_lifetime.Token);
}
catch (OperationCanceledException) { }
catch (Exception ex)
{
SetOperationStatus(ex.Message, true);
}
finally
{
_operationInProgress = false;
UpdateCompanionUi(_activeDevice);
}
}
private void UpdateCompanionUi(AndroidDevice? device)
{
var installed = device?.CompanionState.IsInstalled() == true;
var updateAvailable = device?.CompanionState == CompanionInstallationState.UpdateAvailable;
var connected = device?.IsCompanionConnected == true;
var notificationAccess = device?.CompanionNotificationAccess == true;
var online = device?.State == DeviceConnectionState.Online;
CompanionButtonText.Text = updateAvailable
? "Обновить"
: !installed ? "Компаньон" : connected ? "Открыть" : "Сопрячь";
CompanionButton.IsEnabled = online && !_operationInProgress &&
(installed || _companion.IsInstallerAvailable);
CompanionButton.ToolTip = updateAvailable
? "Установить новую версию companion после подтверждения"
: installed
? connected
? "Открыть Device Widget Companion и настройки доступа"
: "Создать код и ссылку сопряжения"
: _companion.IsInstallerAvailable
? "Установить компаньон только после подтверждения"
: "APK компаньона не входит в эту сборку";
CompanionStatusText.Text = updateAvailable
? "Доступно обновление компаньона · нажмите «Обновить»"
: connected && notificationAccess
? "Компаньон сопряжён · уведомления включены"
: connected
? "Компаньон сопряжён · разрешите доступ к уведомлениям на телефоне"
: installed
? "Компаньон установлен · нажмите «Сопрячь»"
: device is null
? "Companion-функции отключены: телефон не подключён"
: device.CompanionState == CompanionInstallationState.Unknown
? "Companion-функции отключены: статус установки не определён"
: !_companion.IsInstallerAvailable
? "Companion-функции отключены: установщик не входит в сборку"
: "Компаньон не установлен · companion-функции отключены";
}
private void SetOperationStatus(string message, bool isError = false)
{
StatusText.Text = message;
PanelStatusText.Text = message;
var brush = isError
? (Brush)FindResource("DangerText")
: (Brush)FindResource("TextSecondary");
StatusText.Foreground = brush;
PanelStatusText.Foreground = brush;
}
private void RestoreSettings()
{
var settings = _settings.Current;
Topmost = settings.Topmost;
PinButton.Foreground = new SolidColorBrush(Topmost ? Color.FromRgb(138, 115, 255) : Color.FromRgb(120, 132, 163));
var workArea = SystemParameters.WorkArea;
Width = Math.Clamp(settings.MainCardWidth ?? CompactWidth, CompactMinWidth,
Math.Max(CompactMinWidth, Math.Min(MaxWidth, workArea.Width)));
Height = Math.Clamp(settings.MainCardHeight ?? CompactHeight, MinHeight,
Math.Max(MinHeight, Math.Min(MaxHeight, workArea.Height)));
Left = settings.Left is double left && left >= workArea.Left && left < workArea.Right - 80
? left : workArea.Right - Width - 30;
Top = settings.Top is double top && top >= workArea.Top && top < workArea.Bottom - 80
? top : workArea.Bottom - Height - 40;
}
private void SaveSettings()
{
_settings.Update(settings => settings with
{
Left = Left,
Top = Top,
Topmost = Topmost,
MainCardWidth = Math.Clamp(Width, CompactMinWidth, MaxWidth),
MainCardHeight = Math.Clamp(Height, MinHeight, MaxHeight)
});
}
}