BlueGit

ict rusty-teams

Files

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

main.rs

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