-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame_lifecycle.go
More file actions
259 lines (241 loc) · 8.87 KB
/
Copy pathgame_lifecycle.go
File metadata and controls
259 lines (241 loc) · 8.87 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
package main
import (
"image"
"io/fs"
"os"
"strings"
"time"
"github.com/hajimehoshi/ebiten/v2"
)
func (g *Game) handleFocus() {
// screenWakeFlag: set by sleepWatcher goroutine after it restored TPS from 0
// following a WillSleep/DidWake cycle. Trigger full repaint before focus-state
// transitions, which are unreliable after screen-sleep on some configurations.
if consumeScreenWake() {
g.unsuspendAndRedraw()
}
// NSWorkspaceDidWakeNotification (non-screen-sleep path): sleepWatcher only
// consumes wakeFlag when screenSleeping=1, so this handles cases where the
// system woke without the display having been halted by sleepWatcher.
if consumeWake() {
g.unsuspendAndRedraw()
}
// NSApplicationDidChangeScreenParametersNotification: display configuration
// changed (HDMI connect/disconnect, resolution change, lid open/close).
// Unsuspend and mark dirty immediately, but defer the winW=0 trigger by
// 2 frames so macOS can finish EDID negotiation and report the final
// geometry before zurm commits pane rects and sends SIGWINCH.
if consumeScreenChange() {
g.unsuspendAndRedraw()
// unsuspendAndRedraw zeroed winW — restore it and start the stability
// wait. handleResize will keep sampling window size/DPI each frame and
// only commit layout once they have been unchanged for 3 consecutive
// frames, so zurm adapts to however long EDID negotiation actually takes.
w, h := g.logicalSize()
dpi := g.monitorDPI()
g.winW = w
g.screenSettleW = w
g.screenSettleH = h
g.screenSettleDPI = dpi
g.screenSettleFrames = 3
}
focused := ebiten.IsFocused()
// Idle suspension: reduce TPS after 5 seconds unfocused (when auto_idle is enabled).
if g.cfg.Performance.AutoIdle && !focused && !g.wfocus.Suspended && !g.wfocus.UnfocusedAt.IsZero() &&
time.Since(g.wfocus.UnfocusedAt) > unfocusSuspendDelay {
ebiten.SetTPS(5)
g.wfocus.Suspended = true
for _, t := range g.tabMgr.Tabs {
for _, leaf := range t.Layout.Leaves() {
leaf.Pane.Term.SetPaused(true)
}
}
for _, t := range g.tabMgr.Parked {
for _, leaf := range t.Layout.Leaves() {
leaf.Pane.Term.SetPaused(true)
}
}
}
if focused != g.wfocus.PrevFocused {
if focused {
// Unsuspend, zero unfocusedAt, and force full repaint.
g.unsuspendAndRedraw()
// Reset edge-detection state on focus gain.
// Modifier keys are seeded from the hardware state (NSEvent.modifierFlags)
// rather than GLFW's cached IsKeyPressed. GLFW can miss key-up events that
// fire while another window owns focus (e.g. CMD released in the App Switcher
// during CMD+Tab), leaving the key "stuck" as pressed in GLFW's cache
// indefinitely. Reading hardware state directly corrects this stale value.
// Non-modifier keys always start as "not pressed" so the first real keystroke
// after focus regain fires its leading edge correctly.
hwCmd, hwCtrl, hwShift, hwAlt := hardwareModifiers()
for k := ebiten.Key(0); k <= ebiten.KeyMax; k++ {
switch k {
case ebiten.KeyMeta, ebiten.KeyMetaLeft, ebiten.KeyMetaRight:
g.input.PrevKeys[k] = hwCmd
case ebiten.KeyControl, ebiten.KeyControlLeft, ebiten.KeyControlRight:
g.input.PrevKeys[k] = hwCtrl
case ebiten.KeyShift, ebiten.KeyShiftLeft, ebiten.KeyShiftRight:
g.input.PrevKeys[k] = hwShift
case ebiten.KeyAlt, ebiten.KeyAltLeft, ebiten.KeyAltRight:
g.input.PrevKeys[k] = hwAlt
default:
g.input.PrevKeys[k] = false
}
}
// Reset mouse button edge-detection state on focus gain, matching
// prevKeys reset above. Stale prevMouseButtons[left]=true from the
// last interaction before focus loss would cause the first click to
// be silently skipped (pressed==was → no edge detected).
for btn := range g.input.PrevMouseButtons {
g.input.PrevMouseButtons[btn] = false
}
g.input.PtyRepeat.Reset()
g.input.ScrollAccum = 0
// Clear dock badge when window regains focus.
clearDockBadge()
} else {
// Record when focus was lost.
g.wfocus.UnfocusedAt = time.Now()
}
g.wfocus.PrevFocused = focused
if g.activeFocused() != nil {
g.activeFocused().Term.SendFocusEvent(focused)
}
}
// Emergency recovery for systems where IsFocused() doesn't reliably update
// after sleep/wake (e.g. work machines with screen lock or MDM policies).
// If still suspended but the user interacts (click or keystroke), unsuspend
// immediately without waiting for a focus-state transition.
if g.wfocus.Suspended && (ebiten.IsMouseButtonPressed(ebiten.MouseButtonLeft) ||
ebiten.IsMouseButtonPressed(ebiten.MouseButtonRight) ||
len(ebiten.AppendInputChars(nil)) > 0) {
g.unsuspendAndRedraw()
}
}
// unsuspendAndRedraw lifts idle suspension (if active) and forces a full repaint.
// Called from handleFocus (focus-gain, wake notification, and emergency recovery).
func (g *Game) unsuspendAndRedraw() {
// Always restore the configured TPS. This covers the screen-sleep path where
// sleepWatcher set TPS=0 but g.wfocus.Suspended was never set (the window was
// focused when sleep happened, so idle suspension never triggered).
ebiten.SetTPS(g.cfg.Performance.TPS)
if g.wfocus.Suspended {
g.wfocus.Suspended = false
for _, t := range g.tabMgr.Tabs {
for _, leaf := range t.Layout.Leaves() {
leaf.Pane.Term.SetPaused(false)
}
}
for _, t := range g.tabMgr.Parked {
for _, leaf := range t.Layout.Leaves() {
leaf.Pane.Term.SetPaused(false)
}
}
}
g.wfocus.UnfocusedAt = time.Time{}
// Reset cached window size so handleResize fires unconditionally on the
// next Update. handleResize runs before handleFocus, so on wake or
// focus-gain the stale size check would silently skip the resize pass.
// Clearing g.winW guarantees the next frame re-applies pane rects with
// whatever size macOS has settled on after sleep/wake.
g.winW = 0
g.render.Dirty = true
g.renderer.SetLayoutDirty()
for _, t := range g.tabMgr.Tabs {
for _, leaf := range t.Layout.Leaves() {
leaf.Pane.Term.Buf.Lock()
leaf.Pane.Term.Buf.MarkAllDirty()
leaf.Pane.Term.Buf.Unlock()
}
}
}
// monitorDPI returns the device scale factor of the current monitor.
// Falls back to the last known g.dpi when ebiten.Monitor() is nil, which
// can happen transiently during HDMI disconnect / display reconfiguration.
func (g *Game) monitorDPI() float64 {
if m := ebiten.Monitor(); m != nil {
return m.DeviceScaleFactor()
}
return g.dpi
}
// logicalSize returns the window's logical size as ebiten last reported it to
// Layout. ebiten.WindowSize() can lag the framebuffer that drives Layout when
// the window moves between displays, so the Layout-reported size is the
// authoritative source for committing render geometry. Falls back to
// ebiten.WindowSize() before the first Layout call.
func (g *Game) logicalSize() (int, int) {
if g.layoutW > 0 && g.layoutH > 0 {
return g.layoutW, g.layoutH
}
return ebiten.WindowSize()
}
// physSize returns the physical pixel dimensions of the window.
func (g *Game) physSize() (int, int) {
return int(float64(g.winW) * g.dpi), int(float64(g.winH) * g.dpi)
}
// contentRect returns the pane content area: full window minus tab bar and status bar.
func (g *Game) contentRect() image.Rectangle {
physW, physH := g.physSize()
tabBarH := g.renderer.TabBarHeight()
statusBarH := g.renderer.StatusBarHeight()
return image.Rect(0, tabBarH, physW, physH-statusBarH)
}
// handleDroppedFiles checks for files dropped onto the window and sends their
// paths to the focused PTY as space-separated, shell-escaped strings.
func (g *Game) handleDroppedFiles() {
dropped := ebiten.DroppedFiles()
if dropped == nil {
return
}
entries, err := fs.ReadDir(dropped, ".")
if err != nil || len(entries) == 0 {
return
}
var paths []string
for _, e := range entries {
// Open the entry to get the real *os.File with the full path.
// Ebitengine's VirtualFS wraps os.Open on the original absolute path.
f, fErr := dropped.Open(e.Name())
if fErr != nil {
continue
}
if osFile, ok := f.(*os.File); ok {
paths = append(paths, shellEscape(osFile.Name()))
} else {
paths = append(paths, shellEscape(e.Name()))
}
_ = f.Close()
}
if len(paths) == 0 {
return
}
text := strings.Join(paths, " ")
if g.activeFocused() == nil {
return
}
g.activeFocused().Term.SendBytes([]byte(text))
g.render.Dirty = true
}
// shellEscape wraps a path in single quotes for safe shell insertion.
// Interior single quotes are escaped as '\''.
func shellEscape(s string) string {
if s == "" {
return "''"
}
// If the string has no special characters, return as-is.
needsQuote := false
for _, r := range s {
if r == ' ' || r == '\'' || r == '"' || r == '\\' || r == '(' || r == ')' ||
r == '&' || r == '|' || r == ';' || r == '$' || r == '`' || r == '!' ||
r == '*' || r == '?' || r == '[' || r == ']' || r == '{' || r == '}' ||
r == '<' || r == '>' || r == '#' || r == '~' {
needsQuote = true
break
}
}
if !needsQuote {
return s
}
return "'" + strings.ReplaceAll(s, "'", "'\\''") + "'"
}