BlueGit

ict rusty-teams

Files

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

main.rs

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