BlueGit

ict rusty-teams

Files

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

main.rs

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