BlueGit

ict rusty-teams

Files

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

main.rs

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