BlueGit

ict rusty-teams

Files

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

main.rs

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