BlueGit

ict rusty-teams

Files

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

main.rs

main.rs 12.6 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(data_path(crash_log::CRASH_LOG_FILE));
177 app_base::native_dumps::install(
178 data_path("native-dumps"),
179 data_path(crash_log::CRASH_LOG_FILE),
180 );
181 diagnostics::install(data_path(diagnostics::DIAGNOSTICS_FILE));
182 #[cfg(target_os = "linux")]
183 app_base::linux_fonts::hide_system_color_emoji();
184 let arguments = parse_arguments();
185 if !arguments.demo && arguments.database.is_none() {
186 let relaunch_value = std::env::var(updater::RELAUNCH_ENV).ok();
187 if let Some(value) = &relaunch_value {
188 updater::wait_for_previous_exit(value);
189 }
190 let relaunched = relaunch_value.is_some();
191 let command = arguments
192 .remote_command
193 .as_ref()
194 .map(RemoteCommand::encode)
195 .unwrap_or_default();
196 if single_instance::claim(SINGLE_INSTANCE_NAME, relaunched, &command)
197 == single_instance::Claim::Forwarded
198 {
199 return;
200 }
201 }
202 #[cfg(windows)]
203 updater::clean_up_old_binary();
204 let mode = Mode {
205 demo: arguments.demo,
206 read_only: arguments.read_only,
207 demo_sync: arguments.demo_sync,
208 };
209 #[cfg(windows)]
210 if arguments.demo {
211 inline_video::configure(std::env::temp_dir().join(DEMO_WEBVIEW_FOLDER));
212 }
213 let store = if arguments.demo {
214 let store = Store::open_in_memory().expect("in-memory store");
215 demo::seed(&store);
216 store
217 } else {
218 let path = arguments
219 .database
220 .clone()
221 .unwrap_or_else(|| data_path(DATABASE_FILE));
222 open_store(&path)
223 };
224 let store = Arc::new(store);
225 app_base::ui_locale::apply_locale(app_base::ui_locale::effective_locale(
226 app_base::ui_locale::load(&store),
227 ));
228 #[cfg(windows)]
229 let sign_in_title = format!(
230 "{} - {}",
231 app_base::APP_NAME,
232 app_base::ui_locale::tr("auth.sign_in")
233 );
234 let user_input = user_activity::UserInput::new();
235 let receiver = (!arguments.demo).then(|| {
236 let (ui_events, ui_receiver) = tokio::sync::mpsc::unbounded_channel();
237 #[cfg(any(target_os = "linux", target_os = "macos"))]
238 linux_browser::attach_ui_events(ui_events.clone());
239 #[cfg(windows)]
240 let transport = transport(
241 arguments.endpoint.as_deref(),
242 arguments.database.as_deref(),
243 sign_in_title.clone(),
244 );
245 #[cfg(not(windows))]
246 let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());
247 let activity = user_activity::track(user_input.clone());
248 let mut backend_events =
249 backend::start(store.clone(), transport, !arguments.read_only, activity);
250 app_base::runtime::handle().spawn(async move {
251 while let Some(event) = backend_events.recv().await {
252 if ui_events.send(event).is_err() {
253 break;
254 }
255 }
256 });
257 ui_receiver
258 });
259
260 let startup_zoom = appearance::load(&store).zoom;
261 let platform = zoom::wrap(gpui_kit::platform::current_platform(false), startup_zoom);
262 let mut application = Application::with_platform(platform);
263 if let Ok(http_client) = reqwest_client::ReqwestClient::user_agent(HTTP_USER_AGENT) {
264 application = application.with_http_client(Arc::new(http_client));
265 }
266
267 application
268 .with_assets(app_base::assets::AppAssets)
269 .run(move |cx| {
270 gpui_kit::init(cx);
271 cx.on_app_quit(|_| {
272 updater::exit_after_grace();
273 async {}
274 })
275 .detach();
276 theme::load_fonts(cx);
277 active_appearance::install(&store, cx);
278 active_locale::install(&store, cx);
279 theme::apply(cx);
280 bind_keys(cx);
281 let state = cx.new(|_| {
282 let mut state = AppState::new(store, mode);
283 state.start_on_channels = arguments.channels_tab;
284 state
285 });
286 views::shell::install_globals(&state, user_input, cx);
287 agent_api::init(state.read(cx).store.clone(), arguments.demo, cx);
288 agents::install(state.clone(), cx);
289 agent_direct::install(state.clone(), cx);
290 if arguments.demo {
291 demo::start_session(&state, cx);
292 }
293 if let Some(mut receiver) = receiver {
294 let state = state.clone();
295 cx.spawn(async move |cx| {
296 while let Some(event) = receiver.recv().await {
297 let kind = event.kind();
298 let started = std::time::Instant::now();
299 #[cfg(any(target_os = "linux", target_os = "macos"))]
300 linux_browser::note_backend_event(&event);
301 state.update(cx, |state, cx| state.apply(event, cx));
302 app_base::diagnostics::record_if_slow(&kind, started.elapsed());
303 }
304 })
305 .detach();
306 }
307
308 let bounds = Bounds::centered(None, size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), cx);
309 let mut options = TitleBar::window_options();
310 options.window_bounds = Some(WindowBounds::Windowed(bounds));
311 options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT)));
312 options.app_id = Some(LINUX_APP_ID.to_owned());
313 if let Some(titlebar) = options.titlebar.as_mut() {
314 titlebar.title = Some(APP_NAME.into());
315 }
316 let open_target = arguments.open_target;
317 let startup = Startup {
318 switcher_query: arguments.switcher_query,
319 composer_text: arguments.composer_text,
320 reply_to_last: arguments.reply_to_last,
321 launched_by_autostart: arguments.autostart,
322 };
323 let (main_window, _) = gpui_kit::open_window(options, cx, move |window, cx| {
324 cx.new(|cx| AppShell::new(state, open_target, startup, window, cx))
325 })
326 .expect("failed to open window");
327 let main_window_id = main_window.window_id();
328 cx.on_window_closed(move |cx, closed| {
329 if closed == main_window_id {
330 cx.quit();
331 }
332 })
333 .detach();
334 if !arguments.autostart {
335 cx.activate(true);
336 }
337 cx.spawn(async move |cx| {
338 loop {
339 app_base::native_dumps::heartbeat();
340 cx.background_executor().timer(HEARTBEAT_INTERVAL).await;
341 }
342 })
343 .detach();
344 });
345 presence_link::unregister_on_exit(ENDPOINT_UNREGISTER_TIMEOUT);
346 #[cfg(any(target_os = "linux", target_os = "macos"))]
347 linux_browser::stop();
348 #[cfg(windows)]
349 updater::exit_now();
350}