BlueGit

ict rusty-teams

Files

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

main.rs

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