BlueGit

ict rusty-teams

Files

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

main.rs

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