BlueGit

ict rusty-teams

Files

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

main.rs

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