-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathframemanager.go
More file actions
1336 lines (1193 loc) · 38 KB
/
framemanager.go
File metadata and controls
1336 lines (1193 loc) · 38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package vtui
import (
"fmt"
"os"
"sync"
"time"
"strings"
"github.com/unxed/vtinput"
"golang.org/x/term"
)
// FrameType defines the type of a frame for introspection.
type FrameType int
const (
TypeDesktop FrameType = iota
TypeDialog
TypeMenu
TypeUser
)
// Frame is the interface that all top-level screen objects (windows, dialogs, menus) must implement.
type Frame interface {
ProcessKey(e *vtinput.InputEvent) bool
ProcessMouse(e *vtinput.InputEvent) bool
Show(scr *ScreenBuf)
ResizeConsole(w, h int)
GetType() FrameType
SetExitCode(code int)
IsDone() bool
GetHelp() string
IsBusy() bool // If true, FrameManager may skip the rendering phase
HasShadow() bool
GetKeyLabels() *KeySet
HandleCommand(cmd int, args any) bool // Turbo Vision style command routing
HandleBroadcast(cmd int, args any) bool
Valid(cmd int) bool
HitTest(x, y int) bool
// MDI Methods
GetMenuBar() *MenuBar
SetPosition(x1, y1, x2, y2 int)
GetPosition() (x1, y1, x2, y2 int)
IsModal() bool
GetWindowNumber() int
SetWindowNumber(n int)
RequestFocus() bool
Close()
GetTitle() string
GetProgress() int // Returns 0-100, or -1 if no progress
}
// AppScreen represents an isolated workspace with its own frame stack.
type AppScreen struct {
Frames []Frame
CapturedFrame Frame
Transparent bool // Если true, под этим экраном будет рисоваться предыдущий
}
func (s *AppScreen) GetTitle() string {
if len(s.Frames) == 0 {
return "Workspace"
}
// Возвращаем заголовок самого верхнего фрейма, очищенный от декоративных пробелов
return strings.TrimSpace(s.Frames[len(s.Frames)-1].GetTitle())
}
func (s *AppScreen) GetProgress() int {
for i := len(s.Frames) - 1; i >= 0; i-- {
if p := s.Frames[i].GetProgress(); p >= 0 {
return p
}
}
return -1
}
func (s *AppScreen) NeedsAttention() bool {
if len(s.Frames) == 0 { return false }
top := s.Frames[len(s.Frames)-1]
// Проверяем флаг подавления внимания
suppressed := false
if bf, ok := top.(interface{ IsAttentionSuppressed() bool }); ok {
suppressed = bf.IsAttentionSuppressed()
}
return top.IsModal() && !suppressed && top.GetType() != TypeMenu
}
// frameManager manages multiple screens and the main application loop.
type frameManager struct {
Screens []*AppScreen
ActiveIdx int
frames []Frame // Points to the active screen's frame stack
scr *ScreenBuf
RedrawChan chan struct{}
TaskChan chan func()
EventChan chan *vtinput.InputEvent
EventFilter func(*vtinput.InputEvent) bool
injectedEvents []*vtinput.InputEvent
OnRender func(scr *ScreenBuf)
// Global standard UI components
DisabledCommands CommandSet
MenuBar *MenuBar
StatusLine *StatusLine
KeyBar *KeyBar
capturedFrame Frame // Points to the active screen's captured frame
// Switcher State
ctrlPressed bool
switcherActive bool
switcherIdx int
running bool
lastMouseClickTime time.Time
lastMouseX, lastMouseY int
lastMouseButton uint32
Reader *vtinput.Reader
}
// FrameManager is the global instance of the frame manager.
var FrameManager = &frameManager{}
func (fm *frameManager) SyncCurrentScreen() {
if len(fm.Screens) > 0 {
fm.Screens[fm.ActiveIdx].Frames = fm.frames
fm.Screens[fm.ActiveIdx].CapturedFrame = fm.capturedFrame
}
}
func (fm *frameManager) GetActiveFrames(sIdx int) []Frame {
if sIdx == fm.ActiveIdx {
return fm.frames
}
if sIdx >= 0 && sIdx < len(fm.Screens) {
return fm.Screens[sIdx].Frames
}
return nil
}
func (fm *frameManager) SwitchScreen(idx int) {
if idx < 0 || idx >= len(fm.Screens) {
return
}
if idx == fm.ActiveIdx && len(fm.frames) > 0 {
return
}
// 1. Notify current screen it's losing focus
if len(fm.frames) > 0 {
fm.frames[len(fm.frames)-1].ProcessKey(&vtinput.InputEvent{Type: vtinput.FocusEventType, SetFocus: false})
}
fm.SyncCurrentScreen()
// MRU Reordering: Move the selected screen to the end of the array
screen := fm.Screens[idx]
fm.Screens = append(fm.Screens[:idx], fm.Screens[idx+1:]...)
fm.Screens = append(fm.Screens, screen)
fm.ActiveIdx = len(fm.Screens) - 1
fm.frames = fm.Screens[fm.ActiveIdx].Frames
fm.capturedFrame = fm.Screens[fm.ActiveIdx].CapturedFrame
DebugLog("FM: Switched to Screen %d (Workspace: %s)", fm.ActiveIdx, fm.Screens[fm.ActiveIdx].GetTitle())
// 2. Notify new screen it's gaining focus
if len(fm.frames) > 0 {
fm.frames[len(fm.frames)-1].ProcessKey(&vtinput.InputEvent{Type: vtinput.FocusEventType, SetFocus: true})
}
fm.Redraw()
}
func (fm *frameManager) createScreen(f Frame, transparent bool) *AppScreen {
newScreen := &AppScreen{Frames: make([]Frame, 0, 10), Transparent: transparent}
if !transparent {
newScreen.Frames = append(newScreen.Frames, NewDesktop())
}
newScreen.Frames = append(newScreen.Frames, f)
return newScreen
}
func (fm *frameManager) AddScreen(f Frame) {
// If we are already shutting down or in an inconsistent state, bail out.
if fm.Screens == nil { return }
fm.SyncCurrentScreen()
fm.Screens = append(fm.Screens, fm.createScreen(f, false))
fm.SwitchScreen(len(fm.Screens) - 1)
fm.Redraw()
}
func (fm *frameManager) AddScreenHeadless(f Frame) {
if fm.Screens == nil { return }
fm.SyncCurrentScreen()
fm.Screens = append(fm.Screens, fm.createScreen(f, true))
fm.ActiveIdx = len(fm.Screens) - 1
fm.frames = fm.Screens[fm.ActiveIdx].Frames
fm.capturedFrame = nil
f.ProcessKey(&vtinput.InputEvent{Type: vtinput.FocusEventType, SetFocus: true})
fm.Redraw()
}
func (fm *frameManager) AddScreenBackground(f Frame) {
fm.SyncCurrentScreen()
fm.Screens = append(fm.Screens, fm.createScreen(f, false))
// Notice: We intentionally do not call fm.SwitchScreen here
}
func (fm *frameManager) CloseActiveScreen() {
if len(fm.Screens) <= 1 {
fm.EmitCommand(CmQuit, nil)
return
}
fm.Screens = append(fm.Screens[:fm.ActiveIdx], fm.Screens[fm.ActiveIdx+1:]...)
newIdx := fm.ActiveIdx
if newIdx >= len(fm.Screens) {
newIdx = len(fm.Screens) - 1
}
fm.ActiveIdx = newIdx
fm.frames = fm.Screens[newIdx].Frames
fm.capturedFrame = fm.Screens[newIdx].CapturedFrame
fm.Redraw()
}
// GetActiveMenuBar returns the menu bar of the topmost frame that provides one,
// or the global MenuBar if none do.
func (fm *frameManager) GetActiveMenuBar() *MenuBar {
for i := len(fm.frames) - 1; i >= 0; i-- {
if mb := fm.frames[i].GetMenuBar(); mb != nil {
return mb
}
}
return fm.MenuBar
}
// Init initializes the FrameManager with a ScreenBuf.
func (fm *frameManager) Init(scr *ScreenBuf) {
fm.scr = scr
fm.frames = make([]Frame, 0, 10)
fm.Screens = []*AppScreen{{Frames: fm.frames}}
fm.ActiveIdx = 0
fm.RedrawChan = make(chan struct{}, 1)
fm.TaskChan = make(chan func(), 1024)
fm.injectedEvents = make([]*vtinput.InputEvent, 0)
SetDefaultPalette()
fm.scr.ThemePalette = &ThemePalette
// Hide cursor globally at start
fm.scr.SetCursorVisible(false)
// Reset terminal palette to default to clear state from possible previous crashes
os.Stdout.WriteString("\x1b]104\x07")
}
// Push adds a new frame to the top of the stack and assigns a number if it's non-modal.
func (fm *frameManager) Push(f Frame) {
if !f.IsModal() && f.GetType() != TypeDesktop {
// Find a free number from 1 to 9
used := make(map[int]bool)
for _, frame := range fm.frames {
if frame.GetWindowNumber() > 0 {
used[frame.GetWindowNumber()] = true
}
}
for i := 1; i <= 9; i++ {
if !used[i] {
f.SetWindowNumber(i)
break
}
}
}
if len(fm.frames) > 0 {
fm.frames[len(fm.frames)-1].ProcessKey(&vtinput.InputEvent{Type: vtinput.FocusEventType, SetFocus: false})
}
fm.frames = append(fm.frames, f)
fm.SyncCurrentScreen() // Ensure the Screen object is aware of the new frame immediately
f.ProcessKey(&vtinput.InputEvent{Type: vtinput.FocusEventType, SetFocus: true})
}
// PushToFrameScreen adds a frame to the screen that contains the anchor frame.
func (fm *frameManager) PushToFrameScreen(anchor Frame, f Frame) {
fm.SyncCurrentScreen()
for i, s := range fm.Screens {
for _, existing := range s.Frames {
if existing == anchor {
if i == fm.ActiveIdx {
// Target is active screen, use standard Push to ensure proper focus and slice update
fm.Push(f)
} else {
// Target is background screen
s.Frames = append(s.Frames, f)
// Initialize focus state for the new frame
f.ProcessKey(&vtinput.InputEvent{Type: vtinput.FocusEventType, SetFocus: true})
// Auto-switch to this screen if the frame is modal (pull user attention)
if f.IsModal() {
fm.SwitchScreen(i)
}
}
return
}
}
}
// Fallback to active screen if anchor is lost
fm.Push(f)
}
// Flash provides visual feedback for screen transitions (fork/close).
func (fm *frameManager) Flash() {
if fm.scr == nil {
return
}
prevOverlay := fm.scr.OverlayMode
fm.scr.SetOverlayMode(false)
// Pure black blink
fm.scr.FillRect(0, 0, fm.scr.width-1, fm.scr.height-1, ' ', SetRGBBoth(0, 0, 0))
fm.scr.Flush()
time.Sleep(30 * time.Millisecond)
fm.scr.SetOverlayMode(prevOverlay)
fm.Redraw()
}
// Broadcast sends a command to ALL frames in ALL screens, bypassing focus and modality.
// Returns true if at least one element handled the broadcast.
func (fm *frameManager) Broadcast(cmd int, args any) bool {
if fm.Screens == nil {
return false
}
handled := false
for _, s := range fm.Screens {
for i := len(s.Frames) - 1; i >= 0; i-- {
if s.Frames[i].HandleBroadcast(cmd, args) {
handled = true
}
}
}
if handled {
fm.Redraw()
}
return handled
}
// RequestFocus moves the given frame to the top of the stack (brings it to front).
// Returns false if a modal dialog blocks the focus change.
func (fm *frameManager) RequestFocus(f Frame) bool {
// If there's a modal dialog on top, we cannot change focus
for i := len(fm.frames) - 1; i >= 0; i-- {
if fm.frames[i] == f {
break
}
if fm.frames[i].IsModal() {
return false
}
}
idx := -1
for i, frame := range fm.frames {
if frame == f {
idx = i
break
}
}
if idx == -1 || idx == len(fm.frames)-1 {
return true // Already on top or not found
}
// Tell current top frame it lost focus
fm.frames[len(fm.frames)-1].ProcessKey(&vtinput.InputEvent{Type: vtinput.FocusEventType, SetFocus: false})
// Move the frame to the end of the slice
fm.frames = append(fm.frames[:idx], fm.frames[idx+1:]...)
fm.frames = append(fm.frames, f)
// Tell new top frame it got focus
f.ProcessKey(&vtinput.InputEvent{Type: vtinput.FocusEventType, SetFocus: true})
fm.Redraw()
return true
}
// Pop removes the top-most frame from the stack.
func (fm *frameManager) Pop() {
if len(fm.frames) > 0 {
top := fm.frames[len(fm.frames)-1]
if fm.capturedFrame == top {
fm.capturedFrame = nil
}
fm.frames = fm.frames[:len(fm.frames)-1]
if len(fm.frames) > 0 {
fm.frames[len(fm.frames)-1].ProcessKey(&vtinput.InputEvent{Type: vtinput.FocusEventType, SetFocus: true})
}
}
}
// RemoveFrame deletes a specific frame from the stack, regardless of its position.
func (fm *frameManager) RemoveFrame(f Frame) {
isTop := len(fm.frames) > 0 && fm.frames[len(fm.frames)-1] == f
for i, frame := range fm.frames {
if frame == f {
if fm.capturedFrame == f {
fm.capturedFrame = nil
}
fm.frames = append(fm.frames[:i], fm.frames[i+1:]...)
fm.SyncCurrentScreen() // Critical: update the slice header in Screens array
if isTop && len(fm.frames) > 0 {
fm.frames[len(fm.frames)-1].ProcessKey(&vtinput.InputEvent{Type: vtinput.FocusEventType, SetFocus: true})
}
return
}
}
}
// Redraw triggers an asynchronous redraw request.
func (fm *frameManager) Redraw() {
select {
case fm.RedrawChan <- struct{}{}:
default:
}
}
// PostTask schedules a function to be executed safely on the main UI thread.
func (fm *frameManager) PostTask(task func()) {
if fm.TaskChan != nil {
select {
case fm.TaskChan <- task:
// Успешно добавлено
default:
// Очередь полна. Не блокируемся, чтобы не вызвать дедлок.
// В нормальной ситуации UI-поток скоро освободит место.
}
}
}
// EmitCommand broadcasts a command starting from the top-most frame
// and going down the stack until a frame handles it. (Turbo Vision style)
func (fm *frameManager) EmitCommand(cmd int, args any) bool {
if fm.DisabledCommands.IsDisabled(cmd) {
DebugLog("COMMAND: %d is DISABLED, ignoring", cmd)
return false
}
DebugLog("COMMAND: Emitting %d", cmd)
// First, if MenuBar is active, give it a chance
activeMenu := fm.GetActiveMenuBar()
if activeMenu != nil && activeMenu.Active {
if activeMenu.HandleCommand(cmd, args) {
DebugLog("COMMAND: Handled by MenuBar")
return true
}
}
// Route down the frame stack
for i := len(fm.frames) - 1; i >= 0; i-- {
DebugLog("COMMAND: Checking frame %d (type %d)", i, fm.frames[i].GetType())
if fm.frames[i].HandleCommand(cmd, args) {
DebugLog("COMMAND: Handled by frame %d", i)
fm.Redraw()
return true
}
}
DebugLog("COMMAND: No one handled %d", cmd)
return false
}
// InjectEvents adds simulated input events to the front of the queue.
func (fm *frameManager) InjectEvents(events []*vtinput.InputEvent) {
fm.injectedEvents = append(fm.injectedEvents, events...)
}
// Shutdown clears all frames, effectively stopping the application loop.
func (fm *frameManager) Shutdown() {
fm.Screens = nil
fm.frames = nil
fm.capturedFrame = nil
}
// IsShutdown returns true if the FrameManager has been shut down explicitly.
func (fm *frameManager) IsShutdown() bool {
return fm.Screens == nil
}
// WaitForFar2lReply safely blocks and waits for a specific Far2l reply from the event channel.
// Any other events received during this time are stashed to be processed later.
func (fm *frameManager) WaitForFar2lReply(expectedID uint8, timeout time.Duration) *vtinput.Far2lStack {
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
select {
case e, ok := <-fm.EventChan:
if !ok {
return nil
}
if e.Type == vtinput.Far2lEventType && e.Far2lCommand == "reply" {
stk := vtinput.Far2lStack(e.Far2lData)
id := stk.PopU8()
if id == expectedID {
return &stk
}
}
// Stash other events to be processed later by the main loop
fm.injectedEvents = append(fm.injectedEvents, e)
case <-time.After(10 * time.Millisecond):
// Yield and check deadline
}
}
return nil
}
// CycleWindows updates the selection in the switcher overlay
func (fm *frameManager) CycleWindows(forward bool) bool {
if len(fm.Screens) < 2 {
return false
}
if !fm.switcherActive {
fm.switcherActive = true
fm.switcherIdx = fm.ActiveIdx
}
// Active screen is always at len-1. 'Forward' goes to MRU-previous (len-2).
if forward {
fm.switcherIdx = (fm.switcherIdx - 1 + len(fm.Screens)) % len(fm.Screens)
} else {
fm.switcherIdx = (fm.switcherIdx + 1) % len(fm.Screens)
}
fm.Redraw()
return true
}
func (fm *frameManager) renderSwitcher(scr *ScreenBuf) {
if !fm.switcherActive || len(fm.Screens) < 2 { return }
menuW := 60
menuH := len(fm.Screens) + 2
x := (scr.width - menuW) / 2
y := (scr.height - menuH) / 2
attr := Palette[ColMenuText]
selAttr := Palette[ColMenuSelectedText]
boxAttr := Palette[ColMenuBox]
attnAttr := SetRGBBoth(0, 0xFFFFFF, 0xFF0000)
scr.FillRect(x, y, x+menuW-1, y+menuH-1, ' ', attr)
sym := getBoxSymbols(DoubleBox)
scr.Write(x, y, StringToCharInfo(string(sym[bsTL])+strings.Repeat(string(sym[bsH]), menuW-2)+string(sym[bsTR]), boxAttr))
scr.Write(x, y+menuH-1, StringToCharInfo(string(sym[bsBL])+strings.Repeat(string(sym[bsH]), menuW-2)+string(sym[bsBR]), boxAttr))
for i := 1; i < menuH-1; i++ {
scr.Write(x, y+i, StringToCharInfo(string(sym[bsV]), boxAttr))
scr.Write(x+menuW-1, y+i, StringToCharInfo(string(sym[bsV]), boxAttr))
}
maxTitleLen := menuW - 19
for i := range fm.Screens {
itemAttr := attr
if i == fm.switcherIdx { itemAttr = selAttr }
pre, tit, suf, needsAttn := fm.getScreenInfo(i, maxTitleLen)
if i == fm.switcherIdx { pre = "> " }
rowText := pre + tit + suf
scr.Write(x+1, y+1+i, StringToCharInfo(rowText+strings.Repeat(" ", menuW-2-len([]rune(rowText))), itemAttr))
if needsAttn {
scr.Write(x+1, y+1+i, StringToCharInfo("!", attnAttr))
}
}
}
func (fm *frameManager) getScreenInfo(idx int, maxTitleLen int) (prefix, title, suffix string, needsAttn bool) {
s := fm.Screens[idx]
rawTitle := s.GetTitle()
needsAttn = s.NeedsAttention()
isCurrent := (idx == fm.ActiveIdx)
prefix = " "
if isCurrent && needsAttn {
prefix = "? "
} else if isCurrent {
prefix = "* "
} else if needsAttn {
prefix = "! "
}
suffix = ""
if p := s.GetProgress(); p >= 0 {
barLen := 10
filled := (p * barLen) / 100
bar := "["
for b := 0; b < barLen; b++ {
if b < filled { bar += "#" } else { bar += "." }
}
suffix = " " + bar + "]"
}
title = TruncateMiddle(rawTitle, maxTitleLen)
return
}
func (fm *frameManager) showScreensMenu() {
fm.SyncCurrentScreen()
menu := NewVMenu(" Screens ")
scrW := fm.GetScreenSize()
scrH := 25
if fm.scr != nil { scrH = fm.scr.height }
menuW := (scrW * 60) / 100
if menuW < 40 { menuW = 40 }
if menuW > 100 { menuW = 100 }
maxTitleLen := menuW - 19
if maxTitleLen < 10 { maxTitleLen = 10 }
for i := range fm.Screens {
pre, tit, suf, _ := fm.getScreenInfo(i, maxTitleLen)
menu.AddItem(MenuItem{Text: pre + tit + suf, UserData: i})
}
menu.OnAction = func(idx int) {
fm.SwitchScreen(menu.Items[idx].UserData.(int))
}
menuH := len(fm.Screens) + 2
if menuH > 15 { menuH = 15 }
x := (scrW - menuW) / 2
y := (scrH - menuH) / 2
menu.SetPosition(x, y, x+menuW-1, y+menuH-1)
fm.Push(menu)
}
func (fm *frameManager) cleanupDoneFrames() {
fm.SyncCurrentScreen()
for sIdx := len(fm.Screens) - 1; sIdx >= 0; sIdx-- {
s := fm.Screens[sIdx]
wasModified := false
for i := len(s.Frames) - 1; i >= 0; i-- {
if s.Frames[i].IsDone() {
if s.CapturedFrame == s.Frames[i] { s.CapturedFrame = nil }
s.Frames = append(s.Frames[:i], s.Frames[i+1:]...)
wasModified = true
DebugLog("FM: Frame removed from Screen %d. Remaining: %d", sIdx, len(s.Frames))
}
}
// Экран считается мертвым, если:
// 1. В нем вообще нет фреймов.
// 2. В нем остался только Desktop, и МЫ ТОЛЬКО ЧТО закрыли в нем
// последнее окно (wasModified), и это НЕ единственный экран.
isDead := len(s.Frames) == 0
if !isDead && wasModified && len(s.Frames) == 1 && s.Frames[0].GetType() == TypeDesktop && len(fm.Screens) > 1 {
isDead = true
}
if isDead {
DebugLog("FM: Removing dead Screen %d (Total screens: %d)", sIdx, len(fm.Screens))
fm.Screens = append(fm.Screens[:sIdx], fm.Screens[sIdx+1:]...)
if fm.ActiveIdx >= sIdx && fm.ActiveIdx > 0 {
fm.ActiveIdx--
}
}
}
if len(fm.Screens) > 0 {
if fm.ActiveIdx >= len(fm.Screens) {
fm.ActiveIdx = len(fm.Screens) - 1
}
fm.frames = fm.Screens[fm.ActiveIdx].Frames
fm.capturedFrame = fm.Screens[fm.ActiveIdx].CapturedFrame
} else {
fm.Shutdown()
}
}
func (fm *frameManager) cleanupOrphanedMenus() {
activeMenu := fm.GetActiveMenuBar()
if activeMenu != nil && !activeMenu.Active && activeMenu.activeSubMenu != nil {
activeMenu.closeSub()
}
}
// GetTopFrameType returns the type of the topmost frame or -1 if empty.
func (fm *frameManager) GetTopFrameType() FrameType {
if len(fm.frames) == 0 {
DebugLog("FRAMEWORK: GetTopFrameType(), len(fm.frames) == 0")
return -1
}
return fm.frames[len(fm.frames)-1].GetType()
}
func (fm *frameManager) GetTopFrame() Frame {
if len(fm.frames) == 0 {
return nil
}
return fm.frames[len(fm.frames)-1]
}
func (fm *frameManager) GetScreenSize() int {
if fm.scr == nil { return 80 }
return fm.scr.width
}
func (fm *frameManager) GetScreenHeight() int {
if fm.scr == nil { return 25 }
return fm.scr.height
}
func (fm *frameManager) GetSyncStats() string {
tLen, tCap := 0, 0
if fm.TaskChan != nil {
tLen, tCap = len(fm.TaskChan), cap(fm.TaskChan)
}
eLen, eCap := 0, 0
if fm.EventChan != nil {
eLen, eCap = len(fm.EventChan), cap(fm.EventChan)
}
return fmt.Sprintf("Tasks:%d/%d, Events:%d/%d", tLen, tCap, eLen, eCap)
}
// GetTerminalSize is a variable to allow mocking terminal size in tests.
var GetTerminalSize = func() (int, int, error) {
w, h, err := term.GetSize(int(os.Stdout.Fd()))
if err != nil {
w, h, err = term.GetSize(int(os.Stdin.Fd()))
}
return w, h, err
}
// Stop signals the main loop to exit.
func (fm *frameManager) Stop() {
DebugLog("FM: Stop() requested. Deactivating menus and exiting loop.")
// Safety: deactivate top menu before leaving to avoid stale sub-menus on return
if fm.MenuBar != nil {
fm.MenuBar.Active = false
}
fm.running = false
// Wake up the select loop immediately
select {
case fm.RedrawChan <- struct{}{}:
default:
}
}
// Run starts the main application event loop.
func (fm *frameManager) Run(reader *vtinput.Reader) {
DebugLog("FM: Run() ENTERED with Reader[%p]", reader)
fm.Reader = reader
fm.running = true
// Restore cursor visibility on exit
defer func() {
if r := recover(); r != nil {
// Note: RecordCrash now generates its own full stack dump
DebugLog("FATAL PANIC IN RUN LOOP: %v", r)
crashPath := RecordCrash(r, nil)
Suspend()
CleanupStderrLog()
fmt.Fprintf(os.Stderr, "\n[f4] FATAL PANIC: %v\n", r)
if crashPath != "" {
fmt.Fprintf(os.Stderr, "[f4] Crash report saved to: %s\n", crashPath)
}
os.Exit(2)
}
fm.running = false
fm.scr.SetCursorVisible(true)
fm.scr.Flush()
}()
ch := make(chan *vtinput.InputEvent, 1024)
fm.EventChan = ch
stopChan := make(chan struct{})
var once sync.Once
go func() {
for {
select {
case <-stopChan:
return
default:
e, err := reader.ReadEvent()
if err != nil {
once.Do(func() { close(ch) })
return
}
select {
case ch <- e:
case <-stopChan:
return
}
}
}
}()
defer close(stopChan)
// Configure channel for tracking window resizing
sigChan := make(chan os.Signal, 1)
watchResizeSignal(sigChan)
// Heartbeat for animations and cursor blinking
go func() {
for fm.running {
time.Sleep(250 * time.Millisecond)
fm.Redraw()
}
}()
// Terminal size polling (handles Windows and fallback for missed SIGWINCH)
sizeChan := make(chan struct{}, 1)
go func() {
lastW, lastH, _ := GetTerminalSize()
for fm.running {
time.Sleep(200 * time.Millisecond)
w, h, err := GetTerminalSize()
if err == nil && w > 0 && h > 0 && (w != lastW || h != lastH) {
lastW, lastH = w, h
select {
case sizeChan <- struct{}{}:
default:
}
}
}
}()
handleResize := func() {
width, height, err := GetTerminalSize()
if err != nil {
return // Keep existing size if we can't determine the new one
}
if width > 0 && height > 0 && (width != fm.scr.width || height != fm.scr.height) {
fm.scr.AllocBuf(width, height)
for _, s := range fm.Screens {
for _, f := range s.Frames {
f.ResizeConsole(width, height)
}
}
fm.Redraw()
}
}
// --- Main application loop ---
// Persistent timer to avoid allocations in the drain loop
idleTimer := time.NewTimer(time.Hour)
if !idleTimer.Stop() {
select {
case <-idleTimer.C:
default:
}
}
DebugLog("FM: Entering Run loop. MenuBar set: %v, KeyBar set: %v", fm.MenuBar != nil, fm.KeyBar != nil)
for fm.running {
if len(fm.frames) == 0 {
DebugLog("FM: No frames left, exiting Run loop.")
return
}
// 1. Rendering
fm.renderPhase()
// 3. Event waiting (Blocking)
var e *vtinput.InputEvent
injected := false
loopAgain := false
if len(fm.injectedEvents) > 0 {
e = fm.injectedEvents[0]
fm.injectedEvents = fm.injectedEvents[1:]
injected = true
} else {
select {
case <-fm.RedrawChan:
loopAgain = true
case task := <-fm.TaskChan:
task()
fm.cleanupDoneFrames()
fm.Redraw()
loopAgain = true
case <-sigChan:
handleResize()
loopAgain = true
case <-sizeChan:
handleResize()
loopAgain = true
case ev, ok := <-fm.EventChan:
if !ok {
DebugLog("FM: eventChan closed, exiting Run() // in Event waiting (Blocking)")
return
}
e = ev
}
}
if loopAgain {
continue
}
if e.Type == vtinput.Far2lEventType {
// Protocol level events handled inside dispatchEvent to cover both main loop and drain loop
fm.dispatchEvent(e, injected)
continue
}
if e.Type == vtinput.ResizeEventType {
handleResize()
continue
}
if e.Type == vtinput.KeyEventType && e.KeyDown {
DebugLog("KEY: VK=%s Char=%d Src=%s ActiveFrames=%d", vtinput.VKString(e.VirtualKeyCode), e.Char, e.InputSource, len(fm.frames))
}
fm.dispatchEvent(e, injected)
// 4. Queue "Drain"
// Burst process pending events and tasks to avoid redundant renders.
// This naturally throttles the UI when a background thread spams updates.
for fm.running && !fm.IsShutdown() {
idleTimer.Reset(2 * time.Millisecond)
select {
case ev, ok := <-fm.EventChan:
if !idleTimer.Stop() {
select { case <-idleTimer.C: default: }
}
if !ok { return }
if len(fm.frames) > 0 {
fm.dispatchEvent(ev, false)
}
continue
case task := <-fm.TaskChan:
if !idleTimer.Stop() {
select { case <-idleTimer.C: default: }
}
task()
fm.cleanupDoneFrames()
fm.Redraw()
continue
case <-idleTimer.C:
}
break
}
}
}
func (fm *frameManager) renderPhase() {
if len(fm.frames) == 0 {
return
}
topFrame := fm.frames[len(fm.frames)-1]
// Update global status line context automatically
if fm.StatusLine != nil {
topic := ""
// Priority: Focused item's help -> Frame's help -> Menu context
if fm.MenuBar != nil && fm.MenuBar.Active {
topic = "menu"
} else {
if fc, ok := topFrame.(FocusContainer); ok {
if foc := fc.GetFocusedItem(); foc != nil && foc.GetHelp() != "" {
topic = foc.GetHelp()
}
}
if topic == "" {
topic = topFrame.GetHelp()
}
}
fm.StatusLine.UpdateContext(topic)
}
// Update KeyBar content from the active frame
if fm.KeyBar != nil {
// Find the topmost frame that provides key labels
for i := len(fm.frames) - 1; i >= 0; i-- {
if ks := fm.frames[i].GetKeyLabels(); ks != nil {
fm.KeyBar.Normal = ks.Normal
fm.KeyBar.Shift = ks.Shift
fm.KeyBar.Ctrl = ks.Ctrl
fm.KeyBar.Alt = ks.Alt
break
}
}
}
// If the frame is "busy" (e.g., mass insertion in progress), skip drawing
// and Flush to avoid flickering and save CPU.
if !topFrame.IsBusy() {
// Cleanup orphaned menus safely outside the frames iteration loop
// to avoid "index out of range" during rendering.
fm.cleanupOrphanedMenus()
fm.scr.SetCursorVisible(false)
fm.scr.ActivePalette = nil
// By default, we use OverlayMode (Early Binding) for host UI elements.
// Desktop and TerminalView will explicitly disable it during their render.
fm.scr.SetOverlayMode(true)
// 1. Находим "базовый" экран (первый непрозрачный, идя назад от активного)
baseIdx := fm.ActiveIdx
for baseIdx > 0 && fm.Screens[baseIdx].Transparent {
baseIdx--
}
// 2. Отрисовываем стэк экранов от базового до текущего
for sIdx := baseIdx; sIdx <= fm.ActiveIdx; sIdx++ {
frames := fm.GetActiveFrames(sIdx)
for _, frame := range frames {
if frame.HasShadow() {
x1, y1, x2, y2 := frame.GetPosition()
isFullScreen := x1 <= 0 && y1 <= 0 && x2 >= fm.scr.width-1 && y2 >= fm.scr.height-1
if !isFullScreen {