BlueGit

ict rusty-teams

Files

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

main.rs

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