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
//! Window creation, destruction, and monitor positioning.
//!
//! This module handles the core lifecycle of terminal windows: creating new
//! windows with proper configuration, applying monitor-based positioning, and
//! closing windows cleanly.
//!
//! Session save/restore and arranged-window creation live in the sibling
//! `window_session` module.
//!
//! CLI timer handling (check_cli_timers, send_command_to_shell, take_screenshot)
//! lives in the sibling `cli_timer` module.
use std::sync::Arc;
use std::time::Instant;
use winit::event_loop::ActiveEventLoop;
use winit::window::WindowId;
use crate::app::window_state::WindowState;
use crate::config::Config;
use crate::menu::MenuManager;
use super::WindowManager;
use super::update_checker::update_available_version;
impl WindowManager {
/// Create a new window with a fresh terminal session
pub fn create_window(&mut self, event_loop: &ActiveEventLoop) {
use crate::config::WindowType;
use crate::font_metrics::window_size_from_config;
use winit::window::Window;
// Reload config from disk to pick up any changes made by other windows
if let Ok(fresh_config) = Config::load() {
self.config = fresh_config;
}
// Re-apply CLI shader override (fresh config load above would wipe it)
if let Some(ref shader) = self.runtime_options.shader {
self.config.shader.custom_shader = Some(shader.clone());
self.config.shader.custom_shader_enabled = true;
self.config.background_image_enabled = false;
}
// Calculate window size from cols/rows BEFORE window creation.
let (width, height) = window_size_from_config(&self.config, 1.0).unwrap_or((800, 600));
// Build window title, optionally including window number
let window_number = self.windows.len() + 1;
let title = if self.config.show_window_number {
format!("{} [{}]", self.config.window_title, window_number)
} else {
self.config.window_title.clone()
};
let mut window_attrs = Window::default_attributes()
.with_title(&title)
.with_inner_size(winit::dpi::LogicalSize::new(width, height))
.with_decorations(self.config.window.window_decorations);
// Lock window size if requested (prevent resize)
if self.config.lock_window_size {
window_attrs = window_attrs.with_resizable(false);
log::info!("Window size locked (resizing disabled)");
}
// Start in fullscreen if window_type is Fullscreen
if self.config.window_type == WindowType::Fullscreen {
window_attrs =
window_attrs.with_fullscreen(Some(winit::window::Fullscreen::Borderless(None)));
log::info!("Window starting in fullscreen mode");
}
// Load and set the application icon
let icon_bytes = include_bytes!("../../../assets/icon.png");
if let Ok(icon_image) = image::load_from_memory(icon_bytes) {
let rgba = icon_image.to_rgba8();
let (width, height) = rgba.dimensions();
if let Ok(icon) = winit::window::Icon::from_rgba(rgba.into_raw(), width, height) {
window_attrs = window_attrs.with_window_icon(Some(icon));
log::info!("Window icon set ({}x{})", width, height);
} else {
log::warn!("Failed to create window icon from RGBA data");
}
} else {
log::warn!("Failed to load embedded icon image");
}
// Set window always-on-top if requested
if self.config.window.window_always_on_top {
window_attrs = window_attrs.with_window_level(winit::window::WindowLevel::AlwaysOnTop);
log::info!("Window always-on-top enabled");
}
// Always enable window transparency support for runtime opacity changes
window_attrs = window_attrs.with_transparent(true);
log::info!(
"Window transparency enabled (opacity: {})",
self.config.window.window_opacity
);
// macOS: accept the first mouse click so that clicking the tab bar or
// any other UI element while the window is in the background both brings
// the window into focus AND delivers the click to the application.
// Without this, macOS silently eats the activation click and the user
// must click a second time to interact. The existing focus-click
// suppression path (`focus_click_pending`) still guards the terminal
// area against forwarding clicks to PTY mouse-tracking apps.
#[cfg(target_os = "macos")]
{
use winit::platform::macos::WindowAttributesExtMacOS as _;
window_attrs = window_attrs.with_accepts_first_mouse(true);
}
match event_loop.create_window(window_attrs) {
Ok(window) => {
let window_id = window.id();
// Initialize menu BEFORE the blocking GPU init so that macOS
// menu accelerators (Cmd+, for Settings, Cmd+Q for Quit) are
// registered immediately. Without this, there is a multi-second
// window during GPU setup where winit's default menu is active
// and unhandled key combos can cause the app to exit via
// [NSApp terminate:].
if self.menu.is_none() {
match MenuManager::new() {
Ok(menu) => {
if let Err(e) = menu.init_global() {
log::warn!("Failed to initialize global menu: {}", e);
}
self.menu = Some(menu);
}
Err(e) => {
log::warn!("Failed to create menu: {}", e);
}
}
}
let mut window_state =
WindowState::new(self.config.clone(), Arc::clone(&self.runtime));
// Set window index for title formatting (window_number calculated earlier)
window_state.window_index = window_number;
// Initialize async components using the shared runtime
// (GPU setup — this blocks for 2-3 seconds)
let runtime = Arc::clone(&self.runtime);
if let Err(e) = runtime.block_on(window_state.initialize_async(window, None)) {
log::error!("Failed to initialize window: {}", e);
return;
}
// Attach menu to the window (platform-specific: per-window on Windows/Linux)
if let Some(menu) = &self.menu
&& let Some(win) = &window_state.window
&& let Err(e) = menu.init_for_window(win)
{
log::warn!("Failed to initialize menu for window: {}", e);
}
// Apply target monitor and edge positioning after window creation
if let Some(win) = &window_state.window {
self.apply_window_positioning(win, event_loop);
}
// Handle tmux auto-attach on first window only
if self.windows.is_empty()
&& window_state.config.tmux_enabled
&& window_state.config.tmux_auto_attach
{
let session_name = window_state.config.tmux_auto_attach_session.clone();
// Use gateway mode: writes tmux commands to existing PTY
if let Some(ref name) = session_name {
if !name.is_empty() {
log::info!(
"tmux auto-attach: attempting to attach to session '{}' via gateway",
name
);
match window_state.attach_tmux_gateway(name) {
Ok(()) => {
log::info!(
"tmux auto-attach: gateway initiated for session '{}'",
name
);
}
Err(e) => {
log::warn!(
"tmux auto-attach: failed to attach to '{}': {} - continuing without tmux",
name,
e
);
// Continue without tmux - don't fail startup
}
}
} else {
// Empty string means create new session
log::info!(
"tmux auto-attach: no session specified, creating new session via gateway"
);
if let Err(e) = window_state.initiate_tmux_gateway(None) {
log::warn!(
"tmux auto-attach: failed to create new session: {} - continuing without tmux",
e
);
}
}
} else {
// None means create new session
log::info!(
"tmux auto-attach: no session specified, creating new session via gateway"
);
if let Err(e) = window_state.initiate_tmux_gateway(None) {
log::warn!(
"tmux auto-attach: failed to create new session: {} - continuing without tmux",
e
);
}
}
}
self.windows.insert(window_id, window_state);
self.pending_window_count += 1;
// Sync existing update state to new window's status bar and dialog
let update_version = self
.last_update_result
.as_ref()
.and_then(update_available_version);
let update_result_clone = self.last_update_result.clone();
let install_type = self.detect_installation_type();
if let Some(ws) = self.windows.get_mut(&window_id) {
ws.status_bar_ui.update_available_version = update_version;
ws.update_state.last_result = update_result_clone;
ws.update_state.installation_type = install_type;
}
// Set start time on first window creation (for CLI timers)
if self.start_time.is_none() {
self.start_time = Some(Instant::now());
}
log::info!(
"Created new window {:?} (total: {})",
window_id,
self.windows.len()
);
}
Err(e) => {
log::error!("Failed to create window: {}", e);
}
}
}
/// Apply window positioning based on config (target monitor and edge anchoring)
pub(super) fn apply_window_positioning(
&self,
window: &std::sync::Arc<winit::window::Window>,
event_loop: &ActiveEventLoop,
) {
use crate::config::WindowType;
// Get list of available monitors
let monitors: Vec<_> = event_loop.available_monitors().collect();
if monitors.is_empty() {
log::warn!("No monitors available for window positioning");
return;
}
// Select target monitor (default to primary/first)
let monitor = if let Some(index) = self.config.target_monitor {
monitors
.get(index)
.cloned()
.or_else(|| monitors.first().cloned())
} else {
event_loop
.primary_monitor()
.or_else(|| monitors.first().cloned())
};
let Some(monitor) = monitor else {
log::warn!("Could not determine target monitor");
return;
};
let monitor_pos = monitor.position();
let monitor_size = monitor.size();
let window_size = window.outer_size();
// Apply edge positioning if configured
match self.config.window_type {
WindowType::EdgeTop => {
// Position at top of screen, spanning full width
window.set_outer_position(winit::dpi::PhysicalPosition::new(
monitor_pos.x,
monitor_pos.y,
));
let _ = window.request_inner_size(winit::dpi::PhysicalSize::new(
monitor_size.width,
window_size.height,
));
log::info!("Window positioned at top edge of monitor");
}
WindowType::EdgeBottom => {
// Position at bottom of screen, spanning full width
let y = monitor_pos.y + monitor_size.height as i32 - window_size.height as i32;
window.set_outer_position(winit::dpi::PhysicalPosition::new(monitor_pos.x, y));
let _ = window.request_inner_size(winit::dpi::PhysicalSize::new(
monitor_size.width,
window_size.height,
));
log::info!("Window positioned at bottom edge of monitor");
}
WindowType::EdgeLeft => {
// Position at left of screen, spanning full height
window.set_outer_position(winit::dpi::PhysicalPosition::new(
monitor_pos.x,
monitor_pos.y,
));
let _ = window.request_inner_size(winit::dpi::PhysicalSize::new(
window_size.width,
monitor_size.height,
));
log::info!("Window positioned at left edge of monitor");
}
WindowType::EdgeRight => {
// Position at right of screen, spanning full height
let x = monitor_pos.x + monitor_size.width as i32 - window_size.width as i32;
window.set_outer_position(winit::dpi::PhysicalPosition::new(x, monitor_pos.y));
let _ = window.request_inner_size(winit::dpi::PhysicalSize::new(
window_size.width,
monitor_size.height,
));
log::info!("Window positioned at right edge of monitor");
}
WindowType::Normal | WindowType::Fullscreen => {
// For normal/fullscreen, just position on target monitor if specified
if self.config.target_monitor.is_some() {
// Center window on target monitor
let x =
monitor_pos.x + (monitor_size.width as i32 - window_size.width as i32) / 2;
let y = monitor_pos.y
+ (monitor_size.height as i32 - window_size.height as i32) / 2;
window.set_outer_position(winit::dpi::PhysicalPosition::new(x, y));
log::info!(
"Window centered on monitor {} at ({}, {})",
self.config.target_monitor.unwrap_or(0),
x,
y
);
}
}
}
// Move window to target macOS Space if configured (macOS only, no-op on other platforms)
if let Some(space) = self.config.target_space
&& let Err(e) = crate::macos_space::move_window_to_space(window, space)
{
log::warn!("Failed to move window to Space {}: {}", space, e);
}
}
/// Close a specific window
pub fn close_window(&mut self, window_id: WindowId) {
// Save session state before removing the last window (while data is still available).
if self.config.restore_session
&& self.windows.len() == 1
&& self.windows.contains_key(&window_id)
{
self.save_session_state_background();
}
if let Some(window_state) = self.windows.remove(&window_id) {
log::info!(
"Closing window {:?} (remaining: {})",
window_id,
self.windows.len()
);
// Hide window immediately for instant visual feedback
if let Some(ref window) = window_state.window {
window.set_visible(false);
}
// WindowState's Drop impl handles cleanup
drop(window_state);
}
// Exit app when last window closes
if self.windows.is_empty() {
log::info!("Last window closed, exiting application");
// Close settings window FIRST before marking exit
if self.settings_window.is_some() {
log::info!("Closing settings window before exit");
self.close_settings_window();
}
self.should_exit = true;
}
}
}