Repository navigation
Expand file tree
/
Copy pathFastbootUI.cs
More file actions
1722 lines (1497 loc) · 73 KB
/
Copy pathFastbootUI.cs
File metadata and controls
1722 lines (1497 loc) · 73 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 ChromeosUpdateEngine;
using FastbootEnhance.Core.Fastboot;
using FastbootEnhance.Core.Images;
using FastbootEnhance.Core.Payload;
using FastbootEnhance.Core.Usb;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows;
namespace FastbootEnhance
{
class FastbootUI
{
/// <summary>
/// Staging area for images on their way to the device. It lives under the user's temp
/// directory rather than next to the executable, which may sit somewhere unwritable.
/// </summary>
public static readonly string PAYLOAD_TMP =
Path.Combine(Path.GetTempPath(), "FastbootStudio", "flash");
static List<fastboot_devices_row> devices;
static string cur_serial;
static FastbootData fastbootData;
/// <summary>True while a payload is being extracted or written; the window asks before closing.</summary>
public static volatile bool flashing;
static void appendLog(string logs)
{
LogStore.Append(logs);
}
enum FastbootStatus
{
show_devices,
show_actions
}
static FastbootStatus cur_status;
static void refreshDeviceList()
{
MainWindow.THIS.Dispatcher.Invoke(new Action(delegate
{
MainWindow.THIS.fastboot_devices_list.Items.Clear();
foreach (fastboot_devices_row row in devices)
{
MainWindow.THIS.fastboot_devices_list.Items.Add(row);
}
MainWindow.THIS.fastboot_devices_empty.Visibility =
devices.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
MainWindow.THIS.main_tabs.Tag = string.Format(Properties.Resources.rail_devices, devices.Count);
}));
}
static bool checkCurDevExist()
{
using (Fastboot fastboot = new Fastboot(null, "devices"))
{
while (true)
{
string line = fastboot.stdout.ReadLine();
if (line == null)
break;
string[] param = line.Split(new char[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);
if (param.Length > 0 && cur_serial == param[0])
return true;
}
ThemedDialog.Show(Properties.Resources.fastboot_device_not_exist);
leaveDevice();
return false;
}
}
/// <summary>
/// Back to the device list. The variables read from the device go too, so nothing later
/// (a payload flash, the pre-flash checks) can act on what an earlier device reported.
/// </summary>
static void leaveDevice()
{
cur_serial = null;
fastbootData = null;
cur_status = FastbootStatus.show_devices;
change_page();
}
static void devicesListRefresher()
{
while (true)
{
Thread.Sleep(1000);
if (cur_status == FastbootStatus.show_actions)
continue;
List<fastboot_devices_row> tmp;
try
{
tmp = listDevices();
}
catch (FileNotFoundException e)
{
// Without fastboot.exe there is nothing to poll; say so once and stop,
// rather than letting the exception take the whole app down.
MainWindow.THIS.Dispatcher.BeginInvoke(new Action(delegate
{
MainWindow.THIS.main_tabs.Tag = Properties.Resources.rail_no_fastboot;
ThemedDialog.Show(e.Message + "\n" + e.FileName, Properties.Resources.error,
MessageBoxButton.OK, MessageBoxImage.Error);
}));
return;
}
catch (Exception e)
{
appendLog("device poll failed: " + e.Message);
continue;
}
if (tmp.Count != devices.Count)
{
devices = tmp;
refreshDeviceList();
}
else
{
int i;
for (i = 0; i < tmp.Count; i++)
{
if (devices[i].name != tmp[i].name || devices[i].serial != tmp[i].serial)
break;
}
if (i != tmp.Count)
{
devices = tmp;
refreshDeviceList();
}
}
}
}
static List<fastboot_devices_row> listDevices()
{
List<fastboot_devices_row> found = new List<fastboot_devices_row>();
using (Fastboot fastboot = new Fastboot(null, "devices"))
{
while (true)
{
string line = fastboot.stdout.ReadLine();
if (line == null)
break;
string[] param = line.Split(new char[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);
if (param.Length < 2)
continue;
found.Add(new fastboot_devices_row(param[0], param[1]));
}
}
return found;
}
class fastboot_devices_row
{
public string serial { get; }
public string name { get; }
public fastboot_devices_row(string serial, string name)
{
this.serial = serial;
this.name = name;
}
}
class fastboot_info_row
{
public string name { get; }
public string value { get; }
public fastboot_info_row(string name, string value)
{
this.name = name;
this.value = Helper.ltr(value);
}
}
class fastboot_partition_row
{
public string name { get; }
public string size { get; }
public string is_logical { get; }
public fastboot_partition_row(string name, string size, string is_logical)
{
this.name = name;
this.size = size;
this.is_logical = is_logical;
}
}
/// <summary>
/// How many operations hold the controls. Each lock is matched by exactly one unlock,
/// and the controls come back only when the last one finishes.
/// </summary>
static int lockDepth;
static void action_lock()
{
lockDepth++;
if (lockDepth > 1)
return;
MainWindow.THIS.fastboot_progress_bar.Value = 0;
MainWindow.THIS.fastboot_action_bar.IsEnabled = false;
MainWindow.THIS.fastboot_progress_bar.Visibility = Visibility.Visible;
MainWindow.THIS.fastboot_progress_bar.IsIndeterminate = false;
Helper.TaskbarItemHelper.start();
MainWindow.THIS.fastboot_single_part_op.IsEnabled = false;
MainWindow.THIS.fastboot_flash_payload.IsEnabled = false;
// Leaving the device mid-operation would let a flash continue with no target serial.
MainWindow.THIS.fastboot_remove.IsEnabled = false;
}
static void action_unlock()
{
if (lockDepth > 0)
lockDepth--;
if (lockDepth > 0)
return;
MainWindow.THIS.fastboot_progress_bar.Visibility = Visibility.Hidden;
MainWindow.THIS.fastboot_action_bar.IsEnabled = true;
Helper.TaskbarItemHelper.stop();
MainWindow.THIS.fastboot_single_part_op.IsEnabled = true;
MainWindow.THIS.fastboot_flash_payload.IsEnabled = true;
MainWindow.THIS.fastboot_remove.IsEnabled = true;
}
static Helper.ListHelper<fastboot_partition_row> listHelper;
/// <summary>Long enough for a phone rebooting into fastbootd to come back.</summary>
static readonly TimeSpan GetvarTimeout = TimeSpan.FromMinutes(3);
static void load_fastboot_vars()
{
//reset
fastbootData = null;
listHelper.clear();
MainWindow.THIS.fastboot_partition_name_textbox.Text = "";
MainWindow.THIS.fastboot_info_list.Items.Clear();
MainWindow.THIS.fastboot_checks.ItemsSource = null;
action_lock();
MainWindow.THIS.fastboot_progress_bar.IsIndeterminate = true;
string serial = cur_serial;
Thread loader = new Thread(new ThreadStart(delegate
{
FastbootData loaded;
try
{
using (Fastboot fastboot = new Fastboot(serial, "getvar all", GetvarTimeout))
{
// fastboot bug: Must read stderr first or stdout would be blocked
string output = fastboot.stderr.ReadToEnd();
int? exitCode = fastboot.WaitForExit();
if (exitCode == null)
{
throw new TimeoutException("the device did not answer \"getvar all\" within "
+ GetvarTimeout.TotalMinutes + " minutes");
}
loaded = new FastbootData(output);
// Some old bootloaders reject "all" but still list a few variables; only
// a failure that told us nothing at all is treated as one.
bool learned = loaded.product != null || loaded.current_slot != null
|| loaded.partition_size.Count > 0 || loaded.max_download_size > 0;
if (exitCode != 0 && !learned)
{
string[] lines = output.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
throw new IOException("fastboot getvar all exited with code " + exitCode
+ (lines.Length > 0 ? ": " + lines[lines.Length - 1].Trim() : ""));
}
}
}
catch (Exception e)
{
appendLog("getvar all failed: " + e.Message);
MainWindow.THIS.Dispatcher.BeginInvoke(new Action(delegate
{
MainWindow.THIS.fastboot_progress_bar.IsIndeterminate = false;
action_unlock();
if (cur_serial != serial)
return;
ThemedDialog.Show(e.Message, Properties.Resources.error, MessageBoxButton.OK, MessageBoxImage.Error);
leaveDevice();
}));
return;
}
MainWindow.THIS.Dispatcher.Invoke(delegate
{
MainWindow.THIS.fastboot_progress_bar.IsIndeterminate = false;
action_unlock();
if (cur_serial != serial)
return;
fastbootData = loaded;
showFastbootVars();
});
}));
loader.IsBackground = true;
loader.Start();
}
static void showFastbootVars()
{
//Partition list init
foreach (string key in fastbootData.partition_size.Keys)
{
long raw_size = fastbootData.partition_size[key];
string size_str = raw_size >= 0 ? Helper.byte2AUnit((ulong)raw_size) : Properties.Resources.fastboot_0_size;
bool? raw_logical = null;
fastbootData.partition_is_logical.TryGetValue(key, out raw_logical);
string logical_str = raw_logical != null && raw_logical == true ? Properties.Resources.yes : Properties.Resources.no;
listHelper.addItem(new fastboot_partition_row(key, size_str, logical_str));
}
listHelper.render();
//info list init
MainWindow.THIS.fastboot_info_list.Items.Add(new fastboot_info_row(Properties.Resources.fastboot_device,
fastbootData.product ?? Properties.Resources.unknown));
MainWindow.THIS.fastboot_info_list.Items.Add(new fastboot_info_row(Properties.Resources.fastboot_secure_boot,
fastbootData.secure ? Properties.Resources.enabled : Properties.Resources.disabled));
MainWindow.THIS.fastboot_info_list.Items.Add(new fastboot_info_row(Properties.Resources.fastboot_seamless_update,
fastbootData.current_slot != null ? Properties.Resources.yes : Properties.Resources.no));
if (fastbootData.current_slot != null)
MainWindow.THIS.fastboot_info_list.Items.Add(new fastboot_info_row(Properties.Resources.fastboot_current_slot,
fastbootData.current_slot));
MainWindow.THIS.fastboot_info_list.Items.Add(new fastboot_info_row(Properties.Resources.fastboot_is_userspace,
fastbootData.fastbootd ? Properties.Resources.yes : Properties.Resources.no));
if (fastbootData.max_download_size > 0)
MainWindow.THIS.fastboot_info_list.Items.Add(new fastboot_info_row("max-download-size",
Helper.byte2AUnit(fastbootData.max_download_size)));
string vab_status_str = null;
switch (fastbootData.snapshot_update_status)
{
case "none":
vab_status_str = Properties.Resources.fastboot_update_status_none;
break;
case "snapshotted":
vab_status_str = Properties.Resources.fastboot_update_status_snapshotted;
break;
case "merging":
vab_status_str = Properties.Resources.fastboot_update_status_merging;
break;
default:
vab_status_str = fastbootData.snapshot_update_status;
break;
}
if (vab_status_str != null)
MainWindow.THIS.fastboot_info_list.Items.Add(new fastboot_info_row(Properties.Resources.fastboot_update_status,
vab_status_str));
//buttons init
MainWindow.THIS.fastboot_logical_create.IsEnabled = fastbootData.fastbootd;
MainWindow.THIS.fastboot_reboot_d.Content = fastbootData.fastbootd ?
Properties.Resources.fastboot_reboot_bootloader : Properties.Resources.fastboot_reboot_fastbootd;
if (fastbootData.current_slot == "a" || fastbootData.current_slot == "b")
{
MainWindow.THIS.fastboot_ab_switch.Visibility = Visibility.Visible;
MainWindow.THIS.fastboot_ab_switch.Content = fastbootData.current_slot == "a"
? Properties.Resources.fastboot_setactive_b
: Properties.Resources.fastboot_setactive_a;
}
else
{
MainWindow.THIS.fastboot_ab_switch.Visibility = Visibility.Collapsed;
}
// Only offer to cancel a Virtual A/B update when there is one. The old code hid this
// button the first time it saw "none" and never showed it again.
MainWindow.THIS.fastboot_cancel_update.Visibility =
fastbootData.HasPendingUpdate ? Visibility.Visible : Visibility.Collapsed;
MainWindow.THIS.fastboot_mode_text.Text = fastbootData.fastbootd ? "fastbootd" : "bootloader";
MainWindow.THIS.fastboot_mode_badge.Visibility = Visibility.Visible;
MainWindow.THIS.fastboot_checks.ItemsSource = buildChecks();
showSuperSpace();
}
/// <summary>What to look at before writing anything to this device.</summary>
static List<CheckRow> buildChecks()
{
List<CheckRow> checks = new List<CheckRow>();
if (fastbootData.unlocked == true)
checks.Add(new CheckRow(CheckRow.Level.Ok, Properties.Resources.check_unlocked));
else if (fastbootData.unlocked == false)
checks.Add(new CheckRow(CheckRow.Level.Danger, Properties.Resources.check_locked));
if (fastbootData.fastbootd)
checks.Add(new CheckRow(CheckRow.Level.Ok, Properties.Resources.check_fastbootd));
else
checks.Add(new CheckRow(CheckRow.Level.Warn, Properties.Resources.check_bootloader));
if (!fastbootData.HasPendingUpdate)
checks.Add(new CheckRow(CheckRow.Level.Ok, Properties.Resources.check_no_update));
else
checks.Add(new CheckRow(CheckRow.Level.Warn,
string.Format(Properties.Resources.check_update_pending, fastbootData.snapshot_update_status)));
if (fastbootData.HasCowPartitions)
checks.Add(new CheckRow(CheckRow.Level.Warn, Properties.Resources.check_cow));
if (fastbootData.current_slot != null)
checks.Add(new CheckRow(CheckRow.Level.Ok,
string.Format(Properties.Resources.check_slot, fastbootData.current_slot)));
return checks;
}
/// <summary>The "Super" card on the partition tab: what each slot takes and what is free.</summary>
static void showSuperSpace()
{
SuperSpace space = SuperSpace.From(fastbootData);
MainWindow.THIS.fastboot_super_bar.Value = 0;
MainWindow.THIS.fastboot_super_bar.Foreground = Palette.Get("Accent");
if (!fastbootData.fastbootd)
{
MainWindow.THIS.fastboot_super_text.Text = Properties.Resources.super_space_bootloader;
return;
}
if (!space.Known)
{
MainWindow.THIS.fastboot_super_text.Text = Properties.Resources.super_space_unknown;
return;
}
MainWindow.THIS.fastboot_super_bar.Value = Math.Min(100, space.Used * 100.0 / space.SuperSize);
MainWindow.THIS.fastboot_super_bar.Foreground = Palette.Get(
space.Free < (512L << 20) ? "Danger" : space.Free < (2L << 30) ? "Warn" : "Accent");
List<string> lines = new List<string>();
lines.Add(string.Format(Properties.Resources.super_space_total,
Helper.byte2AUnit(space.SuperSize), Helper.byte2AUnit(space.Free)));
if (space.CurrentSlot != null)
lines.Add(string.Format(Properties.Resources.super_space_slot, space.CurrentSlot,
Helper.byte2AUnit(space.CurrentSlotBytes)) + " " + Properties.Resources.super_space_in_use);
if (space.OtherSlot != null)
lines.Add(string.Format(Properties.Resources.super_space_slot, space.OtherSlot,
Helper.byte2AUnit(space.OtherSlotBytes)));
if (space.CowBytes > 0)
lines.Add(string.Format(Properties.Resources.super_space_cow, Helper.byte2AUnit(space.CowBytes)));
if (space.UnslottedBytes > 0)
lines.Add(string.Format(Properties.Resources.super_space_unslotted, Helper.byte2AUnit(space.UnslottedBytes)));
MainWindow.THIS.fastboot_super_text.Text = string.Join("\n", lines);
}
/// <summary>
/// Before writing to logical partitions in fastbootd: when super is known to be too
/// small for the images, says by how much and what could make room, and asks.
/// True to go ahead.
/// </summary>
static bool superSpaceAllowed(IEnumerable<KeyValuePair<string, long>> writes, IEnumerable<string> created = null)
{
if (fastbootData == null || !fastbootData.fastbootd)
return true;
SuperSpace space = SuperSpace.From(fastbootData);
SuperFit fit = space.Check(writes, created);
appendLog("super space: " + (space.Known ? Helper.byte2AUnit(space.Free) + " free" : "size unknown")
+ ", writes need " + Helper.byte2AUnit(fit.Needed) + (fit.Fits ? "" : " (does not fit)"));
if (fit.Fits)
return true;
List<string> ways = new List<string>();
if (space.OtherSlotPartitions.Count > 0)
ways.Add(string.Format(Properties.Resources.super_full_other_slot, space.OtherSlot,
string.Join(", ", space.OtherSlotPartitions.Take(6)
.Select(p => p.Name + " (" + Helper.byte2AUnit(p.Size) + ")"))));
if (space.CowPartitions.Count > 0 || fastbootData.HasPendingUpdate)
ways.Add(Properties.Resources.super_full_cow);
if (ways.Count == 0)
ways.Add(Properties.Resources.super_full_nothing);
string text = string.Format(Properties.Resources.super_full,
Helper.byte2AUnit(fit.Needed), string.Join(", ", fit.Growing), Helper.byte2AUnit(fit.Free))
+ "\n\n" + string.Join("\n\n", ways.Select(w => "• " + w))
+ "\n\n" + Properties.Resources.super_full_ask;
return Helper.confirm(text, Properties.Resources.super_full_title, true);
}
/// <summary>
/// The USB check: looks at what Windows sees on USB and explains why a phone may be
/// missing from the list (no driver, a broken driver, a download mode, Android mode).
/// </summary>
static void checkUsb()
{
MainWindow.THIS.fastboot_usb_check.IsEnabled = false;
IReadOnlyList<UsbFinding> findings = null;
Exception failure = null;
Helper.offloadAndRun(new Action(delegate
{
try
{
findings = UsbDiagnosis.Diagnose(UsbScan.Read());
}
catch (Exception e)
{
failure = e;
}
}), new Action(delegate
{
MainWindow.THIS.fastboot_usb_check.IsEnabled = true;
if (failure != null)
{
appendLog("usb check failed: " + failure.Message);
ThemedDialog.Show(failure.Message, Properties.Resources.error, MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
showUsbFindings(findings);
}));
}
static void showUsbFindings(IReadOnlyList<UsbFinding> findings)
{
List<string> lines = new List<string>();
bool driverTrouble = false;
bool adbReady = false;
foreach (UsbFinding finding in findings)
{
appendLog("usb: " + finding.Kind + ", " + finding.Device.Name + " " + finding.UsbId
+ ", code " + finding.Device.ErrorCode);
string device = finding.Device.Name + (finding.UsbId != null ? " (" + finding.UsbId + ")" : "");
switch (finding.Kind)
{
case UsbFindingKind.MissingDriver:
lines.Add(string.Format(Properties.Resources.usb_missing_driver, device));
driverTrouble = true;
break;
case UsbFindingKind.DriverProblem:
lines.Add(string.Format(Properties.Resources.usb_driver_problem, device, finding.Device.ErrorCode));
driverTrouble = true;
break;
case UsbFindingKind.QualcommEdl:
lines.Add(string.Format(Properties.Resources.usb_edl, device));
break;
case UsbFindingKind.MediaTekDownload:
lines.Add(string.Format(Properties.Resources.usb_mediatek, device));
break;
case UsbFindingKind.UnisocDownload:
lines.Add(string.Format(Properties.Resources.usb_unisoc, device));
break;
case UsbFindingKind.SamsungDownload:
lines.Add(string.Format(Properties.Resources.usb_samsung, device));
break;
case UsbFindingKind.FastbootReady:
lines.Add(string.Format(Properties.Resources.usb_fastboot_ready, device));
break;
case UsbFindingKind.AdbReady:
lines.Add(string.Format(Properties.Resources.usb_adb_ready, device));
adbReady = true;
break;
}
}
if (lines.Count == 0)
{
ThemedDialog.Show(Properties.Resources.usb_nothing, Properties.Resources.usb_check_title,
MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
string text = string.Join("\n\n", lines.Select(line => "• " + line));
if (driverTrouble)
{
if (ThemedDialog.Show(text + "\n\n" + Properties.Resources.usb_driver_howto
+ "\n\n" + Properties.Resources.usb_open_device_manager,
Properties.Resources.usb_check_title, MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
{
try
{
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("devmgmt.msc") { UseShellExecute = true });
}
catch (Exception e)
{
ThemedDialog.Show(e.Message, Properties.Resources.error, MessageBoxButton.OK, MessageBoxImage.Error);
}
}
return;
}
if (adbReady)
{
if (!Helper.confirm(text + "\n\n" + Properties.Resources.usb_reboot_bootloader_ask, Properties.Resources.usb_check_title))
return;
string problem = null;
Helper.offloadAndRun(new Action(delegate
{
try
{
Adb.Result result = Adb.Run("reboot bootloader", Adb.ShortCommand);
if (!result.Succeeded)
problem = result.Problem;
}
catch (Exception e)
{
problem = e.Message;
}
}), new Action(delegate
{
appendLog("adb reboot bootloader: " + (problem ?? "ok"));
if (problem != null)
ThemedDialog.Show(problem, Properties.Resources.error, MessageBoxButton.OK, MessageBoxImage.Error);
}));
return;
}
ThemedDialog.Show(text, Properties.Resources.usb_check_title, MessageBoxButton.OK, MessageBoxImage.Information);
}
static void change_page()
{
bool showActions = cur_status == FastbootStatus.show_actions;
if (showActions)
load_fastboot_vars();
else
MainWindow.THIS.fastboot_mode_badge.Visibility = Visibility.Collapsed;
MainWindow.THIS.fastboot_devices_page.Visibility = showActions ? Visibility.Collapsed : Visibility.Visible;
MainWindow.THIS.fastboot_actions_page.Visibility = showActions ? Visibility.Visible : Visibility.Collapsed;
MainWindow.THIS.fastboot_device_chip.Visibility = showActions ? Visibility.Visible : Visibility.Collapsed;
MainWindow.THIS.fastboot_remove.Visibility = showActions ? Visibility.Visible : Visibility.Collapsed;
MainWindow.THIS.flash_target_device.Text = showActions && cur_serial != null
? string.Format(Properties.Resources.flash_target, cur_serial)
: Properties.Resources.flash_target_none;
}
class StepCmdRunnerParam
{
public string cmd;
public int step_count;
public bool show_dialog_on_done;
public bool skip_var_refresh;
/// <summary>
/// Captured on the UI thread when the command is created. Reboot clears cur_serial
/// straight after starting the worker, so reading it there could send the command
/// without -s, and fastboot would then act on whichever device it found first.
/// </summary>
public string serial;
/// <summary>Control commands get a limit; anything that writes is left to finish.</summary>
public TimeSpan timeout;
/// <summary>Shown instead of "operation completed" when set.</summary>
public string done_message;
/// <summary>Back to the device list once the command succeeded (the phone left fastboot).</summary>
public bool leave_after;
public StepCmdRunnerParam(string cmd, int step_count, bool hint_on_done, bool skip_var_refresh = false)
{
this.timeout = cmd.StartsWith("reboot") || cmd.StartsWith("set_active") || cmd.StartsWith("snapshot-update")
? Fastboot.LongCommand
: Fastboot.NoLimit;
this.cmd = cmd;
this.step_count = step_count;
this.show_dialog_on_done = hint_on_done;
this.skip_var_refresh = skip_var_refresh;
this.serial = cur_serial;
}
}
static void runStep(StepCmdRunnerParam param)
{
// Locked here, on the click, so a second click cannot start the command again
// before the worker gets going.
action_lock();
if (param.step_count <= 0)
MainWindow.THIS.fastboot_progress_bar.IsIndeterminate = true;
Thread worker = new Thread(new ParameterizedThreadStart(step_cmd_runner_err));
worker.IsBackground = true;
worker.Start(param);
}
static void step_cmd_runner_err(object raw_param)
{
StepCmdRunnerParam param = (StepCmdRunnerParam)raw_param;
appendLog("> fastboot " + param.cmd);
string failure = null;
try
{
using (Fastboot fastboot = new Fastboot(param.serial, param.cmd, param.timeout))
{
int count = 0;
while (true)
{
string err = fastboot.stderr.ReadLine();
if (err == null)
break;
appendLog(err);
if (param.step_count > 0)
MainWindow.THIS.Dispatcher.BeginInvoke(new Action(delegate
{
count++;
int percent = Math.Min(100, count * 100 / param.step_count);
MainWindow.THIS.fastboot_progress_bar.Value = percent;
Helper.TaskbarItemHelper.update(percent);
}));
}
int? exitCode = fastboot.WaitForExit();
if (exitCode != 0)
{
failure = "fastboot " + param.cmd + ": " + (exitCode == null
? "did not finish within " + param.timeout.TotalMinutes + " minutes and was stopped"
: "exited with code " + exitCode);
appendLog(failure);
}
}
}
catch (Exception e)
{
failure = e.Message;
appendLog("fastboot " + param.cmd + " failed: " + e.Message);
}
MainWindow.THIS.Dispatcher.BeginInvoke(new Action(delegate
{
MainWindow.THIS.fastboot_progress_bar.IsIndeterminate = false;
action_unlock();
if (failure != null)
{
ThemedDialog.Show(failure, Properties.Resources.error, MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
if (param.leave_after && cur_serial == param.serial)
leaveDevice();
else if (!param.skip_var_refresh && cur_serial != null && cur_serial == param.serial)
load_fastboot_vars();
if (param.show_dialog_on_done)
ThemedDialog.Done(param.done_message ?? Properties.Resources.operation_completed);
}));
}
/// <summary>
/// Checks the target slot's boot state and, in fastbootd, its logical partitions, then
/// asks (or refuses) accordingly. True when the switch may go ahead.
/// </summary>
static bool slotSwitchAllowed(string target)
{
SlotSwitchCheck check = SlotSwitchCheck.Evaluate(fastbootData, target);
appendLog("slot " + target + " check: " + check.Level
+ (check.Findings.Count > 0 ? " (" + string.Join(", ", check.Findings.Select(f => f.Reason)) + ")" : ""));
List<string> lines = new List<string>();
foreach (SlotCheckFinding finding in check.Findings.Where(f => f.Level != SlotCheckLevel.Ok))
{
switch (finding.Reason)
{
case SlotCheckReason.NeverBooted:
lines.Add(string.Format(Properties.Resources.slot_reason_never_booted, target));
break;
case SlotCheckReason.Unbootable:
lines.Add(string.Format(Properties.Resources.slot_reason_unbootable, target));
break;
case SlotCheckReason.NoRetriesLeft:
lines.Add(string.Format(Properties.Resources.slot_reason_no_retries, target));
break;
case SlotCheckReason.EmptyPartitions:
lines.Add(string.Format(Properties.Resources.slot_reason_empty, target, string.Join(", ", finding.Partitions)));
break;
}
}
string details = string.Join("\n\n", lines.Select(l => "• " + l));
switch (check.Level)
{
case SlotCheckLevel.Block:
ThemedDialog.Show(string.Format(Properties.Resources.slot_switch_blocked, target) + "\n\n" + details,
Properties.Resources.slot_switch_title, MessageBoxButton.OK, MessageBoxImage.Error);
return false;
case SlotCheckLevel.Danger:
return Helper.confirm(string.Format(Properties.Resources.slot_switch_danger, target) + "\n\n" + details,
Properties.Resources.slot_switch_title, true);
case SlotCheckLevel.Warn:
return Helper.confirm(string.Format(Properties.Resources.slot_switch_warn, target) + "\n\n" + details,
Properties.Resources.slot_switch_title);
default:
return true;
}
}
/// <summary>
/// "fastboot boot": starts an image once from memory. Only an image with a kernel can
/// start, and only the bootloader (not fastbootd) can do it.
/// </summary>
static void bootOnce(string path)
{
BootImageHeader header;
try
{
header = BootImageHeader.Read(path);
}
catch (Exception e)
{
ThemedDialog.Show(e.Message, Properties.Resources.error, MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
string refusal = header.Kind == BootImageKind.NoKernel ? Properties.Resources.boot_once_no_kernel
: header.Kind == BootImageKind.VendorBoot ? Properties.Resources.boot_once_vendor_boot
: header.Kind == BootImageKind.NotBootImage ? Properties.Resources.boot_once_not_boot
: null;
if (refusal != null)
{
appendLog("boot once refused for " + path + ": " + header.Kind);
ThemedDialog.Show(refusal, Properties.Resources.fastboot_boot_once_title, MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
if (fastbootData.fastbootd)
{
if (Helper.confirm(Properties.Resources.boot_once_fastbootd, Properties.Resources.fastboot_boot_once_title))
runStep(new StepCmdRunnerParam("reboot bootloader", 2, false));
return;
}
runStep(new StepCmdRunnerParam("boot \"" + path + "\"", 0, true, true)
{
done_message = Properties.Resources.boot_once_started,
leave_after = true,
});
}
static bool singlePartitionCheck()
{
if (MainWindow.THIS.fastboot_partition_list.SelectedItems.Count == 0)
{
ThemedDialog.Show(Properties.Resources.fastboot_target_partition_not_selected);
return true;
}
if (MainWindow.THIS.fastboot_partition_list.SelectedItems.Count > 1)
{
ThemedDialog.Show(Properties.Resources.fastboot_not_support_multiselect);
return true;
}
return false;
}
static bool logicalCheck()
{
bool? ret = null;
fastbootData.partition_is_logical.TryGetValue(
((fastboot_partition_row)
MainWindow.THIS.fastboot_partition_list.SelectedItem).name, out ret);
if (ret == null || ret == false)
{
ThemedDialog.Show(Properties.Resources.fastboot_only_logical);
return true;
}
return false;
}
static bool vabStagingCheck()
{
if (fastbootData.HasPendingUpdate)
{
bool proceed = Helper.confirm(
Properties.Resources.fastboot_vab_staging_str1 + "\n" +
Properties.Resources.fastboot_vab_staging_str2 + "\n" +
Properties.Resources.fastboot_vab_staging_str3,
Properties.Resources.fastboot_vab_staging_str0, true);
if (!proceed)
{
return true;
}
}
if (fastbootData.HasCowPartitions)
{
bool proceed = Helper.confirm(
Properties.Resources.fastboot_cow_exist_str1 + "\n" +
Properties.Resources.fastboot_cow_exist_str2 + "\n" +
Properties.Resources.fastboot_cow_exist_str3,
Properties.Resources.fastboot_cow_exist_str0, true);
if (!proceed)
{
return true;
}
}
return false;
}
/// <summary>
/// Opens a payload, makes sure the device can take it, then hands over to the flasher.
/// </summary>
static void openPayloadThenFlash(string path, string serial)
{
PayloadFile opened = null;
Exception failure = null;
action_lock();
MainWindow.THIS.fastboot_progress_bar.IsIndeterminate = true;
Helper.offloadAndRun(
new Action(delegate
{
try
{
opened = PayloadFile.Open(path, PAYLOAD_TMP);
}
catch (Exception e)
{
failure = e;
}
}),
new Action(delegate
{
MainWindow.THIS.fastboot_progress_bar.IsIndeterminate = false;
if (failure != null)
{
action_unlock();
ThemedDialog.Show(Properties.Resources.payload_unsupported_format
+ "\n" + failure.Message);
return;
}
MissingPartitions missing = findMissingPartitions(opened);
if (missing.Unknown.Count > 0)
{
opened.Dispose();
action_unlock();
string hint = fastbootData.fastbootd
? "\n" + Properties.Resources.fastboot_unknown_partition_str1
: "\n" + Properties.Resources.fastboot_unknown_partition_str2;
ThemedDialog.Show(Properties.Resources.fastboot_unknown_partition_str0
+ "\n" + string.Join(" ", missing.Unknown) + hint);
return;
}
// Logical partitions the update adds (or the phone lost) are created first.
if (missing.Create.Count > 0)
{
appendLog("missing logical partitions: " + string.Join(", ", missing.Create));
if (!Helper.confirm(string.Format(Properties.Resources.create_missing,
string.Join(", ", missing.Create)), Properties.Resources.create_missing_title))
{
opened.Dispose();
action_unlock();
return;
}
}
List<string> blocked = opened.Partitions
.Where(part => !part.CanExtract)
.Select(part => part.Name)
.ToList();
if (blocked.Count > 0)
{
opened.Dispose();
action_unlock();
ThemedDialog.Show(Properties.Resources.payload_incremental_warning
+ "\n\n" + string.Join(", ", blocked));
return;
}