BlueGit

ict rusty-teams

Files

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

main.rs

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