BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / main.rs

main.rs

main.rs 14.6 KiB Download Raw
1#![cfg_attr(
2 all(not(debug_assertions), target_os = "windows"),
3 windows_subsystem = "windows"
4)]
5
6mod active_appearance;
7mod active_locale;
8mod agent_direct;
9pub mod agents;
10pub mod call;
11mod i18n;
12mod inline_video;
13#[cfg(test)]
14mod layout_guard;
15#[cfg(any(target_os = "linux", target_os = "macos"))]
16mod linux_browser;
17#[cfg(target_os = "linux")]
18mod linux_install;
19#[cfg(target_os = "linux")]
20mod linux_update;
21mod main_window;
22pub mod notify;
23mod settings;
24mod views;
25
26pub use state::*;
27
28use std::path::PathBuf;
29use std::sync::Arc;
30use std::time::Duration;
31
32use directories::ProjectDirs;
33use gpui_kit::component::TitleBar;
34use gpui_kit::*;
35use store::Store;
36
37use crate::app_state::{AppState, Mode};
38use crate::call::remote_command::{
39 ADMIT_ALL_FLAG, CALL_FLAG, HANG_UP_FLAG, JOIN_FLAG, RemoteCommand, UNMUTE_FLAG,
40};
41use views::shell::{AppShell, OpenTarget, Startup, bind_keys};
42
43const LINUX_APP_ID: &str = "rusty-teams";
44const VERSION_MARKER: &str = concat!("teams-build:", env!("TEAMS_BUILD_VERSION"));
45const HTTP_USER_AGENT: &str = "teams-linux";
46const WINDOW_WIDTH: f32 = 1240.;
47const WINDOW_HEIGHT: f32 = 820.;
48const WINDOW_MIN_WIDTH: f32 = 640.;
49const WINDOW_MIN_HEIGHT: f32 = 480.;
50const ENDPOINT_UNREGISTER_TIMEOUT: Duration = Duration::from_millis(800);
51const SINGLE_INSTANCE_NAME: &str = "rusty-teams";
52const DATABASE_FILE: &str = "cache.sqlite3";
53#[cfg(windows)]
54const WEBVIEW_FOLDER: &str = "WebView2";
55#[cfg(windows)]
56const DEMO_WEBVIEW_FOLDER: &str = "rusty-teams-demo-WebView2";
57
58#[derive(Default)]
59struct Arguments {
60 demo: bool,
61 read_only: bool,
62 database: Option<PathBuf>,
63 endpoint: Option<String>,
64 open_target: Option<OpenTarget>,
65 switcher_query: Option<String>,
66 composer_text: Option<String>,
67 reply_to_last: bool,
68 channels_tab: bool,
69 autostart: bool,
70 demo_sync: Option<Duration>,
71 remote_command: Option<RemoteCommand>,
72}
73
74fn parse_arguments() -> Arguments {
75 let mut arguments = Arguments::default();
76 let mut input = std::env::args().skip(1);
77 while let Some(flag) = input.next() {
78 match flag.as_str() {
79 "--demo" => arguments.demo = true,
80 "--read-only" => arguments.read_only = true,
81 "--switcher" => {
82 arguments.switcher_query.get_or_insert_with(String::new);
83 }
84 "--query" => arguments.switcher_query = input.next(),
85 "--type" => arguments.composer_text = input.next(),
86 "--reply-last" => arguments.reply_to_last = true,
87 "--channels-tab" => arguments.channels_tab = true,
88 autostart::AUTOSTART_FLAG => arguments.autostart = true,
89 "--demo-sync" => {
90 arguments.demo_sync = input
91 .next()
92 .and_then(|value| value.parse().ok())
93 .map(Duration::from_secs_f32)
94 }
95 JOIN_FLAG => arguments.remote_command = input.next().map(RemoteCommand::Join),
96 HANG_UP_FLAG => arguments.remote_command = Some(RemoteCommand::HangUp),
97 ADMIT_ALL_FLAG => arguments.remote_command = Some(RemoteCommand::AdmitAll),
98 UNMUTE_FLAG => arguments.remote_command = Some(RemoteCommand::Unmute),
99 CALL_FLAG => {
100 arguments.remote_command =
101 input.next().and_then(|text| RemoteCommand::decode(&text))
102 }
103 "--database" => arguments.database = input.next().map(PathBuf::from),
104 "--endpoint" => arguments.endpoint = input.next(),
105 "--open" => {
106 arguments.open_target = input
107 .next()
108 .and_then(|value| value.parse().ok())
109 .map(OpenTarget::Chat)
110 }
111 "--open-channel" => {
112 arguments.open_target = input
113 .next()
114 .and_then(|value| value.parse().ok())
115 .map(OpenTarget::Channel)
116 }
117 _ => {}
118 }
119 }
120 arguments
121}
122
123const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(1);
124
125fn data_path(name: &str) -> PathBuf {
126 ProjectDirs::from("", "", store::DATA_DIR_NAME)
127 .map(|directories| directories.data_local_dir().join(name))
128 .unwrap_or_else(|| PathBuf::from(name))
129}
130
131fn transport(
132 endpoint: Option<&str>,
133 database: Option<&std::path::Path>,
134 #[cfg(windows)] sign_in_title: String,
135) -> Arc<dyn session::Transport> {
136 #[cfg(windows)]
137 if endpoint.is_none() {
138 let user_data_folder = match database.and_then(std::path::Path::parent) {
139 Some(directory) => directory.join(WEBVIEW_FOLDER),
140 None => data_path(WEBVIEW_FOLDER),
141 };
142 inline_video::configure(user_data_folder.clone());
143 let transport = webview::start(webview::HostConfig {
144 user_data_folder,
145 window_title: sign_in_title,
146 log: |line| app_base::diagnostics::record(line),
147 });
148 task_dialog::install_host(transport.clone());
149 return transport;
150 }
151 #[cfg(not(windows))]
152 let _ = database;
153 #[cfg(any(target_os = "linux", target_os = "macos"))]
154 if endpoint.is_none() {
155 return linux_browser::start(session::DEFAULT_ENDPOINT);
156 }
157 Arc::new(session::CdpTransport::new(
158 endpoint.unwrap_or(session::DEFAULT_ENDPOINT),
159 ))
160}
161
162fn main_window_options(cx: &App) -> WindowOptions {
163 let bounds = Bounds::centered(None, size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), cx);
164 let mut options = TitleBar::window_options();
165 options.window_bounds = Some(WindowBounds::Windowed(bounds));
166 options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT)));
167 options.app_id = Some(LINUX_APP_ID.to_owned());
168 if let Some(titlebar) = options.titlebar.as_mut() {
169 titlebar.title = Some(APP_NAME.into());
170 }
171 options
172}
173
174const STORE_OPEN_ATTEMPTS: u32 = 20;
175const STORE_OPEN_INTERVAL: std::time::Duration = std::time::Duration::from_millis(500);
176
177fn open_store(path: &std::path::Path) -> Store {
178 for _ in 1..STORE_OPEN_ATTEMPTS {
179 match Store::open(path) {
180 Ok(store) => return store,
181 Err(_) => std::thread::sleep(STORE_OPEN_INTERVAL),
182 }
183 }
184 Store::open(path).expect("cache database")
185}
186
187fn main() {
188 session::ensure_crypto_provider();
189 app_base::version::set_build_version(VERSION_MARKER.trim_start_matches("teams-build:"));
190 if let Some(tag) = option_env!("TEAMS_RELEASE_TAG") {
191 app_base::version::set_release_tag(tag);
192 }
193 crash_log::install(
194 app_base::support::crash_log_path().unwrap_or_else(|| data_path(crash_log::CRASH_LOG_FILE)),
195 );
196 app_base::native_dumps::install(
197 data_path("native-dumps"),
198 app_base::support::crash_log_path().unwrap_or_else(|| data_path(crash_log::CRASH_LOG_FILE)),
199 );
200 diagnostics::install(
201 app_base::support::diagnostics_log_path()
202 .unwrap_or_else(|| data_path(diagnostics::DIAGNOSTICS_FILE)),
203 );
204 let _ = diagnostics::enable_from_override();
205 store::report_slow_locks_to(|message| diagnostics::record(message));
206 #[cfg(target_os = "linux")]
207 app_base::linux_fonts::hide_system_color_emoji();
208 let arguments = parse_arguments();
209 if !arguments.demo && arguments.database.is_none() {
210 let relaunch_value = std::env::var(updater::RELAUNCH_ENV).ok();
211 if let Some(value) = &relaunch_value {
212 updater::wait_for_previous_exit(value);
213 }
214 let relaunched = relaunch_value.is_some();
215 let command = arguments
216 .remote_command
217 .as_ref()
218 .map(RemoteCommand::encode)
219 .unwrap_or_default();
220 if single_instance::claim(SINGLE_INSTANCE_NAME, relaunched, &command)
221 == single_instance::Claim::Forwarded
222 {
223 return;
224 }
225 }
226 #[cfg(any(windows, target_os = "linux"))]
227 updater::clean_up_old_binary();
228 let mode = Mode {
229 demo: arguments.demo,
230 read_only: arguments.read_only,
231 demo_sync: arguments.demo_sync,
232 };
233 #[cfg(windows)]
234 if arguments.demo {
235 inline_video::configure(std::env::temp_dir().join(DEMO_WEBVIEW_FOLDER));
236 }
237 let store = if arguments.demo {
238 let store = Store::open_in_memory().expect("in-memory store");
239 demo::seed(&store);
240 store
241 } else {
242 let path = arguments
243 .database
244 .clone()
245 .unwrap_or_else(|| data_path(DATABASE_FILE));
246 open_store(&path)
247 };
248 let store = Arc::new(store);
249 let stored_diag = store
250 .meta(diagnostics::DIAGNOSTICS_SETTING_KEY)
251 .ok()
252 .flatten();
253 diagnostics::load_enabled_from_store(stored_diag.as_deref());
254 let ui_locale = app_base::ui_locale::effective_locale(app_base::ui_locale::load(&store));
255 app_base::ui_locale::apply_locale(ui_locale);
256 let call_reports = app_call_model::report::load_enabled(&store);
257 app_base::support::record_startup_client_line(
258 env!("CARGO_PKG_VERSION"),
259 ui_locale,
260 crate::data::me(&store).is_some(),
261 call_reports,
262 );
263 #[cfg(windows)]
264 let sign_in_title = format!(
265 "{} - {}",
266 app_base::APP_NAME,
267 app_base::ui_locale::tr("auth.sign_in")
268 );
269 let user_input = user_activity::UserInput::new();
270 let receiver = (!arguments.demo).then(|| {
271 let (ui_events, ui_receiver) = tokio::sync::mpsc::unbounded_channel();
272 #[cfg(any(target_os = "linux", target_os = "macos"))]
273 linux_browser::attach_ui_events(ui_events.clone());
274 #[cfg(windows)]
275 let transport = transport(
276 arguments.endpoint.as_deref(),
277 arguments.database.as_deref(),
278 sign_in_title.clone(),
279 );
280 #[cfg(not(windows))]
281 let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());
282 let activity = user_activity::track(user_input.clone());
283 let mut backend_events =
284 backend::start(store.clone(), transport, !arguments.read_only, activity);
285 app_base::runtime::handle().spawn(async move {
286 while let Some(event) = backend_events.recv().await {
287 if ui_events.send(event).is_err() {
288 break;
289 }
290 }
291 });
292 ui_receiver
293 });
294
295 let startup_zoom = appearance::load(&store).zoom;
296 let platform = zoom::wrap(gpui_kit::platform::current_platform(false), startup_zoom);
297 let mut application = Application::with_platform(platform);
298 if let Ok(http_client) = reqwest_client::ReqwestClient::user_agent(HTTP_USER_AGENT) {
299 application = application.with_http_client(Arc::new(http_client));
300 }
301
302 application
303 .with_assets(app_base::assets::AppAssets)
304 .run(move |cx| {
305 gpui_kit::init(cx);
306 cx.on_app_quit(|_| {
307 updater::exit_after_grace();
308 async {}
309 })
310 .detach();
311 theme::load_fonts(cx);
312 active_appearance::install(&store, cx);
313 active_locale::install(&store, cx);
314 theme::apply(cx);
315 bind_keys(cx);
316 let state = cx.new(|_| {
317 let mut state = AppState::new(store, mode);
318 state.start_on_channels = arguments.channels_tab;
319 state
320 });
321 views::shell::install_globals(&state, user_input, cx);
322 agent_api::init(state.read(cx).store.clone(), arguments.demo, cx);
323 agents::install(state.clone(), cx);
324 agent_direct::install(state.clone(), cx);
325 if arguments.demo {
326 demo::start_session(&state, cx);
327 }
328 if let Some(mut receiver) = receiver {
329 let state = state.clone();
330 cx.spawn(async move |cx| {
331 while let Some(event) = receiver.recv().await {
332 let kind = event.kind();
333 let started = std::time::Instant::now();
334 #[cfg(any(target_os = "linux", target_os = "macos"))]
335 linux_browser::note_backend_event(&event);
336 state.update(cx, |state, cx| state.apply(event, cx));
337 app_base::diagnostics::record_if_slow(&kind, started.elapsed());
338 }
339 })
340 .detach();
341 }
342
343 // The main window decides when to quit (see `main_window`): closing it into
344 // the tray leaves the app running without windows.
345 cx.set_quit_mode(QuitMode::Explicit);
346 // The command line only applies to the first window, not to one reopened from the tray.
347 let first_open = std::cell::Cell::new(Some((
348 arguments.open_target,
349 Startup {
350 switcher_query: arguments.switcher_query,
351 composer_text: arguments.composer_text,
352 reply_to_last: arguments.reply_to_last,
353 launched_by_autostart: arguments.autostart,
354 },
355 )));
356 main_window::install(
357 move |cx| {
358 let (open_target, startup) = first_open.take().unwrap_or_default();
359 let state = state.clone();
360 let opened =
361 gpui_kit::open_window(main_window_options(cx), cx, move |window, cx| {
362 cx.new(|cx| AppShell::new(state, open_target, startup, window, cx))
363 });
364 match opened {
365 Ok((handle, _)) => Some(handle.into()),
366 Err(error) => {
367 log::error!("failed to open the main window: {error}");
368 None
369 }
370 }
371 },
372 cx,
373 )
374 .expect("failed to open window");
375 cx.on_window_closed(|cx, closed| {
376 if main_window::note_closed(closed, cx) {
377 cx.quit();
378 }
379 })
380 .detach();
381 #[cfg(target_os = "linux")]
382 if !arguments.demo {
383 linux_install::start(cx);
384 linux_update::start(cx);
385 }
386 if !arguments.autostart {
387 cx.activate(true);
388 }
389 cx.spawn(async move |cx| {
390 loop {
391 app_base::native_dumps::heartbeat();
392 cx.background_executor().timer(HEARTBEAT_INTERVAL).await;
393 }
394 })
395 .detach();
396 });
397 presence_link::unregister_on_exit(ENDPOINT_UNREGISTER_TIMEOUT);
398 #[cfg(any(target_os = "linux", target_os = "macos"))]
399 linux_browser::stop();
400 #[cfg(windows)]
401 updater::exit_now();
402}