-
Notifications
You must be signed in to change notification settings - Fork 118
/
Main.py
5994 lines (5483 loc) · 314 KB
/
Main.py
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
#!/usr/bin/env python
# This file is part of PixelFlasher https://github.com/badabing2005/PixelFlasher
#
# Copyright (C) 2024 Badabing2005
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
# for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
# Also add information on how to contact you by electronic and paper mail.
#
# If your software can interact with users remotely through a computer network,
# you should also make sure that it provides a way for users to get its source.
# For example, if your program is a web application, its interface could
# display a "Source" link that leads users to an archive of the code. There are
# many ways you could offer source, and different solutions will be better for
# different programs; see section 13 for the specific requirements.
#
# You should also get your employer (if you work as a programmer) or school, if
# any, to sign a "copyright disclaimer" for the program, if necessary. For more
# information on this, and how to apply and follow the GNU AGPL, see
# <https://www.gnu.org/licenses/>.
import argparse
import contextlib
import ctypes
import json
import locale
import math
import ntpath
import os
import sys
import time
import traceback
import webbrowser
import threading
from datetime import datetime, timedelta
from urllib.parse import urlparse
import darkdetect
import wx
import wx.adv
import wx.lib.agw.aui as aui
import wx.lib.inspection
import wx.lib.mixins.inspection
import wx.lib.buttons as buttons
from packaging.version import parse
import images as images
import cProfile, pstats
with contextlib.suppress(Exception):
ctypes.windll.shcore.SetProcessDpiAwareness(True)
from advanced_settings import AdvancedSettings
from backup_manager import BackupManager
from wifi import Wireless
from config import Config
from constants import *
from magisk_downloads import MagiskDownloads
from magisk_modules import MagiskModules
from pif_manager import PifManager
from message_box_ex import MessageBoxEx
from modules import (adb_kill_server, auto_resize_boot_list,
check_platform_tools, flash_phone, live_flash_boot_phone,
patch_boot_img, populate_boot_list, process_file,
select_firmware, set_flash_button_state, setup_for_downgrade)
from package_manager import PackageManager
from partition_manager import PartitionManager
from phone import get_connected_devices
from runtime import *
from my_tools import MyToolsDialog
# see https://discuss.wxpython.org/t/wxpython4-1-1-python3-8-locale-wxassertionerror/35168
locale.setlocale(locale.LC_ALL, 'C')
# For troubleshooting, set inspector = True
inspector = False
dont_initialize = False
do_profiling = False
# Declare global_args at the global scope
global_args = None
# ============================================================================
# Class RedirectText
# ============================================================================
class RedirectText():
def __init__(self, aWxTextCtrl):
self.out = aWxTextCtrl
self.logfile_stack = []
self.original_logfile_path = os.path.join(get_config_path(), 'logs', f"PixelFlasher_{datetime.now():%Y-%m-%d_%Hh%Mm%Ss}.log")
self.logfile = open(self.original_logfile_path, "w", buffering=1, encoding="utf-8", errors="replace")
self.logfile_stack.append(self.original_logfile_path)
set_logfile(self.original_logfile_path)
def write(self, string):
global global_args
if hasattr(global_args, 'console_only') and global_args.console_only and sys.platform != "win32":
# If --console-only is set, redirect output only to the console
sys.__stdout__.write(string)
else:
# Otherwise, redirect output to the text control, the console (if --console is set), and the logfile
wx.CallAfter(self.out.AppendText, string)
if hasattr(global_args, 'console') and global_args.console and sys.platform != "win32":
sys.__stdout__.write(string)
if not self.logfile.closed:
self.logfile.write(string)
self.logfile.flush()
# # noinspection PyMethodMayBeStatic
# def flush(self):
# # noinspection PyStatementEffect
# None
def flush(self):
if not self.logfile.closed:
self.logfile.flush()
def close(self):
if not self.logfile.closed:
self.logfile.close()
def set_logfile(self, new_logfile_path):
"""Set a new logfile and close the current one if open."""
self.flush()
self.close()
self.logfile = open(new_logfile_path, "w", buffering=1, encoding="utf-8", errors="replace")
self.logfile_stack.append(new_logfile_path)
set_logfile(new_logfile_path)
def reset_logfile(self):
"""Reset to the previous logfile."""
if len(self.logfile_stack) > 1:
self.flush()
self.close()
self.logfile_stack.pop() # Remove the current logfile
previous_logfile_path = self.logfile_stack[-1]
self.logfile = open(previous_logfile_path, "a", buffering=1, encoding="utf-8", errors="replace")
set_logfile(previous_logfile_path)
# ============================================================================
# Class FilePickerComboBox
# ============================================================================
class FilePickerComboBox(wx.Panel):
def __init__(self, parent, dialog_title="Select a file", wildcard="All files (*.*)|*.*"):
super(FilePickerComboBox, self).__init__(parent)
self.history_file = get_device_images_history_file_path()
self.dialog_title = dialog_title
self.wildcard = wildcard
self.history = []
self.combo_box = wx.ComboBox(self, wx.ID_ANY, style=wx.CB_READONLY)
self.browse_button = wx.Button(self, wx.ID_ANY, 'Browse')
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(self.combo_box, 1, wx.EXPAND)
sizer.Add(self.browse_button, 0, wx.EXPAND)
self.SetSizer(sizer)
self.browse_button.Bind(wx.EVT_BUTTON, self.on_browse)
self.combo_box.Bind(wx.EVT_MOUSEWHEEL, self.on_mousewheel)
if os.path.exists(self.history_file):
try:
encoding = detect_encoding(self.history_file)
with open(self.history_file, 'r', encoding=encoding, errors="replace") as f:
self.history = json.load(f)
self.combo_box.SetItems(self.history)
except Exception as e:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: encountered an exception during device_images_history_file loading.")
print(f"Exception: {e}")
print("Deleting the device_images_history_file to recover ...")
os.remove(self.history_file)
def on_browse(self, event):
file_dialog = wx.FileDialog(self, self.dialog_title, wildcard=self.wildcard)
if file_dialog.ShowModal() == wx.ID_OK:
file_path = file_dialog.GetPath()
if file_path not in self.history:
self.history.insert(0, file_path)
self.combo_box.Insert(file_path, 0)
if len(self.history) > 16:
self.history.pop()
if self.combo_box.Count > 16:
self.combo_box.Delete(self.combo_box.Count - 1)
self.combo_box.SetValue(file_path)
wx.PostEvent(self.combo_box, wx.CommandEvent(wx.EVT_COMBOBOX.typeId, self.combo_box.GetId()))
def SetPath(self, path):
if path and path != '' and path not in self.history:
self.history.insert(0, path)
self.combo_box.Insert(path, 0)
if len(self.history) > 16:
self.history.pop()
if self.combo_box.Count > 16:
self.combo_box.Delete(self.combo_box.Count - 1)
with open(self.history_file, 'w') as f:
json.dump(self.history, f)
self.combo_box.SetValue(path)
def on_combo_box_change(self, event):
path = event.GetString()
if path == '':
path = self.combo_box.GetValue()
if not os.path.exists(path):
self.history.remove(path)
self.combo_box.Delete(self.combo_box.FindString(path))
if path in self.history:
self.history.remove(path)
self.history.insert(0, path)
self.combo_box.Delete(self.combo_box.FindString(path))
self.combo_box.Insert(path, 0)
self.combo_box.SetValue(path)
with open(self.history_file, 'w') as f:
json.dump(self.history, f)
def Bind(self, event, handler):
if event == wx.EVT_FILEPICKER_CHANGED:
self.handler = handler
self.combo_box.Bind(wx.EVT_COMBOBOX, self._on_combo_box_change)
def _on_combo_box_change(self, event):
self.handler(event)
self.on_combo_box_change(event)
def GetPath(self):
return self.combo_box.GetStringSelection()
def SetToolTip(self, tooltip_text):
self.combo_box.SetToolTip(tooltip_text)
def on_mousewheel(self, event):
# Stop the event propagation to disable mouse wheel scrolling
event.StopPropagation()
# ============================================================================
# Class NoScrollComboBox
# ============================================================================
class NoScrollComboBox(wx.ComboBox):
def __init__(self, *args, **kwargs):
super(NoScrollComboBox, self).__init__(*args, **kwargs)
self.Bind(wx.EVT_MOUSEWHEEL, self.on_mousewheel)
def on_mousewheel(self, event):
# Stop the event propagation to disable mouse wheel scrolling
event.StopPropagation()
# ============================================================================
# Class NoScrollChoice
# ============================================================================
class NoScrollChoice(wx.Choice):
def __init__(self, *args, **kwargs):
super(NoScrollChoice, self).__init__(*args, **kwargs)
self.Bind(wx.EVT_MOUSEWHEEL, self.on_mousewheel)
def on_mousewheel(self, event):
# Stop the event propagation to disable mouse wheel scrolling
event.StopPropagation()
# ============================================================================
# Class DropDownLink
# ============================================================================
class DropDownLink(wx.BitmapButton):
def __init__(self, parent, id=wx.ID_ANY, bitmap=wx.NullBitmap, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.BU_AUTODRAW):
super().__init__(parent, id, bitmap, pos, size, style)
self.Bind(wx.EVT_BUTTON, self.OnButtonClick)
self.popup_menu = wx.Menu()
def OnButtonClick(self, event):
self.PopupMenu(self.popup_menu)
def AddLink(self, label, url, icon=None):
item = self.popup_menu.Append(wx.ID_ANY, label)
if icon:
item.SetBitmap(icon)
self.Bind(wx.EVT_MENU, lambda event, url=url: self.OnLinkSelected(event, url), item)
def OnLinkSelected(self, event, url):
# Handle the selected link here
print(f"Selected link: {url}")
open_device_image_download_link(url)
# ============================================================================
# Class DropDownButton
# ============================================================================
class DropDownButton(buttons.GenBitmapTextButton):
# def __init__(self, parent, id=wx.ID_ANY, label='', pos=wx.DefaultPosition, size=wx.DefaultSize, style=0):
# super().__init__(parent, id, wx.NullBitmap, label, pos, size, style)
def __init__(self, parent, id, bitmap, label, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0):
super().__init__(parent, id, bitmap, label, pos, size, style)
self.Bind(wx.EVT_BUTTON, self.OnButtonClick)
self.popup_menu = wx.Menu()
def SetBitmap(self, bitmap):
if bitmap.IsOk():
self.SetBitmapLabel(bitmap)
else:
print("Invalid bitmap")
def OnButtonClick(self, event):
self.PopupMenu(self.popup_menu)
def AddFunction(self, label, function, icon_bitmap=None, enabled=True):
item = self.popup_menu.Append(wx.ID_ANY, label)
item.Enable(enabled)
if icon_bitmap:
item.SetBitmap(icon_bitmap)
self.Bind(wx.EVT_MENU, lambda event, function=function: self.OnFunctionSelected(event, function), item)
return item
def OnFunctionSelected(self, event, function):
# Call the selected function here
function()
# ============================================================================
# Class DownloadProgressWindow
# ============================================================================
class DownloadProgressWindow(wx.Frame):
def __init__(self, parent=None):
super().__init__(parent, title="Downloads Progress", size=(800, 300))
self.downloads = {} # {url: (gauge, cancel_button, panel)}
self.main_panel = wx.Panel(self)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.main_panel.SetSizer(self.sizer)
self.Bind(wx.EVT_CLOSE, self.on_close)
if parent:
self.CenterOnParent()
else:
self.Center()
def add_download(self, url, filename):
download_panel = wx.Panel(self.main_panel)
download_sizer = wx.BoxSizer(wx.HORIZONTAL)
# File name label
name_label = wx.StaticText(download_panel, label=filename)
download_sizer.Add(name_label, 0, wx.ALL | wx.CENTER, 5)
# Progress bar
gauge = wx.Gauge(download_panel, range=100, size=(200, 25))
download_sizer.Add(gauge, 1, wx.ALL | wx.EXPAND, 5)
# Cancel button
cancel_button = wx.Button(download_panel, label="Cancel", size=(70, 25))
download_sizer.Add(cancel_button, 0, wx.ALL, 5)
download_panel.SetSizer(download_sizer)
self.sizer.Add(download_panel, 0, wx.ALL | wx.EXPAND, 5)
self.downloads[url] = (gauge, cancel_button, download_panel)
self.sizer.Layout()
self.Show()
return gauge, cancel_button
def remove_download(self, url):
if url in self.downloads:
gauge, cancel_button, panel = self.downloads[url]
panel.Destroy()
del self.downloads[url]
self.sizer.Layout()
# Hide window if no downloads
if not self.downloads:
self.Hide()
def on_close(self, event):
self.Hide()
# ============================================================================
# Class GoogleImagesBaseMenu
# ============================================================================
class GoogleImagesBaseMenu(wx.Menu):
BASE_MENU_ID_START = 5000
def __init__(self, parent):
super(GoogleImagesBaseMenu, self).__init__()
self.parent = parent
self.load_data()
self.current_menu_id = self.BASE_MENU_ID_START
self.progress_window = None
def generate_unique_id(self):
unique_id = self.current_menu_id
while unique_id in[wx.ID_EXIT, wx.ID_ABOUT, wx.ID_PREFERENCES]:
self.current_menu_id += 1
unique_id = self.current_menu_id
self.current_menu_id += 1
return unique_id
def reset_menu_id(self):
self.current_menu_id = self.BASE_MENU_ID_START
def bind_download_event(self, menu, url):
if menu is None:
print(f"Error: menu is None when adding menu item for {url}")
return
unique_id = self.generate_unique_id()
# next line is for debugging
# menu.SetItemLabel(f"{menu.GetItemLabel()} ({unique_id})")
def on_download_handler(event):
self.on_download(url, event, unique_id)
menu_id = menu.GetId()
self.parent.Bind(wx.EVT_MENU, on_download_handler, id=menu_id)
def load_data(self):
json_file_path = os.path.join(get_config_path(), "google_images.json").strip()
if not os.path.exists(json_file_path) or self.is_data_update_required():
get_google_images()
self.parent.config.google_images_last_checked = int(datetime.now().timestamp())
try:
with open(json_file_path, 'r', encoding='utf-8') as json_file:
self.data = json.load(json_file)
except FileNotFoundError:
print("google_images.json file not found.")
self.data = {}
def is_data_update_required(self):
last_checked = self.parent.config.google_images_last_checked
update_frequency = self.parent.config.google_images_update_frequency
# don't check for updates if it is set to -1
if update_frequency == -1:
return False
if last_checked is None:
return True
current_time = int(datetime.now().timestamp())
update_threshold = current_time - (update_frequency * 24 * 60 * 60)
return last_checked < update_threshold
def get_progress_window(self):
if self.progress_window is None:
self.progress_window = DownloadProgressWindow(self.parent)
return self.progress_window
def download_with_progress(self, url, destination_path, callback):
progress_window = self.get_progress_window()
filename = os.path.basename(destination_path)
gauge, cancel_button = progress_window.add_download(url, filename)
cancel_flag = {'cancelled': False}
# Store file handle to ensure proper cleanup
file_handle = {'f': None}
def on_cancel(event):
cancel_flag['cancelled'] = True
print(f"Download cancelled for: {url}")
try:
# Close file handle if it exists
if file_handle['f']:
file_handle['f'].close()
file_handle['f'] = None
# Small delay to ensure file operations complete
time.sleep(0.1)
if os.path.exists(destination_path):
try:
# Close any remaining handles
os.close(os.open(destination_path, os.O_RDONLY))
except:
pass
try:
print(f"Deleting partial download: {destination_path}")
os.remove(destination_path)
except Exception as e:
print(f"Error deleting partial download: {e}")
except Exception as e:
print(f"Error in cleanup: {e}")
try:
wx.CallAfter(progress_window.remove_download, url)
except Exception as e:
print(f"Error removing download from UI: {e}")
cancel_button.Bind(wx.EVT_BUTTON, on_cancel)
def update_gauge(value):
try:
if not cancel_flag['cancelled'] and gauge:
gauge.SetValue(value)
except Exception:
pass
def download_thread():
try:
response = requests.get(url, stream=True)
total_length = int(response.headers.get('content-length', 0))
downloaded = 0
with open(destination_path, 'wb') as f:
# Store file handle for cleanup
file_handle['f'] = f
for chunk in response.iter_content(chunk_size=4096):
if cancel_flag['cancelled']:
f.close()
return
if chunk:
downloaded += len(chunk)
f.write(chunk)
if total_length:
try:
wx.CallAfter(update_gauge, int(100 * downloaded / total_length))
except Exception:
pass
# Clear file handle reference
file_handle['f'] = None
if not cancel_flag['cancelled']:
try:
wx.CallAfter(progress_window.remove_download, url)
wx.CallAfter(callback)
except Exception as e:
print(f"Error in download completion: {e}")
except Exception as e:
print(f"Download error: {e}")
try:
wx.CallAfter(progress_window.remove_download, url)
except Exception:
pass
# Ensure file handle is closed
if file_handle['f']:
file_handle['f'].close()
file_handle['f'] = None
# Small delay before deletion
time.sleep(0.1)
if os.path.exists(destination_path):
try:
os.close(os.open(destination_path, os.O_RDONLY))
os.remove(destination_path)
except Exception as e:
print(f"Error cleaning up failed download: {e}")
threading.Thread(target=download_thread).start()
def on_download(self, url, event=None, unique_id=any):
# debug(f"Download triggered for URL: {url}, Menu ID: {unique_id}")
def download_completed(destination_path):
self.parent.toast("Download Successful", f"File downloaded successfully: {url} and saved to {destination_path}")
print(f"{datetime.now():%Y-%m-%d %H:%M:%S} Download Successful", f"File downloaded successfully: {url} and saved to {destination_path}")
# self.parent.firmware_picker.SetPath(destination_path)
# self.parent.update_firmware_selection(destination_path)
filename = os.path.basename(url)
dialog = wx.FileDialog(None, "Save File", defaultFile=filename, wildcard="All files (*.*)|*.*", style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
if dialog.ShowModal() == wx.ID_OK:
destination_path = dialog.GetPath()
print(f"{datetime.now():%Y-%m-%d %H:%M:%S} Starting background download for: {url} to be saved to {destination_path}\nplease be patient ...")
self.download_with_progress(url, destination_path, lambda: download_completed(destination_path))
def on_refresh_google_images(self, event):
print("Refreshing Google Images Menu ...")
self.parent._on_spin('start')
self.parent.config.google_images_last_checked = False
# Refresh the Google Images menu
self.parent.update_google_images_menu()
print("Completed refreshing Google Images Menu.")
self.parent._on_spin('stop')
def on_show_progress_window(self, event):
if self.progress_window:
self.progress_window.Show()
else:
self.parent.toast("No Downloads", "No downloads in progress.")
# ============================================================================
# Class GoogleImagesMenu
# ============================================================================
class GoogleImagesMenu(GoogleImagesBaseMenu):
def __init__(self, parent):
super(GoogleImagesMenu, self).__init__(parent)
try:
self.phones_menu = wx.Menu()
self.watches_menu = wx.Menu()
device = get_phone()
device_hardware = None
device_firmware_date = None
download_available = False
phone_icon = images.phone_green_24.GetBitmap()
watch_icon = images.watch_green_24.GetBitmap()
device_icon = images.star_green_24.GetBitmap()
if hasattr(self.parent, 'firmware_button') and self.parent.firmware_button:
self.parent.firmware_button.SetBitmap(images.open_link_24.GetBitmap())
if device:
device_hardware = device.hardware
device_firmware_date = device.firmware_date
for device_id, device_data in self.data.items():
device_label = device_data['label']
device_type = device_data['type']
device_menu = wx.Menu()
device_download_flag = False
for download_type in ['ota', 'factory']:
download_menu = wx.Menu()
for download_entry in reversed(device_data[download_type]):
version = download_entry['version']
sha256 = download_entry['sha256']
menu_label = f"{version} ({device_label})"
menu_id = self.generate_unique_id()
download_menu_item = download_menu.Append(menu_id, menu_label, sha256)
if download_menu_item is None:
print(f"Failed to create menu item with id {menu_id}, label {menu_label}, and sha256 {sha256}")
else:
download_date = download_entry['date']
# Set the background color and the icon for the current device. (background color is not working)
if device_id == device_hardware and device_firmware_date and download_date and int(download_date) > int(device_firmware_date):
download_menu_item.SetBackgroundColour((100, 155, 139, 255))
download_menu_item.SetBitmap(images.download_24.GetBitmap())
device_download_flag = True
download_available = True
device_icon = images.download_24.GetBitmap()
if device_type == "phone":
phone_icon = images.download_24.GetBitmap()
elif device_type == "watch":
watch_icon = images.download_24.GetBitmap()
url = download_entry['url']
self.bind_download_event(download_menu_item, url)
download_type_menu_item = device_menu.AppendSubMenu(download_menu, download_type.capitalize())
if download_type == "ota":
download_type_menu_item.SetBitmap(images.cloud_24.GetBitmap())
elif download_type == "factory":
download_type_menu_item.SetBitmap(images.factory_24.GetBitmap())
if device_download_flag:
download_type_menu_item.SetBitmap(images.download_24.GetBitmap())
if device_type == 'phone':
device_menu_item = self.phones_menu.AppendSubMenu(device_menu, f"{device_id} ({device_label})")
# Set the background color and the icon for the current device. (background color is not working)
if device_id == device_hardware:
device_menu_item.SetBitmap(device_icon)
device_menu_item.SetBackgroundColour((100, 155, 139, 255))
elif device_type == 'watch':
device_menu_item = self.watches_menu.AppendSubMenu(device_menu, f"{device_id} ({device_label})")
# Set the background color and the icon for the current device. (background color is not working)
if device_id == device_hardware:
device_menu_item.SetBitmap(device_icon)
device_menu_item.SetBackgroundColour((100, 155, 139, 255))
phone_menu_item = self.AppendSubMenu(self.phones_menu, "Phones")
phone_menu_item.SetBitmap(phone_icon)
watches_menu_item = self.AppendSubMenu(self.watches_menu, "Watches")
watches_menu_item.SetBitmap(watch_icon)
self.AppendSeparator()
refresh_images_menu_item = self.Append(wx.ID_ANY, "Refresh images list")
self.Bind(wx.EVT_MENU, self.on_refresh_google_images, refresh_images_menu_item)
self.AppendSeparator()
show_progress_menu_item = self.Append(wx.ID_ANY, "Show Progress Window")
self.Bind(wx.EVT_MENU, self.on_show_progress_window, show_progress_menu_item)
if download_available:
self.parent.toast("Updates are available", f"There are updates available for your device.\nCheck Google Images menu.")
if hasattr(self.parent, 'firmware_button') and self.parent.firmware_button:
self.parent.firmware_button.SetBitmap(images.open_link_red_24.GetBitmap())
except Exception as e:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Encountered an error while building Google Images Menu.")
traceback.print_exc()
# ============================================================================
# Class GoogleImagesPopupMenu
# ============================================================================
class GoogleImagesPopupMenu(GoogleImagesBaseMenu):
def __init__(self, parent, device=None, date_filter=None):
super(GoogleImagesPopupMenu, self).__init__(parent)
try:
if device in self.data:
device_data = self.data[device]
submenu_ota = wx.Menu()
submenu_factory = wx.Menu()
download_flag = False
for download_entry in reversed(device_data['ota']):
if download_entry['date'] is not None and (not date_filter or (date_filter is not None and int(download_entry['date']) >= int(date_filter))):
version = download_entry['version']
menu_label = f"{version} (OTA)"
menu_id = wx.NewId()
menu_item = submenu_ota.Append(menu_id, menu_label)
self.parent.Bind(wx.EVT_MENU, lambda event, u=download_entry['url']: self.on_download(u), menu_item)
if date_filter and int(download_entry['date']) != int(date_filter):
menu_item.SetBitmap(images.download_24.GetBitmap())
download_flag = True
for download_entry in reversed(device_data['factory']):
if download_entry['date'] is not None and (not date_filter or (date_filter is not None and int(download_entry['date']) >= int(date_filter))):
version = download_entry['version']
menu_label = f"{version} (Factory)"
menu_id = wx.NewId()
menu_item = submenu_factory.Append(menu_id, menu_label)
self.parent.Bind(wx.EVT_MENU, lambda event, u=download_entry['url']: self.on_download(u), menu_item)
if date_filter and int(download_entry['date']) != int(date_filter):
menu_item.SetBitmap(images.download_24.GetBitmap())
download_flag = True
with contextlib.suppress(Exception):
ota_menu_item = self.AppendSubMenu(submenu_ota, "OTA")
factory_menu_item = self.AppendSubMenu(submenu_factory, "Factory")
if download_flag:
ota_menu_item.SetBitmap(images.download_24.GetBitmap())
factory_menu_item.SetBitmap(images.download_24.GetBitmap())
else:
ota_menu_item.SetBitmap(images.cloud_24.GetBitmap())
factory_menu_item.SetBitmap(images.factory_24.GetBitmap())
except Exception as e:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Encountered an error while building Google Images Popup Menu.")
traceback.print_exc()
# ============================================================================
# Class PixelFlasher
# ============================================================================
class PixelFlasher(wx.Frame):
def __init__(self, parent, title):
config_file = get_config_file_path()
self.config = Config.load(config_file)
self.init_complete = False
self.wipe = False
self.tools = []
set_config(self.config)
init_db()
wx.Frame.__init__(self, parent, -1, title, size=(self.config.width, self.config.height),
style=wx.DEFAULT_FRAME_STYLE | wx.NO_FULL_REPAINT_ON_RESIZE | wx.SYSTEM_MENU | wx.CLOSE_BOX)
# Base first run size on resolution.
if self.config.first_run:
x = int((self.CharWidth * self.config.width) / 11)
y = int((self.CharHeight * self.config.height) / 25)
self.SetSize(x, y)
self.toolbar_flags = self.get_toolbar_config()
self.Center()
self._build_status_bar()
self._set_icons()
self._build_menu_bar()
self._init_ui()
self.redirect_text = RedirectText(self.console_ctrl)
sys.stdout = self.redirect_text
sys.stderr = self.redirect_text
# self.Centre(wx.BOTH)
if self.config.pos_x and self.config.pos_y:
self.SetPosition((self.config.pos_x, self.config.pos_y))
self.resizing = False
if not dont_initialize:
self.initialize()
set_window_shown(True)
self.Show(True)
def change_logfile(self, new_logfile_path):
"""Change the logfile to a new one."""
self.redirect_text.set_logfile(new_logfile_path)
def reset_logfile(self):
"""Reset the logfile to the original one."""
self.redirect_text.reset_logfile()
# -----------------------------------------------
# initialize
# -----------------------------------------------
def initialize(self):
try:
if do_profiling:
profiler = cProfile.Profile()
profiler.enable()
t = f":{datetime.now():%Y-%m-%d %H:%M:%S}"
print(f"PixelFlasher {VERSION} started on {t}")
puml(f"{t};\n")
puml(f"#palegreen:PixelFlasher {VERSION} started;\n")
start = time.time()
print(f"Platform: {sys.platform}")
puml(f"note left:Platform: {sys.platform}\n")
# check timezone
timezone_offset = time.timezone if (time.localtime().tm_isdst == 0) else time.altzone
print(f"System Timezone: {time.tzname} Offset: {timezone_offset / 60 / 60 * -1}")
print(f"Configuration Folder Path: {get_config_path()}")
print(f"Configuration File Path: {get_config_file_path()}")
puml(":Loading Configuration;\n")
puml(f"note left: {get_config_path()}\n")
# load verbose settings
if self.config.verbose:
self.verbose_checkBox.SetValue(self.config.verbose)
set_verbose(self.config.verbose)
if self.config.first_run:
print("First Run: No previous configuration file is found.")
else:
print(f"{json.dumps(self.config.data, indent=4, sort_keys=True)}")
puml("note right\n")
puml(f"{json.dumps(self.config.data, indent=4, sort_keys=True)}\n")
puml("end note\n")
# enable / disable advanced_options
if self.config.advanced_options:
self._advanced_options_hide(False)
else:
self._advanced_options_hide(True)
# check codepage
print(f"System Default Encoding: {sys.getdefaultencoding()}")
print(f"File System Encoding: {sys.getfilesystemencoding()}")
get_code_page()
# delete specified libraries from the bundle
print(f"Bundle Directory: {get_bundle_dir()}")
delete_bundled_library(self.config.delete_bundled_libs)
# Get Available Memory
free_memory, total_memory = get_free_memory()
formatted_free_memory = format_memory_size(free_memory)
formatted_total_memory = format_memory_size(total_memory)
print(f"Available Free Memory: {formatted_free_memory} / {formatted_total_memory}")
# Get available free disk on system drive
print(f"Available Free Disk on system drive: {str(get_free_space())} GB")
print(f"Available Free Disk on PixelFlasher data drive: {str(get_free_space(get_config_path()))} GB\n")
# load android_versions into a dict.
try:
file_path = os.path.join(get_bundle_dir(), 'android_versions.json')
encoding = detect_encoding(file_path)
with open(file_path, 'r', encoding=encoding, errors="replace") as file:
android_versions = json.load(file)
set_android_versions(android_versions)
except Exception as e:
print(f"Error: Unable to load {file_path} {e}")
# load android_devices into a dict.
try:
file_path = os.path.join(get_bundle_dir(), 'android_devices.json')
encoding = detect_encoding(file_path)
with open(file_path, 'r', encoding=encoding, errors="replace") as file:
android_devices = json.load(file)
set_android_devices(android_devices)
except Exception as e:
print(f"Error: Unable to load {file_path} {e}")
# clear file_path
file_path = None
# load Magisk Package Name
set_magisk_package(self.config.magisk)
# load the low_mem settings
set_low_memory(self.config.low_mem)
# load Linux Shell
set_linux_shell(self.config.linux_shell)
# load firmware_has_init_boot
set_firmware_has_init_boot(self.config.firmware_has_init_boot)
# load rom_has_init_boot
set_rom_has_init_boot(self.config.rom_has_init_boot)
# extract firmware info
try:
if self.config.firmware_path and os.path.exists(self.config.firmware_path):
self.firmware_picker.SetPath(self.config.firmware_path)
firmware = ntpath.basename(self.config.firmware_path)
filename, extension = os.path.splitext(firmware)
extension = extension.lower()
firmware = filename.split("-")
if len(firmware) == 1:
set_firmware_model(None)
set_firmware_id(filename)
else:
try:
set_firmware_model(firmware[0])
if firmware[1] == 'ota' or firmware[0] == 'crDroidAndroid':
set_firmware_id(f"{firmware[0]}-{firmware[1]}-{firmware[2]}")
self.config.firmware_is_ota = True
else:
set_firmware_id(f"{firmware[0]}-{firmware[1]}")
except Exception as e:
set_firmware_model(None)
set_firmware_id(filename)
set_ota(self, self.config.firmware_is_ota)
if self.config.check_for_firmware_hash_validity:
if self.config.firmware_sha256:
print("Using previously stored firmware SHA-256 ...")
firmware_hash = self.config.firmware_sha256
else:
print("Computing firmware SHA-256 ...")
firmware_hash = sha256(self.config.firmware_path)
self.config.firmware_sha256 = firmware_hash
print(f"Firmware SHA-256: {firmware_hash}")
self.firmware_picker.SetToolTip(f"SHA-256: {firmware_hash}")
# Check to see if the first 8 characters of the checksum is in the filename, Google published firmwares do have this.
if firmware_hash[:8] in self.config.firmware_path:
print(f"Expected to match {firmware_hash[:8]} in the firmware filename and did. This is good!")
puml(f"#CDFFC8:Checksum matches portion of the firmware filename {self.config.firmware_path};\n")
# self.toast("Firmware SHA256", "SHA256 of the selected file matches the segment in the filename.")
set_firmware_hash_validity(True)
else:
print(f"⚠️ WARNING: Expected to match {firmware_hash[:8]} in the firmware filename but didn't, please double check to make sure the checksum is good.")
puml("#orange:Unable to match the checksum in the filename;\n")
self.toast("Firmware SHA256", "WARNING! SHA256 of the selected file does not match segments in the filename.\nPlease double check to make sure the checksum is good.")
set_firmware_hash_validity(False)
except Exception as e:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Encountered an error while extracting firmware info during initialization.")
traceback.print_exc()
# check platform tools
try:
res_sdk = check_platform_tools(self)
if res_sdk != -1:
# load platform tools value
if self.config.platform_tools_path and get_adb() and get_fastboot():
self.platform_tools_picker.SetPath(self.config.platform_tools_path)
# if adb is found, display the version
if get_sdk_version():
self.platform_tools_label.SetLabel(f"Android Platform Tools\nVersion {get_sdk_version()}")
except Exception as e:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Encountered an error while checking for platform tools during initialization.")
traceback.print_exc()
# load custom_rom settings
try:
self.custom_rom_checkbox.SetValue(self.config.custom_rom)
if self.config.custom_rom_path and os.path.exists(self.config.custom_rom_path):
self.custom_rom.SetPath(self.config.custom_rom_path)
set_custom_rom_id(os.path.splitext(ntpath.basename(self.config.custom_rom_path))[0])
if self.config.rom_sha256:
rom_hash = self.config.rom_sha256
else:
rom_hash = sha256(self.config.custom_rom_path)
self.config.rom_sha256 = rom_hash
self.custom_rom.SetToolTip(f"SHA-256: {rom_hash}")
except Exception as e:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Encountered an error while checking for custom rom during initialization.")
traceback.print_exc()
# refresh boot.img list
try:
populate_boot_list(self)
except Exception as e:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Encountered an error while populating boot list during initialization.")
traceback.print_exc()
# set the flash mode
mode = self.config.flash_mode
# set flash option
self.flash_both_slots_checkBox.SetValue(self.config.flash_both_slots)
self.flash_to_inactive_slot_checkBox.SetValue(self.config.flash_to_inactive_slot)
self.disable_verity_checkBox.SetValue(self.config.disable_verity)
self.disable_verification_checkBox.SetValue(self.config.disable_verification)
self.fastboot_force_checkBox.SetValue(self.config.fastboot_force)
self.fastboot_verbose_checkBox.SetValue(self.config.fastboot_verbose)
self.temporary_root_checkBox.SetValue(self.config.temporary_root)
self.no_reboot_checkBox.SetValue(self.config.no_reboot)
self.wipe_checkBox.SetValue(self.wipe)
self.no_wipe_downgrade_checkbox.SetValue(False)
self.no_wipe_downgrade_checkbox.Enable(False)
self.no_wipe_downgrade_checkbox.Hide()
# get the image choice and update UI
set_image_mode(self.image_choice.Items[self.image_choice.GetSelection()])
# set the state of flash button.
try:
set_flash_button_state(self)
except Exception as e:
print(f"\n❌ {datetime.now():%Y-%m-%d %H:%M:%S} ERROR: Encountered an error while setting flash button state during initialization.")
traceback.print_exc()