BlueGit

ict rusty-teams

Files

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

main.rs

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