forked from Nxzume/GUI-for-Android-Debug-Bridge-ADB-UI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadb_gui.py
More file actions
4389 lines (3744 loc) · 208 KB
/
Copy pathadb_gui.py
File metadata and controls
4389 lines (3744 loc) · 208 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
import sys
import subprocess
import threading
import os
import shlex
import tempfile
import json
import shutil
import time
from datetime import datetime
from PyQt6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QGridLayout,
QLabel, QPushButton, QComboBox, QTextEdit, QLineEdit, QFileDialog,
QMessageBox, QInputDialog, QFrame, QScrollArea, QGroupBox, QSizePolicy,
QDialog, QListWidget, QCheckBox, QRadioButton, QButtonGroup, QTabWidget
)
from PyQt6.QtCore import Qt, QThread, pyqtSignal, QTimer, QUrl, QObject
from PyQt6.QtGui import QFont, QColor, QPalette, QIcon
class DeviceFileListWidget(QListWidget):
"""List widget that accepts file drops for upload to device."""
files_dropped = pyqtSignal(list)
def __init__(self, parent=None):
super().__init__(parent)
self.setAcceptDrops(True)
self.setDragDropMode(QListWidget.DragDropMode.DropOnly)
def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.acceptProposedAction()
return
super().dragEnterEvent(event)
def dragMoveEvent(self, event):
if event.mimeData().hasUrls():
event.acceptProposedAction()
return
super().dragMoveEvent(event)
def dropEvent(self, event):
if event.mimeData().hasUrls():
paths = []
for url in event.mimeData().urls():
if isinstance(url, QUrl) and url.isLocalFile():
p = url.toLocalFile()
if p:
paths.append(p)
if paths:
self.files_dropped.emit(paths)
event.acceptProposedAction()
return
super().dropEvent(event)
class _UICaller(QObject):
"""Thread-safe UI callback helper."""
call = pyqtSignal(object)
def __init__(self, parent=None):
super().__init__(parent)
self.call.connect(lambda fn: fn())
class ADBManager:
"""Manages ADB operations"""
def __init__(self, adb_path=None):
if adb_path:
self.adb_path = adb_path
else:
self.adb_path = self.find_adb()
def find_adb(self):
"""Try to find ADB executable (fallback only - should use saved path from settings)"""
# Try to find in PATH first (most reliable if installed system-wide)
try:
if sys.platform == 'win32':
# Windows: use "where"
result = subprocess.run(['where', 'adb'], capture_output=True, text=True, timeout=5)
if result.returncode == 0 and result.stdout.strip():
path = result.stdout.strip().split('\n')[0]
if os.path.exists(path):
return path
else:
# macOS / Linux: rely on PATH lookup for "adb"
result = subprocess.run(['which', 'adb'], capture_output=True, text=True, timeout=5)
if result.returncode == 0 and result.stdout.strip():
path = result.stdout.strip().split('\n')[0]
if os.path.exists(path):
return path
except Exception:
pass
# Check common locations as fallback
if sys.platform == 'win32':
common_paths = [
os.path.join(os.environ.get('LOCALAPPDATA', ''), 'Android', 'Sdk', 'platform-tools', 'adb.exe'),
os.path.join(os.environ.get('ProgramFiles', ''), 'Android', 'android-sdk', 'platform-tools', 'adb.exe'),
os.path.join(os.path.expanduser('~'), 'Downloads', 'platform-tools-latest-windows', 'platform-tools', 'adb.exe'),
]
elif sys.platform == 'darwin':
# Default Android SDK and Homebrew locations on macOS
common_paths = [
os.path.join(os.path.expanduser('~'), 'Library', 'Android', 'sdk', 'platform-tools', 'adb'),
'/opt/homebrew/bin/adb', # Apple Silicon Homebrew
'/usr/local/bin/adb', # Intel Homebrew / manual installs
]
else:
# Common Linux locations
common_paths = [
os.path.join(os.path.expanduser('~'), 'Android', 'Sdk', 'platform-tools', 'adb'),
'/usr/bin/adb',
'/usr/local/bin/adb',
]
for path in common_paths:
if os.path.exists(path):
return path
return 'adb' # Fallback to assuming it's in PATH
def set_adb_path(self, path):
"""Set custom ADB path"""
if os.path.exists(path):
self.adb_path = path
return True
# If a directory is provided, look for adb / adb.exe inside it
if os.path.isdir(path):
candidates = []
if sys.platform == 'win32':
candidates.append(os.path.join(path, 'adb.exe'))
else:
candidates.append(os.path.join(path, 'adb'))
# Also accept adb.exe in case user selected a Windows SDK location
candidates.append(os.path.join(path, 'adb.exe'))
for candidate in candidates:
if os.path.exists(candidate):
self.adb_path = candidate
return True
return False
def run_command(self, command, timeout=30):
"""Run ADB command and return result"""
try:
# Use shlex.split to properly handle quoted arguments
# Split the command string into parts, handling quotes properly
command_parts = shlex.split(command, posix=False) if command else []
full_command = [self.adb_path] + command_parts
result = subprocess.run(
full_command,
capture_output=True,
text=True,
encoding='utf-8',
errors='replace',
timeout=timeout,
creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == 'win32' else 0
)
return {
'success': result.returncode == 0,
'stdout': result.stdout,
'stderr': result.stderr,
'returncode': result.returncode
}
except subprocess.TimeoutExpired:
return {
'success': False,
'stdout': '',
'stderr': 'Command timed out',
'returncode': -1
}
except Exception as e:
return {
'success': False,
'stdout': '',
'stderr': str(e),
'returncode': -1
}
def get_devices(self, silent=False):
"""Get list of connected devices with model information
Args:
silent: If True, don't log debug output (for auto-refresh)
"""
result = self.run_command('devices -l')
# Log the raw output for debugging (only if not silent)
if not silent and hasattr(self, 'log_callback'):
# Only log stderr if it's not empty
stderr_part = f"\nstderr: {result['stderr']}" if result.get('stderr', '').strip() else "\nstderr: (empty)"
self.log_callback(f"ADB devices command output:\nstdout: {result['stdout']}{stderr_part}\nsuccess: {result['success']}", "DEBUG")
if not result['success']:
if hasattr(self, 'log_callback'):
self.log_callback(f"ADB command failed: {result['stderr']}", "ERROR")
return []
devices = []
output = result['stdout'].strip()
if not output:
return []
lines = output.split('\n')
# Skip header line (usually "List of devices attached")
for line in lines[1:]:
line = line.strip()
if not line:
continue
# Handle both tab and space separated formats
if '\t' in line:
parts = line.split('\t', 1)
elif ' ' in line:
parts = line.split(' ', 1)
else:
# Just device ID, no status
devices.append({'id': line, 'status': 'unknown', 'model': None, 'product': None})
continue
device_id = parts[0].strip()
if device_id:
rest = parts[1].strip() if len(parts) > 1 else ''
status = rest.split()[0] if rest else 'unknown'
# Parse model and product from -l output (e.g., "device product:mustang model:Pixel_10_Pro_XL")
model = None
product = None
if 'model:' in rest:
try:
model_part = rest.split('model:')[1].split()[0]
model = model_part.replace('_', ' ')
except:
pass
if 'product:' in rest:
try:
product_part = rest.split('product:')[1].split()[0]
product = product_part.replace('_', ' ')
except:
pass
devices.append({
'id': device_id,
'status': status,
'model': model,
'product': product
})
# For devices without model info from -l, try to get it via getprop
for device in devices:
if not device.get('model') and device['status'] == 'device':
# Try to get model name
model_result = self.run_command(f"-s {device['id']} shell getprop ro.product.model")
if model_result['success'] and model_result['stdout'].strip():
device['model'] = model_result['stdout'].strip()
# Also get manufacturer if model is available
if device.get('model'):
mfr_result = self.run_command(f"-s {device['id']} shell getprop ro.product.manufacturer")
if mfr_result['success'] and mfr_result['stdout'].strip():
device['manufacturer'] = mfr_result['stdout'].strip()
return devices
def get_device_info(self, device_id):
"""Get device information"""
info = {}
commands = {
'Model': 'shell getprop ro.product.model',
'Manufacturer': 'shell getprop ro.product.manufacturer',
'Android Version': 'shell getprop ro.build.version.release',
'SDK Version': 'shell getprop ro.build.version.sdk',
'Serial': 'shell getprop ro.serialno',
}
for key, cmd in commands.items():
result = self.run_command(f'-s {device_id} {cmd}')
if result['success']:
info[key] = result['stdout'].strip()
else:
info[key] = 'N/A'
return info
class ADBGUI(QMainWindow):
"""Main GUI Application"""
# Signal for showing custom dialog (must be defined at class level)
custom_dialog_ready = pyqtSignal(dict)
app_list_ready = pyqtSignal(list)
def __init__(self):
super().__init__()
self.setWindowTitle("ADB Tool")
self.setGeometry(100, 100, 1200, 800)
self.setMinimumSize(1000, 700)
# Color schemes
self.light_colors = {
'bg': '#f5f5f5',
'fg': '#1f1f1f',
'accent': '#0078d4',
'accent_hover': '#106ebe',
'success': '#107c10',
'warning': '#ff8c00',
'error': '#d13438',
'card_bg': '#ffffff',
'border': '#e1e1e1',
'text_secondary': '#666666',
'text_tertiary': '#999999',
}
self.dark_colors = {
'bg': '#1e1e1e',
'fg': '#e0e0e0',
'accent': '#0078d4',
'accent_hover': '#106ebe',
'success': '#4ec9b0',
'warning': '#ffaa44',
'error': '#f48771',
'card_bg': '#252526',
'border': '#3e3e42',
'text_secondary': '#cccccc',
'text_tertiary': '#858585',
}
# Current color scheme (will be set by apply_theme)
self.colors = self.light_colors.copy()
# Get project directory - executable's directory if running as exe, script directory if from source
if getattr(sys, 'frozen', False):
# Running as compiled executable
project_dir = os.path.dirname(sys.executable)
else:
# Running as script
project_dir = os.path.dirname(os.path.abspath(__file__))
# DeGoogle state storage
self.degoogle_state_file = os.path.join(project_dir, 'degoogle_state.json')
self.degoogle_state = self.load_degoogle_state()
# Settings storage
self.settings_file = os.path.join(project_dir, 'settings.json')
self.settings = self.load_settings()
# Load dark mode preference
self.dark_mode = self.settings.get('dark_mode', False)
# Apply theme based on preference
self.apply_theme()
# Check for saved ADB path in settings
saved_adb_path = self.settings.get('adb_path', None)
# If no saved path, try to auto-detect ADB before bothering the user
if not saved_adb_path or not os.path.exists(saved_adb_path):
auto_manager = ADBManager()
auto_path = getattr(auto_manager, 'adb_path', None)
if auto_path and isinstance(auto_path, str) and os.path.exists(auto_path):
# Auto-detected ADB successfully, save it
saved_adb_path = auto_path
self.settings['adb_path'] = auto_path
self.save_settings()
else:
# Auto-detection failed – prompt user to select ADB path
QMessageBox.information(
self,
"ADB Path Required",
"Please select the ADB executable to continue.\n\n"
"This is typically located in the 'platform-tools' folder of your Android SDK."
)
# Prompt user to select ADB folder or executable
adb_path = self.prompt_for_adb_path()
if not adb_path:
# User cancelled - use fallback
QMessageBox.warning(
self,
"ADB Path Required",
"ADB path is required. The application will use 'adb' from PATH as fallback.\n\n"
"You can set the ADB path later using the 'ADB Path' button."
)
saved_adb_path = 'adb' # Fallback
else:
# Save the selected path
self.settings['adb_path'] = adb_path
self.save_settings()
saved_adb_path = adb_path
# Create ADBManager with saved path
self.adb = ADBManager(adb_path=saved_adb_path)
# Set up logging callback for ADB manager
self.adb.log_callback = self.log
self.current_device = None
self.log_thread = None
self.log_running = False
self.setup_ui()
self.update_adb_path_display()
self.refresh_devices()
# Auto-refresh devices every 5 seconds (silent mode to avoid log spam)
self.auto_refresh_timer = QTimer()
self.auto_refresh_timer.timeout.connect(lambda: self.refresh_devices(silent=True))
self.auto_refresh_timer.start(5000)
# Connect signal for custom dialog
self.custom_dialog_ready.connect(self._show_custom_dialog)
# Connect signal for app list dialog
self.app_list_ready.connect(self.show_app_list_window)
def setup_ui(self):
"""Setup the modern user interface"""
# Central widget
central_widget = QWidget()
self.setCentralWidget(central_widget)
# Main layout
main_layout = QVBoxLayout(central_widget)
main_layout.setContentsMargins(15, 15, 15, 15)
main_layout.setSpacing(15)
# Header with title
header_layout = QHBoxLayout()
self.title_label = QLabel("ADB Tool")
self.title_label.setFont(QFont('', 20, QFont.Weight.Bold))
self.title_label.setStyleSheet(f"color: {self.colors['fg']};")
header_layout.addWidget(self.title_label)
self.subtitle_label = QLabel("Android Device Manager")
self.subtitle_label.setFont(QFont('', 10))
self.subtitle_label.setStyleSheet(f"color: {self.colors['text_secondary']};")
header_layout.addWidget(self.subtitle_label)
header_layout.addStretch()
# Dark mode toggle button
self.dark_mode_btn = QPushButton("🌙 Dark Mode" if not self.dark_mode else "☀️ Light Mode")
self.dark_mode_btn.setMaximumWidth(120)
self.dark_mode_btn.clicked.connect(self.toggle_dark_mode)
header_layout.addWidget(self.dark_mode_btn)
main_layout.addLayout(header_layout)
# Device selection card
device_group = QGroupBox("📱 Device Management")
# Styles are applied globally via apply_theme
device_layout = QVBoxLayout(device_group)
device_layout.setSpacing(10)
# Device selection row
device_row = QHBoxLayout()
device_row.addWidget(QLabel("Connected Devices:"))
self.device_combo = QComboBox()
self.device_combo.setMinimumWidth(400)
self.device_combo.currentTextChanged.connect(self.on_device_selected)
device_row.addWidget(self.device_combo)
refresh_btn = QPushButton("🔄 Refresh")
refresh_btn.clicked.connect(self.refresh_devices)
device_row.addWidget(refresh_btn)
info_btn = QPushButton("ℹ️ Info")
info_btn.clicked.connect(self.show_device_info)
device_row.addWidget(info_btn)
path_btn = QPushButton("📂 ADB Path")
path_btn.clicked.connect(self.set_adb_path_dialog)
device_row.addWidget(path_btn)
test_btn = QPushButton("✓ Test")
test_btn.clicked.connect(self.test_adb)
device_row.addWidget(test_btn)
device_layout.addLayout(device_row)
# Device status row
status_row = QHBoxLayout()
self.device_info_label = QLabel("No device selected")
self.device_info_label.setStyleSheet(f"color: {self.colors['text_secondary']};")
status_row.addWidget(self.device_info_label)
self.adb_path_label = QLabel("ADB: Checking...")
self.adb_path_label.setStyleSheet(f"color: {self.colors['text_tertiary']};")
status_row.addWidget(self.adb_path_label)
status_row.addStretch()
device_layout.addLayout(status_row)
main_layout.addWidget(device_group)
# Main content area (operations + logs side by side)
content_layout = QHBoxLayout()
content_layout.setSpacing(7)
# Left side - Operations (scrollable)
ops_scroll = QScrollArea()
ops_scroll.setWidgetResizable(True)
ops_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
ops_widget = QWidget()
ops_layout = QVBoxLayout(ops_widget)
ops_layout.setSpacing(12)
# File operations
file_group = self.create_card("📁 File Transfer")
push_pull_row = QHBoxLayout()
push_btn = QPushButton("⬆️ Push")
push_btn.clicked.connect(self.push_file)
pull_btn = QPushButton("⬇️ Pull")
pull_btn.clicked.connect(self.pull_file)
push_pull_row.addWidget(push_btn)
push_pull_row.addWidget(pull_btn)
file_group.layout().addLayout(push_pull_row)
self.create_button(file_group, "🗂️ File Explorer (/sdcard)", self.open_file_explorer)
ops_layout.addWidget(file_group)
# App operations
app_group = self.create_card("📱 App Management")
self.create_button(app_group, "📦 Install APK", self.install_apk)
self.create_button(app_group, "🗑️ Uninstall App", self.uninstall_app)
self.create_button(app_group, "♻️ Reinstall for User", self.reinstall_for_user)
self.create_button(app_group, "📋 List Installed Apps", self.list_apps)
self.create_button(app_group, "📂 Open APKs Folder", self.open_apks_folder)
# Separator
self.separator = QFrame()
self.separator.setFrameShape(QFrame.Shape.HLine)
self.separator.setStyleSheet(f"color: {self.colors['border']};")
app_group.layout().addWidget(self.separator)
degoogle_row = QHBoxLayout()
degoogle_btn = QPushButton("🚫 DeGoogle")
degoogle_btn.clicked.connect(self.degoogle_device)
degoogle_btn.setProperty("accent", "true")
undo_degoogle_btn = QPushButton("↩️ Undo DeGoogle")
undo_degoogle_btn.clicked.connect(self.undo_degoogle)
degoogle_row.addWidget(degoogle_btn)
degoogle_row.addWidget(undo_degoogle_btn)
app_group.layout().addLayout(degoogle_row)
ops_layout.addWidget(app_group)
# Device operations
device_ops_group = self.create_card("⚡ Device Operations")
self.create_button(device_ops_group, "📸 Take Screenshot", self.take_screenshot)
self.create_button(device_ops_group, "🪞 Mirror Screen (scrcpy)", self.scrcpy_device)
self.create_button(device_ops_group, "🔄 Reboot Device", self.reboot_device)
self.create_button(device_ops_group, "🔧 Reboot to Recovery", self.reboot_recovery)
self.create_button(device_ops_group, "⚙️ Reboot to Bootloader", self.reboot_bootloader)
ops_layout.addWidget(device_ops_group)
# Shell operations
shell_group = self.create_card("💻 Shell Commands")
host_os = "Windows" if sys.platform == "win32" else ("macOS" if sys.platform == "darwin" else "Linux")
shell_group.layout().addWidget(QLabel(f"Run commands ON YOUR ANDROID DEVICE (not {host_os}):"))
help_text = (f"⚠️ These commands run on your Android device (Linux), not on {host_os}.\n\n"
"Examples: 'ls /sdcard', 'pm list packages', 'dumpsys battery | grep level'\n"
"Use Android/Linux shell commands: 'grep', 'ls', 'cat' (not desktop OS commands).\n\n"
"Note: You can include 'adb shell' prefix, but it's not required (auto-stripped)")
self.shell_help_label = QLabel(help_text)
self.shell_help_label.setStyleSheet(f"color: {self.colors['text_secondary']}; font-size: 8pt;")
self.shell_help_label.setWordWrap(True)
shell_group.layout().addWidget(self.shell_help_label)
self.shell_entry = QTextEdit()
self.shell_entry.setMaximumHeight(100)
self.shell_entry.setMinimumHeight(80)
self.shell_entry.setStyleSheet("padding: 6px; font-size: 10pt;")
self.shell_entry.setPlaceholderText("Enter Android shell command (e.g., 'ls /sdcard' or 'adb shell pm list packages')\nYou can enter multi-line commands here...")
# QTextEdit doesn't have returnPressed, so we'll use Ctrl+Enter or just the button
shell_group.layout().addWidget(self.shell_entry)
self.create_button(shell_group, "▶️ Run Command", self.run_shell_command, accent=True)
ops_layout.addWidget(shell_group)
ops_layout.addStretch()
ops_scroll.setWidget(ops_widget)
content_layout.addWidget(ops_scroll, 1)
# Right side - Logs
self.logs_group = QGroupBox("📊 Logs & Output")
# Styles are applied globally via apply_theme
logs_layout = QVBoxLayout(self.logs_group)
# Logcat controls
log_controls = QHBoxLayout()
self.log_button = QPushButton("▶️ Start Logcat")
self.log_button.clicked.connect(self.toggle_logcat)
log_controls.addWidget(self.log_button)
clear_btn = QPushButton("🗑️ Clear")
clear_btn.clicked.connect(self.clear_output)
log_controls.addWidget(clear_btn)
log_controls.addStretch()
logs_layout.addLayout(log_controls)
# Output text area
self.output_text = QTextEdit()
self.output_text.setReadOnly(True)
self.output_text.setFont(QFont('Consolas', 9))
logs_layout.addWidget(self.output_text)
content_layout.addWidget(self.logs_group, 2)
main_layout.addLayout(content_layout, 1)
# Status bar
self.status_bar = QLabel("Ready")
self.status_bar.setStyleSheet(f"""
background-color: {self.colors['card_bg']};
border: 1px solid {self.colors['border']};
padding: 8px 15px;
color: {self.colors['text_secondary']};
""")
main_layout.addWidget(self.status_bar)
def create_card(self, title):
"""Create a modern card container"""
group = QGroupBox(title)
# Styles are applied globally via apply_theme, no need for individual stylesheet
layout = QVBoxLayout(group)
layout.setContentsMargins(15, 20, 15, 15)
layout.setSpacing(4)
return group
def create_button(self, parent, text, command, accent=False):
"""Create a modern button"""
btn = QPushButton(text)
btn.clicked.connect(command)
if accent:
btn.setProperty("accent", "true")
parent.layout().addWidget(btn)
return btn
def log(self, message, level="INFO"):
"""Add message to output"""
timestamp = datetime.now().strftime("%H:%M:%S")
self.output_text.append(f"[{timestamp}] [{level}] {message}")
# Auto-scroll to bottom
scrollbar = self.output_text.verticalScrollBar()
scrollbar.setValue(scrollbar.maximum())
def clear_output(self):
"""Clear output text"""
self.output_text.clear()
def update_status(self, message):
"""Update status bar"""
self.status_bar.setText(message)
def update_adb_path_display(self):
"""Update ADB path display label"""
if os.path.exists(self.adb.adb_path):
self.adb_path_label.setText(f"✓ ADB: {self.adb.adb_path}")
self.adb_path_label.setStyleSheet(f"color: {self.colors['success']};")
else:
self.adb_path_label.setText("✗ ADB: Not found - Click 'ADB Path' to configure")
self.adb_path_label.setStyleSheet(f"color: {self.colors['error']};")
def refresh_devices(self, silent=False):
"""Refresh list of connected devices
Args:
silent: If True, don't log routine refresh messages (for auto-refresh)
"""
if not silent:
self.update_status("Refreshing devices...")
# Test ADB connection first
test_result = self.adb.run_command('version')
if not test_result['success']:
error_msg = test_result['stderr'] if test_result['stderr'] else "Unknown error"
self.log(f"ADB test failed: {error_msg}", "ERROR")
self.log(f"ADB path: {self.adb.adb_path}", "ERROR")
self.update_status(f"ADB error: {error_msg[:50]}")
self.device_info_label.setText(f"ADB Error: {error_msg[:100]}")
self.device_info_label.setStyleSheet(f"color: {self.colors['error']};")
return
devices = self.adb.get_devices(silent=silent)
# Get current device list for comparison
current_device_ids = set()
if hasattr(self, 'device_display_map'):
current_device_ids = set(self.device_display_map.values())
if devices:
# Create display strings with device name/model
device_list = []
device_display_map = {} # Map display string to device ID
new_device_ids = set()
for d in devices:
device_id = d['id']
new_device_ids.add(device_id)
model = d.get('model')
manufacturer = d.get('manufacturer', '')
product = d.get('product')
# Build display name
if model:
if manufacturer:
display_name = f"{manufacturer} {model}"
else:
display_name = model
elif product:
display_name = product.replace('_', ' ').title()
else:
display_name = "Unknown Device"
# Format: "Device Name (ID)"
display_str = f"{display_name} ({device_id})"
device_list.append(display_str)
device_display_map[display_str] = device_id
# Only log if device list changed
devices_changed = current_device_ids != new_device_ids
# Disconnect signal before modifying combo box to prevent unwanted triggers
self.device_combo.currentTextChanged.disconnect()
self.device_combo.clear()
self.device_combo.addItems(device_list)
self.device_display_map = device_display_map # Store mapping for selection
# Only auto-select if no device is currently selected
was_no_device = not self.current_device
if was_no_device and device_list:
self.device_combo.setCurrentIndex(0)
# Call on_device_selected directly with silent parameter (signal is disconnected so won't trigger)
self.on_device_selected(silent=silent) # Use silent parameter from refresh_devices
elif self.current_device and device_list:
# Device is already selected - just update the combo box index if needed
# Find the current device in the new list
current_display = None
for display_str, device_id in device_display_map.items():
if device_id == self.current_device:
current_display = display_str
break
if current_display:
index = self.device_combo.findText(current_display)
if index >= 0:
self.device_combo.setCurrentIndex(index)
# Don't call on_device_selected when device is already selected (avoids redundant get_devices call)
# Reconnect signal after all combo box operations are complete
self.device_combo.currentTextChanged.connect(self.on_device_selected)
if not silent or devices_changed:
self.update_status(f"Found {len(devices)} device(s)")
if devices_changed:
# Log with device names only when list changes
device_names = [f"{d.get('model', d.get('product', 'Unknown'))} ({d['id']})" for d in devices]
self.log(f"Found {len(devices)} device(s): {', '.join(device_names)}")
else:
had_devices = hasattr(self, 'device_display_map') and len(self.device_display_map) > 0
self.device_combo.clear()
self.current_device = None
self.device_info_label.setText("No devices connected - Check USB connection and USB debugging")
self.device_info_label.setStyleSheet(f"color: {self.colors['warning']};")
if not silent or had_devices:
self.update_status("No devices found")
if had_devices:
self.log("No devices found. Make sure USB debugging is enabled and device is connected.", "WARNING")
def on_device_selected(self, selection=None, silent=False):
"""Handle device selection
Args:
selection: Device selection string (if None, uses current combo selection)
silent: If True, don't log the selection (for auto-refresh)
"""
if selection is None:
selection = self.device_combo.currentText()
if selection:
# Extract device ID from display string using the mapping
if hasattr(self, 'device_display_map') and selection in self.device_display_map:
self.current_device = self.device_display_map[selection]
else:
# Fallback: try to extract from parentheses
if '(' in selection and ')' in selection:
self.current_device = selection.split('(')[1].split(')')[0].strip()
else:
self.current_device = selection.split()[0]
# Get device info for display
# In silent mode, skip get_devices call to avoid redundant logging
if silent:
# In silent mode, just use the device ID we already have
# Don't call get_devices to avoid logging
device_info = None
# Set a simple display text without calling get_devices
display_text = f"Selected: {self.current_device}"
else:
# Not in silent mode, get full device info
devices = self.adb.get_devices(silent=silent)
device_info = next((d for d in devices if d['id'] == self.current_device), None)
if device_info:
model = device_info.get('model', 'Unknown')
manufacturer = device_info.get('manufacturer', '')
if manufacturer:
display_text = f"Selected: {manufacturer} {model} ({self.current_device})"
else:
display_text = f"Selected: {model} ({self.current_device})"
else:
display_text = f"Selected: {self.current_device}"
# Only update UI and log if not in silent mode (for auto-refresh)
if not silent:
self.device_info_label.setText(display_text)
self.device_info_label.setStyleSheet(f"color: {self.colors['success']};")
self.log(f"Selected device: {display_text}")
# In silent mode, only update the label if it's not already set correctly
elif not hasattr(self, 'device_info_label') or self.device_info_label.text() != display_text:
self.device_info_label.setText(display_text)
self.device_info_label.setStyleSheet(f"color: {self.colors['success']};")
else:
self.current_device = None
def show_device_info(self):
"""Show detailed device information"""
if not self.current_device:
QMessageBox.warning(self, "No Device", "Please select a device first")
return
info = self.adb.get_device_info(self.current_device)
info_text = "\n".join([f"{k}: {v}" for k, v in info.items()])
QMessageBox.information(self, "Device Information", info_text)
def test_adb(self):
"""Test ADB connection and show detailed output"""
self.log("Testing ADB connection...", "INFO")
self.update_status("Testing ADB...")
# Test version
version_result = self.adb.run_command('version')
self.log(f"ADB Version Command:\nSuccess: {version_result['success']}\nReturn Code: {version_result['returncode']}", "DEBUG")
if version_result['stdout']:
self.log(f"Version Output:\n{version_result['stdout']}", "INFO")
if version_result['stderr'] and version_result['stderr'].strip():
self.log(f"Version Error:\n{version_result['stderr']}", "ERROR")
# Test devices
devices_result = self.adb.run_command('devices -l')
self.log(f"ADB Devices Command:\nSuccess: {devices_result['success']}\nReturn Code: {devices_result['returncode']}", "DEBUG")
if devices_result['stdout']:
self.log(f"Devices Output:\n{devices_result['stdout']}", "INFO")
if devices_result['stderr'] and devices_result['stderr'].strip():
self.log(f"Devices Error:\n{devices_result['stderr']}", "ERROR")
# Show summary
if version_result['success']:
self.update_status("ADB is working correctly")
QMessageBox.information(
self,
"ADB Test",
f"ADB Path: {self.adb.adb_path}\n\n"
f"Version: {'✓ Working' if version_result['success'] else '✗ Failed'}\n"
f"Devices: {'✓ Working' if devices_result['success'] else '✗ Failed'}\n\n"
f"Check the output log for details."
)
else:
self.update_status("ADB test failed - check output log")
QMessageBox.critical(
self,
"ADB Test Failed",
f"ADB Path: {self.adb.adb_path}\n\n"
f"Error: {version_result['stderr'] or 'Unknown error'}\n\n"
f"Please check:\n"
f"1. ADB path is correct\n"
f"2. ADB executable exists\n"
f"3. Check output log for details"
)
def prompt_for_adb_path(self):
"""Prompt user to select ADB folder or executable (used on first boot)"""
initial_dir = os.path.expanduser('~')
# First, try folder selection (most common use case)
folder_path = QFileDialog.getExistingDirectory(
self,
"Select platform-tools folder (contains adb)",
initial_dir
)
if folder_path:
# Accept both adb (Unix) and adb.exe (Windows)
candidates = [
os.path.join(folder_path, 'adb'),
os.path.join(folder_path, 'adb.exe'),
]
for candidate in candidates:
if os.path.exists(candidate):
return candidate
else:
QMessageBox.warning(
self,
"Error",
f"adb/adb.exe not found in:\n{folder_path}\n\nPlease select the folder that contains the adb executable"
)
return None
# Allow file selection as alternative
adb_path, _ = QFileDialog.getOpenFileName(
self,
"Or select ADB executable directly",
initial_dir,
"All files (*.*)"
)
if adb_path:
# Just return whatever the user selected; validation happens in ADBManager.set_adb_path / test
return adb_path
return None
def set_adb_path_dialog(self):
"""Open dialog to set ADB path"""
# Get initial directory from saved path or use home directory
saved_path = self.settings.get('adb_path', '')
if saved_path and os.path.exists(saved_path):
if os.path.isfile(saved_path):
initial_dir = os.path.dirname(saved_path)
else:
initial_dir = saved_path
else:
initial_dir = os.path.expanduser('~')
# First, try folder selection (most common use case)
folder_path = QFileDialog.getExistingDirectory(
self,
"Select platform-tools folder (contains adb)",
initial_dir
)
if folder_path:
adb_exe = os.path.join(folder_path, 'adb.exe')
if os.path.exists(adb_exe):
if self.adb.set_adb_path(adb_exe):
# Save to settings
self.settings['adb_path'] = adb_exe
self.save_settings()
self.adb_path_label.setText(f"✓ ADB: {adb_exe}")
self.adb_path_label.setStyleSheet(f"color: {self.colors['success']};")
self.log(f"ADB path set to: {adb_exe}")
self.update_status("ADB path updated successfully")
QMessageBox.information(self, "Success", f"ADB path set to:\n{adb_exe}")
# Refresh devices to test the new path
self.refresh_devices()
else:
QMessageBox.critical(self, "Error", "Failed to set ADB path")
else:
QMessageBox.warning(self, "Error", f"adb.exe not found in:\n{folder_path}\n\nPlease select the folder that contains adb.exe")
else:
# Allow file selection as alternative
adb_path, _ = QFileDialog.getOpenFileName(
self,
"Or select ADB executable directly",
initial_dir,
"All files (*.*)"
)
if adb_path:
if self.adb.set_adb_path(adb_path):
# Save to settings
self.settings['adb_path'] = adb_path
self.save_settings()
self.adb_path_label.setText(f"✓ ADB: {adb_path}")
self.adb_path_label.setStyleSheet(f"color: {self.colors['success']};")
self.log(f"ADB path set to: {adb_path}")
self.update_status("ADB path updated successfully")
QMessageBox.information(self, "Success", f"ADB path set to:\n{adb_path}")
# Refresh devices to test the new path
self.refresh_devices()
else:
QMessageBox.critical(self, "Error", "Failed to set ADB path")
def get_device_flag(self):
"""Get device flag for ADB commands"""
return f"-s {self.current_device}" if self.current_device else ""
def push_file(self):
"""Push file to device"""
if not self.current_device:
QMessageBox.warning(self, "No Device", "Please select a device first")
return
file_path, _ = QFileDialog.getOpenFileName(self, "Select file to push")
if not file_path:
return
dest_path, ok = QInputDialog.getText(self, "Destination", "Enter destination path on device (e.g., /sdcard/file.txt):")
if not ok or not dest_path:
return
self.log(f"Pushing {file_path} to {dest_path}...")