1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
use std::str::FromStr as _;
use egui::{Direction, Layout, OpenUrl, RichText};
use egui_extras::{Size, StripBuilder};
use re_auth::Jwt;
use re_redap_client::ConnectionRegistryHandle;
use re_ui::modal::{ModalHandler, ModalWrapper};
use re_ui::{ReButton, UiExt as _};
use re_uri::Scheme;
use re_viewer_context::{
AppContext, EditRedapServerModalCommand, Route, SystemCommand, SystemCommandSender as _,
};
use crate::context::Context;
use crate::servers::Command;
mod login_flow;
pub use login_flow::{LoginFlow, LoginFlowResult};
/// Should the modal edit an existing server or add a new one?
pub enum ServerModalMode {
/// Show an empty modal to add a new server.
Add,
/// Show a modal to edit an existing server.
///
/// You should ensure that the [`re_uri::Origin`] exists. (Otherwise, this leads to bad UX,
/// since the modal will be titled "Edit server" but for the user it's a new server.)
Edit(EditRedapServerModalCommand),
}
impl ServerModalMode {
/// Should we show a warning about the catalog server being experimental?
pub fn should_show_experimental_warning(&self) -> bool {
matches!(self, Self::Add)
}
}
enum AuthKind {
None,
Token(String),
RerunAccount(Option<Box<LoginFlow>>),
}
/// Authentication state for the server modal.
struct Authentication {
kind: AuthKind,
error: Option<String>,
}
impl Authentication {
/// Initialize auth state.
///
/// This attempts to load credentials from disk if `use_stored_credentials`
/// is set to `true`. Note that they are accepted even if they are expired,
/// the assumption being that they'll be refreshed automatically before usage.
///
/// Optionally, this can be given a token, which takes
/// precedence over stored credentials.
fn new(kind: AuthKind) -> Self {
Self { kind, error: None }
}
/// This cleans up the login flow's resources, such as
/// closing popup windows.
fn reset_login_flow(&mut self) {
if let AuthKind::RerunAccount(flow) = &mut self.kind {
*flow = None;
}
}
/// `signed_in_url` is only used on web as the `OAuth` redirect URI.
fn start_login_flow(&mut self, ui: &egui::Ui, signed_in_url: Option<&str>) {
let result = LoginFlow::open(ui.ctx(), signed_in_url);
match result {
Ok(flow) => {
self.kind = AuthKind::RerunAccount(Some(Box::new(flow)));
self.error = None;
}
Err(err) => {
self.error = Some(err);
}
}
}
}
pub struct ServerModal {
modal: ModalHandler,
mode: ServerModalMode,
scheme: Scheme,
host: String,
auth: Authentication,
port: u16,
}
impl Default for ServerModal {
fn default() -> Self {
Self {
modal: Default::default(),
mode: ServerModalMode::Add,
scheme: Scheme::RerunHttps,
host: String::new(),
auth: Authentication::new(AuthKind::RerunAccount(None)),
port: 443,
}
}
}
impl ServerModal {
pub fn open(
&mut self,
mode: ServerModalMode,
connection_registry: &ConnectionRegistryHandle,
login_enabled: bool,
) {
let default_auth_kind = if login_enabled {
AuthKind::RerunAccount(None)
} else {
AuthKind::None
};
*self = match mode {
ServerModalMode::Add => {
let auth = Authentication::new(default_auth_kind);
Self {
mode: ServerModalMode::Add,
auth,
..Default::default()
}
}
ServerModalMode::Edit(edit) => {
let re_uri::Origin { scheme, host, port } = edit.origin.clone();
let credentials = connection_registry.credentials(&edit.origin);
let auth = match credentials {
Some(re_redap_client::Credentials::Token(token)) => {
Authentication::new(AuthKind::Token(token.to_string()))
}
Some(re_redap_client::Credentials::Stored) => {
Authentication::new(AuthKind::RerunAccount(None))
}
None => Authentication::new(AuthKind::None),
};
Self {
modal: Default::default(),
mode: ServerModalMode::Edit(edit),
scheme,
host: host.to_string(),
auth,
port,
}
}
};
self.modal.open();
}
pub fn logout(&mut self) {
self.auth.reset_login_flow();
}
pub fn ui(&mut self, app_ctx: &AppContext<'_>, ctx: &Context<'_>, ui: &egui::Ui) {
let was_open = self.modal.is_open();
self.modal.ui(
ui.ctx(),
|| {
let title = match &self.mode {
ServerModalMode::Add => "Add server".to_owned(),
ServerModalMode::Edit(edit) => {
if let Some(title) = &edit.title {
title.clone()
} else {
format!("Edit server: {}", edit.origin.host)
}
}
};
ModalWrapper::new(&title)
.default_height(300.0)
.min_height(300.0)
},
|ui| {
if self.mode.should_show_experimental_warning() {
ui.warning_label(
"Rerun Hub is experimental and not generally \
available yet. Proceed with caution!",
);
}
let label = ui.label("Address:");
egui::Sides::new()
.shrink_left()
.height(ui.spacing().interact_size.y)
.show(
ui,
|ui| {
egui::ComboBox::new("scheme", "")
.selected_text(if self.scheme == Scheme::RerunHttp {
"http"
} else {
"https"
})
.show_ui(ui, |ui| {
ui.selectable_value(
&mut self.scheme,
Scheme::RerunHttps,
"https",
);
ui.selectable_value(
&mut self.scheme,
Scheme::RerunHttp,
"http",
);
});
ui.scope(|ui| {
// make field red if host is invalid
if url::Host::parse(&self.host).is_err() {
ui.style_invalid_field();
}
ui.add(
egui::TextEdit::singleline(&mut self.host)
.lock_focus(false)
.hint_text("Host name")
.desired_width(ui.available_width()),
)
.labelled_by(label.id);
self.host = self.host.trim().to_owned();
});
},
|ui| {
ui.add(egui::DragValue::new(&mut self.port));
},
);
let mut host = url::Host::parse(&self.host);
if host.is_err()
&& let Ok(url) = url::Url::parse(&self.host)
{
// Maybe the user pasted a full URL, with scheme and port?
// Then handle that gracefully! `from_str` requires the url
// with the "://" part so we just pass the whole url.
match url.scheme() {
"https" => self.scheme = Scheme::RerunHttps,
"http" => self.scheme = Scheme::RerunHttp,
_ => {
if let Ok(scheme) = Scheme::from_str(&self.host) {
self.scheme = scheme;
}
}
}
if let Some(url_host) = url.host_str() {
self.host = url_host.to_owned();
host = url::Host::parse(&self.host);
}
if let Some(port) = url.port() {
self.port = port;
}
}
ui.add_space(14.0);
ui.label("Authentication:");
let login_enabled = app_ctx.login_enabled;
ui.selectable_toggle(|ui| {
let num_options = if login_enabled { 3 } else { 2 };
StripBuilder::new(ui)
.sizes(Size::relative(1.0 / num_options as f32), num_options)
.cell_layout(Layout::centered_and_justified(Direction::TopDown))
.horizontal(|mut strip| {
if login_enabled {
strip.cell(|ui| {
if ui
.selectable_label(
matches!(self.auth.kind, AuthKind::RerunAccount(_)),
"Account login",
)
.clicked()
{
self.auth.kind = AuthKind::RerunAccount(None);
}
});
}
strip.cell(|ui| {
if ui
.selectable_label(
matches!(self.auth.kind, AuthKind::Token(_)),
"Access token",
)
.clicked()
{
self.auth.kind = AuthKind::Token(String::new());
}
});
strip.cell(|ui| {
if ui
.selectable_label(
matches!(self.auth.kind, AuthKind::None),
"No authentication",
)
.clicked()
{
self.auth.kind = AuthKind::None;
}
});
});
});
auth_ui(ui, app_ctx, &mut self.auth);
ui.add_space(24.0);
let save_text = match &self.mode {
ServerModalMode::Add => "Add",
ServerModalMode::Edit(_) => "Save",
};
let origin = host.map(|host| re_uri::Origin {
scheme: self.scheme,
host,
port: self.port,
});
let credentials = match &self.auth.kind {
AuthKind::Token(token) => Jwt::try_from(token.clone())
.map(re_redap_client::Credentials::Token)
.map(Some)
.map_err(|_err| ()),
AuthKind::RerunAccount(_) => {
if app_ctx.logged_in() {
Ok(Some(re_redap_client::Credentials::Stored))
} else {
Err(())
}
}
AuthKind::None => Ok(None),
};
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let enabled = origin.is_ok() && credentials.is_ok();
let save_button_response =
ui.add_enabled(enabled, ReButton::new(save_text).primary().small());
if let Ok(origin) = origin
&& let Ok(credentials) = credentials
&& (save_button_response.clicked()
|| ui.input(|i| i.key_pressed(egui::Key::Enter)))
{
self.auth.reset_login_flow();
ui.close();
if let ServerModalMode::Edit(edit) = &self.mode {
app_ctx
.command_sender
.send_system(SystemCommand::RemoveRedapServer(edit.origin.clone()));
}
let on_add: Box<dyn FnOnce() + Send> =
if let ServerModalMode::Edit(EditRedapServerModalCommand {
open_on_success: Some(url),
..
}) = &self.mode
{
let egui_ctx = ui.ctx().clone();
let url = url.clone();
Box::new(move || {
egui_ctx.open_url(OpenUrl::same_tab(url));
})
} else {
let command_sender = app_ctx.command_sender.clone();
let origin = origin.clone();
Box::new(move || {
command_sender.send_system(SystemCommand::SetRoute(
Route::RedapServer(origin),
));
})
};
re_quota_channel::send_crossbeam(
ctx.command_sender,
Command::AddServer {
origin: origin.clone(),
credentials,
on_add: Some(on_add),
},
)
.ok();
}
let cancel_button_response = ui.add(ReButton::new("Cancel").small());
if cancel_button_response.clicked() {
self.auth = Authentication::new(AuthKind::RerunAccount(None));
self.auth.reset_login_flow();
ui.close();
}
});
},
);
// reset login flow if modal was just closed (e.g., by backdrop click)
if was_open && !self.modal.is_open() {
re_log::debug!("modal closed; reset login flow");
self.auth.reset_login_flow();
}
}
}
fn auth_ui(ui: &mut egui::Ui, ctx: &AppContext<'_>, auth: &mut Authentication) {
match &mut auth.kind {
AuthKind::RerunAccount(login_flow) => {
ui.label("Account login:");
if let Some(flow) = login_flow {
// Login flow is in progress - show login buttons or loading indicator
if let Some(result) = flow.ui(ui, ctx.command_sender) {
match result {
LoginFlowResult::Success => {
auth.error = None;
auth.reset_login_flow();
}
LoginFlowResult::Failure(err) => {
auth.error = Some(err);
auth.reset_login_flow();
}
}
}
} else if let Some(logged_in) = &ctx.auth_context {
// User is logged in
ui.horizontal(|ui| {
ui.label("Continue as");
ui.label(RichText::new(&logged_in.email).strong());
ui.weak("or");
if ui
.link(RichText::new("log out").color(ui.tokens().text_subdued))
.clicked()
{
ctx.command_sender.send_system(SystemCommand::Logout);
}
});
} else {
// User is not logged in - start the login flow to show buttons
auth.start_login_flow(ui, ctx.login_signed_in_url);
}
if let Some(error) = &auth.error {
ui.error_label(error.clone());
}
}
AuthKind::Token(token) => {
ui.label("Access token (will be stored in plain text):");
ui.scope(|ui| {
let jwt = (!token.is_empty())
.then(|| Jwt::try_from(token.clone()))
.transpose();
if jwt.is_err() {
ui.style_invalid_field();
}
ui.add(
egui::TextEdit::singleline(token)
.code_editor()
.desired_width(f32::INFINITY),
);
});
}
AuthKind::None => {
// No UI needed for "No authentication"
}
}
}