BlueGit

ict rusty-teams

Files

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

main.rs

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