BlueGit

ict rusty-teams

Files

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

main.rs

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