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