BlueGit

ict rusty-teams

Files

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

main.rs

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