BlueGit

ict rusty-teams

Files

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

main.rs

main.rs 10.4 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 });
136 task_dialog::install_host(transport.clone());
137 return transport;
138 }
139 #[cfg(not(windows))]
140 let _ = database;
141 Arc::new(session::CdpTransport::new(
142 endpoint.unwrap_or(session::DEFAULT_ENDPOINT),
143 ))
144}
145
146const STORE_OPEN_ATTEMPTS: u32 = 20;
147const STORE_OPEN_INTERVAL: std::time::Duration = std::time::Duration::from_millis(500);
148
149fn open_store(path: &std::path::Path) -> Store {
150 for _ in 1..STORE_OPEN_ATTEMPTS {
151 match Store::open(path) {
152 Ok(store) => return store,
153 Err(_) => std::thread::sleep(STORE_OPEN_INTERVAL),
154 }
155 }
156 Store::open(path).expect("cache database")
157}
158
159fn main() {
160 app_base::version::set_build_version(VERSION_MARKER.trim_start_matches("teams-build:"));
161 if let Some(tag) = option_env!("TEAMS_RELEASE_TAG") {
162 app_base::version::set_release_tag(tag);
163 }
164 crash_log::install(data_path(crash_log::CRASH_LOG_FILE));
165 app_base::native_dumps::install(
166 data_path("native-dumps"),
167 data_path(crash_log::CRASH_LOG_FILE),
168 );
169 diagnostics::install(data_path(diagnostics::DIAGNOSTICS_FILE));
170 let arguments = parse_arguments();
171 if !arguments.demo && arguments.database.is_none() {
172 let relaunch_value = std::env::var(updater::RELAUNCH_ENV).ok();
173 if let Some(value) = &relaunch_value {
174 updater::wait_for_previous_exit(value);
175 }
176 let relaunched = relaunch_value.is_some();
177 let command = arguments
178 .remote_command
179 .as_ref()
180 .map(RemoteCommand::encode)
181 .unwrap_or_default();
182 if single_instance::claim(SINGLE_INSTANCE_NAME, relaunched, &command)
183 == single_instance::Claim::Forwarded
184 {
185 return;
186 }
187 }
188 #[cfg(windows)]
189 updater::clean_up_old_binary();
190 let mode = Mode {
191 demo: arguments.demo,
192 read_only: arguments.read_only,
193 demo_sync: arguments.demo_sync,
194 };
195 #[cfg(windows)]
196 if arguments.demo {
197 inline_video::configure(std::env::temp_dir().join(DEMO_WEBVIEW_FOLDER));
198 }
199 let store = if arguments.demo {
200 let store = Store::open_in_memory().expect("in-memory store");
201 demo::seed(&store);
202 store
203 } else {
204 let path = arguments
205 .database
206 .clone()
207 .unwrap_or_else(|| data_path(DATABASE_FILE));
208 open_store(&path)
209 };
210 let store = Arc::new(store);
211 let user_input = user_activity::UserInput::new();
212 let receiver = (!arguments.demo).then(|| {
213 let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());
214 let activity = user_activity::track(user_input.clone());
215 backend::start(store.clone(), transport, !arguments.read_only, activity)
216 });
217
218 let startup_zoom = appearance::load(&store).zoom;
219 let platform = zoom::wrap(gpui_kit::platform::current_platform(false), startup_zoom);
220 let mut application = Application::with_platform(platform);
221 if let Ok(http_client) = reqwest_client::ReqwestClient::user_agent(HTTP_USER_AGENT) {
222 application = application.with_http_client(Arc::new(http_client));
223 }
224
225 application.with_assets(app_base::assets::AppAssets).run(move |cx| {
226 gpui_kit::init(cx);
227 cx.on_app_quit(|_| {
228 updater::exit_after_grace();
229 async {}
230 })
231 .detach();
232 theme::load_fonts(cx);
233 active_appearance::install(&store, cx);
234 theme::apply(cx);
235 bind_keys(cx);
236 let state = cx.new(|_| {
237 let mut state = AppState::new(store, mode);
238 state.start_on_channels = arguments.channels_tab;
239 state
240 });
241 views::shell::install_globals(&state, user_input, cx);
242 agent_api::init(state.read(cx).store.clone(), arguments.demo, cx);
243 agents::install(state.clone(), cx);
244 if arguments.demo {
245 demo::start_session(&state, cx);
246 }
247 if let Some(mut receiver) = receiver {
248 let state = state.clone();
249 cx.spawn(async move |cx| {
250 while let Some(event) = receiver.recv().await {
251 state.update(cx, |state, cx| state.apply(event, cx));
252 }
253 })
254 .detach();
255 }
256
257 let bounds = Bounds::centered(None, size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), cx);
258 let mut options = TitleBar::window_options();
259 options.window_bounds = Some(WindowBounds::Windowed(bounds));
260 options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT)));
261 options.app_id = Some(LINUX_APP_ID.to_owned());
262 if let Some(titlebar) = options.titlebar.as_mut() {
263 titlebar.title = Some(APP_NAME.into());
264 }
265 let open_target = arguments.open_target;
266 let startup = Startup {
267 switcher_query: arguments.switcher_query,
268 composer_text: arguments.composer_text,
269 reply_to_last: arguments.reply_to_last,
270 launched_by_autostart: arguments.autostart,
271 };
272 let (main_window, _) = gpui_kit::open_window(options, cx, move |window, cx| {
273 cx.new(|cx| AppShell::new(state, open_target, startup, window, cx))
274 })
275 .expect("failed to open window");
276 let main_window_id = main_window.window_id();
277 cx.on_window_closed(move |cx, closed| {
278 if closed == main_window_id {
279 cx.quit();
280 }
281 })
282 .detach();
283 if !arguments.autostart {
284 cx.activate(true);
285 }
286 cx.spawn(async move |cx| {
287 loop {
288 app_base::native_dumps::heartbeat();
289 cx.background_executor().timer(HEARTBEAT_INTERVAL).await;
290 }
291 })
292 .detach();
293 });
294 presence_link::unregister_on_exit(ENDPOINT_UNREGISTER_TIMEOUT);
295 #[cfg(windows)]
296 updater::exit_now();
297}