turbo-vision 2.4.0

A Rust implementation of the classic Borland Turbo Vision text-mode UI framework
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
1385
1386
1387
1388
1389
// (C) 2026 - Enzo Lombardi

//! Application structure and event loop implementation.
//! Manages the main application window, menu bar, status line, and desktop.
//! Provides the central event loop and command dispatching system.

use crate::core::command::{
    CM_CANCEL, CM_CASCADE, CM_COMMAND_SET_CHANGED, CM_HELP_INDEX, CM_QUIT, CM_REDRAW,
    CM_SCREENSHOT, CM_TILE, CommandId,
};
use crate::core::command_set;
use crate::core::error::Result;
use crate::core::event::{Event, EventType, KB_ALT_X, KB_CTRL_F12, KB_F1, KB_F12};
use crate::core::geometry::Rect;
use crate::terminal::Terminal;
use crate::views::help_context::HelpContext;
use crate::views::help_file::HelpFile;
use crate::views::help_window::HelpWindow;
use crate::views::{IdleView, View, desktop::Desktop, menu_bar::MenuBar, status_line::StatusLine};
use std::cell::RefCell;
use std::rc::Rc;
use std::time::Duration;

pub struct Application {
    pub terminal: Terminal,
    pub menu_bar: Option<MenuBar>,
    pub status_line: Option<StatusLine>,
    pub desktop: Desktop,
    pub running: bool,
    needs_redraw: bool, // Track if full redraw is needed
    /// One-slot pending event queue (Borland: TProgram::putEvent/pending):
    /// returned by the event loops before polling the terminal
    pending_event: Option<Event>,
    /// Overlay widgets that need idle processing and are drawn on top of everything
    /// These widgets continue to animate even during modal dialogs
    /// Matches Borland: TProgram::idle() continues running during execView()
    pub(crate) overlay_widgets: Vec<Box<dyn IdleView>>,
    // Note: Command set is now stored in thread-local static (command_set module)
    // This matches Borland's architecture where TView::curCommandSet is static
    /// Help file for F1 context-sensitive help
    /// Matches Borland: TProgram::helpFile (tprogram.cc)
    help_file: Option<Rc<RefCell<HelpFile>>>,
    /// Help context mappings (context ID to topic ID)
    help_context: HelpContext,
    /// Current help context driving StatusDef switching (Borland: the
    /// focused view's helpCtx; set explicitly in this architecture)
    current_help_ctx: u16,
    /// True between a mouse press and its release. While it is set, `idle`
    /// broadcasts `CM_MOUSE_AUTO_REPEAT` so held-down controls, scrollbar
    /// arrows above all, can keep repeating without any polling of their own.
    mouse_held: bool,
}

impl Application {
    /// Creates a new application instance and initializes the terminal.
    ///
    /// This function sets up the complete application structure including:
    /// - Terminal initialization in raw mode
    /// - Desktop creation with background
    /// - Global command set initialization
    ///
    /// The menu bar and status line must be set separately using
    /// [`set_menu_bar()`](Self::set_menu_bar) and
    /// [`set_status_line()`](Self::set_status_line).
    ///
    /// # Errors
    ///
    /// Returns an error if terminal initialization fails. See
    /// [`Terminal::init()`](crate::Terminal::init) for details on possible
    /// error conditions.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use turbo_vision::app::Application;
    /// use turbo_vision::core::error::Result;
    ///
    /// fn main() -> Result<()> {
    ///     let mut app = Application::new()?;
    ///     // Set up menu bar, status line, add windows...
    ///     Ok(())
    /// }
    /// ```
    pub fn new() -> Result<Self> {
        let terminal = Terminal::init()?;
        let (width, height) = terminal.size();

        // Create Desktop with full screen bounds initially
        // Will be adjusted when menu_bar/status_line are set
        let desktop = Desktop::new(Rect::new(0, 0, width, height));

        // Initialize global command set
        // Matches Borland's initCommands() (tview.cc:58-68)
        command_set::init_command_set();

        let mut app = Self {
            terminal,
            menu_bar: None,
            status_line: None,
            desktop,
            running: true,
            needs_redraw: true, // Initial draw needed
            pending_event: None,
            current_help_ctx: 0,
            mouse_held: false,
            overlay_widgets: Vec::new(),
            help_file: None,
            help_context: HelpContext::new(),
        };

        // Opt-in remote key injection for testing/automation. Off unless the
        // TV_REMOTE_KEYS environment variable holds a port number.
        if let Ok(port_str) = std::env::var("TV_REMOTE_KEYS") {
            if let Ok(port) = port_str.trim().parse::<u16>() {
                if let Err(e) = app.enable_remote_input(port) {
                    log::warn!("TV_REMOTE_KEYS: failed to listen on port {port}: {e}");
                }
            }
        }

        // Set initial Desktop bounds (adjusts for missing menu/status)
        // Matches Borland: TProgram::initDeskTop() with no menuBar/statusLine
        app.update_desktop_bounds();

        // Initialize Desktop's palette chain now that it's in its final location
        // This sets up the owner chain so views can resolve colors through Desktop's CP_APP_COLOR palette
        app.desktop.init_palette_chain();

        Ok(app)
    }

    pub fn set_menu_bar(&mut self, menu_bar: MenuBar) {
        self.menu_bar = Some(menu_bar);
        // Update Desktop bounds to exclude menu bar
        // Matches Borland: TProgram::initDeskTop() adjusts r.a.y based on menuBar
        self.update_desktop_bounds();
    }

    pub fn set_status_line(&mut self, status_line: StatusLine) {
        self.status_line = Some(status_line);
        // Update Desktop bounds to exclude status line
        // Matches Borland: TProgram::initDeskTop() adjusts r.b.y based on statusLine
        self.update_desktop_bounds();
    }

    /// Add an overlay widget that needs idle processing and is drawn on top of everything
    /// These widgets continue to animate even during modal dialogs
    /// Matches Borland: TProgram::idle() continues running during execView()
    ///
    /// # Examples
    /// ```rust,no_run
    /// use turbo_vision::app::Application;
    /// # use turbo_vision::views::IdleView;
    /// # struct AnimatedWidget;
    /// # impl turbo_vision::views::View for AnimatedWidget {
    /// #     fn bounds(&self) -> turbo_vision::core::geometry::Rect { unimplemented!() }
    /// #     fn set_bounds(&mut self, _: turbo_vision::core::geometry::Rect) {}
    /// #     fn draw(&mut self, _: &mut turbo_vision::terminal::Terminal) {}
    /// #     fn handle_event(&mut self, _: &mut turbo_vision::core::event::Event) {}
    /// #     fn update_cursor(&self, _: &mut turbo_vision::terminal::Terminal) {}
    /// #     fn get_palette(&self) -> Option<turbo_vision::core::palette::Palette> { None }
    /// # }
    /// # impl IdleView for AnimatedWidget { fn idle(&mut self) {} }
    ///
    /// let mut app = Application::new()?;
    /// let widget = AnimatedWidget { /* ... */ };
    /// app.add_overlay_widget(Box::new(widget));
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn add_overlay_widget(&mut self, widget: Box<dyn IdleView>) {
        self.overlay_widgets.push(widget);
    }

    /// Update Desktop bounds to exclude menu bar and status line areas
    /// Matches Borland: TProgram::initDeskTop() calculates bounds based on menuBar/statusLine
    fn update_desktop_bounds(&mut self) {
        let (width, height) = self.terminal.size();
        let mut desktop_bounds = Rect::new(0, 0, width, height);

        // Adjust top edge for menu bar
        // Borland: if (menuBar) r.a.y += menuBar->size.y; else r.a.y++;
        if let Some(ref menu_bar) = self.menu_bar {
            desktop_bounds.a.y += menu_bar.bounds().height();
        } else {
            desktop_bounds.a.y += 1;
        }

        // Adjust bottom edge for status line
        // Borland: if (statusLine) r.b.y -= statusLine->size.y; else r.b.y--;
        if let Some(ref status_line) = self.status_line {
            desktop_bounds.b.y -= status_line.bounds().height();
        } else {
            desktop_bounds.b.y -= 1;
        }

        self.desktop.set_bounds(desktop_bounds);
    }

    /// Request a full redraw on the next frame
    /// Call this after changing the palette or other global settings
    pub fn needs_redraw(&mut self) {
        self.needs_redraw = true;
    }

    /// Handle a full screen redraw (terminal resize, palette change, etc.).
    ///
    /// Queries the actual terminal size, resizes internal buffers, and
    /// re-lays out the menu bar, status line, and desktop to match.
    pub fn handle_redraw(&mut self) {
        if let Ok((w, h)) = self.terminal.backend_size() {
            let (cur_w, cur_h) = self.terminal.size();
            if w != cur_w || h != cur_h {
                self.terminal.resize(w as u16, h as u16);

                // Re-layout menu bar and status line to the new width
                if let Some(ref mut menu_bar) = self.menu_bar {
                    let mb = menu_bar.bounds();
                    menu_bar.set_bounds(Rect::new(0, mb.a.y, w, mb.b.y));
                }
                if let Some(ref mut status_line) = self.status_line {
                    let sb = status_line.bounds();
                    status_line.set_bounds(Rect::new(0, h - sb.height(), w, h));
                }

                self.update_desktop_bounds();
            }
        }
        self.needs_redraw = true;
    }

    /// Set a custom application palette and automatically trigger redraw if changed
    /// Pass None to reset to the default Borland palette
    ///
    /// This is a convenience method that combines palette setting with automatic redraw.
    /// It only triggers a redraw if the palette actually changes.
    ///
    /// # Example
    /// ```rust,no_run
    /// use turbo_vision::app::Application;
    ///
    /// let mut app = Application::new()?;
    /// // Set a custom dark theme palette
    /// let dark_palette = vec![/* 63 color bytes */];
    /// app.set_palette(Some(dark_palette));
    /// // Redraw is triggered automatically
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn set_palette(&mut self, palette: Option<Vec<u8>>) {
        use crate::core::palette::palettes;

        // Get the current palette to check if it's actually changing
        let current_palette = palettes::get_app_palette();
        let is_changing = match &palette {
            Some(new_palette) => new_palette != &current_palette,
            None => {
                // Check if we're currently using a custom palette
                // by comparing with the default (CP_APP_COLOR)
                current_palette != palettes::CP_APP_COLOR
            }
        };

        // Set the new palette
        palettes::set_custom_palette(palette);

        // Trigger redraw only if the palette actually changed
        if is_changing {
            self.needs_redraw = true;
        }
    }

    /// Poll the terminal, treating a dead backend as a quit request.
    ///
    /// A `poll_event` error means the backend connection is gone (e.g. the
    /// SSH client disconnected); swallowing it would leave the event loop
    /// spinning forever on a dead session.
    /// Queue an event to be returned before the next terminal poll.
    ///
    /// Matches Borland TProgram::putEvent: a single-slot pending event that
    /// the event loops consume first (used e.g. to re-enter a command from
    /// event handlers).
    pub fn put_event(&mut self, event: Event) {
        self.pending_event = Some(event);
    }

    fn poll_event_or_quit(&mut self) -> Option<Event> {
        if let Some(pending) = self.pending_event.take() {
            return Some(pending);
        }
        match self.terminal.poll_event(Duration::from_millis(20)) {
            Ok(event) => event,
            Err(err) => {
                log::warn!("terminal backend error, shutting down: {err}");
                self.running = false;
                None
            }
        }
    }

    /// Get an event (with drawing)
    /// Matches Borland/Magiblot: TProgram::getEvent() (tprogram.cc:105-174)
    /// This is called by modal views' execute() methods.
    ///
    /// Key behavior (matches magiblot):
    /// - Draws the screen first
    /// - Blocks waiting for events (default 20ms timeout)
    /// - Only calls idle() when there are NO events after timeout
    /// - This gives true event-driven behavior with minimal CPU usage
    pub fn get_event(&mut self) -> Option<Event> {
        // Draw everything (this is the key: drawing happens BEFORE getting events)
        // Matches Borland's CLY_Redraw() in getEvent
        self.draw();
        let _ = self.terminal.flush();

        // Poll for event with 20ms timeout (matches magiblot's eventTimeoutMs)
        // This blocks until an event arrives or timeout occurs
        match self.poll_event_or_quit() {
            Some(event) => {
                // Event received - return it immediately without calling idle()
                // Matches magiblot: idle() is NOT called when events are present
                Some(event)
            }
            None => {
                // Timeout occurred with no events - now we call idle()
                // Matches magiblot: idle() only called when truly idle
                // This is where animations update, command sets broadcast, etc.
                self.idle();
                None
            }
        }
    }

    /// Execute a view (modal or modeless)
    /// Matches Borland: TProgram::execView() (tprogram.cc:177-197)
    ///
    /// If the view has SF_MODAL flag set, runs a modal event loop.
    /// Otherwise, adds the view to the desktop and returns immediately.
    ///
    /// Returns the view's end_state (the command that closed the modal view)
    pub fn exec_view(&mut self, view: Box<dyn View>) -> CommandId {
        use crate::core::state::SF_MODAL;

        // Check if view is modal
        let is_modal = (view.state() & SF_MODAL) != 0;

        // Add view to desktop; track it by identity so other children being
        // added or removed during the modal loop can't shift it out from
        // under us (C++ TGroup::execView uses pointer identity)
        self.desktop.add(view);
        let view_id = self
            .desktop
            .top_view_id()
            .expect("view was just added to the desktop");

        if !is_modal {
            // Modeless view - just add to desktop and return
            return 0;
        }

        // Modal view - run event loop
        // Matches Borland: TProgram::execView() runs modal loop (tprogram.cc:184-194)
        // Matches magiblot: Only calls idle() when no events (true event-driven)
        loop {
            // Draw everything
            self.draw();
            let _ = self.terminal.flush();

            // Poll for event with 20ms timeout (blocks until event or timeout)
            match self.poll_event_or_quit() {
                Some(mut event) => {
                    // Event received - handle it immediately without calling idle()
                    self.handle_event(&mut event);
                }
                None => {
                    // Timeout with no events - call idle() to update animations, etc.
                    self.idle();
                }
            }

            // Check if application wants to quit (Alt+X, CM_QUIT)
            // This allows quit to work even when modal dialogs are open
            if !self.running {
                // Matches Borland: TProgram::handleEvent endModal(cmQuit) —
                // callers can distinguish app shutdown from a plain cancel
                self.desktop.remove_child_by_id(view_id);
                return CM_QUIT;
            }

            // Check if the modal view wants to close
            // Matches Borland: TGroup::execute() checks endState (tgroup.cc:192)
            // followed by the valid(endState) re-entry check
            if self.desktop.contains_id(view_id) {
                let end_state = self
                    .desktop
                    .child_by_id(view_id)
                    .map(|child| child.get_end_state())
                    .unwrap_or(0);
                if end_state != 0 {
                    // A failing validator vetoes the close (Borland:
                    // do { ... } while( !valid(endState) ))
                    let close_ok = self
                        .desktop
                        .child_by_id_mut(view_id)
                        .map(|child| child.valid(end_state))
                        .unwrap_or(true);
                    if close_ok {
                        self.desktop.remove_child_by_id(view_id);
                        return end_state;
                    }
                    if let Some(child) = self.desktop.child_by_id_mut(view_id) {
                        child.set_end_state(0);
                    }
                }
            } else {
                // View was removed (closed externally)
                return CM_CANCEL;
            }
        }
    }

    pub fn run(&mut self) {
        self.running = true;

        // Initial draw
        self.draw();
        let _ = self.terminal.flush();

        while self.running {
            // Optimized drawing strategy (matches Borland's approach):
            // Draw first, then wait for events
            // Only redraw when something changed (not every frame)
            let needs_draw = self.needs_redraw;

            if needs_draw {
                // Explicit redraw requested (window closed, resize, palette change, etc.)
                self.draw();
                self.needs_redraw = false;
                let _ = self.terminal.flush();
            }

            // Poll for event with 20ms timeout (matches magiblot's eventTimeoutMs)
            // This blocks until an event arrives or timeout occurs
            match self.poll_event_or_quit() {
                Some(mut event) => {
                    // Event received - handle it immediately without calling idle()
                    // Matches magiblot: idle() is NOT called when events are present
                    self.handle_event(&mut event);

                    // Event occurred: do full redraw for content changes
                    // This could be optimized further by tracking which views changed
                    self.draw();
                    let _ = self.terminal.flush();
                }
                None => {
                    // Timeout with no events - call idle() to update animations, etc.
                    // Matches magiblot: idle() only called when truly idle
                    self.idle();

                    // After idle, draw overlay widgets (animations) if any
                    // Don't redraw everything, just flush overlay widget changes
                    if !self.overlay_widgets.is_empty() {
                        for widget in &mut self.overlay_widgets {
                            widget.draw(&mut self.terminal);
                        }
                        let _ = self.terminal.flush();
                    }
                }
            }

            // Remove closed windows (those with SF_CLOSED flag)
            // In Borland, views call CLY_destroy() to remove themselves
            // In Rust, views set SF_CLOSED and parent removes them
            let had_closed_windows = self.desktop.remove_closed_windows();
            if had_closed_windows {
                self.needs_redraw = true; // Window removal requires full redraw
            }

            // Check for moved windows and redraw affected areas (Borland's drawUnderRect pattern)
            // Matches Borland: TView::locate() checks for movement and calls drawUnderRect
            // This optimized redraw only redraws the union of old + new position
            let had_moved_windows = self.desktop.handle_moved_windows(&mut self.terminal);
            if had_moved_windows {
                // Window movement: partial redraw already done via draw_under_rect
                // Just flush the terminal buffer
                let _ = self.terminal.flush();
            }
        }
    }

    pub fn draw(&mut self) {
        // Draw desktop first, then menu bar on top (so dropdown appears over desktop)
        self.desktop.draw(&mut self.terminal);

        if let Some(ref mut menu_bar) = self.menu_bar {
            menu_bar.draw(&mut self.terminal);
        }

        if let Some(ref mut status_line) = self.status_line {
            status_line.draw(&mut self.terminal);
        }

        // Draw overlay widgets on top of everything
        // These continue to animate even during modal dialogs
        for widget in &mut self.overlay_widgets {
            widget.draw(&mut self.terminal);
        }

        // Update cursor after drawing all views
        // Desktop contains windows/dialogs with focused controls
        self.desktop.update_cursor(&mut self.terminal);
    }

    pub fn handle_event(&mut self, event: &mut Event) {
        // Handle CM_REDRAW before anything else — resize the terminal buffers
        // and re-layout all top-level views so subsequent drawing is correct.
        if event.what == EventType::Broadcast && event.command == CM_REDRAW {
            self.handle_redraw();
            event.clear();
            return;
        }

        // Pre-dispatch global shortcuts — these must be handled before any
        // view sees the event, because focused views (e.g. the editor) would
        // otherwise consume the key code.
        if event.what == EventType::Keyboard {
            match event.key_code {
                KB_F1 => {
                    self.show_help();
                    event.clear();
                    return;
                }
                KB_ALT_X => {
                    *event = Event::command(CM_QUIT);
                    self.running = false;
                    return;
                }
                KB_F12 => {
                    self.dump_screen_ansi();
                    event.clear();
                    return;
                }
                KB_CTRL_F12 => {
                    self.take_screenshot();
                    event.clear();
                    return;
                }
                code @ crate::core::event::KB_ALT_1..=crate::core::event::KB_ALT_9 => {
                    // Alt+digit selects the numbered window
                    // (Borland: TProgram::handleEvent -> cmSelectWindowNum)
                    let num = ((code - crate::core::event::KB_ALT_1) >> 8) as u16 + 1;
                    *event =
                        Event::broadcast_with_info(crate::core::command::CM_SELECT_WINDOW_NUM, num);
                }
                _ => {}
            }
        }

        // Track the button so idle knows whether to drive auto-repeat.
        match event.what {
            EventType::MouseDown => self.mouse_held = true,
            EventType::MouseUp => self.mouse_held = false,
            _ => {}
        }

        // Menu bar gets first shot
        if let Some(ref mut menu_bar) = self.menu_bar {
            menu_bar.handle_event(event);
            if event.what == EventType::Nothing {
                return;
            }
        }

        // Desktop/windows
        self.desktop.handle_event(event);
        if event.what == EventType::Nothing {
            return;
        }

        // Status line
        if let Some(ref mut status_line) = self.status_line {
            status_line.handle_event(event);
            if event.what == EventType::Nothing {
                return;
            }
        }

        // Application-level command handling
        if event.what == EventType::Command {
            match event.command {
                CM_QUIT => {
                    self.running = false;
                    event.clear();
                }
                CM_TILE => {
                    self.tile();
                    event.clear();
                }
                CM_CASCADE => {
                    self.cascade();
                    event.clear();
                }
                CM_HELP_INDEX => {
                    self.show_help();
                    event.clear();
                }
                crate::core::command::CM_TOGGLE_BLOCK_MODE => {
                    self.toggle_block_edit_mode();
                    event.clear();
                }
                CM_SCREENSHOT => {
                    self.take_screenshot();
                    event.clear();
                }
                crate::core::command::CM_SHOW_HISTORY => {
                    // A History button was clicked in a dialog running under
                    // exec_view()/run(); open the popup here where we have
                    // terminal access, then broadcast the selection back.
                    use crate::core::geometry::Point;
                    use crate::core::history::HistoryManager;

                    let history_id = event.info;
                    let pos = Point::new((event.mouse.pos.x - 20).max(0), event.mouse.pos.y + 1);
                    let mut window =
                        crate::views::history_window::HistoryWindow::new(pos, history_id, 30);
                    if let Some(selected) = window.execute(&mut self.terminal) {
                        HistoryManager::add(history_id, selected);
                        let mut sel = Event::broadcast_with_info(
                            crate::core::command::CM_HISTORY_SELECTED,
                            history_id,
                        );
                        self.desktop.handle_event(&mut sel);
                    }
                    event.clear();
                }
                crate::core::command::CM_SHOW_DROPDOWN => {
                    // A ComboBox on a plain window asked to drop its list down;
                    // open it here, where the terminal is reachable.
                    crate::views::dialog::show_dropdown_popup(event, &mut self.terminal);
                }
                _ => {}
            }
        }
    }

    /// Enable the remote keyboard-input listener on the given TCP port.
    ///
    /// This is **off by default**. It is a thin wrapper around
    /// [`Terminal::enable_remote_input`](crate::terminal::Terminal::enable_remote_input):
    /// once enabled, key chords sent to `127.0.0.1:port` (e.g. `"CTRL+F12"`) are
    /// injected into the event loop as real key presses. Useful for automated
    /// testing of global shortcuts such as the Ctrl+F12 screenshot.
    ///
    /// It can also be enabled without code changes by setting the
    /// `TV_REMOTE_KEYS` environment variable to the desired port.
    ///
    /// # Errors
    ///
    /// Returns an error if the port cannot be bound.
    pub fn enable_remote_input(&mut self, port: u16) -> Result<()> {
        self.terminal.enable_remote_input(port)?;
        Ok(())
    }

    /// Save a PNG screenshot of the current screen (bound to Ctrl+F12).
    ///
    /// The file is written to the current working directory with a
    /// timestamped name like `screenshot-20260607-194800.png`. Rendering
    /// queries the current font cell size; see
    /// [`Terminal::save_screenshot_png`](crate::terminal::Terminal::save_screenshot_png).
    pub fn take_screenshot(&mut self) {
        let filename = format!(
            "screenshot-{}.png",
            chrono::Local::now().format("%Y%m%d-%H%M%S")
        );
        match self.terminal.save_screenshot_png(&filename) {
            Ok(()) => log::info!("Screenshot saved to {filename}"),
            Err(e) => log::warn!("Failed to save screenshot: {e}"),
        }
    }

    /// Save an ASCII (ANSI-colored) dump of the whole screen (bound to F12).
    ///
    /// The file is written to the current working directory with a timestamped
    /// name like `screen-20260607-194800.ans` and can be viewed with `cat` or
    /// `less -R`. See [`Terminal::dump_screen`](crate::terminal::Terminal::dump_screen).
    pub fn dump_screen_ansi(&mut self) {
        let filename = format!(
            "screen-{}.ans",
            chrono::Local::now().format("%Y%m%d-%H%M%S")
        );
        match self.terminal.dump_screen(&filename) {
            Ok(()) => log::info!("Screen dump saved to {filename}"),
            Err(e) => log::warn!("Failed to save screen dump: {e}"),
        }
    }

    // Help System Methods
    // Matches Borland: TProgram help support (tprogram.cc)

    /// Set the help file for F1 context-sensitive help
    /// Matches Borland: TApplication::helpFile initialization
    ///
    /// # Arguments
    /// * `path` - Path to a markdown help file
    ///
    /// # Returns
    /// Result indicating success or file load error
    ///
    /// # Examples
    /// ```ignore
    /// app.set_help_file("help/manual.md")?;
    /// ```
    pub fn set_help_file(&mut self, path: &str) -> std::io::Result<()> {
        let help_file = HelpFile::new(path)?;
        self.help_file = Some(Rc::new(RefCell::new(help_file)));
        Ok(())
    }

    /// Set a pre-built help file for F1 context-sensitive help
    pub fn set_help(&mut self, help_file: HelpFile) {
        self.help_file = Some(Rc::new(RefCell::new(help_file)));
    }

    /// Register a help context mapping (context ID to topic ID)
    /// This allows views to have help_context set, and F1 will open the corresponding topic
    ///
    /// # Arguments
    /// * `context_id` - Numeric context ID (assigned to views)
    /// * `topic_id` - String topic ID in the help file (e.g., "file-open")
    pub fn register_help_context(&mut self, context_id: u16, topic_id: &str) {
        self.help_context.register(context_id, topic_id);
    }

    /// Show help for a specific topic
    /// Opens the help window and displays the given topic
    pub fn show_help_topic(&mut self, topic_id: &str) {
        use crate::core::state::SF_MODAL;

        if let Some(ref help_file) = self.help_file {
            let (width, height) = self.terminal.size();
            let help_width = (width * 3 / 4).max(40).min(width - 4);
            let help_height = (height * 3 / 4).max(10).min(height - 4);
            let x = (width - help_width) / 2;
            let y = (height - help_height) / 2;

            let bounds = Rect::new(x, y, x + help_width, y + help_height);
            let mut help_window = HelpWindow::new(bounds, "Help", Rc::clone(help_file));
            help_window.show_topic(topic_id);

            // Set SF_MODAL flag so exec_view runs the modal loop
            // Matches Borland: THelpWindow is displayed modally
            let current_state = help_window.state();
            help_window.set_state(current_state | SF_MODAL);

            // Execute the help window as modal
            self.exec_view(Box::new(help_window));
        }
    }

    /// Show context-sensitive help
    /// Looks up the focused view's help context and opens the appropriate topic
    /// Matches Borland: TProgram::getEvent() F1 handling
    pub fn show_help(&mut self) {
        // For now, show default topic. In future, this would:
        // 1. Get the focused view's help context
        // 2. Look up the topic ID from help_context
        // 3. Show that topic
        //
        // Since views don't have help_context field yet, we show the default topic
        let topic_id = if let Some(ref help_file) = self.help_file {
            help_file.borrow().get_default_topic().map(|t| t.id.clone())
        } else {
            None
        };

        if let Some(topic_id) = topic_id {
            self.show_help_topic(&topic_id);
        }
    }

    // Window Management Methods
    // Matches Borland: TApplication tile/cascade methods (tapplica.cpp:75-127)

    /// Tile all tileable windows in a grid pattern
    /// Matches Borland: TApplication::tile() (tapplica.cpp:123-127)
    pub fn tile(&mut self) {
        let rect = self.get_tile_rect();
        self.desktop.tile_with_rect(rect);
    }

    /// Cascade all tileable windows in a staircase pattern
    /// Matches Borland: TApplication::cascade() (tapplica.cpp:75-79)
    pub fn cascade(&mut self) {
        let rect = self.get_tile_rect();
        self.desktop.cascade_with_rect(rect);
    }

    /// Get the rectangle to use for tiling/cascading operations
    /// Matches Borland: TApplication::getTileRect() (tapplica.cpp:94-97)
    /// Default implementation returns the full desktop extent
    /// Can be overridden to customize the tile area
    pub fn get_tile_rect(&self) -> Rect {
        self.desktop.get_bounds()
    }

    // Command Set Management
    // Delegates to global command set functions (command_set module)
    // Matches Borland's TView command set methods (tview.cc:161-389, 672-677)

    /// Check if a command is currently enabled
    /// Matches Borland: TView::commandEnabled(ushort command) (tview.cc:142-147)
    pub fn command_enabled(&self, command: CommandId) -> bool {
        command_set::command_enabled(command)
    }

    /// Enable a single command
    /// Matches Borland: TView::enableCommand(ushort command) (tview.cc:384-389)
    pub fn enable_command(&mut self, command: CommandId) {
        command_set::enable_command(command);
    }

    /// Disable a single command
    /// Matches Borland: TView::disableCommand(ushort command) (tview.cc:161-166)
    pub fn disable_command(&mut self, command: CommandId) {
        command_set::disable_command(command);
    }

    // Block-edit mode
    // Global flag (core::state) rather than a keyboard modifier: terminals
    // disagree on whether they deliver Alt/Option with cursor keys and drags.

    /// Is block-edit mode on? Editors start rectangular selections while it is.
    pub fn block_edit_mode(&self) -> bool {
        crate::core::state::block_edit_mode()
    }

    /// Turn block-edit mode on or off.
    pub fn set_block_edit_mode(&mut self, on: bool) {
        crate::core::state::set_block_edit_mode(on);
    }

    /// Flip block-edit mode and return the new value.
    pub fn toggle_block_edit_mode(&mut self) -> bool {
        crate::core::state::toggle_block_edit_mode()
    }

    /// Emit a beep sound
    /// Matches Borland: TScreen::makeBeep() - provides audio feedback for errors/alerts
    /// Commonly used in dialog validation failures and error messages
    pub fn beep(&mut self) {
        let _ = self.terminal.beep();
    }

    /// Set the ESC timeout in milliseconds
    ///
    /// This controls how long the terminal waits after ESC to detect ESC+letter sequences
    /// for macOS Alt key emulation.
    ///
    /// # Arguments
    /// * `timeout_ms` - Timeout in milliseconds, must be between 250 and 1500
    ///
    /// # Errors
    /// Returns an error if the timeout is not between 250 and 1500 milliseconds
    ///
    /// # Examples
    /// ```rust,no_run
    /// # use turbo_vision::app::Application;
    /// # use turbo_vision::core::error::Result;
    /// # fn main() -> Result<()> {
    /// let mut app = Application::new()?;
    /// app.set_esc_timeout(750)?;  // Set to 750ms
    /// # Ok(())
    /// # }
    /// ```
    pub fn set_esc_timeout(&mut self, timeout_ms: u64) -> Result<()> {
        if timeout_ms < 250 || timeout_ms > 1500 {
            return Err(crate::core::error::TurboVisionError::invalid_input(
                format!(
                    "ESC timeout must be between 250 and 1500 milliseconds, got {}",
                    timeout_ms
                ),
            ));
        }
        self.terminal.set_esc_timeout(timeout_ms);
        Ok(())
    }

    /// Idle processing - broadcasts command set changes and updates command states
    /// Matches Borland: TProgram::idle() (tprogram.cc:248-257)
    /// Set the current help context.
    ///
    /// Matches Borland: TProgram tracks the focused view's helpCtx; since
    /// views here don't carry one, applications set it when the active
    /// window changes. The status line's TStatusDef item set follows it on
    /// the next idle tick (see StatusLine::with_defs).
    pub fn set_help_context(&mut self, help_ctx: u16) {
        self.current_help_ctx = help_ctx;
    }

    pub fn idle(&mut self) {
        // Safety net for a resize that never reached us as an event: a
        // SIGWINCH raised before crossterm's event source exists (Warp does
        // this when the alternate screen changes the pty size at startup) is
        // never delivered, leaving the app laid out for the wrong size. idle()
        // only runs when nothing else is happening, so re-checking the size
        // here is cheap and self-heals that case.
        if let Ok((w, h)) = self.terminal.backend_size() {
            let (cur_w, cur_h) = self.terminal.size();
            if w != cur_w || h != cur_h {
                self.handle_redraw();
            }
        }

        // Status line follows the current help context (Borland:
        // TProgram::idle calls statusLine->update())
        if let Some(ref mut status_line) = self.status_line {
            status_line.update(self.current_help_ctx);
        }

        // Update overlay widgets (animations, etc.)
        // These continue running even during modal dialogs
        for widget in &mut self.overlay_widgets {
            widget.idle();
        }

        // While a button is held, let views repeat their press action. Nothing
        // is sent when no button is down, so an idle app stays idle.
        if self.mouse_held {
            let mut repeat = Event::broadcast(crate::core::command::CM_MOUSE_AUTO_REPEAT);
            self.desktop.handle_event(&mut repeat);
        }

        // A plain tick for views that need a timer of their own: a tooltip's
        // hover delay, an animation. `idle` only runs when the event poll times
        // out, so this fires a few times a second while the user is not typing,
        // and not at all while they are. Views must not clear it, since a
        // broadcast stops travelling once it is consumed.
        let mut tick = Event::broadcast(crate::core::command::CM_IDLE_TICK);
        self.desktop.handle_event(&mut tick);

        // Update tile/cascade command states based on desktop state
        // Matches Borland: TVDemo::idle() checks deskTop->firstThat(isTileable, 0)
        if self.desktop.has_tileable_windows() {
            command_set::enable_command(CM_TILE);
            command_set::enable_command(CM_CASCADE);
        } else {
            command_set::disable_command(CM_TILE);
            command_set::disable_command(CM_CASCADE);
        }

        // Check if command set changed and broadcast to all views
        if command_set::command_set_changed() {
            let mut event = Event::broadcast(CM_COMMAND_SET_CHANGED);

            // Broadcast to desktop (which propagates to all children)
            self.desktop.handle_event(&mut event);

            // Also send to menu bar and status line
            if let Some(ref mut menu_bar) = self.menu_bar {
                menu_bar.handle_event(&mut event);
            }
            if let Some(ref mut status_line) = self.status_line {
                status_line.handle_event(&mut event);
            }

            command_set::clear_command_set_changed();
        }
    }

    /// Suspend the application (for Ctrl+Z handling)
    /// Matches Borland: TProgram::suspend() - temporarily exits TUI mode
    /// Restores terminal to normal mode, allowing user to return to shell
    /// Call resume() to return to TUI mode
    pub fn suspend(&mut self) -> crate::core::error::Result<()> {
        self.terminal.suspend()
    }

    /// Resume the application after suspension (for Ctrl+Z handling)
    /// Matches Borland: TProgram::resume() - returns to TUI mode and redraws
    /// Re-enters raw mode and forces a complete screen redraw
    pub fn resume(&mut self) -> crate::core::error::Result<()> {
        self.terminal.resume()?;

        // Force complete redraw of the entire UI
        // Draw desktop (which includes all windows)
        self.desktop.draw(&mut self.terminal);

        // Draw menu bar if present
        if let Some(ref mut menu_bar) = self.menu_bar {
            menu_bar.draw(&mut self.terminal);
        }

        // Draw status line if present
        if let Some(ref mut status_line) = self.status_line {
            status_line.draw(&mut self.terminal);
        }

        self.terminal.flush()?;
        Ok(())
    }
}

impl Drop for Application {
    fn drop(&mut self) {
        let _ = self.terminal.shutdown();
    }
}

#[cfg(test)]
mod resize_tests {
    use super::*;
    use crate::core::state::{GF_GROW_HI_X, GF_GROW_HI_Y};
    use crate::terminal::Backend;
    use std::cell::Cell as StdCell;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicU16, Ordering};

    /// A backend whose reported size can be changed mid-test, standing in
    /// for a real terminal being resized by the user (e.g. via SIGWINCH).
    struct ResizableBackend {
        size: Arc<(AtomicU16, AtomicU16)>,
    }

    impl Backend for ResizableBackend {
        fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
            self
        }
        fn init(&mut self) -> std::io::Result<()> {
            Ok(())
        }
        fn cleanup(&mut self) -> std::io::Result<()> {
            Ok(())
        }
        fn size(&self) -> std::io::Result<(u16, u16)> {
            Ok((
                self.size.0.load(Ordering::SeqCst),
                self.size.1.load(Ordering::SeqCst),
            ))
        }
        fn poll_event(&mut self, _timeout: Duration) -> std::io::Result<Option<Event>> {
            Ok(None)
        }
        fn write_raw(&mut self, _data: &[u8]) -> std::io::Result<()> {
            Ok(())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
        fn show_cursor(&mut self, _x: u16, _y: u16) -> std::io::Result<()> {
            Ok(())
        }
        fn hide_cursor(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    /// A child view that records every `set_bounds` call, standing in for a
    /// real consumer (e.g. the text scrollback re-wrap in `TextViewer`) that
    /// depends on `set_bounds` actually being called on resize.
    struct RecordingView {
        bounds: Rect,
        grow_mode: crate::core::state::GrowFlags,
        set_bounds_calls: Rc<StdCell<u32>>,
    }

    impl View for RecordingView {
        fn bounds(&self) -> Rect {
            self.bounds
        }
        fn set_bounds(&mut self, bounds: Rect) {
            self.bounds = bounds;
            self.set_bounds_calls.set(self.set_bounds_calls.get() + 1);
        }
        fn draw(&mut self, _terminal: &mut Terminal) {}
        fn handle_event(&mut self, _event: &mut Event) {}
        fn get_palette(&self) -> Option<crate::core::palette::Palette> {
            None
        }
        fn grow_mode(&self) -> crate::core::state::GrowFlags {
            self.grow_mode
        }
        fn set_grow_mode(&mut self, grow_mode: crate::core::state::GrowFlags) {
            self.grow_mode = grow_mode;
        }
    }

    /// Wraps a plain `Group` so it can itself be added as a Desktop child;
    /// it forwards `set_bounds` down to its own children (the
    /// `RecordingView`) via `Group`'s existing grow-mode logic, so the
    /// resize cascade crosses two levels of nesting — like a window's frame
    /// containing a scrollable widget.
    struct GroupView(crate::views::group::Group);

    impl View for GroupView {
        fn bounds(&self) -> Rect {
            self.0.bounds()
        }
        fn set_bounds(&mut self, bounds: Rect) {
            View::set_bounds(&mut self.0, bounds);
        }
        fn draw(&mut self, terminal: &mut Terminal) {
            View::draw(&mut self.0, terminal);
        }
        fn handle_event(&mut self, event: &mut Event) {
            View::handle_event(&mut self.0, event);
        }
        fn get_palette(&self) -> Option<crate::core::palette::Palette> {
            None
        }
        fn grow_mode(&self) -> crate::core::state::GrowFlags {
            View::grow_mode(&self.0)
        }
        fn set_grow_mode(&mut self, grow_mode: crate::core::state::GrowFlags) {
            View::set_grow_mode(&mut self.0, grow_mode);
        }
    }

    /// Builds an Application on a `ResizableBackend`, with a menu bar,
    /// status line, and one nested `RecordingView`.
    fn build_test_app(
        width: i16,
        height: i16,
    ) -> (Application, Arc<(AtomicU16, AtomicU16)>, Rc<StdCell<u32>>) {
        let size = Arc::new((
            AtomicU16::new(u16::try_from(width).unwrap()),
            AtomicU16::new(u16::try_from(height).unwrap()),
        ));
        let backend = ResizableBackend {
            size: Arc::clone(&size),
        };
        let terminal = Terminal::with_backend(Box::new(backend)).unwrap();

        let desktop = Desktop::new(Rect::new(0, 0, width, height));

        let mut app = Application {
            terminal,
            menu_bar: None,
            status_line: None,
            desktop,
            running: true,
            needs_redraw: true,
            pending_event: None,
            overlay_widgets: Vec::new(),
            mouse_held: false,
            help_file: None,
            help_context: HelpContext::new(),
            current_help_ctx: 0,
        };

        app.set_menu_bar(MenuBar::new(Rect::new(0, 0, width, 1)));
        app.set_status_line(StatusLine::new(
            Rect::new(0, height - 1, width, height),
            Vec::new(),
        ));

        let set_bounds_calls = Rc::new(StdCell::new(0));
        let mut inner_group = crate::views::group::Group::new(Rect::new(0, 0, width, height - 2));
        inner_group.set_grow_mode(GF_GROW_HI_X | GF_GROW_HI_Y);
        inner_group.add(Box::new(RecordingView {
            bounds: Rect::new(0, 0, width, height - 2),
            grow_mode: GF_GROW_HI_X | GF_GROW_HI_Y,
            set_bounds_calls: Rc::clone(&set_bounds_calls),
        }));

        let mut group_view = GroupView(inner_group);
        group_view.set_grow_mode(GF_GROW_HI_X | GF_GROW_HI_Y);
        app.desktop.add(Box::new(group_view));

        (app, size, set_bounds_calls)
    }

    #[test]
    fn resize_resizes_desktop_to_new_bounds() {
        let (mut app, size, _calls) = build_test_app(80, 25);
        size.0.store(100, Ordering::SeqCst);
        size.1.store(40, Ordering::SeqCst);

        app.handle_redraw();

        let desktop_bounds = app.desktop.get_bounds();
        assert_eq!(desktop_bounds.width(), 100);
        // Desktop height excludes the 1-row menu bar and 1-row status line.
        assert_eq!(desktop_bounds.height(), 40 - 2);
        assert_eq!(app.terminal.size(), (100, 40));
    }

    #[test]
    fn resize_lays_out_grow_mode_children_and_reaches_nested_view() {
        let (mut app, size, calls) = build_test_app(80, 25);
        let before = calls.get();
        size.0.store(120, Ordering::SeqCst);
        size.1.store(50, Ordering::SeqCst);

        app.handle_redraw();

        // set_bounds must actually reach the nested RecordingView, not just
        // the top-level Group.
        assert!(calls.get() > before);
        let child_bounds = app.desktop.child_at(app.desktop.child_count() - 1).bounds();
        assert_eq!(child_bounds.width(), 120);
        assert_eq!(child_bounds.height(), 50 - 2);
    }

    #[test]
    fn resize_moves_status_line_to_new_bottom_row() {
        let (mut app, size, _calls) = build_test_app(80, 25);
        size.0.store(80, Ordering::SeqCst);
        size.1.store(50, Ordering::SeqCst);

        app.handle_redraw();

        let sb = app.status_line.as_ref().unwrap().bounds();
        assert_eq!(sb.a.y, 49);
        assert_eq!(sb.b.y, 50);
    }

    #[test]
    fn resize_moves_menu_bar_to_new_width() {
        let (mut app, size, _calls) = build_test_app(80, 25);
        size.0.store(120, Ordering::SeqCst);
        size.1.store(25, Ordering::SeqCst);

        app.handle_redraw();

        let mb = app.menu_bar.as_ref().unwrap().bounds();
        assert_eq!(mb.b.x, 120);
    }

    #[test]
    fn shrink_then_grow_returns_sane_geometry() {
        let (mut app, size, _calls) = build_test_app(80, 25);

        size.0.store(40, Ordering::SeqCst);
        size.1.store(12, Ordering::SeqCst);
        app.handle_redraw();
        let shrunk = app.desktop.get_bounds();
        assert_eq!(shrunk.width(), 40);
        assert_eq!(shrunk.height(), 12 - 2);
        assert!(shrunk.a.x <= shrunk.b.x);
        assert!(shrunk.a.y <= shrunk.b.y);

        size.0.store(80, Ordering::SeqCst);
        size.1.store(25, Ordering::SeqCst);
        app.handle_redraw();
        let restored = app.desktop.get_bounds();
        assert_eq!(restored.width(), 80);
        assert_eq!(restored.height(), 25 - 2);
        assert_eq!(app.terminal.size(), (80, 25));

        let child_bounds = app.desktop.child_at(app.desktop.child_count() - 1).bounds();
        assert_eq!(child_bounds.width(), 80);
        assert_eq!(child_bounds.height(), 25 - 2);
    }

    #[test]
    fn no_size_change_does_not_disturb_layout() {
        let (mut app, _size, calls) = build_test_app(80, 25);
        let before_bounds = app.desktop.get_bounds();
        let before_calls = calls.get();

        app.handle_redraw();

        assert_eq!(app.desktop.get_bounds(), before_bounds);
        assert_eq!(calls.get(), before_calls);
    }

    // --- Window participation in the resize cascade -----------------------
    //
    // Regression coverage for the bug where every `Window` reported
    // `grow_mode() == 0` (fixed) because `Window` didn't override the
    // `View` trait's default grow-mode accessors, so the desktop resize
    // cascade correctly visited windows and then did nothing to them.

    use crate::core::geometry::Point;
    use crate::views::window::Window;

    #[test]
    fn window_added_to_desktop_follows_desktop_resize() {
        let (mut app, size, _calls) = build_test_app(80, 25);
        // Establish the real (post-menu/status-line) desktop bounds before
        // sizing the window, and leave room for the window's shadow so
        // `Desktop::add`'s `constrain_to_parent_bounds` doesn't shift it.
        app.handle_redraw();
        let (shadow_x, shadow_y) = crate::core::state::shadow_size();
        let desktop_bounds = app.desktop.get_bounds();
        let window_bounds = Rect::new(
            desktop_bounds.a.x,
            desktop_bounds.a.y,
            desktop_bounds.b.x - shadow_x,
            desktop_bounds.b.y - shadow_y,
        );

        // Window::add (via the interior Group) takes bounds relative to the
        // window's interior origin, not absolute screen coordinates. Span
        // the whole interior (0,0)..(interior width, interior height), like
        // a content view (e.g. a TextViewer) that fills its window.
        let interior_w = window_bounds.width() - 2;
        let interior_h = window_bounds.height() - 2;

        let mut window = Window::new(window_bounds, "Test Window");
        let set_bounds_calls = Rc::new(StdCell::new(0));
        window.add(Box::new(RecordingView {
            bounds: Rect::new(0, 0, interior_w, interior_h),
            grow_mode: GF_GROW_HI_X | GF_GROW_HI_Y,
            set_bounds_calls: Rc::clone(&set_bounds_calls),
        }));
        app.desktop.add(Box::new(window));

        size.0.store(120, Ordering::SeqCst);
        size.1.store(50, Ordering::SeqCst);
        app.handle_redraw();

        let window_index = app.desktop.child_count() - 1;
        let new_desktop_bounds = app.desktop.get_bounds();
        let window = app
            .desktop
            .child_at_mut(window_index)
            .as_any_mut()
            .downcast_mut::<Window>()
            .expect("last desktop child should be the Window");

        // The window's own bounds (and therefore its frame, which shares
        // them) must have grown along with the desktop.
        let expected = Rect::new(
            new_desktop_bounds.a.x,
            new_desktop_bounds.a.y,
            new_desktop_bounds.b.x - shadow_x,
            new_desktop_bounds.b.y - shadow_y,
        );
        assert_eq!(window.bounds(), expected);

        // The interior child (a stand-in for a window's real content, e.g.
        // an editor's TextViewer) must have been re-laid-out too, not just
        // the window's own bounds: it fills the interior, whose top-left
        // (window top-left + 1) stays put and whose bottom-right (window
        // bottom-right - 1) must have grown by the same amount as the
        // window.
        assert!(set_bounds_calls.get() > 0);
        let interior_child_bounds = window.interior_mut().child_at(0).bounds();
        let expected_interior_top_left = Point::new(window_bounds.a.x + 1, window_bounds.a.y + 1);
        assert_eq!(interior_child_bounds.a, expected_interior_top_left);
        assert_eq!(
            interior_child_bounds.b,
            Point::new(expected.b.x - 1, expected.b.y - 1)
        );
    }

    #[test]
    fn window_set_grow_mode_takes_effect_and_reads_back() {
        let mut window = Window::new(Rect::new(0, 0, 20, 10), "W");

        // Deliberately not gfGrowAll — see the field doc on Window::grow_mode.
        assert_eq!(window.grow_mode(), GF_GROW_HI_X | GF_GROW_HI_Y);

        window.set_grow_mode(GF_GROW_HI_X);
        assert_eq!(window.grow_mode(), GF_GROW_HI_X);
    }

    #[test]
    fn window_with_fixed_grow_mode_stays_put_on_desktop_resize() {
        let (mut app, size, _calls) = build_test_app(80, 25);
        app.handle_redraw();
        let (shadow_x, shadow_y) = crate::core::state::shadow_size();
        let desktop_bounds = app.desktop.get_bounds();
        let window_bounds = Rect::new(
            desktop_bounds.a.x,
            desktop_bounds.a.y,
            desktop_bounds.b.x - shadow_x,
            desktop_bounds.b.y - shadow_y,
        );

        let mut window = Window::new(window_bounds, "Fixed Window");
        window.set_grow_mode(0);
        app.desktop.add(Box::new(window));

        size.0.store(120, Ordering::SeqCst);
        size.1.store(50, Ordering::SeqCst);
        app.handle_redraw();

        let window_index = app.desktop.child_count() - 1;
        let window = app
            .desktop
            .child_at(window_index)
            .as_any()
            .downcast_ref::<Window>()
            .expect("last desktop child should be the Window");

        assert_eq!(window.bounds(), window_bounds);
    }
}