-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
8330 lines (7855 loc) · 421 KB
/
Copy pathProgram.cs
File metadata and controls
8330 lines (7855 loc) · 421 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
/*
* Android ADB Quick Tools
* Copyright (C) 2026 Liao Ah-Hui (廖阿輝)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License version 3.
* This program is distributed WITHOUT ANY WARRANTY; see LICENSE for details.
* SPDX-License-Identifier: AGPL-3.0-only
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Globalization;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows.Forms;
[assembly: AssemblyTitle("Android ADB 快速工具")]
[assembly: AssemblyDescription("Android ADB 連線確認、APK/XAPK 快速安裝與檔案傳輸工具")]
[assembly: AssemblyCompany("AndroidADBTools")]
[assembly: AssemblyProduct("Android ADB 快速工具")]
[assembly: AssemblyCopyright("Copyright © 2026 廖阿輝")]
[assembly: AssemblyVersion("2.0.7.0")]
[assembly: AssemblyFileVersion("2.0.7.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
namespace AndroidADBTools
{
static class Program
{
[DllImport("user32.dll")]
private static extern bool SetProcessDpiAwarenessContext(IntPtr dpiContext);
[DllImport("user32.dll")]
private static extern bool SetProcessDPIAware();
[STAThread]
static void Main(string[] args)
{
if (args != null && args.Length >= 3 &&
String.Equals(args[0], "--apply-update", StringComparison.OrdinalIgnoreCase))
{
RunSelfUpdate(args);
return;
}
try
{
// DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 = -4.
// This must happen before any WinForms handle is created.
if (!SetProcessDpiAwarenessContext(new IntPtr(-4))) SetProcessDPIAware();
}
catch (EntryPointNotFoundException)
{
SetProcessDPIAware();
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
private static void RunSelfUpdate(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
try
{
int processId;
if (!Int32.TryParse(args[1], out processId) || processId < 0)
throw new InvalidOperationException("更新程序收到無效的主程式識別碼。");
string targetPath = Path.GetFullPath(args[2]);
bool restart = !args.Any(delegate(string value)
{
return String.Equals(value, "--no-restart", StringComparison.OrdinalIgnoreCase);
});
if (processId > 0)
{
try
{
Process running = Process.GetProcessById(processId);
if (!running.WaitForExit(120000))
throw new TimeoutException("等待舊版程式關閉逾時。");
}
catch (ArgumentException) { }
}
string sourcePath = Path.GetFullPath(Application.ExecutablePath);
if (String.Equals(sourcePath, targetPath, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException("更新來源與安裝位置相同,無法安全替換。");
string targetDirectory = Path.GetDirectoryName(targetPath);
if (String.IsNullOrWhiteSpace(targetDirectory))
throw new InvalidOperationException("找不到程式安裝資料夾。");
Directory.CreateDirectory(targetDirectory);
string newPath = targetPath + ".update-new";
string backupPath = targetPath + ".update-backup";
try
{
if (File.Exists(newPath)) File.Delete(newPath);
File.Copy(sourcePath, newPath, true);
if (File.Exists(backupPath)) File.Delete(backupPath);
if (File.Exists(targetPath))
File.Replace(newPath, targetPath, backupPath, true);
else
File.Move(newPath, targetPath);
if (restart)
{
Process.Start(new ProcessStartInfo(targetPath)
{
UseShellExecute = true,
WorkingDirectory = targetDirectory
});
}
try { if (File.Exists(backupPath)) File.Delete(backupPath); } catch { }
}
catch
{
try
{
if (File.Exists(backupPath))
{
if (File.Exists(targetPath)) File.Delete(targetPath);
File.Move(backupPath, targetPath);
}
}
catch { }
throw;
}
}
catch (Exception ex)
{
MessageBox.Show("自動更新無法完成。原本版本將予以保留。\n\n" + ex.Message,
"Android ADB 快速工具更新失敗", MessageBoxButtons.OK, MessageBoxIcon.Error);
Environment.ExitCode = 1;
}
}
}
public sealed class GithubReleaseInfo
{
public string tag_name { get; set; }
public string name { get; set; }
public bool draft { get; set; }
public bool prerelease { get; set; }
public List<GithubReleaseAsset> assets { get; set; }
public GithubReleaseInfo()
{
tag_name = "";
name = "";
assets = new List<GithubReleaseAsset>();
}
}
public sealed class GithubReleaseAsset
{
public string name { get; set; }
public string browser_download_url { get; set; }
public string digest { get; set; }
public long size { get; set; }
public GithubReleaseAsset()
{
name = "";
browser_download_url = "";
digest = "";
}
}
public sealed class AppSettings
{
public string AdbPath { get; set; }
public bool AllowDowngrade { get; set; }
public List<ApkGroup> Groups { get; set; }
public List<string> GroupOrder { get; set; }
public string SelectedGroupId { get; set; }
public int WindowWidth { get; set; }
public int WindowHeight { get; set; }
public bool WindowMaximized { get; set; }
public string DownloadFolder { get; set; }
public bool SkipLargeDownloadFiles { get; set; }
public decimal MaxDownloadFileSizeGb { get; set; }
public string DownloadMode { get; set; }
public bool? IncrementalFolderDownload { get; set; }
public List<DownloadCheckpoint> DownloadCheckpoints { get; set; }
public string SelectedDeviceSerial { get; set; }
public bool InstallToAllDevices { get; set; }
public List<WifiDeviceRecord> WifiDevices { get; set; }
public bool WifiAutoReconnect { get; set; }
public string SpotreadPath { get; set; }
public string SpotreadCorrectionPath { get; set; }
public decimal AutoBrightnessTargetNit { get; set; }
public decimal AutoBrightnessToleranceNit { get; set; }
public AppSettings()
{
AdbPath = "";
Groups = new List<ApkGroup>();
GroupOrder = new List<string>();
SelectedGroupId = "";
DownloadFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Android手機資料下載");
SkipLargeDownloadFiles = true;
MaxDownloadFileSizeGb = 2M;
DownloadMode = "Zip";
IncrementalFolderDownload = true;
DownloadCheckpoints = new List<DownloadCheckpoint>();
SelectedDeviceSerial = "";
WifiDevices = new List<WifiDeviceRecord>();
SpotreadPath = "";
SpotreadCorrectionPath = "";
AutoBrightnessTargetNit = 200M;
AutoBrightnessToleranceNit = 2M;
}
}
public sealed class WifiDeviceRecord
{
public string Host { get; set; }
public int PairingPort { get; set; }
public int DebugPort { get; set; }
public string DisplayName { get; set; }
public DateTime LastConnected { get; set; }
public WifiDeviceRecord()
{
Host = "";
DisplayName = "Android 裝置";
}
public string DebugEndpoint
{
get
{
if (String.IsNullOrWhiteSpace(Host) || DebugPort <= 0) return "";
return MainForm.FormatNetworkEndpoint(Host, DebugPort);
}
}
public override string ToString()
{
string endpoint = DebugEndpoint;
if (String.IsNullOrWhiteSpace(endpoint))
endpoint = String.IsNullOrWhiteSpace(Host) ? "尚未設定偵錯位址" : Host;
string name = String.IsNullOrWhiteSpace(DisplayName) ? "Android 裝置" : DisplayName;
return name + " | " + endpoint;
}
}
public sealed class ApkGroup
{
public string Id { get; set; }
public string Name { get; set; }
public List<ApkEntry> Apks { get; set; }
public bool IsFolderGroup { get; set; }
public string FolderPath { get; set; }
public ApkGroup()
{
Id = Guid.NewGuid().ToString("N");
Name = "新的安裝組合";
Apks = new List<ApkEntry>();
FolderPath = "";
}
public override string ToString()
{
return Name + " (" + (Apks == null ? 0 : Apks.Count) + ")";
}
}
public sealed class ApkEntry
{
public string Path { get; set; }
public ApkEntry() { Path = ""; }
public ApkEntry(string path) { Path = path; }
}
public sealed class AdbResult
{
public int ExitCode { get; set; }
public string Output { get; set; }
public string Error { get; set; }
public bool Started { get; set; }
}
public sealed class DeviceInfo
{
public string Serial { get; set; }
public string State { get; set; }
public string Model { get; set; }
public string Product { get; set; }
public string DisplayName
{
get { return String.IsNullOrWhiteSpace(Model) ? "Android 裝置" : Model; }
}
public bool IsWireless
{
get
{
string serial = Serial ?? "";
return serial.IndexOf(':') >= 0 ||
serial.IndexOf("_adb-tls", StringComparison.OrdinalIgnoreCase) >= 0 ||
serial.StartsWith("adb-", StringComparison.OrdinalIgnoreCase);
}
}
public string ConnectionLabel { get { return IsWireless ? "Wi-Fi" : "USB"; } }
public override string ToString()
{
return DisplayName + " | " + (Serial ?? "") + " | " + ConnectionLabel;
}
}
public sealed class PackageInstallResult
{
public bool Success { get; set; }
public string Output { get; set; }
public PackageInstallResult()
{
Output = "";
}
}
public sealed class ExtractedXapk : IDisposable
{
public string TemporaryDirectory { get; set; }
public List<string> ApkPaths { get; set; }
public List<Tuple<string, string>> ObbFiles { get; set; }
public ExtractedXapk()
{
TemporaryDirectory = "";
ApkPaths = new List<string>();
ObbFiles = new List<Tuple<string, string>>();
}
public void Dispose()
{
try
{
if (!String.IsNullOrWhiteSpace(TemporaryDirectory) && Directory.Exists(TemporaryDirectory))
Directory.Delete(TemporaryDirectory, true);
}
catch { }
}
}
public sealed class CopyDeviceField
{
public string Name { get; private set; }
public string Value { get; private set; }
public CopyDeviceField(string name, string value)
{
Name = name ?? "";
Value = value ?? "";
}
}
public sealed class DeviceInformationField
{
public string Category { get; set; }
public string Name { get; set; }
public string Value { get; set; }
public string Source { get; set; }
public DeviceInformationField()
{
Category = "";
Name = "";
Value = "";
Source = "";
}
}
public sealed class DeviceInformationReport
{
public string DeviceName { get; set; }
public string DeviceSerial { get; set; }
public DateTime GeneratedAt { get; set; }
public List<DeviceInformationField> Fields { get; set; }
public DeviceInformationReport()
{
DeviceName = "Android 裝置";
DeviceSerial = "";
GeneratedAt = DateTime.Now;
Fields = new List<DeviceInformationField>();
}
}
public sealed class DeviceInformationCacheEntry
{
public int SchemaVersion { get; set; }
public string AndroidId { get; set; }
public string SystemSerial { get; set; }
public List<string> AdbSerials { get; set; }
public DateTime SavedAt { get; set; }
public DeviceInformationReport Report { get; set; }
public DeviceInformationCacheEntry()
{
SchemaVersion = 1;
AndroidId = "";
SystemSerial = "";
AdbSerials = new List<string>();
SavedAt = DateTime.Now;
}
}
public sealed class MdnsServiceInfo
{
public string Name { get; set; }
public string ServiceType { get; set; }
public string Host { get; set; }
public int Port { get; set; }
public bool IsPairing
{
get { return (ServiceType ?? "").IndexOf("pairing", StringComparison.OrdinalIgnoreCase) >= 0; }
}
public override string ToString()
{
return (IsPairing ? "配對" : "偵錯") + " | " + MainForm.FormatNetworkEndpoint(Host, Port) +
(String.IsNullOrWhiteSpace(Name) ? "" : " | " + Name);
}
}
public sealed class RemoteFileInfo
{
public string Path { get; set; }
public long Size { get; set; }
public long ModifiedUnixSeconds { get; set; }
}
public sealed class DownloadCheckpoint
{
public string DeviceKey { get; set; }
public string DeviceSerial { get; set; }
public string DeviceModel { get; set; }
public string DestinationFolder { get; set; }
public long LastCompletedUnixSeconds { get; set; }
}
public sealed class DownloadDeviceIdentity
{
public string Key { get; set; }
public string StableId { get; set; }
public string Serial { get; set; }
public string Model { get; set; }
}
public sealed class ModernTabControl : TabControl
{
public ModernTabControl()
{
DrawMode = TabDrawMode.OwnerDrawFixed;
SizeMode = TabSizeMode.Fixed;
Alignment = TabAlignment.Left;
Multiline = true;
ItemSize = new Size(58, 154);
Padding = new Point(0, 0);
SetStyle(ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
}
protected override void OnPaintBackground(PaintEventArgs pevent)
{
pevent.Graphics.Clear(Color.FromArgb(247, 249, 250));
}
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.Clear(Color.FromArgb(247, 249, 250));
for (int i = 0; i < TabPages.Count; i++)
{
DrawItemState state = SelectedIndex == i ? DrawItemState.Selected : DrawItemState.Default;
OnDrawItem(new DrawItemEventArgs(e.Graphics, Font, GetTabRect(i), i, state));
}
Rectangle pageBorder = DisplayRectangle;
pageBorder.Inflate(1, 1);
using (Pen pen = new Pen(Color.FromArgb(217, 224, 229))) e.Graphics.DrawRectangle(pen, pageBorder);
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
Rectangle rect = GetTabRect(e.Index);
rect = new Rectangle(rect.X + 4, rect.Y + 2, rect.Width - 7, rect.Height - 4);
bool selected = SelectedIndex == e.Index;
Color accent = Color.FromArgb(38, 158, 142);
Color fill = selected ? Blend(Color.White, accent, 0.12F) : Color.FromArgb(247, 249, 250);
using (SolidBrush brush = new SolidBrush(fill)) e.Graphics.FillRectangle(brush, rect);
if (selected)
{
using (SolidBrush marker = new SolidBrush(accent))
e.Graphics.FillRectangle(marker, rect.Left, rect.Top + 6, 4, Math.Max(1, rect.Height - 12));
}
Rectangle textRect = new Rectangle(rect.Left + 14, rect.Top, Math.Max(1, rect.Width - 18), rect.Height);
using (SolidBrush textBrush = new SolidBrush(selected ? Color.FromArgb(25, 125, 114) : Color.FromArgb(48, 60, 70)))
using (StringFormat format = new StringFormat { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Center, Trimming = StringTrimming.EllipsisCharacter, FormatFlags = StringFormatFlags.NoWrap })
e.Graphics.DrawString(TabPages[e.Index].Text.Replace("&", ""), Font, textBrush, textRect, format);
}
private static GraphicsPath RoundedPath(Rectangle rect, int radius)
{
int diameter = radius * 2;
GraphicsPath path = new GraphicsPath();
path.AddArc(rect.Left, rect.Top, diameter, diameter, 180, 90);
path.AddArc(rect.Right - diameter, rect.Top, diameter, diameter, 270, 90);
path.AddArc(rect.Right - diameter, rect.Bottom - diameter, diameter, diameter, 0, 90);
path.AddArc(rect.Left, rect.Bottom - diameter, diameter, diameter, 90, 90);
path.CloseFigure();
return path;
}
private static Color Blend(Color baseColor, Color tint, float amount)
{
return Color.FromArgb(
(int)(baseColor.R * (1F - amount) + tint.R * amount),
(int)(baseColor.G * (1F - amount) + tint.G * amount),
(int)(baseColor.B * (1F - amount) + tint.B * amount));
}
}
public sealed class MainForm : Form, IMessageFilter
{
private sealed class DpiMetric
{
public Rectangle Bounds;
public Padding Padding;
public Padding Margin;
public Size MinimumSize;
public Size MaximumSize;
public DockStyle Dock;
public bool AutoSize;
public Size TabItemSize;
public int ListBoxItemHeight;
public int[] ListViewColumnWidths;
public float[] TableRowHeights;
public float[] TableColumnWidths;
}
[DllImport("uxtheme.dll", CharSet = CharSet.Unicode)]
private static extern int SetWindowTheme(IntPtr handle, string subAppName, string subIdList);
private readonly Color Bg = Color.FromArgb(247, 249, 250);
private readonly Color Card = Color.FromArgb(255, 255, 255);
private readonly Color Card2 = Color.FromArgb(241, 244, 246);
private readonly Color Accent = Color.FromArgb(38, 158, 142);
private readonly Color Green = Color.FromArgb(31, 157, 122);
private readonly Color Red = Color.FromArgb(210, 70, 76);
private readonly Color Muted = Color.FromArgb(105, 117, 126);
private readonly Color TextColor = Color.FromArgb(39, 50, 59);
private AppSettings settings;
private readonly string settingsFile;
private readonly string deviceInformationCacheFolder;
private List<DeviceInfo> devices = new List<DeviceInfo>();
private bool busy;
private bool quickInstalling;
private bool quickTransferring;
private bool quickInstallDragOver;
private bool quickTransferDragOver;
private string quickTransferStatus = "";
private Label adbStatusLabel;
private Label deviceStatusLabel;
private LinkLabel deviceDetailLabel;
private ToolTip deviceCopyToolTip;
private ComboBox deviceSelector;
private CheckBox installAllDevicesCheck;
private bool updatingDeviceSelector;
private Button refreshButton;
private Button browseAdbButton;
private Button installGroupButton;
private Button renameGroupButton;
private Button deleteGroupButton;
private Button addGroupApksButton;
private Button removeGroupApkButton;
private ListBox groupList;
private ListView apkList;
private TextBox logBox;
private CheckBox downgradeCheck;
private Label groupTitle;
private Label groupHint;
private Panel dropPanel;
private Panel transferDropPanel;
private ComboBox quickTransferDestinationComboBox;
private CheckBox autoBrightnessCheck;
private CheckBox timeoutTenMinutesCheck;
private CheckBox timeoutNeverCheck;
private CheckBox stayOnWhileChargingCheck;
private Label quickSettingsStateLabel;
private Button applyQuickSettingsButton;
private Button readQuickSettingsButton;
private Button volumeMinimumButton;
private Button volumeMaximumButton;
private Button openUrlButton;
private Button screenshotButton;
private Button screenshotClipboardButton;
private TextBox downloadFolderTextBox;
private CheckBox skipLargeDownloadCheck;
private NumericUpDown maxDownloadSizeNumber;
private ComboBox downloadModeComboBox;
private CheckBox incrementalDownloadCheck;
private Label downloadCheckpointLabel;
private Label downloadActionHint;
private Button resetDownloadCheckpointButton;
private Button browseDownloadFolderButton;
private Button startDownloadButton;
private Label downloadStatusLabel;
private ProgressBar downloadProgressBar;
private TextBox urlTextBox;
private bool loadingQuickSettings;
private TrackBar brightnessTrackBar;
private NumericUpDown brightnessNumber;
private Label brightnessValueLabel;
private Label brightnessStatusLabel;
private Label brightnessRangeLabel;
private CheckBox brightnessDisableAutoCheck;
private Button readBrightnessButton;
private Button applyBrightnessButton;
private Timer brightnessUpdateTimer;
private bool loadingBrightness;
private bool brightnessApplying;
private int brightnessPendingValue;
private int brightnessLastApplied = -1;
private int brightnessDetectedMaximum = 255;
private bool? brightnessAutoMode;
private TextBox spotreadPathTextBox;
private TextBox spotreadCorrectionTextBox;
private NumericUpDown autoBrightnessTargetNumber;
private NumericUpDown autoBrightnessToleranceNumber;
private Button browseSpotreadButton;
private Button browseSpotreadCorrectionButton;
private Button testMeterButton;
private Button openWhitePatternButton;
private Button startAutoBrightnessButton;
private Label autoBrightnessStatusLabel;
private Label autoBrightnessReadingLabel;
private ProgressBar autoBrightnessProgressBar;
private bool autoBrightnessRunning;
private bool autoBrightnessCancelRequested;
private ToolTip groupNameToolTip;
private int lastGroupTooltipIndex = -1;
private ToolTip apkListToolTip;
private int lastApkTooltipIndex = -1;
private int groupDragStartIndex = -1;
private int groupDragInsertIndex = -1;
private int groupDragLastScrollTick;
private Point groupDragStartPoint;
private ModernTabControl mainTabs;
private TabPage brightnessTabPage;
private ListView deviceInformationList;
private Label deviceInformationStatusLabel;
private Button readDeviceInformationButton;
private Button copyDeviceInformationButton;
private Button exportDeviceInformationButton;
private Button clearDeviceInformationCacheButton;
private DeviceInformationReport currentDeviceInformationReport;
private string currentDeviceInformationCachePath = "";
private int deviceInformationCacheLoadToken;
private readonly Dictionary<Control, DpiMetric> dpiMetrics = new Dictionary<Control, DpiMetric>();
private readonly List<ApkGroup> folderGroups = new List<ApkGroup>();
private float currentDpiScale = 1F;
public MainForm()
{
string folder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "AndroidADBTools");
CleanupOldUpdateDownloads(Path.Combine(folder, "updates"));
settingsFile = Path.Combine(folder, "settings.json");
deviceInformationCacheFolder = Path.Combine(folder, "device-information-cache");
settings = LoadSettings();
Text = "Android ADB 快速工具";
try { Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); } catch { }
StartPosition = FormStartPosition.CenterScreen;
AutoScaleMode = AutoScaleMode.Dpi;
AutoScaleDimensions = new SizeF(96F, 96F);
MinimumSize = new Size(1100, 840);
Size = new Size(1200, 960);
BackColor = Bg;
ForeColor = TextColor;
Font = new Font("Microsoft JhengHei UI", 10F, FontStyle.Regular, GraphicsUnit.Point);
DoubleBuffered = true;
BuildUi();
ApplyLightControlTheme(this);
InitializeBundledToolPaths();
Application.AddMessageFilter(this);
CaptureDpiMetrics(this);
ApplySmoothTextRendering(this);
ScanFolderGroups();
RefreshGroups();
downgradeCheck.Checked = settings.AllowDowngrade;
Load += delegate
{
ApplyDpiLayout(DeviceDpi);
RestoreWindowSize();
};
Shown += async delegate
{
await AutoReconnectWifiDevicesAsync(false);
await CheckConnectionAsync();
};
DpiChanged += delegate(object sender, DpiChangedEventArgs e)
{
int newDpi = e.DeviceDpiNew;
BeginInvoke(new Action(delegate { ApplyDpiLayout(newDpi); }));
};
ResizeEnd += delegate
{
CaptureWindowSize();
SaveSettings();
};
FormClosing += delegate
{
CaptureWindowSize();
SaveSettings();
};
FormClosed += delegate { Application.RemoveMessageFilter(this); };
}
private void BuildUi()
{
TableLayoutPanel root = new TableLayoutPanel();
root.Dock = DockStyle.Fill;
root.Padding = new Padding(16, 14, 16, 14);
root.BackColor = Bg;
root.RowCount = 3;
root.ColumnCount = 1;
root.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
root.RowStyles.Add(new RowStyle(SizeType.Absolute, 70));
root.RowStyles.Add(new RowStyle(SizeType.Absolute, 110));
root.RowStyles.Add(new RowStyle(SizeType.Percent, 100));
Controls.Add(root);
Panel header = new Panel { Dock = DockStyle.Fill };
Label title = new Label
{
Text = "Android ADB 快速工具",
Font = new Font(Font.FontFamily, 20F, FontStyle.Bold),
ForeColor = TextColor,
AutoSize = true,
Location = new Point(10, 4)
};
Label subtitle = new Label
{
Text = "連線確認、常用 APK/XAPK 安裝與快速安裝",
ForeColor = Muted,
AutoSize = true,
Location = new Point(12, 42)
};
Label versionLabel = new Label
{
Text = AppVersionText(),
ForeColor = Muted,
Font = new Font(Font.FontFamily, 8.5F, FontStyle.Regular),
Dock = DockStyle.Right,
Width = 92,
TextAlign = ContentAlignment.MiddleRight
};
header.Controls.Add(title);
header.Controls.Add(subtitle);
header.Controls.Add(versionLabel);
root.Controls.Add(header, 0, 0);
Panel deviceCard = NewCard();
deviceCard.Dock = DockStyle.Fill;
deviceCard.Padding = new Padding(18, 10, 18, 8);
root.Controls.Add(deviceCard, 0, 1);
adbStatusLabel = new Label
{
Text = "● 正在尋找 ADB...",
ForeColor = Muted,
Font = new Font(Font.FontFamily, 10.5F, FontStyle.Bold),
AutoSize = true,
Location = new Point(18, 13)
};
deviceStatusLabel = new Label
{
Text = "尚未檢查手機",
ForeColor = TextColor,
Font = new Font(Font.FontFamily, 11F, FontStyle.Bold),
AutoSize = false,
AutoEllipsis = true,
Location = new Point(178, 11),
Height = 27
};
deviceDetailLabel = new LinkLabel
{
Text = "請開啟 USB 偵錯並連接手機",
ForeColor = Muted,
LinkColor = Color.FromArgb(58, 103, 150),
ActiveLinkColor = Accent,
VisitedLinkColor = Color.FromArgb(58, 103, 150),
LinkBehavior = LinkBehavior.HoverUnderline,
AutoSize = false,
AutoEllipsis = true,
Location = new Point(20, 48),
Height = 23
};
deviceCopyToolTip = new ToolTip
{
InitialDelay = 100,
ReshowDelay = 50,
AutoPopDelay = 1800,
ShowAlways = true
};
deviceDetailLabel.LinkClicked += DeviceDetailLinkClicked;
deviceCard.Controls.Add(adbStatusLabel);
deviceCard.Controls.Add(deviceStatusLabel);
deviceCard.Controls.Add(deviceDetailLabel);
Panel deviceControls = new Panel
{
Dock = DockStyle.Right,
Width = 700,
BackColor = Card
};
FlowLayoutPanel statusActions = new FlowLayoutPanel
{
Dock = DockStyle.Top,
Height = 47,
FlowDirection = FlowDirection.RightToLeft,
WrapContents = false,
Padding = new Padding(0, 5, 0, 0),
BackColor = Card
};
refreshButton = NewButton("重新檢查", true, 108);
refreshButton.Click += async delegate { await CheckConnectionAsync(); };
browseAdbButton = NewButton("選擇 adb.exe", false, 132);
browseAdbButton.Click += BrowseAdb;
Button helpButton = NewButton("Wi-Fi 連線", false, 112);
helpButton.Click += ShowConnectionHelp;
Button aboutButton = NewButton("關於", false, 78);
aboutButton.Click += ShowAbout;
statusActions.Controls.Add(refreshButton);
statusActions.Controls.Add(browseAdbButton);
statusActions.Controls.Add(helpButton);
statusActions.Controls.Add(aboutButton);
FlowLayoutPanel deviceSelectionRow = new FlowLayoutPanel
{
Dock = DockStyle.Bottom,
Height = 40,
FlowDirection = FlowDirection.RightToLeft,
WrapContents = false,
Padding = new Padding(0, 5, 0, 0),
BackColor = Card
};
installAllDevicesCheck = new CheckBox
{
Text = "安裝套件到全部裝置",
ForeColor = Muted,
AutoSize = true,
Enabled = false,
Margin = new Padding(12, 7, 2, 0)
};
installAllDevicesCheck.CheckedChanged += DeviceInstallSelectionChanged;
deviceSelector = new ComboBox
{
DropDownStyle = ComboBoxStyle.DropDownList,
BackColor = Color.White,
ForeColor = TextColor,
FlatStyle = FlatStyle.Flat,
Width = 350,
Enabled = false,
Margin = new Padding(8, 2, 0, 0)
};
deviceSelector.SelectedIndexChanged += DeviceSelectorChanged;
Label deviceSelectorLabel = new Label
{
Text = "操作裝置",
ForeColor = Muted,
AutoSize = true,
Margin = new Padding(0, 8, 0, 0)
};
deviceSelectionRow.Controls.Add(installAllDevicesCheck);
deviceSelectionRow.Controls.Add(deviceSelector);
deviceSelectionRow.Controls.Add(deviceSelectorLabel);
deviceControls.Controls.Add(deviceSelectionRow);
deviceControls.Controls.Add(statusActions);
deviceCard.Controls.Add(deviceControls);
deviceControls.BringToFront();
deviceCard.Resize += delegate
{
int width = Math.Max(ScaleValue(220, currentDpiScale),
deviceCard.ClientSize.Width - deviceControls.Width - ScaleValue(44, currentDpiScale));
deviceStatusLabel.Width = width;
deviceDetailLabel.Width = width;
};
deviceControls.Resize += delegate
{
int width = Math.Max(ScaleValue(220, currentDpiScale),
deviceCard.ClientSize.Width - deviceControls.Width - ScaleValue(44, currentDpiScale));
deviceStatusLabel.Width = width;
deviceDetailLabel.Width = width;
};
mainTabs = new ModernTabControl();
mainTabs.Dock = DockStyle.Fill;
mainTabs.Font = new Font(Font.FontFamily, 10.5F, FontStyle.Bold);
mainTabs.BackColor = Bg;
mainTabs.ItemSize = new Size(58, 154);
TabPage groupsTab = NewTab("▦ 常用 APK/XAPK", Color.FromArgb(53, 120, 219));
TabPage singleTab = NewTab("⇩ 快速安裝 / 傳輸", Color.FromArgb(126, 87, 194));
TabPage brightnessTab = NewTab("☀ 亮度調整", Color.FromArgb(211, 132, 42));
brightnessTabPage = brightnessTab;
TabPage quickSettingsTab = NewTab("⚙ 快速設定", Color.FromArgb(32, 151, 116));
TabPage deviceInformationTab = NewTab("ⓘ 手機資訊", Color.FromArgb(38, 158, 142));
TabPage downloadTab = NewTab("↓ 資料下載", Color.FromArgb(35, 156, 181));
TabPage logTab = NewTab("≡ 執行紀錄", Color.FromArgb(88, 103, 128));
mainTabs.TabPages.Add(groupsTab);
mainTabs.TabPages.Add(singleTab);
mainTabs.TabPages.Add(brightnessTab);
mainTabs.TabPages.Add(quickSettingsTab);
mainTabs.TabPages.Add(deviceInformationTab);
mainTabs.TabPages.Add(downloadTab);
mainTabs.TabPages.Add(logTab);
root.Controls.Add(mainTabs, 0, 2);
BuildGroupsTab(groupsTab);
BuildSingleTab(singleTab);
BuildBrightnessTab(brightnessTab);
BuildQuickSettingsTab(quickSettingsTab);
BuildDeviceInformationTab(deviceInformationTab);
BuildDownloadTab(downloadTab);
BuildLogTab(logTab);
}
private void ApplyLightControlTheme(Control parent)
{
foreach (Control control in parent.Controls)
{
if (control is TextBoxBase || control is ComboBox || control is NumericUpDown ||
control is ListBox || control is ListView)
{
control.BackColor = Color.White;
control.ForeColor = TextColor;
control.HandleCreated += delegate { SetWindowTheme(control.Handle, "Explorer", null); };
if (control.IsHandleCreated) SetWindowTheme(control.Handle, "Explorer", null);
}
if (control.HasChildren) ApplyLightControlTheme(control);
}
}
private void BuildGroupsTab(TabPage tab)
{
SplitContainer split = new SplitContainer
{
Dock = DockStyle.Fill,
SplitterDistance = 420,
SplitterWidth = 10,
BackColor = Bg,
FixedPanel = FixedPanel.Panel1
};
tab.Controls.Add(split);
split.SizeChanged += delegate
{
if (split.Width < ScaleValue(760, currentDpiScale)) return;
int desired = Math.Min(ScaleValue(350, currentDpiScale),
Math.Max(ScaleValue(300, currentDpiScale), split.Width - ScaleValue(560, currentDpiScale)));
if (split.SplitterDistance != desired) split.SplitterDistance = desired;
};
Panel left = NewCard();
left.Dock = DockStyle.Fill;
left.Padding = new Padding(14);
split.Panel1.Controls.Add(left);
Label groupsLabel = NewSectionLabel("我的組合");
groupsLabel.Dock = DockStyle.Top;
left.Controls.Add(groupsLabel);
TableLayoutPanel groupButtons = new TableLayoutPanel
{
Dock = DockStyle.Bottom,
Height = 98,
ColumnCount = 2,
RowCount = 2,
BackColor = Card,