-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevice.rs
More file actions
1433 lines (1303 loc) · 47.7 KB
/
Copy pathdevice.rs
File metadata and controls
1433 lines (1303 loc) · 47.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
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
// This module centralizes per-device UI state, including fields wired in gradually across tabs.
#![allow(dead_code)]
use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use eframe::egui;
use crate::adb::mirror::{
DeviceRotation, DeviceRotationMode, DeviceRotationSnapshot, MirrorConfig, MirrorControl,
MirrorFrameBuffer, MirrorHandle, MirrorMode,
};
use crate::adb::{DeviceInfo, FileEntry, RemoteFileEntry};
const MAX_LOGCAT_LINES: usize = 50_000;
const MAX_SHELL_LINES: usize = 10_000;
const MAX_LOG_BUFFER_LINES: usize = 100_000;
const MAX_ACTION_LOG_LINES: usize = 2_000;
const MAX_EXPLORER_COMMAND_BYTES: usize = 2 * 1024 * 1024;
const MAX_EXPLORER_LOG_LINES: usize = 1_000;
/// Lines rendered per page in the log viewer.
pub const LOG_PAGE_SIZE: usize = 5_000;
/// Available log sources in the Logs tab sidebar.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LogSource {
Logcat,
MainUnfiltered,
Kernel,
CrashLog,
EventLog,
RadioLog,
SystemLog,
SecurityLog,
StatsLog,
AllCombined,
}
impl LogSource {
pub const ALL: &[Self] = &[
Self::Logcat,
Self::MainUnfiltered,
Self::Kernel,
Self::CrashLog,
Self::EventLog,
Self::RadioLog,
Self::SystemLog,
Self::SecurityLog,
Self::StatsLog,
Self::AllCombined,
];
pub const fn label(self) -> &'static str {
match self {
Self::Logcat => "Logcat",
Self::MainUnfiltered => "Main (all)",
Self::Kernel => "Kernel (dmesg)",
Self::CrashLog => "Crash Log",
Self::EventLog => "Event Log",
Self::RadioLog => "Radio Log",
Self::SystemLog => "System Log",
Self::SecurityLog => "Security Log",
Self::StatsLog => "Stats Log",
Self::AllCombined => "All Combined",
}
}
pub const fn is_live(self) -> bool {
matches!(self, Self::Logcat)
}
pub const fn index(self) -> u8 {
self as u8
}
pub fn from_index(idx: u8) -> Option<Self> {
Self::ALL.get(usize::from(idx)).copied()
}
}
pub const MAX_SCREEN_CAPTURES: usize = 50;
const MAX_DEBUG_OUTPUT_BYTES: usize = 2 * 1024 * 1024; // 2 MB per category
/// Debug & profiling categories in the Debug tab sidebar.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DebugRunKind {
Atrace,
Simpleperf,
Strace,
}
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DebugCategory {
ActivityManager,
DumpsysServices,
SystemTrace,
Simpleperf,
Strace,
MemoryAnalysis,
GpuGraphics,
NetworkDiag,
}
impl DebugCategory {
pub const ALL: &[Self] = &[
Self::ActivityManager,
Self::DumpsysServices,
Self::SystemTrace,
Self::Simpleperf,
Self::Strace,
Self::MemoryAnalysis,
Self::GpuGraphics,
Self::NetworkDiag,
];
pub const fn label(self) -> &'static str {
match self {
Self::ActivityManager => "Activity Manager",
Self::DumpsysServices => "Dumpsys Services",
Self::SystemTrace => "System Trace",
Self::Simpleperf => "Simpleperf",
Self::Strace => "Strace",
Self::MemoryAnalysis => "Memory",
Self::GpuGraphics => "GPU / Graphics",
Self::NetworkDiag => "Network",
}
}
pub const fn index(self) -> u8 {
self as u8
}
pub fn from_index(idx: u8) -> Option<Self> {
Self::ALL.get(usize::from(idx)).copied()
}
pub const fn run_kind(self) -> Option<DebugRunKind> {
match self {
Self::SystemTrace => Some(DebugRunKind::Atrace),
Self::Simpleperf => Some(DebugRunKind::Simpleperf),
Self::Strace => Some(DebugRunKind::Strace),
Self::ActivityManager
| Self::DumpsysServices
| Self::MemoryAnalysis
| Self::GpuGraphics
| Self::NetworkDiag => None,
}
}
}
/// System monitor categories in the Monitor tab sidebar.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MonitorCategory {
Processes,
Top,
SystemInfo,
Storage,
BatteryPower,
Thermal,
IoStats,
Services,
}
impl MonitorCategory {
pub const ALL: &[Self] = &[
Self::Processes,
Self::Top,
Self::SystemInfo,
Self::Storage,
Self::BatteryPower,
Self::Thermal,
Self::IoStats,
Self::Services,
];
pub const fn label(self) -> &'static str {
match self {
Self::Processes => "Processes",
Self::Top => "Top / Load",
Self::SystemInfo => "System Info",
Self::Storage => "Storage",
Self::BatteryPower => "Battery & Power",
Self::Thermal => "Thermal",
Self::IoStats => "I/O Stats",
Self::Services => "Services",
}
}
pub const fn index(self) -> u8 {
self as u8
}
pub fn from_index(idx: u8) -> Option<Self> {
Self::ALL.get(usize::from(idx)).copied()
}
}
/// A captured screenshot with metadata.
pub struct ScreenCapture {
pub timestamp: String,
pub png_bytes: Arc<Vec<u8>>,
pub texture: Option<egui::TextureHandle>,
pub width: u32,
pub height: u32,
}
/// Sort criteria for the file list.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FileSortBy {
Name,
Size,
#[default]
Modified,
Source,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DeployMethod {
#[default]
External,
Internal,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CapabilityStatus {
#[default]
Unknown,
Available,
Unavailable,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LogcatUiState {
pub running: bool,
pub auto_scroll: bool,
}
impl Default for LogcatUiState {
fn default() -> Self {
Self {
running: false,
auto_scroll: true,
}
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct FileActivityState {
pub pulling: bool,
pub watching: bool,
pub dirty: bool,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct ShellUiState {
pub running: bool,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct LoadingState {
pub props: bool,
pub explorer: bool,
pub uiautomator: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExplorerPreviewSkipReason {
ListingInProgress,
DirectorySelected,
FileTooLarge(usize),
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct ScreenUiState {
pub capturing: bool,
pub recording: bool,
}
/// UI state for the screen mirror tab.
pub struct MirrorUiState {
/// Whether mirroring is currently active.
pub active: bool,
/// Status message displayed in the toolbar.
pub status: String,
/// Decoded video frame dimensions (from H.264 stream).
pub video_width: u32,
pub video_height: u32,
/// Actual device display resolution (for input coordinate mapping).
pub device_width: u32,
pub device_height: u32,
/// Current display rotation reported by the device while mirroring.
pub current_rotation: Option<DeviceRotation>,
/// Total decoded frames (for FPS calculation).
pub frame_count: u64,
/// Timestamp of last FPS sample.
pub last_fps_time: f64,
/// Frame count at last FPS sample.
pub last_fps_count: u64,
/// Current frames per second.
pub fps: f32,
/// Drag gesture start position (egui screen coords).
pub drag_start: Option<egui::Pos2>,
/// Drag gesture current position (egui screen coords).
pub drag_current: Option<egui::Pos2>,
}
impl Default for MirrorUiState {
fn default() -> Self {
Self {
active: false,
status: String::new(),
video_width: 0,
video_height: 0,
device_width: 0,
device_height: 0,
current_rotation: None,
frame_count: 0,
last_fps_time: 0.0,
last_fps_count: 0,
fps: 0.0,
drag_start: None,
drag_current: None,
}
}
}
/// State for the on-device mirror server management panel.
#[derive(Default)]
pub struct MirrorServerState {
/// Whether the server JAR is installed on the device (`None` = unknown).
pub installed: Option<bool>,
/// Whether the server process is currently running (`None` = unknown).
pub running: Option<bool>,
/// A background server-management operation is in progress.
pub busy: bool,
/// Last status message from a server operation.
pub status: String,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct TestRunState {
pub monkey: bool,
pub bugreport: bool,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct DebugRunState {
pub atrace: bool,
pub simpleperf: bool,
pub strace: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FileSortState {
pub by: FileSortBy,
pub ascending: bool,
}
impl Default for FileSortState {
fn default() -> Self {
Self {
by: FileSortBy::Modified,
ascending: false,
}
}
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct DeployState {
pub running: bool,
pub status: String,
pub method: DeployMethod,
pub run_as: CapabilityStatus,
pub crash_log: String,
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct PackageToolsState {
pub package_name: String,
pub package_filter: String,
pub permission_name: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConnectionToolsState {
pub tcpip_port: String,
pub forward_local: String,
pub forward_remote: String,
pub reverse_local: String,
pub reverse_remote: String,
}
impl Default for ConnectionToolsState {
fn default() -> Self {
Self {
tcpip_port: "5555".to_string(),
forward_local: "tcp:8080".to_string(),
forward_remote: "tcp:8080".to_string(),
reverse_local: "tcp:8081".to_string(),
reverse_remote: "tcp:8081".to_string(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandToolsState {
pub instrument_runner: String,
pub am_command: String,
pub pm_command: String,
pub cmd_service: String,
pub cmd_args: String,
pub wm_size: String,
pub wm_density: String,
pub settings_namespace: String,
pub settings_key: String,
pub settings_value: String,
pub sqlite_path: String,
pub sqlite_query: String,
pub sqlite_run_as_package: String,
pub content_command: String,
}
impl Default for CommandToolsState {
fn default() -> Self {
Self {
instrument_runner: String::new(),
am_command: String::new(),
pm_command: String::new(),
cmd_service: String::new(),
cmd_args: String::new(),
wm_size: String::new(),
wm_density: String::new(),
settings_namespace: "global".to_string(),
settings_key: String::new(),
settings_value: String::new(),
sqlite_path: "databases/app.db".to_string(),
sqlite_query: "SELECT name FROM sqlite_master;".to_string(),
sqlite_run_as_package: String::new(),
content_command: String::new(),
}
}
}
/// State for a single connected device tab.
pub struct DeviceState {
pub info: DeviceInfo,
/// Accumulated logcat lines.
pub logcat_lines: Vec<String>,
/// Logcat UI state.
pub logcat_ui: LogcatUiState,
/// Logcat error/status message.
pub logcat_status: String,
/// Current live-logcat session, used to ignore stale worker output after restarts.
pub logcat_session: u64,
/// Logcat text filter (case-insensitive substring).
pub logcat_filter: String,
/// Optional live logcat tag filter (case-insensitive substring).
pub logcat_tag_filter: String,
/// Optional live logcat PID filter.
pub logcat_pid_filter: String,
/// Log level filter: 0=All, 1=V, 2=D, 3=I, 4=W, 5=E, 6=F
pub level_filter: usize,
/// Pulled file logs keyed by key (e.g. "internal/client.1.log").
pub file_logs: HashMap<String, FileEntry>,
/// Sorted keys cache (rebuilt on change).
pub sorted_keys: Vec<String>,
/// File transfer/watch state.
pub file_activity: FileActivityState,
/// File pull/watcher status message.
pub file_status: String,
/// Current live file-watcher session, used to ignore stale watcher output after restarts.
pub file_watch_session: u64,
/// Active sub-tab: 0=Logs, 1=File Logs, 2=Shell, 3=Screen, 4=Explorer, 5=Device, 6=Debug, 7=Monitor, 8=Deploy, 9=Mirror, 10=App Log
pub active_sub_tab: usize,
/// Currently selected log source in the Logs tab sidebar.
pub active_log_source: LogSource,
/// Snapshot log buffers for non-live sources.
pub log_buffers: HashMap<LogSource, Vec<String>>,
/// Which log sources are currently being fetched.
pub log_loading: HashSet<LogSource>,
/// Current page index for the log viewer (0-based, resets on source switch).
pub log_page: usize,
/// Running log watchers per source (stop flags). Logcat excluded (has its own stream).
pub log_watchers: HashMap<LogSource, Arc<AtomicBool>>,
/// Selected file key for viewing.
pub selected_file: Option<String>,
/// Search filter for file log content.
pub file_content_filter: String,
/// Stop flag for the watcher thread.
pub watcher_stop: Option<Arc<AtomicBool>>,
/// Sort settings for the file list.
pub file_sort: FileSortState,
/// Shell output history.
pub shell_output: Vec<String>,
/// Interactive shell state.
pub shell: ShellUiState,
/// Current command input.
pub shell_input: String,
/// Command history for up/down arrow navigation.
pub shell_history: Vec<String>,
/// Current position in history (`shell_history.len()` = at end / new input).
pub shell_history_pos: usize,
/// Cached device properties (key, value).
pub device_props: Vec<(String, String)>,
/// Shared loading state for async UI tools.
pub loading: LoadingState,
/// Status messages from device actions.
pub action_log: Vec<String>,
/// File explorer: current remote path.
pub explorer_path: String,
/// File explorer: whether at least one listing attempt completed.
pub explorer_loaded_once: bool,
/// File explorer: directory listing.
pub explorer_entries: Vec<RemoteFileEntry>,
/// File explorer: error message.
pub explorer_error: String,
/// File explorer: path currently being loaded, if any.
pub explorer_loading_path: Option<String>,
/// File explorer: editable path input shown in the toolbar.
pub explorer_path_input: String,
/// File explorer: selected entry name.
pub explorer_selected: Option<String>,
/// File explorer: preview content for selected file.
pub explorer_preview: Option<String>,
/// File explorer: preview error message for the selected entry.
pub explorer_preview_error: String,
/// File explorer: navigation history (back stack).
pub explorer_history: Vec<String>,
/// File explorer: generation counter to discard stale async results.
pub explorer_gen: u64,
/// File explorer: generation counter to discard stale preview results.
pub explorer_preview_gen: u64,
/// File explorer: whether preview content is currently loading.
pub explorer_preview_loading: bool,
/// File explorer: active right-side tab (0 = Preview, 1 = Commands).
pub explorer_right_tab: usize,
/// File explorer: command input.
pub explorer_command_input: String,
/// File explorer: command output.
pub explorer_command_output: String,
/// File explorer: command status line.
pub explorer_command_status: String,
/// File explorer: command history.
pub explorer_command_history: Vec<String>,
/// File explorer: history cursor.
pub explorer_command_history_pos: usize,
/// File explorer: command session token.
pub explorer_command_session: u64,
/// File explorer: whether a command is currently running.
pub explorer_command_running: bool,
/// File explorer: stop flag for live follow mode.
pub explorer_follow_stop: Option<Arc<AtomicBool>>,
/// File explorer: lifecycle and response log.
pub explorer_log_lines: Vec<String>,
/// Screen: capture history (timestamp, `texture_id`, width, height, `png_bytes`).
pub screen_captures: Vec<ScreenCapture>,
/// Screen: index of currently viewed capture.
pub screen_view_idx: Option<usize>,
/// Screen capture/record state.
pub screen: ScreenUiState,
/// Screen: auto-capture interval (None = disabled).
pub screen_auto_interval: Option<f64>,
/// Screen: last auto-capture time.
pub screen_last_auto: f64,
/// Screen: status message.
pub screen_status: String,
/// Monkey: event count input string.
pub monkey_event_count: String,
/// Test run state.
pub test_runs: TestRunState,
/// `UIAutomator`: cached XML dump content.
pub uiautomator_dump: Option<String>,
// ── Debug tab ───────────────────────────────────────────────────────
/// Currently selected debug category.
pub active_debug_category: DebugCategory,
/// Cached output per category.
pub debug_outputs: HashMap<DebugCategory, String>,
/// Which categories are currently being fetched.
pub debug_loading: HashSet<DebugCategory>,
/// Text filter for debug output.
pub debug_filter: String,
/// Dumpsys: selected service name.
pub dumpsys_service: String,
/// Dumpsys: available service list (cached).
pub dumpsys_services_list: Vec<String>,
/// Atrace: selected categories for system trace.
pub atrace_categories: Vec<String>,
/// Atrace: available category list (cached).
pub atrace_available_cats: Vec<String>,
/// Atrace: duration in seconds (input string).
pub atrace_duration: String,
/// Debug profiler run state.
pub debug_runs: DebugRunState,
/// Simpleperf: duration in seconds (input string).
pub simpleperf_duration: String,
/// Simpleperf: event to record.
pub simpleperf_event: String,
/// Strace: target PID (input string).
pub strace_pid: String,
/// Strace: duration in seconds (input string).
pub strace_duration: String,
/// Memory analysis: heap watch threshold in megabytes.
pub memory_watch_limit_mb: String,
// ── Monitor tab ────────────────────────────────────────────────────
/// Currently selected monitor category.
pub active_monitor_category: MonitorCategory,
/// Cached output per category.
pub monitor_outputs: HashMap<MonitorCategory, String>,
/// Which categories are currently being fetched.
pub monitor_loading: HashSet<MonitorCategory>,
/// Text filter for monitor output.
pub monitor_filter: String,
/// Process search input (for ps grep).
pub monitor_ps_search: String,
/// PID input for kill/signal.
pub monitor_kill_pid: String,
// ── Deploy tab ─────────────────────────────────────────────────
/// Deploy workflow state.
pub deploy: DeployState,
/// Package manager helpers and inputs.
pub package_tools: PackageToolsState,
/// Connection and forwarding helpers.
pub connection_tools: ConnectionToolsState,
/// Advanced shell-backed command helpers.
pub command_tools: CommandToolsState,
// ── Mirror tab ────────────────────────────────────────────────────
/// Mirror UI state.
pub mirror: MirrorUiState,
/// Mirror encoding/resolution config.
pub mirror_config: MirrorConfig,
/// Shared frame buffer (decode thread → UI thread).
pub mirror_frame_buffer: Option<Arc<MirrorFrameBuffer>>,
/// egui texture for the current mirror frame.
pub mirror_texture: Option<egui::TextureHandle>,
/// Stop flag for the mirror background thread.
pub mirror_stop: Option<Arc<std::sync::atomic::AtomicBool>>,
/// Input control handle for the active mirror session.
pub mirror_control: Option<MirrorControl>,
/// Current mirror session token used to discard stale worker messages.
pub mirror_session: u64,
/// Requested device rotation mode for the mirror tab.
pub mirror_rotation_mode: DeviceRotationMode,
/// Original device rotation state captured before mirror-driven changes.
pub mirror_rotation_snapshot: Option<DeviceRotationSnapshot>,
/// Selected mirror mode (screenrecord or server).
pub mirror_mode: MirrorMode,
/// On-device server management state.
pub mirror_server: MirrorServerState,
}
impl DeviceState {
pub fn new(info: DeviceInfo) -> Self {
Self {
info,
logcat_lines: Vec::with_capacity(4096),
logcat_ui: LogcatUiState::default(),
logcat_status: String::new(),
logcat_session: 0,
logcat_filter: String::new(),
logcat_tag_filter: String::new(),
logcat_pid_filter: String::new(),
level_filter: 0,
file_logs: HashMap::new(),
sorted_keys: Vec::new(),
file_activity: FileActivityState::default(),
file_status: String::new(),
file_watch_session: 0,
active_sub_tab: 0,
active_log_source: LogSource::Logcat,
log_buffers: HashMap::new(),
log_loading: HashSet::new(),
log_page: 0, // page 0 = newest lines
log_watchers: HashMap::new(),
selected_file: None,
file_content_filter: String::new(),
watcher_stop: None,
file_sort: FileSortState::default(),
shell_output: Vec::with_capacity(1024),
shell: ShellUiState::default(),
shell_input: String::new(),
shell_history: Vec::new(),
shell_history_pos: 0,
device_props: Vec::new(),
loading: LoadingState::default(),
action_log: Vec::new(),
explorer_path: "/sdcard".into(),
explorer_loaded_once: false,
explorer_entries: Vec::new(),
explorer_error: String::new(),
explorer_loading_path: None,
explorer_path_input: "/sdcard".into(),
explorer_selected: None,
explorer_preview: None,
explorer_preview_error: String::new(),
explorer_history: Vec::new(),
explorer_gen: 0,
explorer_preview_gen: 0,
explorer_preview_loading: false,
explorer_right_tab: 0,
explorer_command_input: String::new(),
explorer_command_output: String::new(),
explorer_command_status: String::new(),
explorer_command_history: Vec::new(),
explorer_command_history_pos: 0,
explorer_command_session: 0,
explorer_command_running: false,
explorer_follow_stop: None,
explorer_log_lines: Vec::new(),
screen_captures: Vec::new(),
screen_view_idx: None,
screen: ScreenUiState::default(),
screen_auto_interval: None,
screen_last_auto: 0.0,
screen_status: String::new(),
monkey_event_count: "1000".into(),
test_runs: TestRunState::default(),
uiautomator_dump: None,
active_debug_category: DebugCategory::ActivityManager,
debug_outputs: HashMap::new(),
debug_loading: HashSet::new(),
debug_filter: String::new(),
dumpsys_service: String::new(),
dumpsys_services_list: Vec::new(),
atrace_categories: Vec::new(),
atrace_available_cats: Vec::new(),
atrace_duration: "5".into(),
debug_runs: DebugRunState::default(),
simpleperf_duration: "5".into(),
simpleperf_event: "cpu-cycles".into(),
strace_pid: String::new(),
strace_duration: "5".into(),
memory_watch_limit_mb: "256".into(),
active_monitor_category: MonitorCategory::Processes,
monitor_outputs: HashMap::new(),
monitor_loading: HashSet::new(),
monitor_filter: String::new(),
monitor_ps_search: String::new(),
monitor_kill_pid: String::new(),
deploy: DeployState::default(),
package_tools: PackageToolsState::default(),
connection_tools: ConnectionToolsState::default(),
command_tools: CommandToolsState::default(),
mirror: MirrorUiState::default(),
mirror_config: MirrorConfig::default(),
mirror_frame_buffer: None,
mirror_texture: None,
mirror_stop: None,
mirror_control: None,
mirror_session: 0,
mirror_rotation_mode: DeviceRotationMode::default(),
mirror_rotation_snapshot: None,
mirror_mode: MirrorMode::default(),
mirror_server: MirrorServerState::default(),
}
}
pub fn push_logcat_line(&mut self, line: String) {
self.logcat_lines.push(line);
if self.logcat_lines.len() > MAX_LOGCAT_LINES {
let drain = MAX_LOGCAT_LINES / 5;
self.logcat_lines.drain(..drain);
}
if self.logcat_ui.auto_scroll {
self.log_page = 0;
}
}
/// Set a snapshot log buffer (replaces previous content).
pub fn set_log_buffer(&mut self, source: LogSource, lines: Vec<String>) {
let mut buf = lines;
if buf.len() > MAX_LOG_BUFFER_LINES {
buf.drain(..buf.len() - MAX_LOG_BUFFER_LINES);
}
self.log_buffers.insert(source, buf);
self.log_loading.remove(&source);
}
pub fn push_shell_output(&mut self, line: String) {
self.shell_output.push(line);
if self.shell_output.len() > MAX_SHELL_LINES {
let drain = MAX_SHELL_LINES / 5;
self.shell_output.drain(..drain);
}
}
pub fn push_action_log(&mut self, line: String) {
self.action_log.push(line);
if self.action_log.len() > MAX_ACTION_LOG_LINES {
let drain = MAX_ACTION_LOG_LINES / 5;
self.action_log.drain(..drain);
}
}
/// Set debug output for a category (capped to `MAX_DEBUG_OUTPUT_BYTES`).
pub fn set_debug_output(&mut self, cat: DebugCategory, mut text: String) {
text.truncate(MAX_DEBUG_OUTPUT_BYTES);
self.debug_outputs.insert(cat, text);
self.debug_loading.remove(&cat);
}
/// Set monitor output for a category (capped to `MAX_DEBUG_OUTPUT_BYTES`).
pub fn set_monitor_output(&mut self, cat: MonitorCategory, mut text: String) {
text.truncate(MAX_DEBUG_OUTPUT_BYTES);
self.monitor_outputs.insert(cat, text);
self.monitor_loading.remove(&cat);
}
/// Insert or update a file entry. Marks dirty for deferred sort rebuild.
pub fn upsert_file(&mut self, entry: FileEntry) {
self.file_logs.insert(entry.key.clone(), entry);
self.file_activity.dirty = true;
}
/// Rebuild sorted keys if dirty. Call once per frame after draining messages.
pub fn flush_if_dirty(&mut self) {
if self.file_activity.dirty {
self.rebuild_sorted_keys();
self.file_activity.dirty = false;
}
}
/// Rebuild the sorted key list.
pub fn rebuild_sorted_keys(&mut self) {
let mut keys: Vec<String> = self.file_logs.keys().cloned().collect();
let logs = &self.file_logs;
let asc = self.file_sort.ascending;
keys.sort_by(|a, b| {
let ea = &logs[a];
let eb = &logs[b];
let ord = match self.file_sort.by {
FileSortBy::Name => ea.name.to_lowercase().cmp(&eb.name.to_lowercase()),
FileSortBy::Size => ea.size.cmp(&eb.size),
FileSortBy::Modified => ea.modified.cmp(&eb.modified),
FileSortBy::Source => ea.source.cmp(&eb.source).then(ea.name.cmp(&eb.name)),
};
if asc {
ord
} else {
ord.reverse()
}
});
self.sorted_keys = keys;
}
/// Stop the file watcher if running.
pub fn stop_watcher(&mut self) {
if let Some(ref stop) = self.watcher_stop {
stop.store(true, Ordering::Relaxed);
}
self.watcher_stop = None;
self.file_activity.watching = false;
}
/// Advance the live logcat session and return the new session ID.
pub const fn start_next_logcat_session(&mut self) -> u64 {
self.logcat_session = next_session_id(self.logcat_session);
self.logcat_session
}
/// Advance the live file-watcher session and return the new session ID.
pub const fn start_next_file_watch_session(&mut self) -> u64 {
self.file_watch_session = next_session_id(self.file_watch_session);
self.file_watch_session
}
/// Advance the mirror session and return the new session token.
pub const fn start_next_mirror_session(&mut self) -> u64 {
self.mirror_session = next_session_id(self.mirror_session);
self.mirror_session
}
/// Stop the current mirror worker and invalidate any in-flight messages for it.
pub fn cancel_mirror_session(&mut self, status: impl Into<String>) {
if self.mirror_stop.is_some()
|| self.mirror_frame_buffer.is_some()
|| self.mirror_texture.is_some()
|| self.mirror_control.is_some()
|| self.mirror.active
{
self.mirror_session = next_session_id(self.mirror_session);
}
self.finish_mirror_session(status);
}
/// Attach runtime handles for a freshly started mirror session.
pub fn attach_mirror_session(&mut self, session: u64, handle: MirrorHandle) {
self.mirror = MirrorUiState::default();
self.mirror.active = true;
self.mirror.status = "Starting...".to_string();
self.mirror_session = session;
self.mirror_stop = Some(handle.stop);
self.mirror_frame_buffer = Some(handle.frame_buffer);
self.mirror_control = Some(handle.control);
self.mirror_texture = None;
}
/// Tear down runtime handles for the active mirror session and keep a final status message.
pub fn finish_mirror_session(&mut self, status: impl Into<String>) {
if let Some(stop) = self.mirror_stop.take() {
stop.store(true, Ordering::Release);
}
self.mirror = MirrorUiState::default();
self.mirror.status = status.into();
self.mirror_frame_buffer = None;
self.mirror_texture = None;
self.mirror_control = None;
}
/// Stop a log source watcher.
pub fn stop_log_watcher(&mut self, source: LogSource) {
if let Some(stop) = self.log_watchers.remove(&source) {
stop.store(true, Ordering::Relaxed);
}
}
/// Stop all log source watchers.
pub fn stop_all_log_watchers(&mut self) {
for (_, stop) in self.log_watchers.drain() {
stop.store(true, Ordering::Relaxed);
}
}
/// Explorer path shown in the toolbar. While a request is in flight, this is the pending path.
pub fn explorer_visible_path(&self) -> &str {
self.explorer_loading_path
.as_deref()
.unwrap_or(&self.explorer_path)
}
/// Start navigation to a target path and optionally push the current visible path onto history.
pub fn start_explorer_navigation(
&mut self,
target: &str,
push_history: bool,
) -> Option<(u64, String)> {
let target = normalize_remote_dir_path(target);
let current_visible = self.explorer_visible_path().to_string();
if target == current_visible {
return None;
}
if push_history && self.explorer_history.last() != Some(¤t_visible) {
self.explorer_history.push(current_visible);
}
Some(self.begin_explorer_request(target))
}
/// Start a refresh of the current visible path.
pub fn start_explorer_refresh(&mut self) -> (u64, String) {
self.begin_explorer_request(self.explorer_visible_path().to_string())
}
/// Navigate back to the previous path, skipping duplicate entries.
pub fn start_explorer_back_navigation(&mut self) -> Option<(u64, String)> {
let current_visible = self.explorer_visible_path().to_string();
while let Some(path) = self.explorer_history.pop() {
let normalized = normalize_remote_dir_path(&path);
if normalized != current_visible {
return Some(self.begin_explorer_request(normalized));
}
}
None
}
/// Apply a successful directory listing if it belongs to the current request.
pub fn finish_explorer_listing(
&mut self,
request_gen: u64,
path: &str,
entries: Vec<RemoteFileEntry>,
) -> bool {
if request_gen != self.explorer_gen {
return false;
}
self.explorer_path = normalize_remote_dir_path(path);
self.explorer_loaded_once = true;
self.explorer_entries = entries;
self.loading.explorer = false;
self.explorer_loaded_once = true;
self.explorer_loading_path = None;
self.explorer_path_input = self.explorer_path.clone();
self.explorer_error.clear();
self.explorer_selected = None;
self.explorer_preview = None;
self.explorer_preview_error.clear();
self.explorer_preview_loading = false;
true
}
/// Apply a failed directory listing if it belongs to the current request.
pub fn fail_explorer_listing(&mut self, request_gen: u64, error: String) -> bool {