BlueGit

ict rusty-teams

Files

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

main.rs

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