BlueGit

ict rusty-teams

Files

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

main.rs

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