ghostscope-ui 0.1.1

Terminal user interface that streams GhostScope traces with async input handling.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
use crossterm::event::{KeyEvent, MouseEvent};
use ghostscope_protocol::ParsedTraceEvent;
use tokio::sync::mpsc;
use unicode_width::UnicodeWidthStr;

/// Trace status enumeration for shared use between UI and runtime
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TraceStatus {
    Active,
    Disabled,
    Failed,
}

impl std::fmt::Display for TraceStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TraceStatus::Active => write!(f, "Active"),
            TraceStatus::Disabled => write!(f, "Disabled"),
            TraceStatus::Failed => write!(f, "Failed"),
        }
    }
}

impl TraceStatus {
    /// Convert to emoji representation
    pub fn to_emoji(&self) -> String {
        match self {
            TraceStatus::Active => "".to_string(),
            TraceStatus::Disabled => "⏸️".to_string(),
            TraceStatus::Failed => "".to_string(),
        }
    }

    /// Parse from string (for backward compatibility)
    pub fn from_string(s: &str) -> Self {
        match s {
            "Active" => TraceStatus::Active,
            "Disabled" => TraceStatus::Disabled,
            "Failed" => TraceStatus::Failed,
            _ => TraceStatus::Failed, // Default to Failed for unknown status
        }
    }
}

/// TUI events that can be handled by the application
#[derive(Debug, Clone)]
pub enum TuiEvent {
    Key(KeyEvent),
    Mouse(MouseEvent),
    Resize(u16, u16),
    Quit,
}

/// Registry for event communication between TUI and runtime
#[derive(Debug)]
pub struct EventRegistry {
    // TUI -> Runtime communication
    pub command_sender: mpsc::UnboundedSender<RuntimeCommand>,

    // Runtime -> TUI communication
    pub trace_receiver: mpsc::UnboundedReceiver<ParsedTraceEvent>,
    pub status_receiver: mpsc::UnboundedReceiver<RuntimeStatus>,
}

/// Source code information for display in TUI
#[derive(Debug, Clone)]
pub struct SourceCodeInfo {
    pub file_path: String,
    pub current_line: Option<usize>,
}

/// Debug information for a target (function or source location)
#[derive(Debug, Clone)]
pub struct TargetDebugInfo {
    pub target: String,
    pub target_type: TargetType,
    pub file_path: Option<String>,
    pub line_number: Option<u32>,
    pub function_name: Option<String>,
    pub modules: Vec<ModuleDebugInfo>, // Grouped by module/binary
}

impl TargetDebugInfo {
    /// Format target debug info with tree-style layout for display
    pub fn format_for_display(&self, verbose: bool) -> String {
        let mut result = String::new();

        // Calculate statistics
        let module_count = self.modules.len();
        let total_addresses: usize = self
            .modules
            .iter()
            .map(|module| module.address_mappings.len())
            .sum();

        // Header by target type
        let header_prefix = match self.target_type {
            TargetType::Function => "🔧 Function Debug Info",
            TargetType::SourceLocation => "📄 Line Debug Info",
            TargetType::Address => "📍 Address Debug Info",
        };
        result.push_str(&format!(
            "{header_prefix}: {} ({} modules, {} traceable addresses)\n\n",
            self.target, module_count, total_addresses
        ));

        // Format modules with tree structure - modules will show their own paths and source info
        for (module_idx, module) in self.modules.iter().enumerate() {
            let is_last_module = module_idx == self.modules.len() - 1;
            result.push_str(&module.format_for_display(
                is_last_module,
                &self.file_path,
                self.line_number,
                verbose,
            ));
        }

        // Suggestions for address targets
        if let TargetType::Address = self.target_type {
            // Try to pick the first address for an example
            let example_addr = self
                .modules
                .iter()
                .flat_map(|m| m.address_mappings.iter())
                .map(|m| m.address)
                .next();
            if let Some(addr) = example_addr {
                result.push_str("\n💡 Tips:\n");
                result.push_str(&format!(
                    "  - In '-t <module>' mode: use `trace 0x{addr:x} {{ ... }}` (defaults to that module)\n"
                ));
                result.push_str(&format!(
                    "  - In '-p <pid>' mode: default module is the main executable; for library addresses, start GhostScope with '-t <that .so>' then use `trace 0x{addr:x} {{ ... }}`\n"
                ));
            }
        }

        result
    }

    /// Styled version for display (pre-styled lines for UI rendering)
    pub fn format_for_display_styled(&self, verbose: bool) -> Vec<ratatui::text::Line<'static>> {
        use crate::components::command_panel::style_builder::StyledLineBuilder;
        use ratatui::text::Line;

        let mut lines = Vec::new();

        // Title line by type
        let total_addresses: usize = self.modules.iter().map(|m| m.address_mappings.len()).sum();
        let header_prefix = match self.target_type {
            TargetType::Function => "🔧 Function Debug Info",
            TargetType::SourceLocation => "📄 Line Debug Info",
            TargetType::Address => "📍 Address Debug Info",
        };
        lines.push(
            StyledLineBuilder::new()
                .title(format!(
                    "{header_prefix}: {} ({} modules, {} addresses)",
                    self.target,
                    self.modules.len(),
                    total_addresses
                ))
                .build(),
        );
        lines.push(Line::from(""));

        for (idx, module) in self.modules.iter().enumerate() {
            let is_last = idx + 1 == self.modules.len();
            lines.extend(module.format_for_display_styled(
                is_last,
                &self.file_path,
                self.line_number,
                verbose,
            ));
        }

        // Suggestions for address targets
        if let TargetType::Address = self.target_type {
            // Example address from first mapping
            if let Some(addr) = self
                .modules
                .iter()
                .flat_map(|m| m.address_mappings.iter())
                .map(|m| m.address)
                .next()
            {
                lines.push(Line::from(""));
                lines.push(
                    StyledLineBuilder::new()
                        .styled(
                            "💡 Tips:",
                            crate::components::command_panel::style_builder::StylePresets::SECTION,
                        )
                        .build(),
                );
                lines.push(
                    StyledLineBuilder::new()
                        .text("  - In '-t <module>' mode: use ")
                        .value(format!("trace 0x{addr:x} {{ ... }}"))
                        .text(" (defaults to that module)")
                        .build(),
                );
                lines.push(
                    StyledLineBuilder::new()
                        .text("  - In '-p <pid>' mode: default module is main executable; for library addresses, start with '-t <that .so>' then use ")
                        .value(format!("trace 0x{addr:x} {{ ... }}"))
                        .build(),
                );
            }
        }

        lines
    }
}

/// Debug information for a module (binary) containing one or more addresses
#[derive(Debug, Clone)]
pub struct ModuleDebugInfo {
    pub binary_path: String,
    pub address_mappings: Vec<AddressMapping>,
}

impl ModuleDebugInfo {
    /// Format module info with tree-style layout for display
    pub fn format_for_display(
        &self,
        is_last_module: bool,
        source_file: &Option<String>,
        source_line: Option<u32>,
        verbose: bool,
    ) -> String {
        let mut result = String::new();

        // Module header with full path and source info
        result.push_str(&format!("📦 {}", &self.binary_path));

        // Add source information if available
        if let Some(ref file) = source_file {
            if let Some(line) = source_line {
                result.push_str(&format!(" @ {file}:{line}\n"));
            } else {
                result.push_str(&format!(" @ {file}\n"));
            }
        } else {
            result.push('\n');
        }

        for (addr_idx, mapping) in self.address_mappings.iter().enumerate() {
            let is_last_addr = addr_idx == self.address_mappings.len() - 1;
            let addr_prefix = match (is_last_module, is_last_addr) {
                (true, true) => "   └─",
                (true, false) => "   ├─",
                (false, true) => "│  └─",
                (false, false) => "│  ├─",
            };

            // Enhanced PC address display with optional index + classification/source
            let mut pc_description = if let Some(i) = mapping.index {
                format!("[{}] 🎯 0x{:x}", i, mapping.address)
            } else {
                format!("🎯 0x{:x}", mapping.address)
            };
            if let Some(is_inline) = mapping.is_inline {
                pc_description
                    .push_str(&format!("{}", if is_inline { "inline" } else { "call" }));
            }
            if let (Some(ref file), Some(line)) = (&mapping.source_file, mapping.source_line) {
                pc_description.push_str(&format!(" @ {file}:{line}"));
            }

            result.push_str(&format!("{addr_prefix} {pc_description}\n"));

            // Format parameters
            if !mapping.parameters.is_empty() {
                let param_prefix = match (is_last_module, is_last_addr) {
                    (true, true) => "      ├─",
                    (true, false) => "   │  ├─",
                    (false, true) => "│     ├─",
                    (false, false) => "│  │  ├─",
                };

                result.push_str(&format!("{param_prefix} 📥 Parameters\n"));

                for (param_idx, param) in mapping.parameters.iter().enumerate() {
                    let is_last_param =
                        param_idx == mapping.parameters.len() - 1 && mapping.variables.is_empty();
                    let item_prefix = match (is_last_module, is_last_addr, is_last_param) {
                        (true, true, true) => "      │  └─",
                        (true, true, false) => "      │  ├─",
                        (true, false, true) => "   │  │  └─",
                        (true, false, false) => "   │  │  ├─",
                        (false, true, true) => "│     │  └─",
                        (false, true, false) => "│     │  ├─",
                        (false, false, true) => "│  │  │  └─",
                        (false, false, false) => "│  │  │  ├─",
                    };

                    let param_line = Self::format_variable_line(param, verbose);

                    result.push_str(&Self::wrap_long_line(
                        &format!("{item_prefix} {param_line}"),
                        80,
                        item_prefix,
                    ));
                }
            }

            // Format variables
            if !mapping.variables.is_empty() {
                let var_prefix = match (is_last_module, is_last_addr) {
                    (true, true) => "      └─",
                    (true, false) => "   │  └─",
                    (false, true) => "│     └─",
                    (false, false) => "│  │  └─",
                };

                result.push_str(&format!("{var_prefix} 📦 Variables\n"));

                for (var_idx, var) in mapping.variables.iter().enumerate() {
                    let is_last_var = var_idx == mapping.variables.len() - 1;
                    let item_prefix = match (is_last_module, is_last_addr, is_last_var) {
                        (true, true, true) => "         └─",
                        (true, true, false) => "         ├─",
                        (true, false, true) => "   │     └─",
                        (true, false, false) => "   │     ├─",
                        (false, true, true) => "│        └─",
                        (false, true, false) => "│        ├─",
                        (false, false, true) => "│  │     └─",
                        (false, false, false) => "│  │     ├─",
                    };

                    let var_line = Self::format_variable_line(var, verbose);

                    result.push_str(&Self::wrap_long_line(
                        &format!("{item_prefix} {var_line}"),
                        80,
                        item_prefix,
                    ));
                }
            }
        }

        result
    }

    /// Overload helper: build from VariableDebugInfo
    pub fn format_variable_line(var: &VariableDebugInfo, verbose: bool) -> String {
        // Use enhanced DWARF type display (includes type name and size)
        let type_display = var
            .type_pretty
            .as_ref()
            .filter(|pretty| !pretty.is_empty())
            .cloned()
            .unwrap_or_else(|| "unknown".to_string());

        let name = &var.name;
        if !verbose || var.location_description.is_empty() || var.location_description == "None" {
            format!("{name} ({type_display})")
        } else {
            let location = &var.location_description;
            format!("{name} ({type_display}) = {location}")
        }
    }

    /// Wrap long lines with proper indentation
    fn wrap_long_line(text: &str, max_width: usize, indent: &str) -> String {
        if text.len() <= max_width {
            format!("{text}\n")
        } else {
            let mut result = String::new();
            let mut current_line = text.to_string();

            while current_line.len() > max_width {
                let break_point = current_line
                    .rfind(' ')
                    .unwrap_or(max_width.saturating_sub(10));
                let (first_part, rest) = current_line.split_at(break_point);
                result.push_str(&format!("{first_part}\n"));

                // Create continuation line with proper indentation
                let continuation_indent =
                    format!("{}   ", indent.replace("├─", "").replace("└─", "  "));
                let trimmed_rest = rest.trim();
                current_line = format!("{continuation_indent}{trimmed_rest}");
            }

            if !current_line.trim().is_empty() {
                result.push_str(&format!("{current_line}\n"));
            }

            result
        }
    }
}

impl ModuleDebugInfo {
    /// Styled module info lines
    pub fn format_for_display_styled(
        &self,
        is_last_module: bool,
        source_file: &Option<String>,
        source_line: Option<u32>,
        verbose: bool,
    ) -> Vec<ratatui::text::Line<'static>> {
        use crate::components::command_panel::style_builder::{StylePresets, StyledLineBuilder};

        let mut lines = Vec::new();

        let mut builder = StyledLineBuilder::new()
            .styled("📦 ", StylePresets::SECTION)
            .styled(&self.binary_path, StylePresets::SECTION);

        if let Some(ref file) = source_file {
            builder = builder.text(" @ ").styled(
                if let Some(line) = source_line {
                    format!("{file}:{line}")
                } else {
                    file.clone()
                },
                StylePresets::LOCATION,
            );
        }

        lines.push(builder.build());

        for (addr_idx, mapping) in self.address_mappings.iter().enumerate() {
            let is_last_addr = addr_idx + 1 == self.address_mappings.len();
            lines.extend(mapping.format_for_display_styled(is_last_module, is_last_addr, verbose));
        }

        lines
    }
}

/// Debug information for a specific address within a module
#[derive(Debug, Clone)]
pub struct AddressMapping {
    pub address: u64,
    pub binary_path: String, // Full binary path for this address
    pub function_name: Option<String>,
    pub variables: Vec<VariableDebugInfo>,
    pub parameters: Vec<VariableDebugInfo>,
    pub source_file: Option<String>,
    pub source_line: Option<u32>,
    pub is_inline: Option<bool>,
    pub index: Option<usize>, // 1-based global index for selection
}

impl AddressMapping {
    /// Styled address mapping lines with tree prefixes
    pub fn format_for_display_styled(
        &self,
        is_last_module: bool,
        is_last_addr: bool,
        verbose: bool,
    ) -> Vec<ratatui::text::Line<'static>> {
        use crate::components::command_panel::style_builder::{StylePresets, StyledLineBuilder};

        let mut lines = Vec::new();

        let prefix = match (is_last_module, is_last_addr) {
            (true, true) => "   └─",
            (true, false) => "   ├─",
            (false, true) => "│  └─",
            (false, false) => "│  ├─",
        };

        // Header line with index + address + optional classification and source location
        let mut header = StyledLineBuilder::new().styled(prefix, StylePresets::TREE);
        if let Some(i) = self.index {
            header = header
                .text(" ")
                .styled(format!("[{i}]"), StylePresets::ADDRESS);
        }
        header = header.text(" 🎯 ").address(self.address);

        if let Some(is_inline) = self.is_inline {
            header = header
                .text(" ")
                .key("")
                .text(" ")
                .styled(if is_inline { "inline" } else { "call" }, StylePresets::KEY);
        }
        if let (Some(ref file), Some(line)) = (&self.source_file, self.source_line) {
            header = header
                .text(" ")
                .key("@")
                .text(" ")
                .value(format!("{file}:{line}"));
        }

        lines.push(header.build());

        if !self.parameters.is_empty() {
            let param_prefix = match (is_last_module, is_last_addr) {
                (true, true) => "      ├─",
                (true, false) => "   │  ├─",
                (false, true) => "│     ├─",
                (false, false) => "│  │  ├─",
            };

            lines.push(
                StyledLineBuilder::new()
                    .styled(param_prefix, StylePresets::TREE)
                    .styled(" 📥 Parameters", StylePresets::SECTION)
                    .build(),
            );

            for (param_idx, param) in self.parameters.iter().enumerate() {
                let is_last_param =
                    param_idx + 1 == self.parameters.len() && self.variables.is_empty();
                let item_prefix = match (is_last_module, is_last_addr, is_last_param) {
                    (true, true, true) => "      │  └─",
                    (true, true, false) => "      │  ├─",
                    (true, false, true) => "   │  │  └─",
                    (true, false, false) => "   │  │  ├─",
                    (false, true, true) => "│     │  └─",
                    (false, true, false) => "│     │  ├─",
                    (false, false, true) => "│  │  │  └─",
                    (false, false, false) => "│  │  │  ├─",
                };

                lines.push(Self::format_variable_styled(item_prefix, param, verbose));
            }
        }

        if !self.variables.is_empty() {
            let var_prefix = match (is_last_module, is_last_addr) {
                (true, true) => "      └─",
                (true, false) => "   │  └─",
                (false, true) => "│     └─",
                (false, false) => "│  │  └─",
            };

            lines.push(
                StyledLineBuilder::new()
                    .styled(var_prefix, StylePresets::TREE)
                    .styled(" 📦 Variables", StylePresets::SECTION)
                    .build(),
            );

            for (var_idx, var) in self.variables.iter().enumerate() {
                let is_last_var = var_idx + 1 == self.variables.len();
                let item_prefix = match (is_last_module, is_last_addr, is_last_var) {
                    (true, true, true) => "         └─",
                    (true, true, false) => "         ├─",
                    (true, false, true) => "   │     └─",
                    (true, false, false) => "   │     ├─",
                    (false, true, true) => "│        └─",
                    (false, true, false) => "│        ├─",
                    (false, false, true) => "│  │     └─",
                    (false, false, false) => "│  │     ├─",
                };

                lines.push(Self::format_variable_styled(item_prefix, var, verbose));
            }
        }

        lines
    }

    fn format_variable_styled(
        indent_prefix: &str,
        var: &VariableDebugInfo,
        verbose: bool,
    ) -> ratatui::text::Line<'static> {
        use crate::components::command_panel::style_builder::{StylePresets, StyledLineBuilder};

        let type_display = var
            .type_pretty
            .as_ref()
            .filter(|s| !s.is_empty())
            .map(|s| s.as_str())
            .unwrap_or("unknown");

        let mut builder = StyledLineBuilder::new()
            .styled(indent_prefix, StylePresets::TREE)
            .text(" ")
            .value(&var.name)
            .key(": ")
            .styled(type_display, StylePresets::TYPE);

        if let Some(size) = var.size {
            builder = builder.text(" ").text(format!("({size} bytes)"));
        }

        if verbose && !var.location_description.is_empty() && var.location_description != "None" {
            builder = builder
                .text(" ")
                .key("@")
                .text(" ")
                .styled(&var.location_description, StylePresets::LOCATION);
        }

        builder.build()
    }
}

/// Type of target being inspected
#[derive(Debug, Clone)]
pub enum TargetType {
    Function,
    SourceLocation,
    Address,
}

/// Variable debug information
#[derive(Debug, Clone)]
pub struct VariableDebugInfo {
    pub name: String,
    pub type_name: String,
    pub type_pretty: Option<String>,
    pub location_description: String,
    pub size: Option<u64>,
    pub scope_start: Option<u64>,
    pub scope_end: Option<u64>,
}

/// Commands that TUI can send to runtime
#[derive(Debug, Clone)]
pub enum RuntimeCommand {
    ExecuteScript {
        command: String,
        selected_index: Option<usize>,
    },
    RequestSourceCode, // Request source code for current function/address
    DisableTrace(u32), // Disable specific trace by ID
    EnableTrace(u32),  // Enable specific trace by ID
    DisableAllTraces,  // Disable all traces
    EnableAllTraces,   // Enable all traces
    DeleteTrace(u32),  // Completely delete specific trace and all resources
    DeleteAllTraces,   // Delete all traces and resources
    InfoFunction {
        target: String,
        verbose: bool,
    }, // Get debug info for a function by name
    InfoLine {
        target: String,
        verbose: bool,
    }, // Get debug info for a source line (file:line)
    InfoAddress {
        target: String,
        verbose: bool,
    }, // Get debug info for a memory address (TODO: not implemented yet)
    InfoTrace {
        trace_id: Option<u32>,
    }, // Get info for one/all traces (individual messages)
    InfoTraceAll,
    InfoSource, // Get all source files information
    InfoShare,  // Get shared library information (like GDB's "info share")
    InfoFile,   // Get executable file information and sections (like GDB's "info file")
    SaveTraces {
        filename: Option<String>,
        filter: crate::components::command_panel::trace_persistence::SaveFilter,
    }, // Save traces to a file
    LoadTraces {
        filename: String,
        traces: Vec<TraceDefinition>,
    }, // Load traces from a file
    SrcPathList,
    SrcPathAddDir {
        dir: String,
    },
    SrcPathAddMap {
        from: String,
        to: String,
    },
    SrcPathRemove {
        pattern: String,
    },
    SrcPathClear,
    SrcPathReset,
    Shutdown,
}

/// Definition of a trace to be loaded
#[derive(Debug, Clone)]
pub struct TraceDefinition {
    pub target: String,
    pub script: String,
    pub enabled: bool,
    pub selected_index: Option<usize>,
}

/// Result of loading a single trace
#[derive(Debug, Clone)]
pub struct TraceLoadDetail {
    pub target: String,
    pub trace_id: Option<u32>,
    pub status: LoadStatus,
    pub error: Option<String>,
}

/// Status of loading a trace
#[derive(Debug, Clone)]
pub enum LoadStatus {
    Created,         // Successfully created and enabled
    CreatedDisabled, // Created but disabled
    Failed,          // Failed to create
    Skipped,         // Skipped (e.g., duplicate)
}

/// Execution status for individual script targets
#[derive(Debug, Clone)]
pub enum ExecutionStatus {
    Success,
    Failed(String),  // Contains error message
    Skipped(String), // Contains reason for skipping
}

/// Result of executing a single script target (PC/function)
#[derive(Debug, Clone)]
pub struct ScriptExecutionResult {
    pub pc_address: u64,
    pub target_name: String,
    pub binary_path: String, // Full path to the binary
    pub status: ExecutionStatus,
    pub source_file: Option<String>,
    pub source_line: Option<u32>,
    pub is_inline: Option<bool>,
}

/// Detailed compilation result for a script with multiple targets
#[derive(Debug, Clone)]
pub struct ScriptCompilationDetails {
    pub trace_ids: Vec<u32>, // List of generated trace IDs (one per successful compilation)
    pub results: Vec<ScriptExecutionResult>,
    pub total_count: usize,
    pub success_count: usize,
    pub failed_count: usize,
}

#[derive(Debug, Clone)]
pub enum RuntimeStatus {
    DwarfLoadingStarted,
    DwarfLoadingCompleted {
        symbols_count: usize,
    },
    DwarfLoadingFailed(String),
    ScriptCompilationCompleted {
        details: ScriptCompilationDetails, // Contains trace_ids, success/failed counts and results
    },
    UprobeAttached {
        function: String,
        address: u64,
    },
    UprobeDetached {
        function: String,
    },
    SourceCodeLoaded(SourceCodeInfo),
    SourceCodeLoadFailed(String),
    TraceEnabled {
        trace_id: u32,
    },
    TraceDisabled {
        trace_id: u32,
    },
    AllTracesEnabled {
        count: usize,
        error: Option<String>, // Error message if operation completely failed
    },
    AllTracesDisabled {
        count: usize,
        error: Option<String>, // Error message if operation completely failed
    },
    TraceEnableFailed {
        trace_id: u32,
        error: String,
    },
    TraceDisableFailed {
        trace_id: u32,
        error: String,
    },
    TraceDeleted {
        trace_id: u32,
    },
    AllTracesDeleted {
        count: usize,
        error: Option<String>, // Error message if operation completely failed
    },
    TraceDeleteFailed {
        trace_id: u32,
        error: String,
    },
    InfoFunctionResult {
        target: String,
        info: TargetDebugInfo,
        verbose: bool,
    },
    InfoFunctionFailed {
        target: String,
        error: String,
    },
    InfoLineResult {
        target: String,
        info: TargetDebugInfo,
        verbose: bool,
    },
    InfoLineFailed {
        target: String,
        error: String,
    },
    InfoAddressResult {
        target: String,
        info: TargetDebugInfo,
        verbose: bool,
    },
    InfoAddressFailed {
        target: String,
        error: String,
    },
    /// Detailed info for a trace (summary + PC)
    TraceInfo {
        trace_id: u32,
        target: String,
        status: TraceStatus,
        pid: Option<u32>,
        binary: String,
        script_preview: Option<String>,
        pc: u64,
    },
    /// All trace info with structured data for UI rendering
    TraceInfoAll {
        summary: TraceSummaryInfo,
        traces: Vec<TraceDetailInfo>,
    },
    /// Failed to get info for a specific trace
    TraceInfoFailed {
        trace_id: u32,
        error: String,
    },
    /// Source file information response (grouped by module)
    FileInfo {
        groups: Vec<SourceFileGroup>,
    },
    /// Failed to get file information
    FileInfoFailed {
        error: String,
    },
    /// Traces saved to file successfully
    TracesSaved {
        filename: String,
        saved_count: usize,
        total_count: usize,
    },
    /// Failed to save traces
    TracesSaveFailed {
        error: String,
    },
    /// Traces loaded from file successfully
    TracesLoaded {
        filename: String,
        total_count: usize,
        success_count: usize,
        failed_count: usize,
        disabled_count: usize,
        details: Vec<TraceLoadDetail>,
    },
    /// Failed to load traces
    TracesLoadFailed {
        filename: String,
        error: String,
    },
    /// Shared library information response
    ShareInfo {
        libraries: Vec<SharedLibraryInfo>,
    },
    /// Failed to get shared library information
    ShareInfoFailed {
        error: String,
    },
    /// Executable file information response
    ExecutableFileInfo {
        file_path: String,
        file_type: String,
        entry_point: Option<u64>,
        has_symbols: bool,
        has_debug_info: bool,
        debug_file_path: Option<String>,
        text_section: Option<SectionInfo>,
        data_section: Option<SectionInfo>,
        mode_description: String,
    },
    /// Failed to get executable file information
    ExecutableFileInfoFailed {
        error: String,
    },
    // Module-level loading progress (new)
    DwarfModuleDiscovered {
        module_path: String,
        total_modules: usize,
    },
    DwarfModuleLoadingStarted {
        module_path: String,
        current: usize,
        total: usize,
    },
    DwarfModuleLoadingCompleted {
        module_path: String,
        stats: ModuleLoadingStats,
        current: usize,
        total: usize,
    },
    DwarfModuleLoadingFailed {
        module_path: String,
        error: String,
        current: usize,
        total: usize,
    },
    SrcPathInfo {
        info: SourcePathInfo,
    },
    SrcPathUpdated {
        message: String,
    },
    SrcPathFailed {
        error: String,
    },
}

/// Statistics for a loaded module
#[derive(Debug, Clone)]
pub struct ModuleLoadingStats {
    pub functions: usize,
    pub variables: usize,
    pub types: usize,
    pub load_time_ms: u64,
}

/// Summary information for all traces
#[derive(Debug, Clone)]
pub struct TraceSummaryInfo {
    pub total: usize,
    pub active: usize,
    pub disabled: usize,
}

/// Detailed information for a specific trace
#[derive(Debug, Clone)]
pub struct TraceDetailInfo {
    pub trace_id: u32,
    pub target_display: String,
    pub binary_path: String,
    pub pc: u64,
    pub status: TraceStatus,
    pub duration: String, // "5m32s", "1h5m", etc.
}

impl TraceDetailInfo {
    /// Format trace info line with binary path and PC information
    pub fn format_line(&self) -> String {
        // Extract binary name from path for cleaner display
        let binary_name = std::path::Path::new(&self.binary_path)
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or(&self.binary_path);

        format!(
            "#{} | {}+0x{:x} | {} ({}) ",
            self.trace_id, binary_name, self.pc, self.target_display, self.status
        )
    }
}

/// Source file information
#[derive(Debug, Clone)]
pub struct SourceFileInfo {
    pub path: String,
    pub directory: String,
}

/// Group of source files for a specific module
#[derive(Debug, Clone)]
pub struct SourceFileGroup {
    pub module_path: String,
    pub files: Vec<SourceFileInfo>,
}

/// Shared library information (similar to GDB's "info share" output)
#[derive(Debug, Clone)]
pub struct SharedLibraryInfo {
    pub from_address: u64,               // Starting address in memory
    pub to_address: u64,                 // Ending address in memory
    pub symbols_read: bool,              // Whether symbols were successfully read
    pub debug_info_available: bool,      // Whether debug information is available
    pub library_path: String,            // Full path to the library file
    pub size: u64,                       // Size of the library in memory
    pub debug_file_path: Option<String>, // Path to separate debug file (if via .gnu_debuglink)
}

/// Section information for executable files
#[derive(Debug, Clone)]
pub struct SectionInfo {
    pub start_address: u64, // Starting address of the section
    pub end_address: u64,   // Ending address of the section
    pub size: u64,          // Size of the section in bytes
}

impl EventRegistry {
    pub fn new() -> (Self, RuntimeChannels) {
        let (command_tx, command_rx) = mpsc::unbounded_channel();
        let (trace_tx, trace_rx) = mpsc::unbounded_channel::<ParsedTraceEvent>();
        let (status_tx, status_rx) = mpsc::unbounded_channel();

        let registry = EventRegistry {
            command_sender: command_tx,
            trace_receiver: trace_rx,
            status_receiver: status_rx,
        };

        let channels = RuntimeChannels {
            command_receiver: command_rx,
            trace_sender: trace_tx.clone(),
            status_sender: status_tx.clone(),
        };

        (registry, channels)
    }
}

/// Channels used by the runtime to receive commands and send events
#[derive(Debug)]
pub struct RuntimeChannels {
    pub command_receiver: mpsc::UnboundedReceiver<RuntimeCommand>,
    pub trace_sender: mpsc::UnboundedSender<ParsedTraceEvent>,
    pub status_sender: mpsc::UnboundedSender<RuntimeStatus>,
}

impl RuntimeChannels {
    /// Create a status sender that can be shared with other tasks
    pub fn create_status_sender(&self) -> mpsc::UnboundedSender<RuntimeStatus> {
        self.status_sender.clone()
    }

    /// Create a trace sender that can be shared with other tasks
    pub fn create_trace_sender(&self) -> mpsc::UnboundedSender<ParsedTraceEvent> {
        self.trace_sender.clone()
    }
}

impl RuntimeStatus {
    /// Format TraceInfo for enhanced display
    pub fn format_trace_info(&self) -> Option<String> {
        match self {
            RuntimeStatus::TraceInfo {
                trace_id,
                target,
                status,
                pid,
                binary,
                script_preview,
                pc,
            } => {
                // Header line
                let mut result =
                    format!("🔎 Trace [{}] {} {}\n", trace_id, status.to_emoji(), status);

                // Collect fields for aligned key-value formatting
                let binary_name = std::path::Path::new(binary)
                    .file_name()
                    .and_then(|name| name.to_str())
                    .unwrap_or(binary);

                let mut fields: Vec<(&str, String)> = Vec::new();
                fields.push(("🎯 Target", target.clone()));
                fields.push(("📦 Binary", binary.clone()));
                fields.push(("📍 Address", format!("{binary_name}+0x{pc:x}")));
                if let Some(pid_val) = pid {
                    fields.push(("🏷️ PID", pid_val.to_string()));
                }
                if let Some(ref script) = script_preview {
                    fields.push(("📝 Script", script.clone()));
                }

                // Compute max key width (accounting for emoji display width)
                let max_key_width = fields.iter().map(|(k, _)| k.width()).max().unwrap_or(0);

                for (key, value) in fields {
                    let key_width = key.width();
                    let pad = max_key_width.saturating_sub(key_width);
                    let spaces = " ".repeat(pad);
                    result.push_str(&format!("  {key}{spaces}: {value}\n"));
                }

                Some(result)
            }
            _ => None,
        }
    }

    /// Styled version of TraceInfo for display
    pub fn format_trace_info_styled(&self) -> Option<Vec<ratatui::text::Line<'static>>> {
        use crate::components::command_panel::style_builder::{StylePresets, StyledLineBuilder};
        use ratatui::text::Line;

        match self {
            RuntimeStatus::TraceInfo {
                trace_id,
                target,
                status,
                pid,
                binary,
                script_preview: _,
                pc,
            } => {
                let mut lines = Vec::new();

                // Title
                lines.push(
                    StyledLineBuilder::new()
                        .title(format!(
                            "🔎 Trace [{}] {} {}",
                            trace_id,
                            status.to_emoji(),
                            status
                        ))
                        .build(),
                );

                let binary_name = std::path::Path::new(binary)
                    .file_name()
                    .and_then(|name| name.to_str())
                    .unwrap_or(binary)
                    .to_string();

                lines.push(
                    StyledLineBuilder::new()
                        .text("  ")
                        .key("🎯 Target:")
                        .text(" ")
                        .value(target)
                        .build(),
                );
                lines.push(
                    StyledLineBuilder::new()
                        .text("  ")
                        .key("📦 Binary:")
                        .text(" ")
                        .value(binary)
                        .build(),
                );
                lines.push(
                    StyledLineBuilder::new()
                        .text("  ")
                        .key("📍 Address:")
                        .text(" ")
                        .value(format!("{binary_name}+0x{pc:x}"))
                        .build(),
                );

                if let Some(p) = pid {
                    lines.push(
                        StyledLineBuilder::new()
                            .text("  ")
                            .key("🏷️ PID:")
                            .text(" ")
                            .value(p.to_string())
                            .build(),
                    );
                }

                Some(lines)
            }
            RuntimeStatus::TraceInfoAll { summary, traces } => {
                let mut lines = Vec::new();
                // Title
                lines.push(
                    StyledLineBuilder::new()
                        .title(format!(
                            "🔍 All Traces ({} total, {} active):",
                            summary.total, summary.active
                        ))
                        .build(),
                );
                lines.push(Line::from(""));

                for t in traces {
                    let binary_name = std::path::Path::new(&t.binary_path)
                        .file_name()
                        .and_then(|name| name.to_str())
                        .unwrap_or(&t.binary_path)
                        .to_string();
                    let status_style = match t.status {
                        TraceStatus::Active => StylePresets::SUCCESS,
                        TraceStatus::Disabled => StylePresets::LOCATION,
                        TraceStatus::Failed => StylePresets::ERROR,
                    };
                    let line = StyledLineBuilder::new()
                        .text("  ")
                        .styled(format!("#{}", t.trace_id), StylePresets::ADDRESS)
                        .text("  | ")
                        .styled(format!("{}+0x{:x}", binary_name, t.pc), StylePresets::KEY)
                        .text("  | ")
                        .value(&t.target_display)
                        .text("  (")
                        .styled(t.status.to_string(), status_style)
                        .text(")")
                        .build();
                    lines.push(line);
                }

                Some(lines)
            }
            _ => None,
        }
    }
}

/// Source path information for display (shared between UI and runtime)
#[derive(Debug, Clone)]
pub struct SourcePathInfo {
    pub substitutions: Vec<PathSubstitution>,
    pub search_dirs: Vec<String>,
    pub runtime_substitution_count: usize,
    pub runtime_search_dir_count: usize,
    pub config_substitution_count: usize,
    pub config_search_dir_count: usize,
}

impl SourcePathInfo {
    /// Format for display in command panel
    pub fn format_for_display(&self) -> String {
        let mut output = String::new();

        output.push_str("🗂️  Source Path Configuration:\n\n");

        // Path substitutions
        if self.substitutions.is_empty() {
            output.push_str("Path Substitutions: (none)\n");
        } else {
            output.push_str(&format!(
                "Path Substitutions ({}):\n",
                self.substitutions.len()
            ));
            for (i, sub) in self.substitutions.iter().enumerate() {
                let marker = if i < self.runtime_substitution_count {
                    "[runtime]"
                } else {
                    "[config] "
                };
                output.push_str(&format!("  {} {} -> {}\n", marker, sub.from, sub.to));
            }
        }

        output.push('\n');

        // Search directories
        if self.search_dirs.is_empty() {
            output.push_str("Search Directories: (none)\n");
        } else {
            output.push_str(&format!(
                "Search Directories ({}):\n",
                self.search_dirs.len()
            ));
            for (i, dir) in self.search_dirs.iter().enumerate() {
                let marker = if i < self.runtime_search_dir_count {
                    "[runtime]"
                } else {
                    "[config] "
                };
                output.push_str(&format!("  {marker} {dir}\n"));
            }
        }

        output.push_str("\n💡 Runtime rules take precedence over config file rules.\n");
        output.push_str(
            "💡 Use 'srcpath clear' to remove runtime rules, 'srcpath reset' to reset to config.\n",
        );

        output
    }

    /// Styled version for display
    pub fn format_for_display_styled(&self) -> Vec<ratatui::text::Line<'static>> {
        use crate::components::command_panel::style_builder::{StylePresets, StyledLineBuilder};
        use ratatui::text::Line;

        let mut lines = Vec::new();

        // Title
        lines.push(
            StyledLineBuilder::new()
                .title("🗂️  Source Path Configuration:")
                .build(),
        );
        lines.push(Line::from(""));

        // Path substitutions
        if self.substitutions.is_empty() {
            lines.push(
                StyledLineBuilder::new()
                    .key("Path Substitutions:")
                    .text(" (none)")
                    .build(),
            );
        } else {
            lines.push(
                StyledLineBuilder::new()
                    .key(format!(
                        "Path Substitutions ({}):",
                        self.substitutions.len()
                    ))
                    .build(),
            );
            for (i, sub) in self.substitutions.iter().enumerate() {
                let marker = if i < self.runtime_substitution_count {
                    "[runtime]"
                } else {
                    "[config] "
                };
                lines.push(
                    StyledLineBuilder::new()
                        .text("  ")
                        .styled(marker, StylePresets::MARKER)
                        .text(" ")
                        .value(&sub.from)
                        .styled(" -> ", StylePresets::TREE)
                        .styled(&sub.to, StylePresets::KEY)
                        .build(),
                );
            }
        }

        lines.push(Line::from(""));

        // Search directories
        if self.search_dirs.is_empty() {
            lines.push(
                StyledLineBuilder::new()
                    .key("Search Directories:")
                    .text(" (none)")
                    .build(),
            );
        } else {
            lines.push(
                StyledLineBuilder::new()
                    .key(format!("Search Directories ({}):", self.search_dirs.len()))
                    .build(),
            );
            for (i, dir) in self.search_dirs.iter().enumerate() {
                let marker = if i < self.runtime_search_dir_count {
                    "[runtime]"
                } else {
                    "[config] "
                };
                lines.push(
                    StyledLineBuilder::new()
                        .text("  ")
                        .styled(marker, StylePresets::MARKER)
                        .text(" ")
                        .value(dir)
                        .build(),
                );
            }
        }

        lines.push(Line::from(""));
        lines.push(
            StyledLineBuilder::new()
                .styled(
                    "💡 Runtime rules take precedence over config file rules.",
                    StylePresets::TIP,
                )
                .build(),
        );
        lines.push(
            StyledLineBuilder::new()
                .styled(
                    "💡 Use 'srcpath clear' to remove runtime rules, 'srcpath reset' to reset to config.",
                    StylePresets::TIP,
                )
                .build(),
        );

        lines
    }
}

/// Path substitution rule (shared definition)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PathSubstitution {
    pub from: String,
    pub to: String,
}