Mountain/Binary/Build/WindowBuild.rs
1//! # Window Build Module
2//!
3//! Creates and configures the main application window.
4
5use tauri::{App, WebviewUrl, WebviewWindow, WebviewWindowBuilder, Wry};
6
7use crate::IPC::WindServiceHandlers::Utilities::RecentlyOpened::ReadRecentlyOpened;
8
9/// Creates and configures the main application window.
10///
11/// # Arguments
12///
13/// * `Application` - The Tauri application instance
14/// * `LocalhostUrl` - The localhost URL for the webview content
15///
16/// # Returns
17///
18/// A configured `WebviewWindow<Wry>` instance.
19///
20/// # Platform-Specific Behavior
21///
22/// - **macOS**: `TitleBarStyle::Overlay` + `hidden_title(true)` keeps the
23/// traffic-light buttons at the top-left but hides the native title bar
24/// strip, so VS Code's custom titlebar (which has `-webkit-app-region: drag`
25/// baked into its CSS) lights up the entire top row as a drag region. The
26/// previous `maximized(true)` was the direct cause of "can't drag the editor
27/// around" - maximized macOS windows are pinned to the screen and refuse all
28/// drag events, regardless of `app-region` CSS.
29/// - **Windows / Linux**: `decorations(false)` keeps the window chrome-less so
30/// the workbench draws its own. We still start `resizable(true)` so the
31/// window can be moved by the drag region.
32/// - **Debug builds**: DevTools auto-open.
33pub fn WindowBuild(Application:&mut App, LocalhostUrl:String) -> tauri::WebviewWindow<Wry> {
34 // Restore the most-recently-opened folder so the webview boots
35 // directly into the workspace. Without this, every launch lands
36 // on the Welcome tab, the user clicks "Open Folder", and the
37 // `pickFolderAndOpen` handler fires `Window.navigate()` - a hard
38 // reload that wipes workbench state mid-initialisation and is
39 // the direct cause of the purple splash flash, stuttering paint,
40 // empty `@builtin` sidebar, and broken keybindings (every layer
41 // has to boot twice and the second pass often loses references
42 // to the first). Using `?folder=...` in the initial URL skips
43 // that destructive round-trip.
44 let InitialUrl = BuildInitialUrl(&LocalhostUrl);
45
46 let WindowUrl = WebviewUrl::External(InitialUrl.parse().expect("FATAL: Failed to parse initial webview URL"));
47
48 // Configure window builder with base settings.
49 //
50 // `visible(false)` is the hidden-until-ready pattern. Tauri's default
51 // is to show the window the instant it's built, which paints the native
52 // chrome + Base.astro's `#1e1e1e` inline background + VS Code theme CSS
53 // + workbench DOM in four separate repaints over the first ~200 ms -
54 // observed as the "purple/dark flash" and panel-pop flicker.
55 //
56 // Mountain shows the window explicitly when the frontend's
57 // `lifecycle:advancePhase(3)` (Restored) arrives, which fires after
58 // `.monaco-workbench` is attached and the first frame is ready. A 3 s
59 // safety timer in `AppLifecycle` guarantees the window appears even if
60 // Sky crashes before signalling phase 3.
61 let mut WindowBuilder = WebviewWindowBuilder::new(Application, "main", WindowUrl)
62 .use_https_scheme(false)
63 .initialization_script("")
64 .zoom_hotkeys_enabled(true)
65 .browser_extensions_enabled(false)
66 // macOS first-responder: by default WKWebView swallows the
67 // first click on an unfocused window as a "make me key"
68 // no-op and the click never reaches the inner content. With
69 // `Inspect=1` running DevTools alongside the main window
70 // every switch-back to the editor needed two clicks - first
71 // to focus the NSWindow, second to actually focus the
72 // Monaco textarea - which the user reports as "I clicked,
73 // I'm typing, nothing's happening". `accept_first_mouse`
74 // flips the responder chain so the first click already
75 // reaches WKWebView's content and the textarea picks up
76 // keyboard input immediately.
77 .accept_first_mouse(true)
78 .title("Mountain")
79 .resizable(true)
80 .inner_size(1400.0, 900.0)
81 .shadow(true)
82 .visible(false);
83
84 #[cfg(target_os = "macos")]
85 {
86 // Overlay style lets VS Code's custom titlebar paint behind the
87 // traffic-light buttons. `hidden_title(true)` suppresses the OS
88 // title text so it doesn't collide with the workbench menubar.
89 // `decorations(true)` is REQUIRED for the traffic lights to
90 // render - turning decorations off also removes the buttons and
91 // breaks the native drag + resize handles entirely on macOS.
92 // `content_protected(true)` tells macOS to reserve a safe zone
93 // around the traffic-light cluster so WKWebView content doesn't
94 // render underneath them, preventing click-through and visual
95 // overlap with the workbench titlebar.
96 WindowBuilder = WindowBuilder
97 .title_bar_style(tauri::TitleBarStyle::Overlay)
98 .hidden_title(true)
99 .decorations(true)
100 .content_protected(true);
101 }
102
103 #[cfg(any(target_os = "windows", target_os = "linux"))]
104 {
105 WindowBuilder = WindowBuilder.decorations(false);
106 }
107
108 // Enable WKWebView inspection when InDebug mode + Inspect=1.
109 // This sets WKWebView.isInspectable via Wry's devtools flag so that
110 // external inspectors (Safari/Web Inspector) can attach.
111 #[cfg(debug_assertions)]
112 {
113 let enable_debugtools = std::env::var("Inspect").map(|v| v != "0" && !v.is_empty()).unwrap_or(false);
114 if enable_debugtools {
115 WindowBuilder = WindowBuilder.devtools(true);
116 }
117 }
118
119 #[cfg(debug_assertions)]
120 {
121 let enable_debug_server = std::env::var("DebugServer").map(|v| v != "0" && !v.is_empty()).unwrap_or(false);
122 if enable_debug_server {
123 WindowBuilder = WindowBuilder.on_page_load(|window, _payload| {
124 let _ = window.eval(
125 r#"(function() {
126 if (!window.__MOUNTAIN_DEBUG_CONSOLE) {
127 window.__MOUNTAIN_DEBUG_CONSOLE = [];
128 const origLog = console.log;
129 const origError = console.error;
130 const origWarn = console.warn;
131 const origInfo = console.info;
132 const origDebug = console.debug;
133 function pushLog(level, args) {
134 const argStrings = args.map(arg => {
135 if (typeof arg === 'object') {
136 try { return JSON.stringify(arg); } catch { return String(arg); }
137 } else {
138 return String(arg);
139 }
140 });
141 window.__MOUNTAIN_DEBUG_CONSOLE.push({ level, messages: argStrings, timestamp: Date.now() });
142 if (window.__MOUNTAIN_DEBUG_CONSOLE.length > 1000) {
143 window.__MOUNTAIN_DEBUG_CONSOLE = window.__MOUNTAIN_DEBUG_CONSOLE.slice(-1000);
144 }
145 }
146 console.log = function(...args) { pushLog('log', args); origLog.apply(console, args); };
147 console.error = function(...args) { pushLog('error', args); origError.apply(console, args); };
148 console.warn = function(...args) { pushLog('warn', args); origWarn.apply(console, args); };
149 console.info = function(...args) { pushLog('info', args); origInfo.apply(console, args); };
150 console.debug = function(...args) { pushLog('debug', args); origDebug.apply(console, args); };
151 }
152 })()"#,
153 );
154 });
155 }
156 }
157
158 // Build the main window
159 let MainWindow = WindowBuilder.build().expect("FATAL: Main window build failed");
160
161 // DevTools auto-open lives in `Binary/Main/AppLifecycle.rs:174`
162 // (gated on `cfg(debug_assertions)`, with a `[Window] Debug build:
163 // opening DevTools.` log line). Calling `open_devtools()` here as
164 // well opened a SECOND DevTools window on every debug launch -
165 // reported as "two DevTools" after the last rebuild. Single-source
166 // the call to AppLifecycle so the log line and the window match.
167
168 MainWindow
169}
170
171/// Build the initial webview URL, optionally appending `?folder=<path>`
172/// when `~/.land/workspaces/RecentlyOpened.json` has an entry for the
173/// previous session's workspace. Falls back to plain `index.html` if
174/// the file is missing, malformed, or has no resolvable path.
175///
176/// The returned string is already URL-encoded and safe to feed to
177/// `WebviewUrl::External`.
178fn BuildInitialUrl(LocalhostUrl:&str) -> String {
179 let Base = format!("{}/index.html", LocalhostUrl);
180
181 let Recent = match ReadRecentlyOpened() {
182 Ok(Value) => Value,
183
184 Err(_) => return Base,
185 };
186
187 let Workspaces = match Recent.get("workspaces").and_then(|V| V.as_array()) {
188 Some(Array) if !Array.is_empty() => Array,
189
190 _ => return Base,
191 };
192
193 // VS Code's Recently-Opened record can store the folder under a few
194 // different shapes depending on whether the entry came from the
195 // extension host, the workbench, or a `$deltaWorkspaceFolders`
196 // broadcast. Probe them in the same priority order the workbench
197 // itself uses in `getRecentlyOpenedWorkspaces`.
198 let Probe = |Entry:&serde_json::Value| -> Option<String> {
199 // Mountain's own writer emits `{ uri: "file://…", label }` (see
200 // `RecentlyOpened.json` on a freshly closed window). VS Code's
201 // historical `folderUri` / `workspace.configPath` shapes are kept
202 // as fallbacks so imported profiles and third-party writers keep
203 // working.
204 if let Some(Uri) = Entry.get("uri").and_then(|V| V.as_str()) {
205 return Some(Uri.to_string());
206 }
207
208 if let Some(Uri) = Entry.get("folderUri").and_then(|V| V.as_str()) {
209 return Some(Uri.to_string());
210 }
211
212 if let Some(Path) = Entry.get("folderUri").and_then(|V| V.get("path")).and_then(|V| V.as_str()) {
213 return Some(Path.to_string());
214 }
215
216 if let Some(Path) = Entry
217 .get("workspace")
218 .and_then(|V| V.get("configPath"))
219 .and_then(|V| V.get("path"))
220 .and_then(|V| V.as_str())
221 {
222 return Some(Path.to_string());
223 }
224
225 None
226 };
227
228 let FolderPath = match Workspaces.iter().find_map(Probe) {
229 Some(Path) => Path,
230
231 None => return Base,
232 };
233
234 // Strip any `file://` scheme so the query param is a plain path
235 // the workbench will stringify into a `file:` URI itself; leaving
236 // the scheme in doubles up and breaks the URL-decode on the other
237 // side (observed as the second `?folder=` boot path appearing as
238 // `file:/Volumes/...` in `wb:boot`).
239 let WithoutScheme = FolderPath.strip_prefix("file://").unwrap_or(FolderPath.as_str()).to_string();
240
241 // RecentlyOpened.json stores workspace URIs with a trailing slash
242 // (`file:///Volumes/.../Mountain/`). Drop it before encoding into
243 // the URL so the workbench-side `URI.revive({ scheme: "file",
244 // path: <param> })` produces a folder URI that matches the
245 // workbench's own `URI.from(<file>)` results - which never carry
246 // a trailing slash on the parent directory. The mismatch caused
247 // `IUriIdentityService.extUri.relativePath` to return absolute
248 // paths and breadcrumbs / quick-pick / Problems-panel labels to
249 // render absolute `/Volumes/<vol>/...` paths instead of the workspace-relative
250 // short form. Preserve `/` itself when the path IS root (vanishing
251 // edge case but cheap to guard).
252 let TrailingTrimmed = WithoutScheme.trim_end_matches('/');
253
254 let Normalised = if TrailingTrimmed.is_empty() {
255 "/".to_string()
256 } else {
257 TrailingTrimmed.to_string()
258 };
259
260 if !std::path::Path::new(&Normalised).is_dir() {
261 return Base;
262 }
263
264 let Encoded = url::form_urlencoded::Serializer::new(String::new())
265 .append_pair("folder", &Normalised)
266 .finish();
267
268 format!("{}/?{}", LocalhostUrl, Encoded)
269}