use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};
use alacritty_terminal::event::Event as TermEvent;
use alacritty_terminal::grid::Scroll;
use alacritty_terminal::index::{Column, Line, Point, Side};
use alacritty_terminal::selection::{Selection, SelectionType};
use alacritty_terminal::term::TermMode;
use alacritty_terminal::vte::ansi::Rgb;
use winit::application::ApplicationHandler;
use winit::dpi::LogicalSize;
use winit::event::{ElementState, KeyEvent, MouseButton, MouseScrollDelta, StartCause, WindowEvent};
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoopProxy};
use winit::keyboard::{Key, ModifiersState, NamedKey};
use winit::platform::windows::WindowAttributesExtWindows;
use winit::window::{CursorIcon, Icon, ResizeDirection, UserAttentionType, Window, WindowId};
mod actions;
mod chat;
mod chrome;
mod frame;
mod host;
mod keyboard;
mod notify;
mod overlays;
mod panes;
mod pointer;
mod reload;
mod review;
mod session;
mod term_events;
mod web;
pub use chrome::{Hit, title_buttons, titlebar_height};
use notify::{notify_done, notify_focus};
pub use web::CodeRequest;
use crate::agent::claude::Usage;
use crate::config::keys::{Action, Chord, Keymap};
use crate::config::{Config, Palette};
use crate::platform::hotkey::Hotkey;
use crate::render;
use crate::render::glyphs::Glyphs;
use crate::render::gpu::{Gpu, Quad};
use crate::terminal::editing::Move;
use crate::terminal::events::{Done, TitleSignal, UserEvent};
use crate::terminal::input;
use crate::terminal::layout::{self, Dir, Node, PaneId, Rect};
use crate::terminal::layouts::{self, Layout};
use crate::terminal::links::{self, ClickMode, Link, Target};
use crate::terminal::pane::{GridSize, Pane};
use crate::terminal::search::Search;
use crate::ui::anim::Tween;
use crate::ui::overlay::{Command, Entry, Menu, MenuAction, MenuItem, Outcome, Overlay, Palette as CommandPalette};
use crate::ui::picker::{Choice, Picker};
use crate::ui::settings::{Page, Settings};
const RESIZE_DEBOUNCE: Duration = Duration::from_millis(60);
const LAYOUT_SECS: f32 = 0.22;
const FADE_IN_SECS: f32 = 0.18;
const FADE_OUT_SECS: f32 = 0.14;
const FOCUS_SECS: f32 = 0.16;
const BELL_SECS: f32 = 0.5;
pub const TOAST_SECS: Duration = Duration::from_millis(2200);
pub struct App {
proxy: EventLoopProxy<UserEvent>,
config: Config,
keymap: Keymap,
hotkey: Option<Hotkey>,
explicit_dir: bool,
startup_layout: Option<String>,
palette: Palette,
start_dir: Option<PathBuf>,
shell_env: Vec<(String, String)>,
install_hint: bool,
state: Option<State>,
}
pub struct State {
web: web::Views,
pub window: Arc<Window>,
pub gpu: Gpu,
pub glyphs: Glyphs,
pub scale: f32,
font_pt: f32,
pub panes: Vec<Pane>,
pub closing: Vec<Pane>,
layout: Node,
pub focused: PaneId,
next_id: PaneId,
mods: ModifiersState,
mouse: (f32, f32),
selecting: Option<PaneId>,
cmd_drag: Option<PaneId>,
mouse_reporting: Option<PaneId>,
last_click: Option<(Instant, u8, (f32, f32))>,
pub now: Instant,
pub blink_epoch: Instant,
pub window_focused: bool,
clipboard: Option<arboard::Clipboard>,
pub quads: Vec<Quad>,
pub multi: f32,
multi_anim: Tween<f32>,
last_focused: PaneId,
pub usage: Usage,
shown: bool,
wake_at: Option<Instant>,
pub window_title: String,
pub picker: Option<Picker>,
pub hover: Hit,
pub pressed: Hit,
last_title_click: Option<Instant>,
last_empty_backspace: Option<Instant>,
hover_link: Option<(PaneId, Link)>,
link_probe: Option<(PaneId, i32, usize, ClickMode)>,
link_press: Option<(PaneId, (f32, f32), Link)>,
pub overlay: Option<Overlay>,
pub zoomed: Option<PaneId>,
pub drop_hover: bool,
pub toast: Option<(String, Instant)>,
notice: Option<String>,
}
impl App {
pub fn new(
proxy: EventLoopProxy<UserEvent>,
config: Config,
start_dir: Option<PathBuf>,
explicit_dir: bool,
startup_layout: Option<String>,
) -> Self {
let palette = Palette::from_theme(&config.theme);
let shell_env = config.shell_env();
if shell_env.iter().any(|(k, _)| k == "RUSTIMAL_STATE")
&& let Some(dir) = crate::config::state_dir()
{
crate::platform::winenv::watch(dir.join("winpath"));
}
let install_hint = config.take_install_hint();
crate::config::watch(proxy.clone());
let hotkey = (!config.hotkey.trim().is_empty()).then(|| Hotkey::start(&config.hotkey, proxy.clone())).flatten();
let (keymap, problems) = Keymap::build(&config.keys);
for problem in problems {
log::warn!("{problem}");
}
Self {
proxy,
config,
keymap,
hotkey,
explicit_dir,
startup_layout,
palette,
start_dir,
shell_env,
install_hint,
state: None,
}
}
fn font_px(&self, pt: f32, scale: f32) -> f32 {
(pt * 96.0 / 72.0 * scale).round()
}
fn dur(&self, secs: f32) -> f32 {
if self.config.animation_speed <= 0.0 { 0.0 } else { secs / self.config.animation_speed }
}
fn focused_pane(&self) -> Option<&Pane> {
let st = self.state.as_ref()?;
st.panes.iter().find(|p| p.id == st.focused)
}
fn toast(&mut self, text: impl Into<String>) {
if let Some(st) = self.state.as_mut() {
st.toast = Some((text.into(), Instant::now()));
st.window.request_redraw();
}
}
}
impl ApplicationHandler<UserEvent> for App {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
if self.state.is_some() {
return;
}
let attrs = Window::default_attributes()
.with_title("rustimal")
.with_inner_size(LogicalSize::new(1180.0, 740.0))
.with_min_inner_size(LogicalSize::new(360.0, 220.0))
.with_theme(Some(winit::window::Theme::Dark))
.with_window_icon(window_icon(32))
.with_taskbar_icon(window_icon(64))
.with_decorations(false)
.with_undecorated_shadow(true)
.with_transparent(self.config.glass)
.with_no_redirection_bitmap(self.config.glass)
.with_visible(false);
let window = Arc::new(event_loop.create_window(attrs).expect("create window"));
window.set_cursor(CursorIcon::Text);
let scale = window.scale_factor() as f32;
let gpu = Gpu::new(window.clone(), self.config.glass);
if gpu.transparent && !crate::platform::glass::apply(&window) {
log::warn!("no blurred backdrop available");
}
let glyphs =
Glyphs::new(&self.config.font_family, self.font_px(self.config.font_size, scale), self.config.line_height);
let now = Instant::now();
let mut st = State {
web: web::Views::default(),
window,
gpu,
glyphs,
scale,
font_pt: self.config.font_size,
panes: Vec::new(),
closing: Vec::new(),
layout: Node::Leaf(1),
focused: 1,
next_id: 2,
mods: ModifiersState::empty(),
mouse: (0.0, 0.0),
selecting: None,
cmd_drag: None,
mouse_reporting: None,
last_click: None,
now,
blink_epoch: now,
window_focused: true,
clipboard: arboard::Clipboard::new().ok(),
quads: Vec::new(),
multi: 0.0,
multi_anim: Tween::new(0.0),
last_focused: 1,
usage: crate::config::state_dir().map(|d| Usage::load(&d.join("claude-usage.json"))).unwrap_or_default(),
shown: false,
wake_at: None,
window_title: String::new(),
picker: None,
hover: Hit::None,
pressed: Hit::None,
last_title_click: None,
last_empty_backspace: None,
overlay: None,
zoomed: None,
drop_hover: false,
toast: None,
hover_link: None,
link_probe: None,
link_press: None,
notice: None,
};
let mut restored = false;
if let Some(layout) = self.startup_layout() {
self.state = Some(st);
restored = self.apply_layout(layout, true);
st = self.state.take().unwrap();
}
if !restored {
st.layout = Node::Leaf(1);
st.next_id = st.next_id.max(2);
let target = self.target_rects(&st)[0].1;
if !self.spawn_pane(&mut st, 1, target, target, self.start_dir.clone()) {
event_loop.exit();
return;
}
st.panes[0].opacity_anim.snap(1.0);
st.panes[0].opacity = 1.0;
}
self.state = Some(st);
if cfg!(debug_assertions) {
let what = std::env::var("RUSTIMAL_OPEN").unwrap_or_default();
if let Some(args) = what.strip_prefix("review:") {
let dir = self.start_dir.clone().unwrap_or_default();
self.shell_review(1, dir, args);
} else if what == "palette" {
self.open_palette();
} else if what == "menu" {
let path = self.start_dir.clone().unwrap_or_default().join("src");
let link = Link { line: 0, start: 0, end: 3, target: Target::Entry { path, name: "src".into() } };
if let Some(st) = self.state.as_mut() {
st.mouse = (300.0, 200.0);
}
self.open_link_menu(1, &link);
} else if what == "toast" {
self.toast("Copied the last output (12 lines)");
} else if what == "t3" {
let dir = self.start_dir.clone().unwrap_or_default();
self.open_t3(1, dir, 1);
} else if let Some(command) = what.strip_prefix("embed:") {
self.debug_embed(command);
} else if what == "zoom" {
self.toggle_zoom();
} else if let Some(page) = what.strip_prefix("settings") {
self.open_settings();
let page = match page {
":theme" => Some(Page::Theme),
":shortcuts" => Some(Page::Shortcuts),
_ => None,
};
if let (Some(page), Some(Overlay::Settings(settings))) =
(page, self.state.as_mut().and_then(|st| st.overlay.as_mut()))
{
settings.show_page(page);
}
}
}
self.redraw();
}
fn exiting(&mut self, _: &ActiveEventLoop) {
if let Some(st) = self.state.as_ref() {
st.web.hosts.close_all();
}
self.autosave_session();
}
fn user_event(&mut self, event_loop: &ActiveEventLoop, event: UserEvent) {
match event {
UserEvent::Term(id, e) => self.handle_user_event(event_loop, id, e),
UserEvent::Hotkey => self.toggle_summon(),
UserEvent::ConfigChanged => self.reload_config(false),
UserEvent::Review(pane, message) => self.review_message(pane, *message),
UserEvent::T3Page { pane, dir, page } => self.t3_page(pane, dir, page),
UserEvent::WebMessage(pane, kind, message) => self.web_message(event_loop, pane, kind, &message),
UserEvent::T3Pairing { pane, link } => self.t3_pair_link(pane, link),
UserEvent::CodeReady { pane, request, server } => self.code_ready(pane, request, server),
UserEvent::HostKey(action) => self.host_key(event_loop, &action),
UserEvent::HostClick(x, y) => self.host_click(x, y),
UserEvent::Chat { pane, run, update } => self.chat_update(pane, run, update),
}
}
fn new_events(&mut self, _: &ActiveEventLoop, cause: StartCause) {
if let StartCause::ResumeTimeReached { .. } = cause
&& let Some(st) = self.state.as_mut()
{
st.wake_at = None;
st.window.request_redraw();
}
}
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
match self.state.as_ref().and_then(|s| s.wake_at) {
Some(t) => event_loop.set_control_flow(ControlFlow::WaitUntil(t)),
None => event_loop.set_control_flow(ControlFlow::Wait),
}
}
fn window_event(&mut self, event_loop: &ActiveEventLoop, _: WindowId, event: WindowEvent) {
if self.state.is_none() {
return;
}
match event {
WindowEvent::CloseRequested => event_loop.exit(),
WindowEvent::RedrawRequested => self.redraw(),
WindowEvent::Moved(_) => {
if let Some(st) = self.state.as_ref() {
st.web.window_moved();
st.window.request_redraw();
}
}
WindowEvent::Resized(size) => {
if let Some(st) = self.state.as_mut() {
st.gpu.resize(size.width, size.height);
crate::platform::glass::hide_caption_buttons(&st.window);
}
self.relayout(true, false);
}
WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
let Some(st) = self.state.as_mut() else { return };
st.scale = scale_factor as f32;
let pt = st.font_pt;
self.set_font_size(pt);
}
WindowEvent::Focused(focused) => self.on_focus(focused),
WindowEvent::ModifiersChanged(m) => {
self.state.as_mut().unwrap().mods = m.state();
self.update_link(false);
}
WindowEvent::KeyboardInput { event, is_synthetic: false, .. } => self.on_key(event_loop, event),
WindowEvent::CursorMoved { position, .. } => self.on_cursor_moved(position),
WindowEvent::MouseInput { state, button, .. } => self.on_mouse_button(event_loop, state, button),
WindowEvent::HoveredFile(_) => {
let st = self.state.as_mut().unwrap();
st.drop_hover = true;
st.window.request_redraw();
}
WindowEvent::HoveredFileCancelled => {
let st = self.state.as_mut().unwrap();
st.drop_hover = false;
st.window.request_redraw();
}
WindowEvent::DroppedFile(path) => {
self.state.as_mut().unwrap().drop_hover = false;
self.drop_path(&path);
}
WindowEvent::CursorLeft { .. } => {
let st = self.state.as_mut().unwrap();
if st.hover != Hit::None {
st.hover = Hit::None;
st.window.request_redraw();
}
}
WindowEvent::MouseWheel { delta, .. } => self.on_mouse_wheel(delta),
_ => {}
}
}
}
fn window_icon(size: u32) -> Option<Icon> {
Icon::from_rgba(crate::platform::icon::render(size), size, size).ok()
}