| 1 | use std::cell::RefCell; |
| 2 | use std::sync::mpsc::{self, Receiver, TryRecvError}; |
| 3 | use std::sync::{ |
| 4 | Arc, |
| 5 | atomic::{AtomicBool, Ordering}, |
| 6 | }; |
| 7 | use std::time::{Duration, Instant}; |
| 8 | |
| 9 | use codewhale_account_cli::{ |
| 10 | AccountClient, AccountLogin, AccountLoginCancellation, AccountLoginPoll, AccountModels, |
| 11 | }; |
| 12 | use codewhale_localization::{Locale, MessageId, tr}; |
| 13 | use codewhale_palette as palette; |
| 14 | use crossterm::event::{ |
| 15 | KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent, MouseEventKind, |
| 16 | }; |
| 17 | use ratatui::{ |
| 18 | buffer::Buffer, |
| 19 | layout::Rect, |
| 20 | style::{Modifier, Style}, |
| 21 | text::{Line, Span}, |
| 22 | widgets::{Padding, Paragraph, Widget, Wrap}, |
| 23 | }; |
| 24 | |
| 25 | use crate::tui::shell_key_routing::{ShellBindingId, binding}; |
| 26 | use crate::tui::views::{ |
| 27 | ActionHint, ModalKind, ModalView, SurfaceFrame, ViewAction, ViewEvent, centered_modal_area, |
| 28 | render_modal_footer, render_rounded_modal, |
| 29 | }; |
| 30 | |
| 31 | pub(crate) const ACCOUNT_SIGN_IN_ENABLED: bool = codewhale_account_cli::ACCOUNT_SIGN_IN_OPEN; |
| 32 | |
| 33 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 34 | pub enum AccountOperationOutcome { |
| 35 | Complete, |
| 36 | LocalSignOut, |
| 37 | Cancelled, |
| 38 | ModelCancelled, |
| 39 | Expired, |
| 40 | Failed, |
| 41 | SignInClosed, |
| 42 | } |
| 43 | |
| 44 | enum WorkerResult { |
| 45 | Started(AccountLogin), |
| 46 | Polled(AccountLogin, AccountLoginPoll), |
| 47 | Models(AccountModels), |
| 48 | ModelsFailed, |
| 49 | SignedOut(bool), |
| 50 | SignedIn, |
| 51 | Cancelled, |
| 52 | Failed, |
| 53 | SignInClosed, |
| 54 | } |
| 55 | |
| 56 | pub(crate) struct AccountLoginView { |
| 57 | locale: Locale, |
| 58 | signing_out: bool, |
| 59 | connecting_models: bool, |
| 60 | profile: Option<String>, |
| 61 | models: Option<AccountModels>, |
| 62 | models_unavailable: bool, |
| 63 | models_failed: bool, |
| 64 | worker: Option<Receiver<WorkerResult>>, |
| 65 | login: Option<AccountLogin>, |
| 66 | cancellation: Option<AccountLoginCancellation>, |
| 67 | url: Option<String>, |
| 68 | code: Option<String>, |
| 69 | next_poll: Instant, |
| 70 | selected: usize, |
| 71 | buttons: RefCell<Vec<(usize, Rect)>>, |
| 72 | cancelled: Arc<AtomicBool>, |
| 73 | } |
| 74 | |
| 75 | impl AccountLoginView { |
| 76 | pub(crate) fn new(profile: Option<String>, signing_out: bool, locale: Locale) -> Self { |
| 77 | Self::start(profile, signing_out, false, locale) |
| 78 | } |
| 79 | |
| 80 | pub(crate) fn connect(profile: Option<String>, locale: Locale) -> Self { |
| 81 | Self::start(profile, false, true, locale) |
| 82 | } |
| 83 | |
| 84 | fn start( |
| 85 | profile: Option<String>, |
| 86 | signing_out: bool, |
| 87 | connecting_models: bool, |
| 88 | locale: Locale, |
| 89 | ) -> Self { |
| 90 | let worker_profile = profile.clone(); |
| 91 | let (sender, receiver) = mpsc::channel(); |
| 92 | let cancelled = Arc::new(AtomicBool::new(false)); |
| 93 | let worker_cancelled = cancelled.clone(); |
| 94 | tokio::task::spawn_blocking(move || { |
| 95 | let result = AccountClient::new(worker_profile.as_deref(), None).and_then(|client| { |
| 96 | if worker_cancelled.load(Ordering::Acquire) { |
| 97 | return Ok(WorkerResult::Cancelled); |
| 98 | } |
| 99 | if signing_out { |
| 100 | let snapshot = client.snapshot()?; |
| 101 | if worker_cancelled.load(Ordering::Acquire) { |
| 102 | return Ok(WorkerResult::Cancelled); |
| 103 | } |
| 104 | client |
| 105 | .logout_if_unchanged(&snapshot) |
| 106 | .map(WorkerResult::SignedOut) |
| 107 | } else if matches!( |
| 108 | client.status()?.account.state, |
| 109 | codewhale_secrets::account::AccountSessionState::Authenticated |
| 110 | | codewhale_secrets::account::AccountSessionState::OfflineCached |
| 111 | ) { |
| 112 | if connecting_models { |
| 113 | Ok(client |
| 114 | .connect_models_with_cancel(&worker_cancelled) |
| 115 | .map(WorkerResult::Models) |
| 116 | .unwrap_or(WorkerResult::ModelsFailed)) |
| 117 | } else { |
| 118 | Ok(WorkerResult::SignedIn) |
| 119 | } |
| 120 | } else if !ACCOUNT_SIGN_IN_ENABLED { |
| 121 | Ok(WorkerResult::SignInClosed) |
| 122 | } else { |
| 123 | client |
| 124 | .start_login_with_cancel( |
| 125 | Duration::from_secs( |
| 126 | codewhale_account_cli::DEFAULT_LOGIN_TIMEOUT_SECONDS, |
| 127 | ), |
| 128 | worker_cancelled.clone(), |
| 129 | ) |
| 130 | .map(WorkerResult::Started) |
| 131 | } |
| 132 | }); |
| 133 | let _ = sender.send(result.unwrap_or(WorkerResult::Failed)); |
| 134 | }); |
| 135 | Self { |
| 136 | locale, |
| 137 | signing_out, |
| 138 | connecting_models, |
| 139 | profile, |
| 140 | models: None, |
| 141 | models_unavailable: false, |
| 142 | models_failed: false, |
| 143 | worker: Some(receiver), |
| 144 | login: None, |
| 145 | cancellation: None, |
| 146 | url: None, |
| 147 | code: None, |
| 148 | next_poll: Instant::now(), |
| 149 | selected: 0, |
| 150 | buttons: RefCell::new(Vec::new()), |
| 151 | cancelled, |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | fn finish(&self, outcome: AccountOperationOutcome) -> ViewAction { |
| 156 | if self.signing_out && outcome == AccountOperationOutcome::Cancelled { |
| 157 | return ViewAction::Close; |
| 158 | } |
| 159 | let outcome = if self.connecting_models && outcome == AccountOperationOutcome::Cancelled { |
| 160 | AccountOperationOutcome::ModelCancelled |
| 161 | } else { |
| 162 | outcome |
| 163 | }; |
| 164 | ViewAction::EmitAndClose(ViewEvent::AccountOperationCompleted { |
| 165 | signing_out: self.signing_out, |
| 166 | outcome, |
| 167 | }) |
| 168 | } |
| 169 | |
| 170 | fn open_browser(&self) { |
| 171 | if let Some(url) = self.url.clone() { |
| 172 | let cancelled = self.cancelled.clone(); |
| 173 | tokio::task::spawn_blocking(move || { |
| 174 | if !cancelled.load(Ordering::Acquire) { |
| 175 | let _ = webbrowser::open(&url); |
| 176 | } |
| 177 | }); |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | fn activate(&mut self, selected: usize) -> ViewAction { |
| 182 | if self.models_unavailable { |
| 183 | return match selected { |
| 184 | 0 => { |
| 185 | self.load_models(); |
| 186 | ViewAction::Redraw |
| 187 | } |
| 188 | 1 => ViewAction::EmitAndClose(ViewEvent::AccountConnectionChoice { |
| 189 | account: Some(false), |
| 190 | }), |
| 191 | _ => self.finish(AccountOperationOutcome::Cancelled), |
| 192 | }; |
| 193 | } |
| 194 | if let Some(models) = &mut self.models { |
| 195 | if let Some(model) = models.models.get(selected) { |
| 196 | let Some(key) = models.credential.take() else { |
| 197 | return self.finish(AccountOperationOutcome::Failed); |
| 198 | }; |
| 199 | return ViewAction::EmitAndClose(ViewEvent::AccountModelSelected { |
| 200 | access: codewhale_runtime::config::AccountModelAccess { |
| 201 | session_id: models.session_id.clone(), |
| 202 | credential: codewhale_runtime::credentials::Credential::ApiKey { key }, |
| 203 | expires_at: models.expires_at, |
| 204 | profile: self.profile.clone(), |
| 205 | }, |
| 206 | api_base: models.api_base.clone(), |
| 207 | account_id: models.account_id.clone(), |
| 208 | expected_revision: models.snapshot.fingerprint(), |
| 209 | model: model.id.clone(), |
| 210 | }); |
| 211 | } |
| 212 | return self.finish(AccountOperationOutcome::Cancelled); |
| 213 | } |
| 214 | match selected { |
| 215 | 0 if !self.signing_out && self.url.is_some() => { |
| 216 | self.open_browser(); |
| 217 | ViewAction::None |
| 218 | } |
| 219 | 1 if !self.signing_out => self.url.as_ref().map_or(ViewAction::None, |url| { |
| 220 | ViewAction::Emit(ViewEvent::CopyToClipboard { |
| 221 | text: url.clone(), |
| 222 | label: tr(self.locale, MessageId::AccountLoginLink).into_owned(), |
| 223 | }) |
| 224 | }), |
| 225 | _ => self.finish(AccountOperationOutcome::Cancelled), |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | fn load_models(&mut self) { |
| 230 | self.url = None; |
| 231 | self.code = None; |
| 232 | self.models = None; |
| 233 | self.models_unavailable = false; |
| 234 | self.models_failed = false; |
| 235 | self.selected = 0; |
| 236 | let profile = self.profile.clone(); |
| 237 | let cancelled = self.cancelled.clone(); |
| 238 | let (sender, receiver) = mpsc::channel(); |
| 239 | self.worker = Some(receiver); |
| 240 | tokio::task::spawn_blocking(move || { |
| 241 | let result = AccountClient::new(profile.as_deref(), None).and_then(|client| { |
| 242 | if !matches!( |
| 243 | client.status()?.account.state, |
| 244 | codewhale_secrets::account::AccountSessionState::Authenticated |
| 245 | | codewhale_secrets::account::AccountSessionState::OfflineCached |
| 246 | ) { |
| 247 | if !ACCOUNT_SIGN_IN_ENABLED { |
| 248 | return Ok(WorkerResult::SignInClosed); |
| 249 | } |
| 250 | return client |
| 251 | .start_login_with_cancel( |
| 252 | Duration::from_secs( |
| 253 | codewhale_account_cli::DEFAULT_LOGIN_TIMEOUT_SECONDS, |
| 254 | ), |
| 255 | cancelled.clone(), |
| 256 | ) |
| 257 | .map(WorkerResult::Started); |
| 258 | } |
| 259 | Ok(client |
| 260 | .connect_models_with_cancel(&cancelled) |
| 261 | .map(WorkerResult::Models) |
| 262 | .unwrap_or(WorkerResult::ModelsFailed)) |
| 263 | }); |
| 264 | let _ = sender.send(result.unwrap_or(WorkerResult::ModelsFailed)); |
| 265 | }); |
| 266 | } |
| 267 | } |
| 268 | |
| 269 | impl Drop for AccountLoginView { |
| 270 | fn drop(&mut self) { |
| 271 | self.cancelled.store(true, Ordering::Release); |
| 272 | if let Some(cancellation) = &self.cancellation { |
| 273 | cancellation.cancel(); |
| 274 | } |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | impl ModalView for AccountLoginView { |
| 279 | fn kind(&self) -> ModalKind { |
| 280 | ModalKind::AccountLogin |
| 281 | } |
| 282 | |
| 283 | fn set_locale(&mut self, locale: Locale) { |
| 284 | self.locale = locale; |
| 285 | } |
| 286 | |
| 287 | fn as_any_mut(&mut self) -> &mut dyn std::any::Any { |
| 288 | self |
| 289 | } |
| 290 | |
| 291 | fn handle_key(&mut self, key: KeyEvent) -> ViewAction { |
| 292 | if key.kind != KeyEventKind::Press { |
| 293 | return ViewAction::None; |
| 294 | } |
| 295 | if binding(ShellBindingId::AccountLoginCancel).matches(&key) |
| 296 | || key.code == KeyCode::Char('c') && key.modifiers == KeyModifiers::CONTROL |
| 297 | { |
| 298 | return self.finish(AccountOperationOutcome::Cancelled); |
| 299 | } |
| 300 | if self.url.is_some() && binding(ShellBindingId::AccountLoginOpenBrowser).matches(&key) { |
| 301 | return self.activate(0); |
| 302 | } |
| 303 | if self.url.is_some() && binding(ShellBindingId::AccountLoginCopyLink).matches(&key) { |
| 304 | return self.activate(1); |
| 305 | } |
| 306 | if key |
| 307 | .modifiers |
| 308 | .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER) |
| 309 | { |
| 310 | return ViewAction::None; |
| 311 | } |
| 312 | let count = if let Some(models) = &self.models { |
| 313 | models.models.len() + 1 |
| 314 | } else if self.url.is_some() || self.models_unavailable { |
| 315 | 3 |
| 316 | } else { |
| 317 | 1 |
| 318 | }; |
| 319 | match key.code { |
| 320 | KeyCode::Tab | KeyCode::Down | KeyCode::Right => { |
| 321 | self.selected = (self.selected + 1) % count; |
| 322 | ViewAction::Redraw |
| 323 | } |
| 324 | KeyCode::BackTab | KeyCode::Up | KeyCode::Left => { |
| 325 | self.selected = (self.selected + count - 1) % count; |
| 326 | ViewAction::Redraw |
| 327 | } |
| 328 | KeyCode::Enter => self.activate(if count == 1 && self.models.is_none() { |
| 329 | 2 |
| 330 | } else { |
| 331 | self.selected |
| 332 | }), |
| 333 | _ => ViewAction::None, |
| 334 | } |
| 335 | } |
| 336 | |
| 337 | fn handle_mouse(&mut self, mouse: MouseEvent) -> ViewAction { |
| 338 | if !matches!(mouse.kind, MouseEventKind::Down(MouseButton::Left)) { |
| 339 | return ViewAction::None; |
| 340 | } |
| 341 | let selected = self.buttons.borrow().iter().find_map(|(index, rect)| { |
| 342 | crate::tui::mouse_ui::mouse_hits_rect(mouse, Some(*rect)).then_some(*index) |
| 343 | }); |
| 344 | selected.map_or(ViewAction::None, |selected| self.activate(selected)) |
| 345 | } |
| 346 | |
| 347 | fn occupied_region(&self, area: Rect) -> Rect { |
| 348 | centered_modal_area(area, 76, 18, 28, 8) |
| 349 | } |
| 350 | |
| 351 | fn render(&self, area: Rect, buf: &mut Buffer) { |
| 352 | let popup = self.occupied_region(area); |
| 353 | let title = if self.signing_out { |
| 354 | MessageId::AccountLogoutTitle |
| 355 | } else if self.connecting_models && self.url.is_none() { |
| 356 | MessageId::AccountModelsTitle |
| 357 | } else { |
| 358 | MessageId::AccountLoginTitle |
| 359 | }; |
| 360 | let (inner, _) = render_rounded_modal( |
| 361 | area, |
| 362 | popup, |
| 363 | buf, |
| 364 | SurfaceFrame::new(tr(self.locale, title)).padding(Padding::uniform(1)), |
| 365 | ); |
| 366 | let dismiss_id = if self.signing_out { |
| 367 | MessageId::CtxInspActionClose |
| 368 | } else { |
| 369 | MessageId::PickerActionCancel |
| 370 | }; |
| 371 | let mut hints = Vec::new(); |
| 372 | if self.models.is_some() || self.models_unavailable { |
| 373 | hints.push(ActionHint::new( |
| 374 | binding(ShellBindingId::AccountLoginNext).footer_chord, |
| 375 | tr(self.locale, MessageId::PickerActionMove), |
| 376 | )); |
| 377 | hints.push(ActionHint::new( |
| 378 | binding(ShellBindingId::AccountLoginSelect).footer_chord, |
| 379 | tr(self.locale, MessageId::PickerActionApply), |
| 380 | )); |
| 381 | } |
| 382 | hints.push(ActionHint::new( |
| 383 | binding(ShellBindingId::AccountLoginCancel).footer_chord, |
| 384 | tr(self.locale, dismiss_id), |
| 385 | )); |
| 386 | let content = render_modal_footer(inner, buf, &hints); |
| 387 | let mut lines = Vec::new(); |
| 388 | if let Some(code) = &self.code { |
| 389 | lines.push(Line::from(Span::styled( |
| 390 | tr(self.locale, MessageId::AccountLoginCode).replace("{code}", code), |
| 391 | Style::default() |
| 392 | .fg(palette::WHALE_ACTION) |
| 393 | .add_modifier(Modifier::BOLD), |
| 394 | ))); |
| 395 | } |
| 396 | if let Some(url) = &self.url { |
| 397 | lines.push(Line::from(url.clone())); |
| 398 | } |
| 399 | lines.push(Line::from( |
| 400 | tr( |
| 401 | self.locale, |
| 402 | if self.signing_out { |
| 403 | MessageId::AccountLogoutStarting |
| 404 | } else if self.url.is_some() { |
| 405 | MessageId::AccountLoginWaiting |
| 406 | } else if self.models_unavailable && self.models_failed { |
| 407 | MessageId::AccountModelsLoadFailed |
| 408 | } else if self.models_unavailable { |
| 409 | MessageId::AccountModelsUnavailable |
| 410 | } else if self.connecting_models { |
| 411 | MessageId::AccountModelsLoading |
| 412 | } else { |
| 413 | MessageId::AccountLoginStarting |
| 414 | }, |
| 415 | ) |
| 416 | .into_owned(), |
| 417 | )); |
| 418 | if let Some(models) = &self.models { |
| 419 | let billing = models |
| 420 | .models |
| 421 | .get(self.selected) |
| 422 | .map(|model| { |
| 423 | tr(self.locale, MessageId::ProviderExternalBillingLine) |
| 424 | .replace("{owner}", &model.provider) |
| 425 | }) |
| 426 | .unwrap_or_default(); |
| 427 | let paragraph = Paragraph::new(billing).wrap(Wrap { trim: false }); |
| 428 | let billing_height = (paragraph.line_count(content.width.max(1)) as u16) |
| 429 | .min(content.height.saturating_sub(2)); |
| 430 | paragraph.render( |
| 431 | Rect { |
| 432 | height: billing_height, |
| 433 | ..content |
| 434 | }, |
| 435 | buf, |
| 436 | ); |
| 437 | let content = Rect { |
| 438 | y: content.y + billing_height, |
| 439 | height: content.height.saturating_sub(billing_height), |
| 440 | ..content |
| 441 | }; |
| 442 | let mut buttons = self.buttons.borrow_mut(); |
| 443 | buttons.clear(); |
| 444 | let count = models.models.len() + 1; |
| 445 | let visible = usize::from(content.height); |
| 446 | let start = self.selected.saturating_sub(visible.saturating_sub(1)); |
| 447 | for (row, index) in (start..count).take(visible).enumerate() { |
| 448 | let label = models |
| 449 | .models |
| 450 | .get(index) |
| 451 | .map(|model| { |
| 452 | let mut clean = String::new(); |
| 453 | codewhale_sanitize::sanitize::strip_ansi_into( |
| 454 | &format!("{} · {}", model.label, model.provider), |
| 455 | &mut clean, |
| 456 | ); |
| 457 | clean |
| 458 | .chars() |
| 459 | .filter(|character| !character.is_control()) |
| 460 | .take(160) |
| 461 | .collect::<String>() |
| 462 | }) |
| 463 | .unwrap_or_else(|| tr(self.locale, dismiss_id).into_owned()); |
| 464 | let rect = Rect::new(content.x, content.y + row as u16, content.width, 1); |
| 465 | let is_selected = index == self.selected; |
| 466 | let style = if is_selected { |
| 467 | codewhale_tui_kit::menu_style::selected_row_style() |
| 468 | } else { |
| 469 | Style::default().fg(palette::TEXT_PRIMARY) |
| 470 | }; |
| 471 | let pointer = codewhale_tui_kit::glyphs::selection_marker(is_selected); |
| 472 | Paragraph::new(format!(" {pointer} {label}")) |
| 473 | .style(style) |
| 474 | .render(rect, buf); |
| 475 | buttons.push((index, rect)); |
| 476 | } |
| 477 | return; |
| 478 | } |
| 479 | let options: Vec<(usize, MessageId, Option<ShellBindingId>)> = if self.models_unavailable { |
| 480 | vec![ |
| 481 | (0, MessageId::SetupActionRetry, None), |
| 482 | (1, MessageId::ConnectionSetupLocal, None), |
| 483 | (2, dismiss_id, Some(ShellBindingId::AccountLoginCancel)), |
| 484 | ] |
| 485 | } else if self.url.is_some() { |
| 486 | vec![ |
| 487 | ( |
| 488 | 0, |
| 489 | MessageId::AccountLoginOpenBrowser, |
| 490 | Some(ShellBindingId::AccountLoginOpenBrowser), |
| 491 | ), |
| 492 | ( |
| 493 | 1, |
| 494 | MessageId::AccountLoginCopyLink, |
| 495 | Some(ShellBindingId::AccountLoginCopyLink), |
| 496 | ), |
| 497 | (2, dismiss_id, Some(ShellBindingId::AccountLoginCancel)), |
| 498 | ] |
| 499 | } else { |
| 500 | vec![(2, dismiss_id, Some(ShellBindingId::AccountLoginCancel))] |
| 501 | }; |
| 502 | let options_height = options.len().min(usize::from(content.height)) as u16; |
| 503 | let text_area = Rect { |
| 504 | height: content.height.saturating_sub(options_height), |
| 505 | ..content |
| 506 | }; |
| 507 | Paragraph::new(lines) |
| 508 | .wrap(Wrap { trim: false }) |
| 509 | .render(text_area, buf); |
| 510 | let mut buttons = self.buttons.borrow_mut(); |
| 511 | buttons.clear(); |
| 512 | for (row, (index, id, shortcut)) in options.iter().enumerate() { |
| 513 | let rect = Rect::new( |
| 514 | content.x, |
| 515 | content.bottom().saturating_sub(options_height) + row as u16, |
| 516 | content.width, |
| 517 | 1, |
| 518 | ); |
| 519 | let selected = *index == if options.len() == 1 { 2 } else { self.selected }; |
| 520 | let style = if selected { |
| 521 | codewhale_tui_kit::menu_style::selected_row_style() |
| 522 | } else { |
| 523 | Style::default().fg(palette::TEXT_PRIMARY) |
| 524 | }; |
| 525 | let pointer = codewhale_tui_kit::glyphs::selection_marker(selected); |
| 526 | let chord = shortcut.map(|id| binding(id).footer_chord).unwrap_or(""); |
| 527 | let line = if chord.is_empty() { |
| 528 | format!(" {pointer} {}", tr(self.locale, *id)) |
| 529 | } else { |
| 530 | format!(" {pointer} {chord} {}", tr(self.locale, *id)) |
| 531 | }; |
| 532 | Paragraph::new(line).style(style).render(rect, buf); |
| 533 | buttons.push((*index, rect)); |
| 534 | } |
| 535 | } |
| 536 | |
| 537 | fn tick(&mut self) -> ViewAction { |
| 538 | let outcome = self.worker.as_ref().map(|worker| worker.try_recv()); |
| 539 | match outcome { |
| 540 | Some(Ok(result)) => { |
| 541 | self.worker = None; |
| 542 | match result { |
| 543 | WorkerResult::Started(login) => { |
| 544 | self.cancellation = Some(login.cancellation()); |
| 545 | self.url = Some(login.prompt().verification_uri_complete.clone()); |
| 546 | self.code = Some(login.prompt().user_code.clone()); |
| 547 | self.login = Some(login); |
| 548 | self.next_poll = Instant::now(); |
| 549 | if std::env::var_os("SSH_CONNECTION").is_none() |
| 550 | && std::env::var_os("SSH_TTY").is_none() |
| 551 | { |
| 552 | self.open_browser(); |
| 553 | } |
| 554 | return ViewAction::Redraw; |
| 555 | } |
| 556 | WorkerResult::Polled(login, AccountLoginPoll::Pending { retry_after }) => { |
| 557 | self.login = Some(login); |
| 558 | self.next_poll = Instant::now() + retry_after; |
| 559 | } |
| 560 | WorkerResult::Polled(_, AccountLoginPoll::Complete { .. }) |
| 561 | if self.connecting_models => |
| 562 | { |
| 563 | self.load_models(); |
| 564 | return ViewAction::Redraw; |
| 565 | } |
| 566 | WorkerResult::Models(models) => { |
| 567 | self.models_unavailable = |
| 568 | models.models.is_empty() || models.credential.is_none(); |
| 569 | if !self.models_unavailable { |
| 570 | self.selected = models |
| 571 | .models |
| 572 | .iter() |
| 573 | .position(|model| Some(&model.id) == models.default_model.as_ref()) |
| 574 | .unwrap_or(0); |
| 575 | self.models = Some(models); |
| 576 | } |
| 577 | return ViewAction::Redraw; |
| 578 | } |
| 579 | WorkerResult::ModelsFailed => { |
| 580 | self.models_unavailable = true; |
| 581 | self.models_failed = true; |
| 582 | return ViewAction::Redraw; |
| 583 | } |
| 584 | WorkerResult::Polled(_, AccountLoginPoll::Complete { .. }) |
| 585 | | WorkerResult::SignedIn |
| 586 | | WorkerResult::SignedOut(true) => { |
| 587 | return self.finish(AccountOperationOutcome::Complete); |
| 588 | } |
| 589 | WorkerResult::SignedOut(false) => { |
| 590 | return self.finish(AccountOperationOutcome::LocalSignOut); |
| 591 | } |
| 592 | WorkerResult::Polled(_, AccountLoginPoll::Cancelled) => { |
| 593 | return self.finish(AccountOperationOutcome::Cancelled); |
| 594 | } |
| 595 | WorkerResult::Polled(_, AccountLoginPoll::Expired) => { |
| 596 | return self.finish(AccountOperationOutcome::Expired); |
| 597 | } |
| 598 | WorkerResult::Cancelled => { |
| 599 | return self.finish(AccountOperationOutcome::Cancelled); |
| 600 | } |
| 601 | WorkerResult::Failed => return self.finish(AccountOperationOutcome::Failed), |
| 602 | WorkerResult::SignInClosed => { |
| 603 | return self.finish(AccountOperationOutcome::SignInClosed); |
| 604 | } |
| 605 | } |
| 606 | } |
| 607 | Some(Err(TryRecvError::Disconnected)) => { |
| 608 | return self.finish(AccountOperationOutcome::Failed); |
| 609 | } |
| 610 | Some(Err(TryRecvError::Empty)) | None => {} |
| 611 | } |
| 612 | if self.worker.is_none() |
| 613 | && Instant::now() >= self.next_poll |
| 614 | && let Some(mut login) = self.login.take() |
| 615 | { |
| 616 | let (sender, receiver) = mpsc::channel(); |
| 617 | self.worker = Some(receiver); |
| 618 | tokio::task::spawn_blocking(move || { |
| 619 | let result = match login.poll() { |
| 620 | Ok(result) => WorkerResult::Polled(login, result), |
| 621 | Err(_) => WorkerResult::Failed, |
| 622 | }; |
| 623 | let _ = sender.send(result); |
| 624 | }); |
| 625 | } |
| 626 | ViewAction::None |
| 627 | } |
| 628 | } |
| 629 | |
| 630 | pub(crate) struct ConnectionSetupView { |
| 631 | locale: Locale, |
| 632 | selected: usize, |
| 633 | buttons: RefCell<Vec<(usize, Rect)>>, |
| 634 | } |
| 635 | |
| 636 | impl ConnectionSetupView { |
| 637 | pub(crate) fn new(locale: Locale) -> Self { |
| 638 | Self { |
| 639 | locale, |
| 640 | selected: usize::from(!ACCOUNT_SIGN_IN_ENABLED), |
| 641 | buttons: RefCell::new(Vec::new()), |
| 642 | } |
| 643 | } |
| 644 | |
| 645 | fn choose(&self, selected: Option<usize>) -> ViewAction { |
| 646 | ViewAction::EmitAndClose(ViewEvent::AccountConnectionChoice { |
| 647 | account: selected.map(|selected| ACCOUNT_SIGN_IN_ENABLED && selected == 0), |
| 648 | }) |
| 649 | } |
| 650 | } |
| 651 | |
| 652 | impl ModalView for ConnectionSetupView { |
| 653 | fn kind(&self) -> ModalKind { |
| 654 | ModalKind::AccountLogin |
| 655 | } |
| 656 | |
| 657 | fn set_locale(&mut self, locale: Locale) { |
| 658 | self.locale = locale; |
| 659 | } |
| 660 | |
| 661 | fn as_any_mut(&mut self) -> &mut dyn std::any::Any { |
| 662 | self |
| 663 | } |
| 664 | |
| 665 | fn handle_key(&mut self, key: KeyEvent) -> ViewAction { |
| 666 | if key.kind != KeyEventKind::Press { |
| 667 | return ViewAction::None; |
| 668 | } |
| 669 | if binding(ShellBindingId::AccountLoginCancel).matches(&key) |
| 670 | || key.code == KeyCode::Char('c') && key.modifiers == KeyModifiers::CONTROL |
| 671 | { |
| 672 | return self.choose(None); |
| 673 | } |
| 674 | if key |
| 675 | .modifiers |
| 676 | .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER) |
| 677 | { |
| 678 | return ViewAction::None; |
| 679 | } |
| 680 | match key.code { |
| 681 | KeyCode::Up | KeyCode::Down | KeyCode::Tab | KeyCode::BackTab |
| 682 | if ACCOUNT_SIGN_IN_ENABLED => |
| 683 | { |
| 684 | self.selected = 1 - self.selected; |
| 685 | ViewAction::Redraw |
| 686 | } |
| 687 | KeyCode::Enter => self.choose(Some(self.selected)), |
| 688 | _ => ViewAction::None, |
| 689 | } |
| 690 | } |
| 691 | |
| 692 | fn handle_mouse(&mut self, mouse: MouseEvent) -> ViewAction { |
| 693 | if !matches!(mouse.kind, MouseEventKind::Down(MouseButton::Left)) { |
| 694 | return ViewAction::None; |
| 695 | } |
| 696 | let selected = self.buttons.borrow().iter().find_map(|(index, rect)| { |
| 697 | crate::tui::mouse_ui::mouse_hits_rect(mouse, Some(*rect)).then_some(*index) |
| 698 | }); |
| 699 | selected.map_or(ViewAction::None, |selected| self.choose(Some(selected))) |
| 700 | } |
| 701 | |
| 702 | fn tick(&mut self) -> ViewAction { |
| 703 | if ACCOUNT_SIGN_IN_ENABLED { |
| 704 | ViewAction::None |
| 705 | } else { |
| 706 | self.choose(Some(1)) |
| 707 | } |
| 708 | } |
| 709 | |
| 710 | fn occupied_region(&self, area: Rect) -> Rect { |
| 711 | centered_modal_area(area, 76, 13, 28, 8) |
| 712 | } |
| 713 | |
| 714 | fn render(&self, area: Rect, buf: &mut Buffer) { |
| 715 | let popup = self.occupied_region(area); |
| 716 | let (inner, _) = render_rounded_modal( |
| 717 | area, |
| 718 | popup, |
| 719 | buf, |
| 720 | SurfaceFrame::new(tr(self.locale, MessageId::ConnectionSetupTitle)) |
| 721 | .padding(Padding::uniform(1)), |
| 722 | ); |
| 723 | let content = render_modal_footer( |
| 724 | inner, |
| 725 | buf, |
| 726 | &[ |
| 727 | ActionHint::new( |
| 728 | binding(ShellBindingId::AccountLoginNext).footer_chord, |
| 729 | tr(self.locale, MessageId::PickerActionMove), |
| 730 | ), |
| 731 | ActionHint::new( |
| 732 | binding(ShellBindingId::AccountLoginSelect).footer_chord, |
| 733 | tr(self.locale, MessageId::PickerActionApply), |
| 734 | ), |
| 735 | ActionHint::new( |
| 736 | binding(ShellBindingId::AccountLoginCancel).footer_chord, |
| 737 | tr(self.locale, MessageId::PickerActionCancel), |
| 738 | ), |
| 739 | ], |
| 740 | ); |
| 741 | let mut buttons = self.buttons.borrow_mut(); |
| 742 | buttons.clear(); |
| 743 | let rows = [ |
| 744 | ( |
| 745 | MessageId::ConnectionSetupAccount, |
| 746 | MessageId::ConnectionSetupAccountDetail, |
| 747 | ), |
| 748 | ( |
| 749 | MessageId::ConnectionSetupLocal, |
| 750 | MessageId::ConnectionSetupLocalDetail, |
| 751 | ), |
| 752 | ]; |
| 753 | let visible = if ACCOUNT_SIGN_IN_ENABLED { 2 } else { 1 }; |
| 754 | let height = content.height / visible; |
| 755 | for (index, (label, detail)) in rows.into_iter().enumerate() { |
| 756 | if !ACCOUNT_SIGN_IN_ENABLED && index == 0 { |
| 757 | continue; |
| 758 | } |
| 759 | let row = index - (2 - visible as usize); |
| 760 | let rect = Rect::new( |
| 761 | content.x, |
| 762 | content.y + row as u16 * height, |
| 763 | content.width, |
| 764 | height, |
| 765 | ); |
| 766 | let is_selected = self.selected == index; |
| 767 | let pointer = codewhale_tui_kit::glyphs::selection_marker(is_selected); |
| 768 | let style = if is_selected { |
| 769 | codewhale_tui_kit::menu_style::selected_row_style() |
| 770 | } else { |
| 771 | Style::default().fg(palette::TEXT_PRIMARY) |
| 772 | }; |
| 773 | let detail_style = if is_selected { |
| 774 | codewhale_tui_kit::menu_style::selected_row_bg_style().fg(palette::SELECTION_TEXT) |
| 775 | } else { |
| 776 | Style::default().fg(palette::TEXT_MUTED) |
| 777 | }; |
| 778 | Paragraph::new(vec![ |
| 779 | Line::from(Span::styled( |
| 780 | format!(" {pointer} {}", tr(self.locale, label)), |
| 781 | Style::default().add_modifier(Modifier::BOLD), |
| 782 | )), |
| 783 | Line::from(Span::styled( |
| 784 | format!(" {}", tr(self.locale, detail)), |
| 785 | detail_style, |
| 786 | )), |
| 787 | ]) |
| 788 | .style(style) |
| 789 | .wrap(Wrap { trim: false }) |
| 790 | .render(rect, buf); |
| 791 | buttons.push((index, rect)); |
| 792 | } |
| 793 | } |
| 794 | } |
| 795 | |
| 796 | #[cfg(test)] |
| 797 | mod tests { |
| 798 | use super::*; |
| 799 | |
| 800 | #[test] |
| 801 | fn hidden_account_sign_in_routes_connection_setup_to_local_model() { |
| 802 | const { assert!(!ACCOUNT_SIGN_IN_ENABLED) }; |
| 803 | let mut view = ConnectionSetupView::new(Locale::En); |
| 804 | let action = view.tick(); |
| 805 | assert!(matches!( |
| 806 | action, |
| 807 | ViewAction::EmitAndClose(ViewEvent::AccountConnectionChoice { |
| 808 | account: Some(false) |
| 809 | }) |
| 810 | )); |
| 811 | assert!(matches!( |
| 812 | view.choose(Some(0)), |
| 813 | ViewAction::EmitAndClose(ViewEvent::AccountConnectionChoice { |
| 814 | account: Some(false) |
| 815 | }) |
| 816 | )); |
| 817 | } |
| 818 | } |
| 819 |