BlueGit

ict rusty-teams

Files

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

main.rs

main.rs 15.2 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 if let Some(titlebar) = options.titlebar.as_mut() {
172 titlebar.title = Some(APP_NAME.into());
173 }
174 options
175}
176
177const STORE_OPEN_ATTEMPTS: u32 = 20;
178const STORE_OPEN_INTERVAL: std::time::Duration = std::time::Duration::from_millis(500);
179
180fn open_store(path: &std::path::Path) -> Store {
181 for _ in 1..STORE_OPEN_ATTEMPTS {
182 match Store::open(path) {
183 Ok(store) => return store,
184 Err(_) => std::thread::sleep(STORE_OPEN_INTERVAL),
185 }
186 }
187 Store::open(path).expect("cache database")
188}
189
190fn main() {
191 session::ensure_crypto_provider();
192 app_base::version::set_build_version(VERSION_MARKER.trim_start_matches("teams-build:"));
193 if let Some(tag) = option_env!("TEAMS_RELEASE_TAG") {
194 app_base::version::set_release_tag(tag);
195 }
196 crash_log::install(
197 app_base::support::crash_log_path().unwrap_or_else(|| data_path(crash_log::CRASH_LOG_FILE)),
198 );
199 app_base::native_dumps::install(
200 data_path("native-dumps"),
201 app_base::support::crash_log_path().unwrap_or_else(|| data_path(crash_log::CRASH_LOG_FILE)),
202 );
203 diagnostics::install(
204 app_base::support::diagnostics_log_path()
205 .unwrap_or_else(|| data_path(diagnostics::DIAGNOSTICS_FILE)),
206 );
207 let _ = diagnostics::enable_from_override();
208 store::report_slow_locks_to(|message| diagnostics::record(message));
209 #[cfg(target_os = "linux")]
210 app_base::linux_fonts::hide_system_color_emoji();
211 let arguments = parse_arguments();
212 if !arguments.demo && arguments.database.is_none() {
213 let relaunch_value = std::env::var(updater::RELAUNCH_ENV).ok();
214 if let Some(value) = &relaunch_value {
215 updater::wait_for_previous_exit(value);
216 }
217 let relaunched = relaunch_value.is_some();
218 let command = arguments
219 .remote_command
220 .as_ref()
221 .map(RemoteCommand::encode)
222 .unwrap_or_default();
223 if single_instance::claim(SINGLE_INSTANCE_NAME, relaunched, &command)
224 == single_instance::Claim::Forwarded
225 {
226 return;
227 }
228 }
229 #[cfg(any(windows, target_os = "linux"))]
230 updater::clean_up_old_binary();
231 let mode = Mode {
232 demo: arguments.demo,
233 read_only: arguments.read_only,
234 demo_sync: arguments.demo_sync,
235 };
236 #[cfg(windows)]
237 if arguments.demo {
238 inline_video::configure(std::env::temp_dir().join(DEMO_WEBVIEW_FOLDER));
239 }
240 let orgs = if arguments.demo {
241 app_base::orgs::Orgs::default()
242 } else {
243 app_base::orgs::Orgs::path()
244 .map(|path| app_base::orgs::Orgs::load(&path))
245 .unwrap_or_default()
246 };
247 let store = if arguments.demo {
248 let store = Store::open_in_memory().expect("in-memory store");
249 demo::seed(&store);
250 store
251 } else {
252 let path = arguments
253 .database
254 .clone()
255 .unwrap_or_else(|| data_path(&orgs.database_file()));
256 open_store(&path)
257 };
258 let store = Arc::new(store);
259 let stored_diag = store
260 .meta(diagnostics::DIAGNOSTICS_SETTING_KEY)
261 .ok()
262 .flatten();
263 diagnostics::load_enabled_from_store(stored_diag.as_deref());
264 let ui_locale = app_base::ui_locale::effective_locale(app_base::ui_locale::load(&store));
265 app_base::ui_locale::apply_locale(ui_locale);
266 let call_reports = app_call_model::report::load_enabled(&store);
267 app_base::support::record_startup_client_line(
268 env!("CARGO_PKG_VERSION"),
269 ui_locale,
270 crate::data::me(&store).is_some(),
271 call_reports,
272 );
273 #[cfg(windows)]
274 let sign_in_title = format!(
275 "{} - {}",
276 app_base::APP_NAME,
277 app_base::ui_locale::tr("auth.sign_in")
278 );
279 let user_input = user_activity::UserInput::new();
280 let receiver = (!arguments.demo).then(|| {
281 let (ui_events, ui_receiver) = tokio::sync::mpsc::unbounded_channel();
282 #[cfg(any(target_os = "linux", target_os = "macos"))]
283 linux_browser::attach_ui_events(ui_events.clone());
284 #[cfg(windows)]
285 let transport = transport(
286 arguments.endpoint.as_deref(),
287 arguments.database.as_deref(),
288 sign_in_title.clone(),
289 );
290 #[cfg(not(windows))]
291 let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());
292 let activity = user_activity::track(user_input.clone());
293 let guest_tenant = orgs.active_guest().map(|org| org.id.clone());
294 let mut backend_events = backend::start(
295 store.clone(),
296 transport,
297 !arguments.read_only,
298 activity,
299 guest_tenant,
300 );
301 app_base::runtime::handle().spawn(async move {
302 while let Some(event) = backend_events.recv().await {
303 if ui_events.send(event).is_err() {
304 break;
305 }
306 }
307 });
308 ui_receiver
309 });
310
311 let startup_zoom = appearance::load(&store).zoom;
312 let platform = zoom::wrap(gpui_kit::platform::current_platform(false), startup_zoom);
313 let mut application = Application::with_platform(platform);
314 if let Ok(http_client) = reqwest_client::ReqwestClient::user_agent(HTTP_USER_AGENT) {
315 application = application.with_http_client(Arc::new(http_client));
316 }
317
318 application
319 .with_assets(app_base::assets::AppAssets)
320 .run(move |cx| {
321 gpui_kit::init(cx);
322 cx.on_app_quit(|_| {
323 updater::exit_after_grace();
324 async {}
325 })
326 .detach();
327 theme::load_fonts(cx);
328 active_appearance::install(&store, cx);
329 active_locale::install(&store, cx);
330 theme::apply(cx);
331 bind_keys(cx);
332 let state = cx.new(|_| {
333 let mut state = AppState::new(store, mode);
334 state.start_on_channels = arguments.channels_tab;
335 state.orgs = orgs;
336 state
337 });
338 views::shell::install_globals(&state, user_input, cx);
339 agent_api::init(state.read(cx).store.clone(), arguments.demo, cx);
340 agents::install(state.clone(), cx);
341 agent_direct::install(state.clone(), cx);
342 if arguments.demo {
343 demo::start_session(&state, cx);
344 }
345 if let Some(mut receiver) = receiver {
346 let state = state.clone();
347 cx.spawn(async move |cx| {
348 while let Some(event) = receiver.recv().await {
349 let kind = event.kind();
350 let started = std::time::Instant::now();
351 #[cfg(any(target_os = "linux", target_os = "macos"))]
352 linux_browser::note_backend_event(&event);
353 state.update(cx, |state, cx| state.apply(event, cx));
354 app_base::diagnostics::record_if_slow(&kind, started.elapsed());
355 }
356 })
357 .detach();
358 }
359
360 // The main window decides when to quit (see `main_window`): closing it into
361 // the tray leaves the app running without windows.
362 cx.set_quit_mode(QuitMode::Explicit);
363 // The command line only applies to the first window, not to one reopened from the tray.
364 let first_open = std::cell::Cell::new(Some((
365 arguments.open_target,
366 Startup {
367 switcher_query: arguments.switcher_query,
368 composer_text: arguments.composer_text,
369 reply_to_last: arguments.reply_to_last,
370 launched_by_autostart: arguments.autostart,
371 },
372 )));
373 main_window::install(
374 move |cx| {
375 let (open_target, startup) = first_open.take().unwrap_or_default();
376 let state = state.clone();
377 let opened =
378 gpui_kit::open_window(main_window_options(cx), cx, move |window, cx| {
379 cx.new(|cx| AppShell::new(state, open_target, startup, window, cx))
380 });
381 match opened {
382 Ok((handle, _)) => Some(handle.into()),
383 Err(error) => {
384 log::error!("failed to open the main window: {error}");
385 None
386 }
387 }
388 },
389 cx,
390 )
391 .expect("failed to open window");
392 cx.on_window_closed(|cx, closed| {
393 if main_window::note_closed(closed, cx) {
394 cx.quit();
395 }
396 })
397 .detach();
398 #[cfg(target_os = "linux")]
399 if !arguments.demo {
400 linux_install::start(cx);
401 }
402 if !arguments.demo {
403 linux_update::start(cx);
404 }
405 if !arguments.autostart {
406 cx.activate(true);
407 }
408 cx.spawn(async move |cx| {
409 loop {
410 app_base::native_dumps::heartbeat();
411 cx.background_executor().timer(HEARTBEAT_INTERVAL).await;
412 }
413 })
414 .detach();
415 });
416 presence_link::unregister_on_exit(ENDPOINT_UNREGISTER_TIMEOUT);
417 #[cfg(any(target_os = "linux", target_os = "macos"))]
418 linux_browser::stop();
419 #[cfg(windows)]
420 updater::exit_now();
421}