BlueGit

ict rusty-teams

Files

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

main.rs

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