8828 lines
278 KiB
Rust
8828 lines
278 KiB
Rust
use std::cmp::Ordering;
|
||
use std::collections::{BTreeSet, HashMap, HashSet};
|
||
use std::path::{Path, PathBuf};
|
||
|
||
use serde::{Deserialize, Serialize};
|
||
|
||
use iced::time::{Duration, Instant};
|
||
use iced::widget::{Id, operation};
|
||
use iced::widget::{
|
||
button, checkbox, column, container, mouse_area, pick_list, responsive, row, rule, scrollable,
|
||
space, stack, text, text_input, toggler, tooltip,
|
||
};
|
||
use iced::{
|
||
Alignment, Animation, Border, Color, Element, Font, Length, Padding, Point, Rectangle, Shadow,
|
||
Size, Subscription, Task, Vector, font, keyboard, mouse, window,
|
||
};
|
||
|
||
mod notifications;
|
||
#[allow(dead_code)]
|
||
mod terminal;
|
||
mod theme;
|
||
|
||
const MENUBAR_HEIGHT: f32 = 40.0;
|
||
/// Tab width bounds and gap, used to fit as many tabs as the strip allows.
|
||
const TAB_MAX_WIDTH: f32 = 230.0;
|
||
const TAB_MIN_WIDTH: f32 = 100.0;
|
||
const TAB_SPACING: f32 = 2.0;
|
||
/// Space kept clear for the hamburger/close button at the end of the menubar.
|
||
const HAMBURGER_WIDTH: f32 = 32.0;
|
||
/// Fixed width of the two tab-strip scroll buttons.
|
||
const SCROLL_BUTTON_WIDTH: f32 = 32.0;
|
||
/// Left padding of the menubar, i.e. where the tab strip starts.
|
||
const TAB_STRIP_LEFT: f32 = 5.0;
|
||
/// Right padding of the menubar.
|
||
const MENUBAR_RIGHT_PADDING: f32 = 8.0;
|
||
/// How close to a tab-strip edge a drag must be before it auto-scrolls.
|
||
const DRAG_EDGE: f32 = 40.0;
|
||
/// Fastest auto-scroll speed while dragging, in pixels per frame.
|
||
const DRAG_SCROLL_SPEED: f32 = 16.0;
|
||
/// Size of the floating tab ghost shown while dragging.
|
||
const DRAG_GHOST_WIDTH: f32 = 190.0;
|
||
const DRAG_GHOST_HEIGHT: f32 = 30.0;
|
||
/// Layout of the in-window "move to window" drop panel.
|
||
const DROP_PANEL_WIDTH: f32 = 280.0;
|
||
const DROP_PANEL_PADDING: f32 = 6.0;
|
||
const DROP_HEADER_HEIGHT: f32 = 22.0;
|
||
const DROP_ROW_HEIGHT: f32 = 30.0;
|
||
const DROP_ROW_GAP: f32 = 2.0;
|
||
/// Longest tab title shown before it gets ellipsized.
|
||
const MAX_TAB_TITLE: usize = 20;
|
||
/// Fixed height for rows in the hamburger menu.
|
||
const MENU_ITEM_HEIGHT: f32 = 24.0;
|
||
/// Fixed height of the hamburger row inside the menu panel.
|
||
const HAMBURGER_ROW_HEIGHT: f32 = 24.0;
|
||
/// Panel padding of the hamburger menu.
|
||
const MENU_PADDING: f32 = 4.0;
|
||
/// Pixels moved per press of a tab-strip scroll button.
|
||
const TAB_SCROLL_STEP: f32 = 120.0;
|
||
/// Identifies the theme-name field so it can be focused when opened.
|
||
const THEME_NAME_INPUT: Id = Id::new("theme-name");
|
||
/// Identifies the new-folder name field so it can be focused when opened.
|
||
const FOLDER_NAME_INPUT: Id = Id::new("folder-name");
|
||
/// Identifies the new-profile name field so it can be focused when opened.
|
||
const PROFILE_NAME_INPUT: Id = Id::new("profile-name");
|
||
/// Folder shown for profiles that have not been put into a group.
|
||
const DEFAULT_PROFILE_FOLDER: &str = "Ungrouped";
|
||
|
||
fn main() -> iced::Result {
|
||
iced::daemon(boot, update, view)
|
||
.title(window_title)
|
||
.theme(|state: &Moorly, _window| state.theme.iced())
|
||
.subscription(subscription)
|
||
.run()
|
||
}
|
||
|
||
/// Opens the first window and gives it the Start tab when configured.
|
||
fn boot() -> (Moorly, Task<Message>) {
|
||
let mut state = Moorly::default();
|
||
let settings = window::Settings {
|
||
exit_on_close_request: false,
|
||
..window::Settings::default()
|
||
};
|
||
let size = settings.size;
|
||
let (id, task) = window::open(settings);
|
||
state
|
||
.windows
|
||
.insert(id, WindowState::new(state.show_start_tab, size));
|
||
state.window_order.push(id);
|
||
state.main_window = Some(id);
|
||
state.focused_window = Some(id);
|
||
(state, task.map(|_| Message::Ignore))
|
||
}
|
||
|
||
fn window_title(state: &Moorly, window: window::Id) -> String {
|
||
if state.main_window == Some(window) {
|
||
return "Moorly".to_owned();
|
||
}
|
||
|
||
match state
|
||
.windows
|
||
.get(&window)
|
||
.and_then(|state| state.active_tab)
|
||
{
|
||
Some(tab) => format!("{} - Moorly", tab.title()),
|
||
None => "Moorly".to_owned(),
|
||
}
|
||
}
|
||
|
||
/// Raw mouse events are needed for tab dragging and cross-window drops.
|
||
fn pointer_event(
|
||
event: iced::Event,
|
||
_status: iced::event::Status,
|
||
window: window::Id,
|
||
) -> Option<Message> {
|
||
match event {
|
||
iced::Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => {
|
||
Some(Message::PointerPressed(window))
|
||
}
|
||
iced::Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) => {
|
||
Some(Message::PointerReleased(window))
|
||
}
|
||
iced::Event::Mouse(mouse::Event::CursorMoved { position }) => {
|
||
Some(Message::PointerMoved(window, position))
|
||
}
|
||
iced::Event::Mouse(mouse::Event::CursorLeft) => Some(Message::PointerLeft(window)),
|
||
_ => None,
|
||
}
|
||
}
|
||
|
||
/// Key presses are captured by focused text inputs, so palette keys are
|
||
/// listened for globally instead of through `keyboard::listen`.
|
||
fn key_press_event(
|
||
event: iced::Event,
|
||
_status: iced::event::Status,
|
||
window: window::Id,
|
||
) -> Option<(keyboard::Key, keyboard::Modifiers, window::Id)> {
|
||
match event {
|
||
iced::Event::Keyboard(keyboard::Event::KeyPressed {
|
||
key,
|
||
modifiers,
|
||
repeat: false,
|
||
..
|
||
}) => Some((key, modifiers, window)),
|
||
_ => None,
|
||
}
|
||
}
|
||
|
||
fn palette_event(
|
||
event: iced::Event,
|
||
_status: iced::event::Status,
|
||
window: window::Id,
|
||
) -> Option<Message> {
|
||
let iced::Event::Keyboard(keyboard::Event::KeyPressed {
|
||
key, repeat: false, ..
|
||
}) = event
|
||
else {
|
||
return None;
|
||
};
|
||
|
||
match key {
|
||
keyboard::Key::Named(keyboard::key::Named::Escape) => {
|
||
Some(Message::CloseCommandPalette(window))
|
||
}
|
||
keyboard::Key::Named(keyboard::key::Named::ArrowUp) => {
|
||
Some(Message::CommandPaletteUp(window))
|
||
}
|
||
keyboard::Key::Named(keyboard::key::Named::ArrowDown) => {
|
||
Some(Message::CommandPaletteDown(window))
|
||
}
|
||
keyboard::Key::Named(keyboard::key::Named::Enter) => {
|
||
Some(Message::RunSelectedCommand(window))
|
||
}
|
||
_ => None,
|
||
}
|
||
}
|
||
|
||
fn subscription(state: &Moorly) -> Subscription<Message> {
|
||
let active_window = state.focused_window.or(state.main_window);
|
||
let keyboard = keyboard::listen()
|
||
.with((
|
||
state.saved_shortcuts.settings.clone(),
|
||
state.saved_shortcuts.quit.clone(),
|
||
state.shortcut_capture.is_some(),
|
||
active_window,
|
||
))
|
||
.filter_map(
|
||
|((settings_shortcut, quit_shortcut, capturing, window), event)| {
|
||
let keyboard::Event::KeyPressed {
|
||
key,
|
||
modifiers,
|
||
repeat: false,
|
||
..
|
||
} = event
|
||
else {
|
||
return None;
|
||
};
|
||
|
||
if capturing {
|
||
return Some(Message::CaptureKey { key, modifiers });
|
||
}
|
||
|
||
if quit_shortcut
|
||
.as_ref()
|
||
.is_some_and(|shortcut| shortcut.matches(&key, modifiers))
|
||
{
|
||
return Some(Message::Quit);
|
||
}
|
||
|
||
if let Some(shortcut) = &settings_shortcut {
|
||
if shortcut.matches(&key, modifiers) {
|
||
return window.map(|window| Message::SelectTab(window, Tab::Settings));
|
||
}
|
||
}
|
||
|
||
match key {
|
||
keyboard::Key::Character(key)
|
||
if cfg!(debug_assertions)
|
||
&& key.eq_ignore_ascii_case("t")
|
||
&& modifiers.control()
|
||
&& modifiers.shift() =>
|
||
{
|
||
window.map(Message::AddTab)
|
||
}
|
||
keyboard::Key::Character(key)
|
||
if cfg!(debug_assertions)
|
||
&& key.eq_ignore_ascii_case("n")
|
||
&& modifiers.control()
|
||
&& modifiers.shift() =>
|
||
{
|
||
Some(Message::ShowNotificationDemo)
|
||
}
|
||
keyboard::Key::Character(key)
|
||
if key.eq_ignore_ascii_case("w")
|
||
&& modifiers.control()
|
||
&& modifiers.shift() =>
|
||
{
|
||
window.map(Message::CloseActiveTab)
|
||
}
|
||
_ => None,
|
||
}
|
||
},
|
||
);
|
||
|
||
// Keep frames coming until the fade-out has been swapped for the new
|
||
// section or the tab close icons have finished fading.
|
||
let now = Instant::now();
|
||
let tab_close_animating = state
|
||
.tab_close_fades
|
||
.values()
|
||
.any(|animation| animation.is_animating(now));
|
||
|
||
let palette_shortcut = iced::event::listen_with(key_press_event)
|
||
.with((
|
||
state.saved_shortcuts.command_palette.clone(),
|
||
state.shortcut_capture.is_some(),
|
||
))
|
||
.filter_map(|((shortcut, capturing), (key, modifiers, window))| {
|
||
(!capturing
|
||
&& shortcut
|
||
.as_ref()
|
||
.is_some_and(|shortcut| shortcut.matches(&key, modifiers)))
|
||
.then_some(Message::ToggleCommandPalette(window))
|
||
});
|
||
|
||
let mut subscriptions = vec![
|
||
keyboard,
|
||
palette_shortcut,
|
||
iced::time::every(Duration::from_secs(1)).map(|_| Message::ReloadThemes),
|
||
window::events().map(|(window, event)| Message::WindowEvent(window, event)),
|
||
iced::event::listen_with(pointer_event),
|
||
iced::event::listen_with(palette_event),
|
||
];
|
||
|
||
if state.drag.is_some() {
|
||
subscriptions.push(iced::time::every(Duration::from_millis(16)).map(|_| Message::DragTick));
|
||
}
|
||
|
||
if state.fade_animation.is_animating(now)
|
||
|| state.pending_settings_section.is_some()
|
||
|| tab_close_animating
|
||
{
|
||
subscriptions.push(window::frames().map(Message::Frame));
|
||
}
|
||
|
||
// Timed notifications only need a coarse expiry timer; fades use frames.
|
||
if state.notifications.has_timed() {
|
||
subscriptions
|
||
.push(iced::time::every(Duration::from_millis(250)).map(Message::NotificationTick));
|
||
}
|
||
|
||
if state.notifications.is_animating(now) {
|
||
subscriptions.push(window::frames().map(Message::NotificationTick));
|
||
}
|
||
|
||
Subscription::batch(subscriptions)
|
||
}
|
||
|
||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||
struct Shortcut {
|
||
control: bool,
|
||
shift: bool,
|
||
alt: bool,
|
||
key: String,
|
||
}
|
||
|
||
impl Shortcut {
|
||
/// Parses text like `Ctrl+Shift+K` into a shortcut. Unknown modifiers and
|
||
/// missing keys are rejected.
|
||
fn parse(input: &str) -> Option<Self> {
|
||
let parts: Vec<&str> = input
|
||
.split('+')
|
||
.map(str::trim)
|
||
.filter(|part| !part.is_empty())
|
||
.collect();
|
||
let (key, modifiers) = parts.split_last()?;
|
||
|
||
// Only single-character keys and Space are supported for now.
|
||
let key = if key.eq_ignore_ascii_case("space") {
|
||
"space".to_owned()
|
||
} else if key.chars().count() == 1 {
|
||
key.to_ascii_lowercase()
|
||
} else {
|
||
return None;
|
||
};
|
||
|
||
let mut shortcut = Self {
|
||
control: false,
|
||
shift: false,
|
||
alt: false,
|
||
key,
|
||
};
|
||
|
||
for modifier in modifiers {
|
||
match modifier.to_ascii_lowercase().as_str() {
|
||
"ctrl" | "control" => shortcut.control = true,
|
||
"shift" => shortcut.shift = true,
|
||
"alt" => shortcut.alt = true,
|
||
_ => return None,
|
||
}
|
||
}
|
||
|
||
Some(shortcut)
|
||
}
|
||
|
||
fn matches(&self, key: &keyboard::Key, modifiers: keyboard::Modifiers) -> bool {
|
||
self.control == modifiers.control()
|
||
&& self.shift == modifiers.shift()
|
||
&& self.alt == modifiers.alt()
|
||
&& key_name(key).is_some_and(|name| name == self.key)
|
||
}
|
||
|
||
/// Builds a shortcut from a captured key press. Plain keys are rejected so
|
||
/// a shortcut cannot hijack ordinary typing.
|
||
fn from_key(key: &keyboard::Key, modifiers: keyboard::Modifiers) -> Option<Self> {
|
||
if !(modifiers.control() || modifiers.alt()) {
|
||
return None;
|
||
}
|
||
|
||
Some(Self {
|
||
control: modifiers.control(),
|
||
shift: modifiers.shift(),
|
||
alt: modifiers.alt(),
|
||
key: key_name(key)?,
|
||
})
|
||
}
|
||
|
||
fn key_label(&self) -> String {
|
||
if self.key == "space" {
|
||
return "Space".to_owned();
|
||
}
|
||
|
||
let is_letter = self.key.chars().count() == 1
|
||
&& self.key.chars().next().is_some_and(char::is_alphabetic);
|
||
|
||
if is_letter {
|
||
self.key.to_ascii_uppercase()
|
||
} else {
|
||
self.key.clone()
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Normalized name of a key that shortcuts can bind to.
|
||
fn key_name(key: &keyboard::Key) -> Option<String> {
|
||
match key {
|
||
keyboard::Key::Character(key) => Some(key.as_str().to_ascii_lowercase()),
|
||
keyboard::Key::Named(keyboard::key::Named::Space) => Some("space".to_owned()),
|
||
_ => None,
|
||
}
|
||
}
|
||
|
||
impl std::fmt::Display for Shortcut {
|
||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||
let mut parts = Vec::new();
|
||
if self.control {
|
||
parts.push("Ctrl".to_owned());
|
||
}
|
||
if self.shift {
|
||
parts.push("Shift".to_owned());
|
||
}
|
||
if self.alt {
|
||
parts.push("Alt".to_owned());
|
||
}
|
||
parts.push(self.key_label());
|
||
|
||
f.write_str(&parts.join("+"))
|
||
}
|
||
}
|
||
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
enum ShortcutAction {
|
||
Settings,
|
||
Quit,
|
||
CommandPalette,
|
||
}
|
||
|
||
impl ShortcutAction {
|
||
fn label(self) -> &'static str {
|
||
match self {
|
||
Self::Settings => "Settings",
|
||
Self::Quit => "Quit",
|
||
Self::CommandPalette => "Command palette",
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||
struct Shortcuts {
|
||
settings: Option<Shortcut>,
|
||
quit: Option<Shortcut>,
|
||
command_palette: Option<Shortcut>,
|
||
}
|
||
|
||
impl Default for Shortcuts {
|
||
fn default() -> Self {
|
||
Self {
|
||
settings: Shortcut::parse("Ctrl+,"),
|
||
quit: Shortcut::parse("Ctrl+Shift+Q"),
|
||
command_palette: Shortcut::parse("Ctrl+Shift+Space"),
|
||
}
|
||
}
|
||
}
|
||
|
||
impl Shortcuts {
|
||
fn get(&self, action: ShortcutAction) -> Option<&Shortcut> {
|
||
match action {
|
||
ShortcutAction::Settings => self.settings.as_ref(),
|
||
ShortcutAction::Quit => self.quit.as_ref(),
|
||
ShortcutAction::CommandPalette => self.command_palette.as_ref(),
|
||
}
|
||
}
|
||
|
||
fn set(&mut self, action: ShortcutAction, shortcut: Option<Shortcut>) {
|
||
match action {
|
||
ShortcutAction::Settings => self.settings = shortcut,
|
||
ShortcutAction::Quit => self.quit = shortcut,
|
||
ShortcutAction::CommandPalette => self.command_palette = shortcut,
|
||
}
|
||
}
|
||
|
||
/// Name of another action already bound to `candidate`, if any. `except`
|
||
/// is the action being rebound, which must not conflict with itself.
|
||
fn conflict(&self, candidate: &Shortcut, except: ShortcutAction) -> Option<&'static str> {
|
||
let configurable = [
|
||
(ShortcutAction::Settings, &self.settings),
|
||
(ShortcutAction::Quit, &self.quit),
|
||
(ShortcutAction::CommandPalette, &self.command_palette),
|
||
];
|
||
if let Some((action, _)) = configurable
|
||
.iter()
|
||
.find(|(action, shortcut)| *action != except && shortcut.as_ref() == Some(candidate))
|
||
{
|
||
return Some(action.label());
|
||
}
|
||
|
||
// Shortcuts that are fixed for now but still own their keys.
|
||
let reserved: &[(&str, &str)] = if cfg!(debug_assertions) {
|
||
&[
|
||
("Close Active Tab", "Ctrl+Shift+W"),
|
||
("Add Tab", "Ctrl+Shift+T"),
|
||
]
|
||
} else {
|
||
&[("Close Active Tab", "Ctrl+Shift+W")]
|
||
};
|
||
|
||
reserved.iter().find_map(|(name, text)| {
|
||
(Shortcut::parse(text).as_ref() == Some(candidate)).then_some(*name)
|
||
})
|
||
}
|
||
}
|
||
|
||
/// Keys picked so far while rebinding a shortcut.
|
||
#[derive(Debug, Clone)]
|
||
struct ShortcutCapture {
|
||
action: ShortcutAction,
|
||
candidate: Option<Shortcut>,
|
||
error: Option<String>,
|
||
}
|
||
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||
#[serde(rename_all = "lowercase")]
|
||
enum ProfileKind {
|
||
#[default]
|
||
Ssh,
|
||
Terminal,
|
||
PowerShell,
|
||
}
|
||
|
||
impl ProfileKind {
|
||
const ALL: [Self; 3] = [Self::Ssh, Self::Terminal, Self::PowerShell];
|
||
|
||
fn label(self) -> &'static str {
|
||
match self {
|
||
Self::Ssh => "SSH",
|
||
Self::Terminal => "Terminal",
|
||
Self::PowerShell => "PowerShell",
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||
#[serde(rename_all = "lowercase")]
|
||
enum SessionEnd {
|
||
#[default]
|
||
Auto,
|
||
Keep,
|
||
Reconnect,
|
||
Close,
|
||
}
|
||
|
||
impl SessionEnd {
|
||
const ALL: [Self; 4] = [Self::Auto, Self::Keep, Self::Reconnect, Self::Close];
|
||
|
||
fn label(self) -> &'static str {
|
||
match self {
|
||
Self::Auto => "Auto",
|
||
Self::Keep => "Keep",
|
||
Self::Reconnect => "Reconnect",
|
||
Self::Close => "Close",
|
||
}
|
||
}
|
||
}
|
||
|
||
impl std::fmt::Display for SessionEnd {
|
||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||
f.write_str(self.label())
|
||
}
|
||
}
|
||
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||
#[serde(rename_all = "lowercase")]
|
||
enum AuthMethod {
|
||
#[default]
|
||
Password,
|
||
Key,
|
||
Agent,
|
||
Interactive,
|
||
}
|
||
|
||
impl AuthMethod {
|
||
const ALL: [Self; 4] = [Self::Password, Self::Key, Self::Agent, Self::Interactive];
|
||
|
||
fn label(self) -> &'static str {
|
||
match self {
|
||
Self::Password => "Password",
|
||
Self::Key => "Key",
|
||
Self::Agent => "Agent",
|
||
Self::Interactive => "Interactive",
|
||
}
|
||
}
|
||
|
||
fn glyph(self) -> &'static str {
|
||
match self {
|
||
Self::Password => "🔑",
|
||
Self::Key => "🗝",
|
||
Self::Agent => "🤖",
|
||
Self::Interactive => "⌨",
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Debug, Clone)]
|
||
#[allow(dead_code)] // Stored for when profiles can actually start sessions.
|
||
struct Profile {
|
||
name: String,
|
||
kind: ProfileKind,
|
||
session_end: SessionEnd,
|
||
host: String,
|
||
port: String,
|
||
username: String,
|
||
auth: AuthMethod,
|
||
password: String,
|
||
start_path: String,
|
||
private_key: String,
|
||
/// File this profile was loaded from or saved to.
|
||
file: Option<PathBuf>,
|
||
}
|
||
|
||
/// Editable state of the "add profile" dialog.
|
||
#[derive(Debug, Clone)]
|
||
struct ProfileDraft {
|
||
name: String,
|
||
folder: usize,
|
||
kind: ProfileKind,
|
||
session_end: SessionEnd,
|
||
host: String,
|
||
port: String,
|
||
username: String,
|
||
auth: AuthMethod,
|
||
password: String,
|
||
password_visible: bool,
|
||
start_path: String,
|
||
private_key: String,
|
||
}
|
||
|
||
impl ProfileDraft {
|
||
fn new(folder: usize) -> Self {
|
||
Self {
|
||
name: String::new(),
|
||
folder,
|
||
kind: ProfileKind::default(),
|
||
session_end: SessionEnd::default(),
|
||
host: String::new(),
|
||
port: "22".to_owned(),
|
||
username: String::new(),
|
||
auth: AuthMethod::default(),
|
||
password: String::new(),
|
||
password_visible: false,
|
||
start_path: default_start_path(),
|
||
private_key: String::new(),
|
||
}
|
||
}
|
||
|
||
fn port_valid(&self) -> bool {
|
||
match self.kind {
|
||
ProfileKind::Ssh => self.port.parse::<u32>().is_ok_and(|port| port <= 65534),
|
||
_ => true,
|
||
}
|
||
}
|
||
|
||
fn valid(&self) -> bool {
|
||
!self.name.trim().is_empty() && self.port_valid()
|
||
}
|
||
}
|
||
|
||
/// An entry in the folder drop-down.
|
||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||
struct FolderChoice {
|
||
index: usize,
|
||
name: String,
|
||
}
|
||
|
||
impl std::fmt::Display for FolderChoice {
|
||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||
f.write_str(&self.name)
|
||
}
|
||
}
|
||
|
||
/// Which profile field a path picker is filling.
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
enum PickerTarget {
|
||
StartPath,
|
||
PrivateKey,
|
||
}
|
||
|
||
/// In-app path browser state. In folder mode only directories are listed and
|
||
/// the current directory can be chosen; in file mode files are listed too.
|
||
#[derive(Debug, Clone)]
|
||
struct DirPicker {
|
||
path: PathBuf,
|
||
entries: Vec<PathBuf>,
|
||
selected: Option<PathBuf>,
|
||
files: bool,
|
||
target: PickerTarget,
|
||
error: Option<String>,
|
||
}
|
||
|
||
impl DirPicker {
|
||
fn open(path: PathBuf, files: bool, target: PickerTarget) -> Self {
|
||
let mut picker = Self {
|
||
path,
|
||
entries: Vec::new(),
|
||
selected: None,
|
||
files,
|
||
target,
|
||
error: None,
|
||
};
|
||
picker.reload();
|
||
picker
|
||
}
|
||
|
||
fn reload(&mut self) {
|
||
match std::fs::read_dir(&self.path) {
|
||
Ok(read) => {
|
||
let mut directories = Vec::new();
|
||
let mut files = Vec::new();
|
||
|
||
for entry in read.filter_map(|entry| entry.ok()) {
|
||
let path = entry.path();
|
||
if path.is_dir() {
|
||
directories.push(path);
|
||
} else if self.files {
|
||
files.push(path);
|
||
}
|
||
}
|
||
|
||
directories.sort();
|
||
files.sort();
|
||
self.entries = directories;
|
||
self.entries.extend(files);
|
||
self.selected = None;
|
||
self.error = None;
|
||
}
|
||
Err(error) => {
|
||
self.entries.clear();
|
||
self.selected = None;
|
||
self.error = Some(error.to_string());
|
||
}
|
||
}
|
||
}
|
||
|
||
fn navigate(&mut self, path: PathBuf) {
|
||
self.path = path;
|
||
self.reload();
|
||
}
|
||
|
||
fn can_confirm(&self) -> bool {
|
||
!self.files || self.selected.is_some()
|
||
}
|
||
}
|
||
|
||
fn home_dir() -> PathBuf {
|
||
if cfg!(windows) {
|
||
std::env::var_os("USERPROFILE")
|
||
.map(PathBuf::from)
|
||
.or_else(|| {
|
||
let drive = std::env::var_os("HOMEDRIVE")?;
|
||
let path = std::env::var_os("HOMEPATH")?;
|
||
let mut home = PathBuf::from(drive);
|
||
home.push(path);
|
||
Some(home)
|
||
})
|
||
.unwrap_or_else(|| PathBuf::from("C:\\"))
|
||
} else {
|
||
std::env::var_os("HOME")
|
||
.map(PathBuf::from)
|
||
.unwrap_or_else(|| PathBuf::from("/"))
|
||
}
|
||
}
|
||
|
||
fn default_start_path() -> String {
|
||
if cfg!(windows) {
|
||
std::env::var("HOMEPATH").unwrap_or_else(|_| home_dir().to_string_lossy().into_owned())
|
||
} else {
|
||
"~/".to_owned()
|
||
}
|
||
}
|
||
|
||
/// Resolves a typed path, expanding `~` to the home directory.
|
||
fn resolve_start_path(input: &str) -> PathBuf {
|
||
let input = input.trim();
|
||
|
||
if input.is_empty() || input == "~" {
|
||
return home_dir();
|
||
}
|
||
|
||
if let Some(rest) = input
|
||
.strip_prefix("~/")
|
||
.or_else(|| input.strip_prefix("~\\"))
|
||
{
|
||
return home_dir().join(rest);
|
||
}
|
||
|
||
PathBuf::from(input)
|
||
}
|
||
|
||
/// A named group of profiles. Folders form a tree through slash-separated
|
||
/// paths such as `Work/Production`, which keeps selection index-based.
|
||
#[derive(Debug, Clone)]
|
||
struct ProfileFolder {
|
||
/// Slash-separated path from the root, e.g. `Work/Production`.
|
||
path: String,
|
||
name: String,
|
||
profiles: Vec<Profile>,
|
||
expanded: bool,
|
||
/// True when a profile references this folder but it is not listed in
|
||
/// `folders.toml`; such folders only exist for this run.
|
||
untracked: bool,
|
||
}
|
||
|
||
impl ProfileFolder {
|
||
fn default_folder() -> Self {
|
||
Self::from_path(DEFAULT_PROFILE_FOLDER.to_owned())
|
||
}
|
||
|
||
fn from_path(path: String) -> Self {
|
||
let name = path
|
||
.rsplit('/')
|
||
.next()
|
||
.filter(|name| !name.is_empty())
|
||
.unwrap_or(DEFAULT_PROFILE_FOLDER)
|
||
.to_owned();
|
||
|
||
Self {
|
||
path,
|
||
name,
|
||
profiles: Vec::new(),
|
||
expanded: true,
|
||
untracked: false,
|
||
}
|
||
}
|
||
|
||
fn depth(&self) -> usize {
|
||
if self.path == DEFAULT_PROFILE_FOLDER {
|
||
0
|
||
} else {
|
||
self.path.split('/').count().saturating_sub(1)
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Contents of `profiles/folders.toml`.
|
||
#[derive(Debug, Serialize, Deserialize)]
|
||
struct FoldersFile {
|
||
#[serde(default)]
|
||
folders: Vec<String>,
|
||
}
|
||
|
||
/// One `profiles/<name>.toml` file.
|
||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||
struct ProfileFile {
|
||
#[serde(default)]
|
||
name: String,
|
||
#[serde(default)]
|
||
folder: String,
|
||
#[serde(default)]
|
||
kind: ProfileKind,
|
||
#[serde(default)]
|
||
session_end: SessionEnd,
|
||
#[serde(default)]
|
||
host: String,
|
||
#[serde(default = "default_profile_port")]
|
||
port: String,
|
||
#[serde(default)]
|
||
username: String,
|
||
#[serde(default)]
|
||
auth: AuthMethod,
|
||
#[serde(default)]
|
||
password: String,
|
||
#[serde(default)]
|
||
start_path: String,
|
||
#[serde(default)]
|
||
private_key: String,
|
||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||
trash: Option<TrashInfo>,
|
||
}
|
||
|
||
/// Metadata added to a profile file after it is moved to `.trash`.
|
||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||
struct TrashInfo {
|
||
#[serde(default)]
|
||
previous_path: String,
|
||
#[serde(default)]
|
||
deleted: String,
|
||
}
|
||
|
||
/// One deleted folder recorded in `.trash/folders.toml`.
|
||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||
struct TrashFolder {
|
||
name: String,
|
||
#[serde(default)]
|
||
previous_path: String,
|
||
#[serde(default)]
|
||
deleted: String,
|
||
}
|
||
|
||
#[derive(Debug, Default, Serialize, Deserialize)]
|
||
struct TrashFoldersFile {
|
||
#[serde(default)]
|
||
folders: Vec<TrashFolder>,
|
||
}
|
||
|
||
#[derive(Debug, Clone)]
|
||
enum TrashEntry {
|
||
Folder(TrashFolder),
|
||
Profile { file: PathBuf, profile: ProfileFile },
|
||
}
|
||
|
||
impl TrashEntry {
|
||
fn name(&self) -> &str {
|
||
match self {
|
||
Self::Folder(folder) => &folder.name,
|
||
Self::Profile { profile, .. } => &profile.name,
|
||
}
|
||
}
|
||
|
||
fn previous_path(&self) -> &str {
|
||
match self {
|
||
Self::Folder(folder) => &folder.previous_path,
|
||
Self::Profile { profile, .. } => profile
|
||
.trash
|
||
.as_ref()
|
||
.map(|trash| trash.previous_path.as_str())
|
||
.unwrap_or_default(),
|
||
}
|
||
}
|
||
|
||
fn deleted(&self) -> &str {
|
||
match self {
|
||
Self::Folder(folder) => &folder.deleted,
|
||
Self::Profile { profile, .. } => profile
|
||
.trash
|
||
.as_ref()
|
||
.map(|trash| trash.deleted.as_str())
|
||
.unwrap_or_default(),
|
||
}
|
||
}
|
||
|
||
fn is_folder(&self) -> bool {
|
||
matches!(self, Self::Folder(_))
|
||
}
|
||
}
|
||
|
||
impl ProfileFile {
|
||
fn from_profile(profile: &Profile, folder: &str) -> Self {
|
||
Self {
|
||
name: profile.name.clone(),
|
||
folder: folder.to_owned(),
|
||
kind: profile.kind,
|
||
session_end: profile.session_end,
|
||
host: profile.host.clone(),
|
||
port: profile.port.clone(),
|
||
username: profile.username.clone(),
|
||
auth: profile.auth,
|
||
password: profile.password.clone(),
|
||
start_path: profile.start_path.clone(),
|
||
private_key: profile.private_key.clone(),
|
||
trash: None,
|
||
}
|
||
}
|
||
|
||
fn into_profile(self) -> Profile {
|
||
Profile {
|
||
name: self.name.trim().to_owned(),
|
||
kind: self.kind,
|
||
session_end: self.session_end,
|
||
host: self.host.trim().to_owned(),
|
||
port: self.port,
|
||
username: self.username.trim().to_owned(),
|
||
auth: self.auth,
|
||
password: self.password,
|
||
start_path: self.start_path,
|
||
private_key: self.private_key,
|
||
file: None,
|
||
}
|
||
}
|
||
}
|
||
|
||
fn default_profile_port() -> String {
|
||
"22".to_owned()
|
||
}
|
||
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||
enum Selection {
|
||
Folder(usize),
|
||
Profile { folder: usize, profile: usize },
|
||
}
|
||
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
enum TransferMode {
|
||
Copy,
|
||
Move,
|
||
}
|
||
|
||
impl TransferMode {
|
||
fn label(self) -> &'static str {
|
||
match self {
|
||
Self::Copy => "Copy to",
|
||
Self::Move => "Move to",
|
||
}
|
||
}
|
||
|
||
fn action(self) -> &'static str {
|
||
match self {
|
||
Self::Copy => "Copy",
|
||
Self::Move => "Move",
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Debug, Clone)]
|
||
struct TransferDialog {
|
||
mode: TransferMode,
|
||
destination: usize,
|
||
}
|
||
|
||
/// Actions offered by the command palette.
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
enum Command {
|
||
Settings,
|
||
Close,
|
||
Move,
|
||
MoveToWindow(window::Id),
|
||
FocusWindow(window::Id),
|
||
FocusTab(window::Id, Tab),
|
||
Exit,
|
||
}
|
||
|
||
impl Command {
|
||
const ALL: [Self; 4] = [Self::Settings, Self::Close, Self::Move, Self::Exit];
|
||
|
||
fn label(&self, state: &Moorly) -> String {
|
||
match self {
|
||
Self::Settings => "Settings".to_owned(),
|
||
Self::Close => "Close".to_owned(),
|
||
Self::Move => "Move".to_owned(),
|
||
Self::MoveToWindow(id) | Self::FocusWindow(id) => window_title(state, *id),
|
||
Self::FocusTab(_, tab) => tab.title(),
|
||
Self::Exit => "Exit".to_owned(),
|
||
}
|
||
}
|
||
|
||
fn description(&self, state: &Moorly) -> String {
|
||
match self {
|
||
Self::Settings => "Opens the settings tab".to_owned(),
|
||
Self::Close => "Closes the active tab".to_owned(),
|
||
Self::Move => "Moves the active tab to a new window".to_owned(),
|
||
Self::MoveToWindow(id) => {
|
||
format!("Moves the active tab to {}", window_title(state, *id))
|
||
}
|
||
Self::FocusWindow(_) => "Focuses this window".to_owned(),
|
||
Self::FocusTab(id, _) => {
|
||
format!("Focuses this tab in {}", window_title(state, *id))
|
||
}
|
||
Self::Exit => "Quits the program".to_owned(),
|
||
}
|
||
}
|
||
|
||
fn matching(state: &Moorly, source: window::Id, query: &str) -> Vec<Self> {
|
||
let mut commands: Vec<Self> = Self::ALL
|
||
.into_iter()
|
||
.filter(|command| fuzzy_match(&command.label(state), query))
|
||
.collect();
|
||
|
||
for id in &state.window_order {
|
||
let Some(window_state) = state.windows.get(id) else {
|
||
continue;
|
||
};
|
||
|
||
if *id != source && fuzzy_match(&window_title(state, *id), query) {
|
||
commands.push(Self::FocusWindow(*id));
|
||
}
|
||
|
||
commands.extend(
|
||
window_state
|
||
.tabs
|
||
.iter()
|
||
.filter(|tab| fuzzy_match(&tab.title(), query))
|
||
.map(|tab| Self::FocusTab(*id, *tab)),
|
||
);
|
||
}
|
||
|
||
// While Move matches, offer every other window as a destination.
|
||
if commands.contains(&Self::Move) {
|
||
commands.extend(
|
||
drop_targets(state, source)
|
||
.into_iter()
|
||
.map(|(id, _)| Self::MoveToWindow(id)),
|
||
);
|
||
}
|
||
|
||
commands
|
||
}
|
||
}
|
||
|
||
/// Case-insensitive subsequence match, so `stg` finds `Settings`.
|
||
fn fuzzy_match(haystack: &str, needle: &str) -> bool {
|
||
let needle = needle.trim();
|
||
if needle.is_empty() {
|
||
return true;
|
||
}
|
||
|
||
let mut haystack = haystack.chars().flat_map(char::to_lowercase);
|
||
needle
|
||
.chars()
|
||
.flat_map(char::to_lowercase)
|
||
.all(|needle| haystack.any(|haystack| haystack == needle))
|
||
}
|
||
|
||
/// Per-window UI state: tabs, menus and tab-strip scrolling.
|
||
struct WindowState {
|
||
tabs: Vec<Tab>,
|
||
active_tab: Option<Tab>,
|
||
menu_open: bool,
|
||
tabs_submenu_open: bool,
|
||
command_palette_open: bool,
|
||
command_palette_query: String,
|
||
command_palette_selected: usize,
|
||
command_palette_input: Id,
|
||
tab_offset: f32,
|
||
scroll_id: Id,
|
||
size: Size,
|
||
position: Option<Point>,
|
||
pointer: Option<Point>,
|
||
}
|
||
|
||
impl WindowState {
|
||
fn new(show_start_tab: bool, size: Size) -> Self {
|
||
Self {
|
||
tabs: if show_start_tab {
|
||
vec![Tab::Start]
|
||
} else {
|
||
Vec::new()
|
||
},
|
||
active_tab: show_start_tab.then_some(Tab::Start),
|
||
menu_open: false,
|
||
tabs_submenu_open: false,
|
||
command_palette_open: false,
|
||
command_palette_query: String::new(),
|
||
command_palette_selected: 0,
|
||
command_palette_input: Id::unique(),
|
||
tab_offset: 0.0,
|
||
scroll_id: Id::unique(),
|
||
size,
|
||
position: None,
|
||
pointer: None,
|
||
}
|
||
}
|
||
|
||
fn with_tab(tab: Tab, size: Size, position: Option<Point>) -> Self {
|
||
Self {
|
||
tabs: vec![tab],
|
||
active_tab: Some(tab),
|
||
menu_open: false,
|
||
tabs_submenu_open: false,
|
||
command_palette_open: false,
|
||
command_palette_query: String::new(),
|
||
command_palette_selected: 0,
|
||
command_palette_input: Id::unique(),
|
||
tab_offset: 0.0,
|
||
scroll_id: Id::unique(),
|
||
size,
|
||
position,
|
||
pointer: None,
|
||
}
|
||
}
|
||
}
|
||
|
||
/// A tab currently being dragged. `pointer` is in the source window's
|
||
/// coordinates and may leave the window while the button is held.
|
||
struct TabDrag {
|
||
window: window::Id,
|
||
tab: Tab,
|
||
origin: Point,
|
||
pointer: Point,
|
||
moved: bool,
|
||
detach: bool,
|
||
}
|
||
|
||
struct Moorly {
|
||
windows: HashMap<window::Id, WindowState>,
|
||
window_order: Vec<window::Id>,
|
||
main_window: Option<window::Id>,
|
||
focused_window: Option<window::Id>,
|
||
drag: Option<TabDrag>,
|
||
theme: theme::Preference,
|
||
saved_theme: theme::Preference,
|
||
theme_choice: ThemeChoice,
|
||
saved_theme_choice: ThemeChoice,
|
||
custom_themes: Vec<CustomTheme>,
|
||
theme_name_dialog: Option<String>,
|
||
theme_signature: Vec<(String, u64)>,
|
||
shortcuts: Shortcuts,
|
||
saved_shortcuts: Shortcuts,
|
||
shortcut_capture: Option<ShortcutCapture>,
|
||
settings_section: SettingsSection,
|
||
pending_settings_section: Option<SettingsSection>,
|
||
show_start_tab: bool,
|
||
show_start_tab_draft: bool,
|
||
fade_settings: bool,
|
||
fade_settings_draft: bool,
|
||
hide_tab_close: bool,
|
||
hide_tab_close_draft: bool,
|
||
advanced_open: bool,
|
||
colors: [Color; 5],
|
||
saved_colors: [Color; 5],
|
||
custom_toasts: bool,
|
||
toast_colors: [Color; 9],
|
||
builtin_custom_toasts: bool,
|
||
builtin_toast_colors: [Color; 9],
|
||
open_color_picker: Option<ColorOption>,
|
||
open_toast_color_picker: Option<ToastColorOption>,
|
||
fade_animation: Animation<bool>,
|
||
hovered_tab: Option<Tab>,
|
||
tab_close_fades: HashMap<Tab, Animation<bool>>,
|
||
profile_filter: String,
|
||
profile_folders: Vec<ProfileFolder>,
|
||
selected: Option<Selection>,
|
||
checked: HashSet<Selection>,
|
||
trash_open: bool,
|
||
trash_entries: Vec<TrashEntry>,
|
||
trash_checked: HashSet<usize>,
|
||
transfer: Option<TransferDialog>,
|
||
confirm_delete: bool,
|
||
hovered_folder: Option<usize>,
|
||
add_menu_open: bool,
|
||
folder_dialog: Option<String>,
|
||
profile_dialog: Option<ProfileDraft>,
|
||
dir_picker: Option<DirPicker>,
|
||
next_blank_tab: u32,
|
||
notifications: notifications::NotificationManager,
|
||
}
|
||
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||
enum Tab {
|
||
Start,
|
||
Settings,
|
||
Blank(u32),
|
||
}
|
||
|
||
impl Tab {
|
||
fn title(self) -> String {
|
||
match self {
|
||
Self::Start => "Start".to_owned(),
|
||
Self::Settings => "Settings".to_owned(),
|
||
Self::Blank(number) => format!("temp {number}"),
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
enum ColorOption {
|
||
Accent,
|
||
ActiveTabOutline,
|
||
MainBackground,
|
||
SidebarBackground,
|
||
Text,
|
||
}
|
||
|
||
impl ColorOption {
|
||
const ALL: [Self; 5] = [
|
||
Self::Accent,
|
||
Self::ActiveTabOutline,
|
||
Self::MainBackground,
|
||
Self::SidebarBackground,
|
||
Self::Text,
|
||
];
|
||
|
||
fn label(self) -> &'static str {
|
||
match self {
|
||
Self::Accent => "Accent color",
|
||
Self::ActiveTabOutline => "Active tab outline",
|
||
Self::MainBackground => "Main background",
|
||
Self::SidebarBackground => "Sidebar background",
|
||
Self::Text => "Text color",
|
||
}
|
||
}
|
||
|
||
fn index(self) -> usize {
|
||
match self {
|
||
Self::Accent => 0,
|
||
Self::ActiveTabOutline => 1,
|
||
Self::MainBackground => 2,
|
||
Self::SidebarBackground => 3,
|
||
Self::Text => 4,
|
||
}
|
||
}
|
||
}
|
||
|
||
const DEFAULT_COLORS: [Color; 5] = [
|
||
theme::SETTINGS_ACTIVE,
|
||
theme::ACTIVE_TAB,
|
||
theme::TAB_ACTIVE_BG,
|
||
theme::TAB_INACTIVE_BG,
|
||
theme::TAB_TEXT,
|
||
];
|
||
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
enum ToastColorOption {
|
||
Background,
|
||
Text,
|
||
Title,
|
||
Border,
|
||
Info,
|
||
Success,
|
||
Warning,
|
||
Error,
|
||
Dismiss,
|
||
}
|
||
|
||
impl ToastColorOption {
|
||
const ALL: [Self; 9] = [
|
||
Self::Background,
|
||
Self::Text,
|
||
Self::Title,
|
||
Self::Border,
|
||
Self::Info,
|
||
Self::Success,
|
||
Self::Warning,
|
||
Self::Error,
|
||
Self::Dismiss,
|
||
];
|
||
|
||
fn label(self) -> &'static str {
|
||
match self {
|
||
Self::Background => "Notification background",
|
||
Self::Text => "Notification text",
|
||
Self::Title => "Notification title",
|
||
Self::Border => "Notification border",
|
||
Self::Info => "Info accent",
|
||
Self::Success => "Success accent",
|
||
Self::Warning => "Warning accent",
|
||
Self::Error => "Error accent",
|
||
Self::Dismiss => "Dismiss icon",
|
||
}
|
||
}
|
||
|
||
fn index(self) -> usize {
|
||
match self {
|
||
Self::Background => 0,
|
||
Self::Text => 1,
|
||
Self::Title => 2,
|
||
Self::Border => 3,
|
||
Self::Info => 4,
|
||
Self::Success => 5,
|
||
Self::Warning => 6,
|
||
Self::Error => 7,
|
||
Self::Dismiss => 8,
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||
enum ThemeChoice {
|
||
BuiltIn(theme::Preference),
|
||
Custom { id: String, name: String },
|
||
}
|
||
|
||
impl ThemeChoice {
|
||
fn label(&self) -> String {
|
||
match self {
|
||
Self::BuiltIn(preference) => preference.label().to_owned(),
|
||
Self::Custom { name, .. } => name.clone(),
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||
enum ThemeOption {
|
||
Theme { choice: ThemeChoice, selected: bool },
|
||
Separator,
|
||
}
|
||
|
||
impl std::fmt::Display for ThemeOption {
|
||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||
match self {
|
||
Self::Separator => f.write_str("────────────────"),
|
||
Self::Theme { choice, selected } => {
|
||
if *selected {
|
||
write!(f, "✓ {}", choice.label())
|
||
} else {
|
||
f.write_str(&choice.label())
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Debug, Clone)]
|
||
struct CustomTheme {
|
||
id: String,
|
||
name: String,
|
||
based_on: theme::Preference,
|
||
colors: [Color; 5],
|
||
custom_toasts: bool,
|
||
toast_colors: [Color; 9],
|
||
}
|
||
|
||
#[derive(Debug, Serialize, Deserialize)]
|
||
struct ThemeFile {
|
||
name: String,
|
||
based_on: String,
|
||
#[serde(skip_serializing_if = "Option::is_none")]
|
||
accent: Option<String>,
|
||
#[serde(skip_serializing_if = "Option::is_none")]
|
||
active_tab_outline: Option<String>,
|
||
#[serde(skip_serializing_if = "Option::is_none")]
|
||
main_background: Option<String>,
|
||
#[serde(skip_serializing_if = "Option::is_none")]
|
||
sidebar_background: Option<String>,
|
||
#[serde(skip_serializing_if = "Option::is_none")]
|
||
text: Option<String>,
|
||
#[serde(default)]
|
||
toast: ToastFile,
|
||
}
|
||
|
||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||
struct ToastFile {
|
||
#[serde(default)]
|
||
enabled: bool,
|
||
#[serde(skip_serializing_if = "Option::is_none")]
|
||
background: Option<String>,
|
||
#[serde(skip_serializing_if = "Option::is_none")]
|
||
text: Option<String>,
|
||
#[serde(skip_serializing_if = "Option::is_none")]
|
||
title: Option<String>,
|
||
#[serde(skip_serializing_if = "Option::is_none")]
|
||
border: Option<String>,
|
||
#[serde(skip_serializing_if = "Option::is_none")]
|
||
info: Option<String>,
|
||
#[serde(skip_serializing_if = "Option::is_none")]
|
||
success: Option<String>,
|
||
#[serde(skip_serializing_if = "Option::is_none")]
|
||
warning: Option<String>,
|
||
#[serde(skip_serializing_if = "Option::is_none")]
|
||
error: Option<String>,
|
||
#[serde(skip_serializing_if = "Option::is_none")]
|
||
dismiss: Option<String>,
|
||
}
|
||
|
||
impl ThemeFile {
|
||
fn from_colors(
|
||
name: String,
|
||
based_on: theme::Preference,
|
||
colors: &[Color; 5],
|
||
base: &[Color; 5],
|
||
custom_toasts: bool,
|
||
toast_colors: &[Color; 9],
|
||
) -> Self {
|
||
let changed = |option: ColorOption| {
|
||
let index = option.index();
|
||
|
||
(colors[index] != base[index]).then(|| color_to_hex(colors[index]))
|
||
};
|
||
|
||
Self {
|
||
name,
|
||
based_on: based_on.as_str().to_owned(),
|
||
accent: changed(ColorOption::Accent),
|
||
active_tab_outline: changed(ColorOption::ActiveTabOutline),
|
||
main_background: changed(ColorOption::MainBackground),
|
||
sidebar_background: changed(ColorOption::SidebarBackground),
|
||
text: changed(ColorOption::Text),
|
||
toast: ToastFile::from_colors(custom_toasts, toast_colors),
|
||
}
|
||
}
|
||
|
||
fn colors(&self, based_on: theme::Preference) -> [Color; 5] {
|
||
let mut colors = builtin_colors(based_on);
|
||
|
||
let mut apply = |option: ColorOption, value: &Option<String>| {
|
||
if let Some(color) = value.as_deref().and_then(color_from_hex) {
|
||
colors[option.index()] = color;
|
||
}
|
||
};
|
||
|
||
apply(ColorOption::Accent, &self.accent);
|
||
apply(ColorOption::ActiveTabOutline, &self.active_tab_outline);
|
||
apply(ColorOption::MainBackground, &self.main_background);
|
||
apply(ColorOption::SidebarBackground, &self.sidebar_background);
|
||
apply(ColorOption::Text, &self.text);
|
||
|
||
colors
|
||
}
|
||
}
|
||
|
||
impl ToastFile {
|
||
fn from_colors(enabled: bool, colors: &[Color; 9]) -> Self {
|
||
Self {
|
||
enabled,
|
||
background: Some(color_to_hex(colors[0])),
|
||
text: Some(color_to_hex(colors[1])),
|
||
title: Some(color_to_hex(colors[2])),
|
||
border: Some(color_to_hex(colors[3])),
|
||
info: Some(color_to_hex(colors[4])),
|
||
success: Some(color_to_hex(colors[5])),
|
||
warning: Some(color_to_hex(colors[6])),
|
||
error: Some(color_to_hex(colors[7])),
|
||
dismiss: Some(color_to_hex(colors[8])),
|
||
}
|
||
}
|
||
|
||
fn colors(&self, based_on: theme::Preference) -> [Color; 9] {
|
||
let mut colors = builtin_toast_colors(based_on);
|
||
|
||
for (color, value) in colors.iter_mut().zip([
|
||
&self.background,
|
||
&self.text,
|
||
&self.title,
|
||
&self.border,
|
||
&self.info,
|
||
&self.success,
|
||
&self.warning,
|
||
&self.error,
|
||
&self.dismiss,
|
||
]) {
|
||
if let Some(parsed) = value.as_deref().and_then(color_from_hex) {
|
||
*color = parsed;
|
||
}
|
||
}
|
||
|
||
colors
|
||
}
|
||
}
|
||
|
||
fn builtin_colors(_preference: theme::Preference) -> [Color; 5] {
|
||
DEFAULT_COLORS
|
||
}
|
||
|
||
fn builtin_toast_colors(preference: theme::Preference) -> [Color; 9] {
|
||
let theme = preference.iced().unwrap_or(iced::Theme::Dark);
|
||
|
||
notifications::ToastColors::default_for(&theme).as_array()
|
||
}
|
||
|
||
/// Everything persisted in the config file, grouped by settings tab.
|
||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||
struct ConfigFile {
|
||
#[serde(default)]
|
||
general: GeneralConfig,
|
||
#[serde(default)]
|
||
startup: StartupConfig,
|
||
#[serde(default)]
|
||
appearance: AppearanceConfig,
|
||
#[serde(default)]
|
||
shortcuts: ShortcutConfig,
|
||
}
|
||
|
||
impl Default for ConfigFile {
|
||
fn default() -> Self {
|
||
Self {
|
||
general: GeneralConfig::default(),
|
||
startup: StartupConfig::default(),
|
||
appearance: AppearanceConfig::default(),
|
||
shortcuts: ShortcutConfig::default(),
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||
struct GeneralConfig {
|
||
#[serde(default = "default_true")]
|
||
fade_settings: bool,
|
||
}
|
||
|
||
impl Default for GeneralConfig {
|
||
fn default() -> Self {
|
||
Self {
|
||
fade_settings: true,
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||
struct StartupConfig {
|
||
#[serde(default = "default_true")]
|
||
show_start_tab: bool,
|
||
}
|
||
|
||
impl Default for StartupConfig {
|
||
fn default() -> Self {
|
||
Self {
|
||
show_start_tab: true,
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||
struct AppearanceConfig {
|
||
#[serde(default = "default_theme")]
|
||
theme: String,
|
||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||
custom_theme: Option<String>,
|
||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||
custom_theme_name: Option<String>,
|
||
#[serde(default = "default_true")]
|
||
hide_tab_close: bool,
|
||
#[serde(default)]
|
||
toast: ToastFile,
|
||
}
|
||
|
||
impl Default for AppearanceConfig {
|
||
fn default() -> Self {
|
||
Self {
|
||
theme: default_theme(),
|
||
custom_theme: None,
|
||
custom_theme_name: None,
|
||
hide_tab_close: true,
|
||
toast: ToastFile::default(),
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||
struct ShortcutConfig {
|
||
#[serde(default = "default_settings_shortcut")]
|
||
settings: String,
|
||
#[serde(default = "default_quit_shortcut")]
|
||
quit: String,
|
||
#[serde(default = "default_command_palette_shortcut")]
|
||
command_palette: String,
|
||
}
|
||
|
||
impl Default for ShortcutConfig {
|
||
fn default() -> Self {
|
||
Self {
|
||
settings: default_settings_shortcut(),
|
||
quit: default_quit_shortcut(),
|
||
command_palette: default_command_palette_shortcut(),
|
||
}
|
||
}
|
||
}
|
||
|
||
fn default_true() -> bool {
|
||
true
|
||
}
|
||
|
||
fn default_theme() -> String {
|
||
theme::Preference::default().as_str().to_owned()
|
||
}
|
||
|
||
fn default_settings_shortcut() -> String {
|
||
Shortcuts::default()
|
||
.settings
|
||
.map(|shortcut| shortcut.to_string())
|
||
.unwrap_or_default()
|
||
}
|
||
|
||
fn default_quit_shortcut() -> String {
|
||
Shortcuts::default()
|
||
.quit
|
||
.map(|shortcut| shortcut.to_string())
|
||
.unwrap_or_default()
|
||
}
|
||
|
||
fn default_command_palette_shortcut() -> String {
|
||
Shortcuts::default()
|
||
.command_palette
|
||
.map(|shortcut| shortcut.to_string())
|
||
.unwrap_or_default()
|
||
}
|
||
|
||
fn color_to_hex(color: Color) -> String {
|
||
let r = (color.r * 255.0).round() as u8;
|
||
let g = (color.g * 255.0).round() as u8;
|
||
let b = (color.b * 255.0).round() as u8;
|
||
|
||
if color.a >= 0.999 {
|
||
format!("#{r:02X}{g:02X}{b:02X}")
|
||
} else {
|
||
let a = (color.a * 255.0).round() as u8;
|
||
format!("#{r:02X}{g:02X}{b:02X}{a:02X}")
|
||
}
|
||
}
|
||
|
||
fn color_from_hex(text: &str) -> Option<Color> {
|
||
let hex = text.trim().trim_start_matches('#');
|
||
|
||
let byte = |range: std::ops::Range<usize>| u8::from_str_radix(&hex[range], 16).ok();
|
||
|
||
match hex.len() {
|
||
6 => Some(Color::from_rgb8(byte(0..2)?, byte(2..4)?, byte(4..6)?)),
|
||
8 => Some(Color::from_rgba8(
|
||
byte(0..2)?,
|
||
byte(2..4)?,
|
||
byte(4..6)?,
|
||
f32::from(byte(6..8)?) / 255.0,
|
||
)),
|
||
_ => None,
|
||
}
|
||
}
|
||
|
||
fn themes_dir() -> Option<PathBuf> {
|
||
config_path().and_then(|path| path.parent().map(|parent| parent.join("Themes")))
|
||
}
|
||
|
||
fn load_custom_themes() -> Vec<CustomTheme> {
|
||
let Some(dir) = themes_dir() else {
|
||
return Vec::new();
|
||
};
|
||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||
return Vec::new();
|
||
};
|
||
|
||
let mut themes = Vec::new();
|
||
|
||
for entry in entries.flatten() {
|
||
let path = entry.path();
|
||
|
||
if path.extension().and_then(|extension| extension.to_str()) != Some("toml") {
|
||
continue;
|
||
}
|
||
|
||
let Some(id) = path
|
||
.file_stem()
|
||
.map(|stem| stem.to_string_lossy().into_owned())
|
||
else {
|
||
continue;
|
||
};
|
||
let Ok(text) = std::fs::read_to_string(&path) else {
|
||
continue;
|
||
};
|
||
let Ok(file) = toml::from_str::<ThemeFile>(&text) else {
|
||
continue;
|
||
};
|
||
let Some(based_on) = theme::Preference::parse(&file.based_on) else {
|
||
continue;
|
||
};
|
||
|
||
let colors = file.colors(based_on);
|
||
let toast_colors = file.toast.colors(based_on);
|
||
themes.push(CustomTheme {
|
||
id,
|
||
name: file.name,
|
||
based_on,
|
||
colors,
|
||
custom_toasts: file.toast.enabled,
|
||
toast_colors,
|
||
});
|
||
}
|
||
|
||
themes
|
||
}
|
||
|
||
fn themes_signature() -> Vec<(String, u64)> {
|
||
let Some(dir) = themes_dir() else {
|
||
return Vec::new();
|
||
};
|
||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||
return Vec::new();
|
||
};
|
||
|
||
let mut signature = Vec::new();
|
||
|
||
for entry in entries.flatten() {
|
||
let path = entry.path();
|
||
|
||
if path.extension().and_then(|extension| extension.to_str()) != Some("toml") {
|
||
continue;
|
||
}
|
||
|
||
let name = path
|
||
.file_name()
|
||
.map(|name| name.to_string_lossy().into_owned())
|
||
.unwrap_or_default();
|
||
let modified = entry
|
||
.metadata()
|
||
.ok()
|
||
.and_then(|metadata| metadata.modified().ok())
|
||
.and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
|
||
.map(|duration| duration.as_nanos() as u64)
|
||
.unwrap_or_default();
|
||
|
||
signature.push((name, modified));
|
||
}
|
||
|
||
signature.sort();
|
||
signature
|
||
}
|
||
|
||
fn write_custom_theme(
|
||
id: &str,
|
||
name: &str,
|
||
based_on: theme::Preference,
|
||
colors: &[Color; 5],
|
||
custom_toasts: bool,
|
||
toast_colors: &[Color; 9],
|
||
) -> Option<()> {
|
||
let dir = themes_dir()?;
|
||
std::fs::create_dir_all(&dir).ok()?;
|
||
|
||
let base = builtin_colors(based_on);
|
||
let file = ThemeFile::from_colors(
|
||
name.to_owned(),
|
||
based_on,
|
||
colors,
|
||
&base,
|
||
custom_toasts,
|
||
toast_colors,
|
||
);
|
||
let text = toml::to_string_pretty(&file).ok()?;
|
||
|
||
std::fs::write(dir.join(format!("{id}.toml")), text).ok()?;
|
||
Some(())
|
||
}
|
||
|
||
/// Directory holding `folders.toml` and one TOML file per profile.
|
||
fn profiles_dir() -> Option<PathBuf> {
|
||
config_path().and_then(|path| path.parent().map(|parent| parent.join("profiles")))
|
||
}
|
||
|
||
fn normalize_folder_path(value: &str) -> String {
|
||
let path = value
|
||
.split(['/', '\\'])
|
||
.map(str::trim)
|
||
.filter(|part| !part.is_empty() && *part != "." && *part != "..")
|
||
.collect::<Vec<_>>()
|
||
.join("/");
|
||
|
||
if path.is_empty() {
|
||
DEFAULT_PROFILE_FOLDER.to_owned()
|
||
} else {
|
||
path
|
||
}
|
||
}
|
||
|
||
/// Keep the default folder first, then sort the tree by path so parents come
|
||
/// before their children.
|
||
fn folder_order(a: &str, b: &str) -> Ordering {
|
||
let rank = |path: &str| usize::from(path != DEFAULT_PROFILE_FOLDER);
|
||
rank(a).cmp(&rank(b)).then_with(|| a.cmp(b))
|
||
}
|
||
|
||
fn add_folder_and_parents(paths: &mut BTreeSet<String>, path: &str) {
|
||
if path.is_empty() {
|
||
return;
|
||
}
|
||
|
||
let mut prefix = String::new();
|
||
for part in path.split('/') {
|
||
if !prefix.is_empty() {
|
||
prefix.push('/');
|
||
}
|
||
prefix.push_str(part);
|
||
paths.insert(prefix.clone());
|
||
}
|
||
}
|
||
|
||
fn load_profiles() -> Vec<ProfileFolder> {
|
||
profiles_dir()
|
||
.map(|dir| load_profiles_from(&dir))
|
||
.unwrap_or_else(|| vec![ProfileFolder::default_folder()])
|
||
}
|
||
|
||
/// Rebuilds the folder tree and profile lists from the `profiles` directory.
|
||
/// Folders referenced by a profile but missing from `folders.toml` are added
|
||
/// as runtime-only folders.
|
||
fn load_profiles_from(dir: &Path) -> Vec<ProfileFolder> {
|
||
let mut tracked = BTreeSet::new();
|
||
tracked.insert(DEFAULT_PROFILE_FOLDER.to_owned());
|
||
let mut untracked = BTreeSet::new();
|
||
|
||
if let Ok(text) = std::fs::read_to_string(dir.join("folders.toml"))
|
||
&& let Ok(file) = toml::from_str::<FoldersFile>(&text)
|
||
{
|
||
for folder in file.folders {
|
||
add_folder_and_parents(&mut tracked, &normalize_folder_path(&folder));
|
||
}
|
||
}
|
||
|
||
let mut profiles = Vec::new();
|
||
|
||
if let Ok(entries) = std::fs::read_dir(dir) {
|
||
let mut files: Vec<PathBuf> = entries
|
||
.flatten()
|
||
.map(|entry| entry.path())
|
||
.filter(|path| {
|
||
path.extension().and_then(|extension| extension.to_str()) == Some("toml")
|
||
&& path.file_name().and_then(|name| name.to_str()) != Some("folders.toml")
|
||
})
|
||
.collect();
|
||
files.sort();
|
||
|
||
for path in files {
|
||
let Ok(text) = std::fs::read_to_string(&path) else {
|
||
continue;
|
||
};
|
||
let Ok(mut file) = toml::from_str::<ProfileFile>(&text) else {
|
||
continue;
|
||
};
|
||
|
||
if file.name.trim().is_empty() {
|
||
file.name = path
|
||
.file_stem()
|
||
.map(|stem| stem.to_string_lossy().into_owned())
|
||
.unwrap_or_default();
|
||
}
|
||
|
||
let folder = normalize_folder_path(&file.folder);
|
||
add_missing_folder_and_parents(&tracked, &mut untracked, &folder);
|
||
let mut profile = file.into_profile();
|
||
profile.file = Some(path);
|
||
profiles.push((folder, profile));
|
||
}
|
||
}
|
||
|
||
let mut folder_paths: Vec<String> = tracked.into_iter().collect();
|
||
folder_paths.extend(untracked.iter().cloned());
|
||
folder_paths.sort_by(|a, b| folder_order(a, b));
|
||
folder_paths.dedup();
|
||
|
||
let mut folders: Vec<ProfileFolder> = folder_paths
|
||
.into_iter()
|
||
.map(|path| {
|
||
let mut folder = ProfileFolder::from_path(path);
|
||
folder.untracked = untracked.contains(&folder.path);
|
||
folder
|
||
})
|
||
.collect();
|
||
|
||
for (folder_path, profile) in profiles {
|
||
if let Some(folder) = folders.iter_mut().find(|folder| folder.path == folder_path) {
|
||
folder.profiles.push(profile);
|
||
}
|
||
}
|
||
|
||
folders
|
||
}
|
||
|
||
/// Adds a profile's folder and any missing parents as runtime-only folders,
|
||
/// unless the path is already part of `folders.toml`.
|
||
fn add_missing_folder_and_parents(
|
||
tracked: &BTreeSet<String>,
|
||
untracked: &mut BTreeSet<String>,
|
||
path: &str,
|
||
) {
|
||
let mut prefix = String::new();
|
||
|
||
for part in path.split('/') {
|
||
if !prefix.is_empty() {
|
||
prefix.push('/');
|
||
}
|
||
prefix.push_str(part);
|
||
|
||
if !tracked.contains(&prefix) {
|
||
untracked.insert(prefix.clone());
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Adds a folder and any missing parents, then returns the folder's index.
|
||
fn ensure_folder(folders: &mut Vec<ProfileFolder>, path: &str) -> usize {
|
||
add_folder_to_list(folders, path);
|
||
folders.sort_by(|a, b| folder_order(&a.path, &b.path));
|
||
folders
|
||
.iter()
|
||
.position(|folder| folder.path == path)
|
||
.unwrap_or(0)
|
||
}
|
||
|
||
fn add_folder_to_list(folders: &mut Vec<ProfileFolder>, path: &str) {
|
||
let mut prefix = String::new();
|
||
|
||
for part in path.split('/') {
|
||
if !prefix.is_empty() {
|
||
prefix.push('/');
|
||
}
|
||
prefix.push_str(part);
|
||
|
||
if let Some(folder) = folders.iter_mut().find(|folder| folder.path == prefix) {
|
||
folder.untracked = false;
|
||
} else {
|
||
folders.push(ProfileFolder::from_path(prefix.clone()));
|
||
}
|
||
}
|
||
}
|
||
|
||
fn profile_file_stem(name: &str) -> String {
|
||
let stem: String = name
|
||
.trim()
|
||
.chars()
|
||
.map(|character| {
|
||
if character.is_control()
|
||
|| matches!(
|
||
character,
|
||
'/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|'
|
||
)
|
||
{
|
||
'_'
|
||
} else {
|
||
character
|
||
}
|
||
})
|
||
.collect();
|
||
let stem = stem.trim().trim_matches('.').trim();
|
||
|
||
if stem.is_empty() {
|
||
"profile".to_owned()
|
||
} else if stem.eq_ignore_ascii_case("folders") {
|
||
"folders-profile".to_owned()
|
||
} else {
|
||
stem.chars().take(100).collect()
|
||
}
|
||
}
|
||
|
||
fn write_profile_file(path: &Path, profile: &Profile, folder: &str) -> Option<()> {
|
||
let text = toml::to_string_pretty(&ProfileFile::from_profile(profile, folder)).ok()?;
|
||
std::fs::write(path, text).ok()?;
|
||
|
||
// Profile files can contain passwords and keys; keep them private.
|
||
#[cfg(unix)]
|
||
{
|
||
use std::os::unix::fs::PermissionsExt;
|
||
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).ok()?;
|
||
}
|
||
|
||
Some(())
|
||
}
|
||
|
||
fn write_profile_to(dir: &Path, profile: &Profile, folder: &str) -> Option<PathBuf> {
|
||
std::fs::create_dir_all(dir).ok()?;
|
||
|
||
let stem = profile_file_stem(&profile.name);
|
||
let mut path = dir.join(format!("{stem}.toml"));
|
||
let mut suffix = 2;
|
||
|
||
while path.exists() {
|
||
path = dir.join(format!("{stem}-{suffix}.toml"));
|
||
suffix += 1;
|
||
}
|
||
|
||
write_profile_file(&path, profile, folder)?;
|
||
Some(path)
|
||
}
|
||
|
||
fn write_profile(profile: &Profile, folder: &str) -> Option<PathBuf> {
|
||
// Never let the unit tests write into the developer's real profile files.
|
||
if cfg!(test) {
|
||
return None;
|
||
}
|
||
|
||
write_profile_to(&profiles_dir()?, profile, folder)
|
||
}
|
||
|
||
/// Persists a profile at its existing file, or creates one if it has none.
|
||
fn save_profile(profile: &mut Profile, folder: &str) {
|
||
if cfg!(test) {
|
||
return;
|
||
}
|
||
|
||
if let Some(file) = &profile.file {
|
||
let _ = write_profile_file(file, profile, folder);
|
||
} else if let Some(path) = write_profile(profile, folder) {
|
||
profile.file = Some(path);
|
||
}
|
||
}
|
||
|
||
fn write_folders_to(dir: &Path, folders: &[ProfileFolder]) -> Option<()> {
|
||
std::fs::create_dir_all(dir).ok()?;
|
||
|
||
let mut paths: Vec<String> = folders
|
||
.iter()
|
||
.filter(|folder| !folder.untracked)
|
||
.map(|folder| folder.path.clone())
|
||
.collect();
|
||
paths.sort_by(|a, b| folder_order(a, b));
|
||
paths.dedup();
|
||
|
||
let text = toml::to_string_pretty(&FoldersFile { folders: paths }).ok()?;
|
||
std::fs::write(dir.join("folders.toml"), text).ok()?;
|
||
Some(())
|
||
}
|
||
|
||
fn save_folders(folders: &[ProfileFolder]) {
|
||
if cfg!(test) {
|
||
return;
|
||
}
|
||
|
||
let Some(dir) = profiles_dir() else {
|
||
return;
|
||
};
|
||
|
||
let _ = write_folders_to(&dir, folders);
|
||
}
|
||
|
||
fn trash_dir() -> Option<PathBuf> {
|
||
config_path().and_then(|path| path.parent().map(|parent| parent.join(".trash")))
|
||
}
|
||
|
||
fn timestamp_now() -> String {
|
||
let seconds = std::time::SystemTime::now()
|
||
.duration_since(std::time::UNIX_EPOCH)
|
||
.map(|duration| duration.as_secs())
|
||
.unwrap_or_default();
|
||
|
||
format_timestamp(seconds)
|
||
}
|
||
|
||
fn format_timestamp(seconds: u64) -> String {
|
||
let days = (seconds / 86_400) as i64;
|
||
let time = seconds % 86_400;
|
||
let z = days + 719_468;
|
||
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
|
||
let doe = z - era * 146_097;
|
||
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
|
||
let year = yoe + era * 400;
|
||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||
let mp = (5 * doy + 2) / 153;
|
||
let day = doy - (153 * mp + 2) / 5 + 1;
|
||
let month = mp + if mp < 10 { 3 } else { -9 };
|
||
let year = year + if month <= 2 { 1 } else { 0 };
|
||
|
||
format!(
|
||
"{year:04}-{month:02}-{day:02} {:02}:{:02}:{:02}",
|
||
time / 3_600,
|
||
(time % 3_600) / 60,
|
||
time % 60
|
||
)
|
||
}
|
||
|
||
fn load_trash_entries() -> Vec<TrashEntry> {
|
||
trash_dir()
|
||
.map(|dir| load_trash_entries_from(&dir))
|
||
.unwrap_or_default()
|
||
}
|
||
|
||
fn load_trash_entries_from(dir: &Path) -> Vec<TrashEntry> {
|
||
let mut entries = Vec::new();
|
||
|
||
if let Ok(text) = std::fs::read_to_string(dir.join("folders.toml"))
|
||
&& let Ok(file) = toml::from_str::<TrashFoldersFile>(&text)
|
||
{
|
||
entries.extend(file.folders.into_iter().map(TrashEntry::Folder));
|
||
}
|
||
|
||
if let Ok(read) = std::fs::read_dir(dir) {
|
||
let mut files: Vec<PathBuf> = read
|
||
.flatten()
|
||
.map(|entry| entry.path())
|
||
.filter(|path| {
|
||
path.extension().and_then(|extension| extension.to_str()) == Some("toml")
|
||
&& path.file_name().and_then(|name| name.to_str()) != Some("folders.toml")
|
||
})
|
||
.collect();
|
||
files.sort();
|
||
|
||
for file in files {
|
||
let Ok(text) = std::fs::read_to_string(&file) else {
|
||
continue;
|
||
};
|
||
let Ok(profile) = toml::from_str::<ProfileFile>(&text) else {
|
||
continue;
|
||
};
|
||
|
||
if profile.trash.is_some() {
|
||
entries.push(TrashEntry::Profile { file, profile });
|
||
}
|
||
}
|
||
}
|
||
|
||
entries
|
||
}
|
||
|
||
fn append_trash_folders(folders: &[TrashFolder]) {
|
||
if cfg!(test) || folders.is_empty() {
|
||
return;
|
||
}
|
||
|
||
let Some(dir) = trash_dir() else {
|
||
return;
|
||
};
|
||
let _ = std::fs::create_dir_all(&dir);
|
||
let path = dir.join("folders.toml");
|
||
let mut file = std::fs::read_to_string(&path)
|
||
.ok()
|
||
.and_then(|text| toml::from_str::<TrashFoldersFile>(&text).ok())
|
||
.unwrap_or_default();
|
||
file.folders.extend_from_slice(folders);
|
||
|
||
if let Ok(text) = toml::to_string_pretty(&file) {
|
||
let _ = std::fs::write(path, text);
|
||
}
|
||
}
|
||
|
||
fn save_trash_folders(folders: &[TrashFolder]) {
|
||
if cfg!(test) {
|
||
return;
|
||
}
|
||
|
||
let Some(dir) = trash_dir() else {
|
||
return;
|
||
};
|
||
let _ = std::fs::create_dir_all(&dir);
|
||
let file = TrashFoldersFile {
|
||
folders: folders.to_vec(),
|
||
};
|
||
|
||
if let Ok(text) = toml::to_string_pretty(&file) {
|
||
let _ = std::fs::write(dir.join("folders.toml"), text);
|
||
}
|
||
}
|
||
|
||
fn move_profile_to_trash(profile: &Profile, folder: &str) -> Option<PathBuf> {
|
||
if cfg!(test) {
|
||
return None;
|
||
}
|
||
|
||
let dir = trash_dir()?;
|
||
std::fs::create_dir_all(&dir).ok()?;
|
||
|
||
let stem = profile_file_stem(&profile.name);
|
||
let mut path = dir.join(format!("{stem}.toml"));
|
||
let mut suffix = 2;
|
||
|
||
while path.exists() {
|
||
path = dir.join(format!("{stem}-{suffix}.toml"));
|
||
suffix += 1;
|
||
}
|
||
|
||
let mut file = ProfileFile::from_profile(profile, folder);
|
||
file.trash = Some(TrashInfo {
|
||
previous_path: folder.to_owned(),
|
||
deleted: timestamp_now(),
|
||
});
|
||
|
||
let text = toml::to_string_pretty(&file).ok()?;
|
||
std::fs::write(&path, text).ok()?;
|
||
|
||
#[cfg(unix)]
|
||
{
|
||
use std::os::unix::fs::PermissionsExt;
|
||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).ok()?;
|
||
}
|
||
|
||
if let Some(original) = &profile.file {
|
||
let _ = std::fs::remove_file(original);
|
||
}
|
||
|
||
Some(path)
|
||
}
|
||
|
||
fn is_folder_under(path: &str, root: &str) -> bool {
|
||
path == root
|
||
|| path
|
||
.strip_prefix(root)
|
||
.is_some_and(|rest| rest.starts_with('/'))
|
||
}
|
||
|
||
fn checked_folder_roots(state: &Moorly) -> Vec<String> {
|
||
let mut roots: Vec<String> = state
|
||
.checked
|
||
.iter()
|
||
.filter_map(|item| match item {
|
||
Selection::Folder(index) => state
|
||
.profile_folders
|
||
.get(*index)
|
||
.map(|folder| folder.path.clone()),
|
||
Selection::Profile { .. } => None,
|
||
})
|
||
.collect();
|
||
|
||
// A checked child folder is already covered by its checked parent.
|
||
roots.sort_by_key(|path| path.split('/').count());
|
||
|
||
let mut filtered: Vec<String> = Vec::new();
|
||
for root in roots {
|
||
if !filtered.iter().any(|parent| is_folder_under(&root, parent)) {
|
||
filtered.push(root);
|
||
}
|
||
}
|
||
|
||
filtered
|
||
}
|
||
|
||
/// Checked profiles that are not already covered by a checked folder.
|
||
fn checked_profile_indices(state: &Moorly, roots: &[String]) -> Vec<(usize, usize)> {
|
||
let mut items = Vec::new();
|
||
|
||
for (folder_index, folder) in state.profile_folders.iter().enumerate() {
|
||
if roots.iter().any(|root| is_folder_under(&folder.path, root)) {
|
||
continue;
|
||
}
|
||
|
||
for profile_index in 0..folder.profiles.len() {
|
||
if state.checked.contains(&Selection::Profile {
|
||
folder: folder_index,
|
||
profile: profile_index,
|
||
}) {
|
||
items.push((folder_index, profile_index));
|
||
}
|
||
}
|
||
}
|
||
|
||
items
|
||
}
|
||
|
||
fn remove_folders(state: &mut Moorly, roots: &[String]) {
|
||
if roots.is_empty() {
|
||
return;
|
||
}
|
||
|
||
let remove_paths: HashSet<String> = state
|
||
.profile_folders
|
||
.iter()
|
||
.filter(|folder| roots.iter().any(|root| is_folder_under(&folder.path, root)))
|
||
.map(|folder| folder.path.clone())
|
||
.collect();
|
||
|
||
state
|
||
.profile_folders
|
||
.retain(|folder| !remove_paths.contains(&folder.path));
|
||
}
|
||
|
||
fn apply_transfer(state: &mut Moorly, mode: TransferMode, destination: usize) {
|
||
let Some(destination_path) = state
|
||
.profile_folders
|
||
.get(destination)
|
||
.map(|folder| folder.path.clone())
|
||
else {
|
||
state.transfer = None;
|
||
return;
|
||
};
|
||
|
||
let roots = checked_folder_roots(state);
|
||
let individual = checked_profile_indices(state, &roots);
|
||
let snapshot = state.profile_folders.clone();
|
||
let mut placements = Vec::new();
|
||
let mut moved_roots = Vec::new();
|
||
|
||
for root in &roots {
|
||
if destination_path == *root || is_folder_under(&destination_path, root) {
|
||
continue;
|
||
}
|
||
|
||
let leaf = root.rsplit('/').next().unwrap_or(root);
|
||
let new_root = format!("{destination_path}/{leaf}");
|
||
|
||
for folder in snapshot
|
||
.iter()
|
||
.filter(|folder| is_folder_under(&folder.path, root))
|
||
{
|
||
let suffix = folder.path.strip_prefix(root).unwrap_or("");
|
||
let new_path = format!("{new_root}{suffix}");
|
||
add_folder_to_list(&mut state.profile_folders, &new_path);
|
||
|
||
for source in &folder.profiles {
|
||
let mut profile = source.clone();
|
||
|
||
match mode {
|
||
TransferMode::Copy => {
|
||
profile.file = write_profile(&profile, &new_path);
|
||
}
|
||
TransferMode::Move => save_profile(&mut profile, &new_path),
|
||
}
|
||
|
||
placements.push((new_path.clone(), profile));
|
||
}
|
||
}
|
||
|
||
moved_roots.push(root.clone());
|
||
}
|
||
|
||
for (folder_index, profile_index) in &individual {
|
||
let Some(source) = snapshot
|
||
.get(*folder_index)
|
||
.and_then(|folder| folder.profiles.get(*profile_index))
|
||
else {
|
||
continue;
|
||
};
|
||
let mut profile = source.clone();
|
||
|
||
match mode {
|
||
TransferMode::Copy => {
|
||
profile.file = write_profile(&profile, &destination_path);
|
||
}
|
||
TransferMode::Move => save_profile(&mut profile, &destination_path),
|
||
}
|
||
|
||
placements.push((destination_path.clone(), profile));
|
||
}
|
||
|
||
if mode == TransferMode::Move {
|
||
// Removing by descending index keeps the remaining indices valid.
|
||
let mut sorted = individual;
|
||
sorted.sort_unstable_by(|a, b| b.cmp(a));
|
||
|
||
for (folder_index, profile_index) in sorted {
|
||
if let Some(folder) = state.profile_folders.get_mut(folder_index)
|
||
&& profile_index < folder.profiles.len()
|
||
{
|
||
folder.profiles.remove(profile_index);
|
||
}
|
||
}
|
||
|
||
remove_folders(state, &moved_roots);
|
||
}
|
||
|
||
for (folder_path, profile) in placements {
|
||
if let Some(folder) = state
|
||
.profile_folders
|
||
.iter_mut()
|
||
.find(|folder| folder.path == folder_path)
|
||
{
|
||
folder.expanded = true;
|
||
folder.profiles.push(profile);
|
||
}
|
||
}
|
||
|
||
add_folder_to_list(&mut state.profile_folders, DEFAULT_PROFILE_FOLDER);
|
||
state
|
||
.profile_folders
|
||
.sort_by(|a, b| folder_order(&a.path, &b.path));
|
||
state.checked.clear();
|
||
state.selected = None;
|
||
state.transfer = None;
|
||
save_folders(&state.profile_folders);
|
||
}
|
||
|
||
fn promoted_path(path: &str, selected_folders: &HashSet<String>) -> String {
|
||
let mut kept = Vec::new();
|
||
let mut prefix = String::new();
|
||
|
||
for part in path.split('/') {
|
||
if !prefix.is_empty() {
|
||
prefix.push('/');
|
||
}
|
||
prefix.push_str(part);
|
||
|
||
if !selected_folders.contains(&prefix) {
|
||
kept.push(part);
|
||
}
|
||
}
|
||
|
||
if kept.is_empty() {
|
||
DEFAULT_PROFILE_FOLDER.to_owned()
|
||
} else {
|
||
kept.join("/")
|
||
}
|
||
}
|
||
|
||
fn apply_delete(state: &mut Moorly) {
|
||
let selected_folders: HashSet<String> = state
|
||
.checked
|
||
.iter()
|
||
.filter_map(|item| match item {
|
||
Selection::Folder(index) => state
|
||
.profile_folders
|
||
.get(*index)
|
||
.map(|folder| folder.path.clone()),
|
||
Selection::Profile { .. } => None,
|
||
})
|
||
.collect();
|
||
let selected_profiles: HashSet<(usize, usize)> = state
|
||
.checked
|
||
.iter()
|
||
.filter_map(|item| match item {
|
||
Selection::Profile { folder, profile } => Some((*folder, *profile)),
|
||
Selection::Folder(_) => None,
|
||
})
|
||
.collect();
|
||
let timestamp = timestamp_now();
|
||
let snapshot = state.profile_folders.clone();
|
||
|
||
let mut trash_folders = Vec::new();
|
||
|
||
for folder in &snapshot {
|
||
if !selected_folders.contains(&folder.path) {
|
||
continue;
|
||
}
|
||
|
||
let previous_path = folder
|
||
.path
|
||
.rsplit_once('/')
|
||
.map(|(parent, _)| parent)
|
||
.unwrap_or("");
|
||
trash_folders.push(TrashFolder {
|
||
name: folder.name.clone(),
|
||
previous_path: previous_path.to_owned(),
|
||
deleted: timestamp.clone(),
|
||
});
|
||
}
|
||
|
||
let mut kept_folders: Vec<ProfileFolder> = Vec::new();
|
||
|
||
for folder in &snapshot {
|
||
if selected_folders.contains(&folder.path) {
|
||
continue;
|
||
}
|
||
|
||
let path = promoted_path(&folder.path, &selected_folders);
|
||
if !kept_folders.iter().any(|folder| folder.path == path) {
|
||
let mut entry = folder.clone();
|
||
entry.path = path;
|
||
entry.profiles.clear();
|
||
kept_folders.push(entry);
|
||
}
|
||
}
|
||
|
||
for (folder_index, folder) in snapshot.iter().enumerate() {
|
||
for (profile_index, profile) in folder.profiles.iter().enumerate() {
|
||
if selected_profiles.contains(&(folder_index, profile_index)) {
|
||
move_profile_to_trash(profile, &folder.path);
|
||
continue;
|
||
}
|
||
|
||
let path = promoted_path(&folder.path, &selected_folders);
|
||
|
||
if !kept_folders.iter().any(|folder| folder.path == path) {
|
||
kept_folders.push(ProfileFolder::from_path(path.clone()));
|
||
}
|
||
|
||
let mut profile = profile.clone();
|
||
if path != folder.path {
|
||
save_profile(&mut profile, &path);
|
||
}
|
||
|
||
if let Some(target) = kept_folders.iter_mut().find(|folder| folder.path == path) {
|
||
target.profiles.push(profile);
|
||
}
|
||
}
|
||
}
|
||
|
||
if !kept_folders
|
||
.iter()
|
||
.any(|folder| folder.path == DEFAULT_PROFILE_FOLDER)
|
||
{
|
||
kept_folders.push(ProfileFolder::default_folder());
|
||
}
|
||
|
||
kept_folders.sort_by(|a, b| folder_order(&a.path, &b.path));
|
||
append_trash_folders(&trash_folders);
|
||
state.profile_folders = kept_folders;
|
||
state.checked.clear();
|
||
state.selected = None;
|
||
state.confirm_delete = false;
|
||
save_folders(&state.profile_folders);
|
||
}
|
||
|
||
fn restore_trash_items(state: &mut Moorly) {
|
||
if state.trash_checked.is_empty() {
|
||
return;
|
||
}
|
||
|
||
let entries = state.trash_entries.clone();
|
||
let mut remaining_folders = Vec::new();
|
||
let mut removed_indices = HashSet::new();
|
||
let mut restored = 0usize;
|
||
|
||
// Restore folders first so their profiles have somewhere to go.
|
||
for (index, entry) in entries.iter().enumerate() {
|
||
let TrashEntry::Folder(folder) = entry else {
|
||
continue;
|
||
};
|
||
|
||
if state.trash_checked.contains(&index) {
|
||
let path = if folder.previous_path.is_empty() {
|
||
folder.name.clone()
|
||
} else {
|
||
format!("{}/{}", folder.previous_path, folder.name)
|
||
};
|
||
add_folder_to_list(&mut state.profile_folders, &path);
|
||
removed_indices.insert(index);
|
||
restored += 1;
|
||
} else {
|
||
remaining_folders.push(folder.clone());
|
||
}
|
||
}
|
||
|
||
for (index, entry) in entries.iter().enumerate() {
|
||
let TrashEntry::Profile { file, profile } = entry else {
|
||
continue;
|
||
};
|
||
|
||
if !state.trash_checked.contains(&index) {
|
||
continue;
|
||
}
|
||
|
||
let folder_path = profile
|
||
.trash
|
||
.as_ref()
|
||
.map(|trash| normalize_folder_path(&trash.previous_path))
|
||
.unwrap_or_else(|| DEFAULT_PROFILE_FOLDER.to_owned());
|
||
|
||
if !state
|
||
.profile_folders
|
||
.iter()
|
||
.any(|folder| folder.path == folder_path)
|
||
{
|
||
add_folder_to_list(&mut state.profile_folders, &folder_path);
|
||
}
|
||
|
||
let mut restored_profile = profile.clone().into_profile();
|
||
let new_file = write_profile(&restored_profile, &folder_path);
|
||
|
||
// Keep the trash entry if the profile could not be written back.
|
||
if !cfg!(test) && new_file.is_none() {
|
||
continue;
|
||
}
|
||
|
||
restored_profile.file = new_file;
|
||
|
||
if let Some(folder) = state
|
||
.profile_folders
|
||
.iter_mut()
|
||
.find(|folder| folder.path == folder_path)
|
||
{
|
||
folder.expanded = true;
|
||
folder.profiles.push(restored_profile);
|
||
removed_indices.insert(index);
|
||
restored += 1;
|
||
}
|
||
|
||
if !cfg!(test) {
|
||
let _ = std::fs::remove_file(file);
|
||
}
|
||
}
|
||
|
||
save_trash_folders(&remaining_folders);
|
||
state.trash_entries = entries
|
||
.into_iter()
|
||
.enumerate()
|
||
.filter(|(index, _)| !removed_indices.contains(index))
|
||
.map(|(_, entry)| entry)
|
||
.collect();
|
||
state.trash_checked.clear();
|
||
|
||
add_folder_to_list(&mut state.profile_folders, DEFAULT_PROFILE_FOLDER);
|
||
state
|
||
.profile_folders
|
||
.sort_by(|a, b| folder_order(&a.path, &b.path));
|
||
save_folders(&state.profile_folders);
|
||
state.selected = None;
|
||
state.checked.clear();
|
||
|
||
let message = if restored == 1 {
|
||
"Restored 1 item from trash.".to_owned()
|
||
} else {
|
||
format!("Restored {restored} items from trash.")
|
||
};
|
||
|
||
state.notifications.add(
|
||
notifications::Notification::new(notifications::NotificationKind::Success, message)
|
||
.title("Restored"),
|
||
);
|
||
}
|
||
|
||
fn apply_theme_choice(state: &mut Moorly, choice: ThemeChoice) {
|
||
match &choice {
|
||
ThemeChoice::BuiltIn(preference) => {
|
||
state.theme = *preference;
|
||
state.colors = builtin_colors(*preference);
|
||
state.custom_toasts = state.builtin_custom_toasts;
|
||
state.toast_colors = state.builtin_toast_colors;
|
||
}
|
||
ThemeChoice::Custom { id, .. } => {
|
||
if let Some(theme) = state.custom_themes.iter().find(|theme| theme.id == *id) {
|
||
state.theme = theme.based_on;
|
||
state.colors = theme.colors;
|
||
state.custom_toasts = theme.custom_toasts;
|
||
state.toast_colors = theme.toast_colors;
|
||
state.theme_choice = ThemeChoice::Custom {
|
||
id: theme.id.clone(),
|
||
name: theme.name.clone(),
|
||
};
|
||
return;
|
||
}
|
||
}
|
||
}
|
||
|
||
state.theme_choice = choice;
|
||
}
|
||
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||
enum SettingsSection {
|
||
#[default]
|
||
General,
|
||
Startup,
|
||
Appearance,
|
||
Shortcuts,
|
||
Profiles,
|
||
}
|
||
|
||
impl SettingsSection {
|
||
const ALL: [Self; 5] = [
|
||
Self::General,
|
||
Self::Startup,
|
||
Self::Appearance,
|
||
Self::Shortcuts,
|
||
Self::Profiles,
|
||
];
|
||
|
||
fn label(self) -> &'static str {
|
||
match self {
|
||
Self::General => "General",
|
||
Self::Startup => "Startup",
|
||
Self::Appearance => "Appearance",
|
||
Self::Shortcuts => "Shortcuts",
|
||
Self::Profiles => "Profiles",
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Path of the settings file. Everything lives in the same file.
|
||
fn config_path() -> Option<PathBuf> {
|
||
theme::config_path()
|
||
}
|
||
|
||
/// Reads the config file, falling back to the old split config files so an
|
||
/// upgrade keeps the user's existing settings.
|
||
fn load_config() -> ConfigFile {
|
||
if let Some(path) = config_path()
|
||
&& let Ok(text) = std::fs::read_to_string(&path)
|
||
&& let Ok(config) = toml::from_str(&text)
|
||
{
|
||
return config;
|
||
}
|
||
|
||
let mut config = ConfigFile::default();
|
||
|
||
if let Some(path) = config_path().map(|path| path.with_file_name("config"))
|
||
&& let Ok(text) = std::fs::read_to_string(path)
|
||
{
|
||
let load = |key: &str| {
|
||
let prefix = format!("{key}=");
|
||
|
||
text.lines()
|
||
.find_map(|line| line.strip_prefix(&prefix))
|
||
.map(|value| value.trim().eq_ignore_ascii_case("true"))
|
||
};
|
||
|
||
if let Some(value) = load("show_start_tab") {
|
||
config.startup.show_start_tab = value;
|
||
}
|
||
if let Some(value) = load("fade_settings") {
|
||
config.general.fade_settings = value;
|
||
}
|
||
if let Some(value) = load("hide_tab_close") {
|
||
config.appearance.hide_tab_close = value;
|
||
}
|
||
}
|
||
|
||
if let Some(path) = config_path().map(|path| path.with_file_name("theme"))
|
||
&& let Ok(text) = std::fs::read_to_string(path)
|
||
&& let Some(preference) = theme::Preference::parse(text.trim())
|
||
{
|
||
config.appearance.theme = preference.as_str().to_owned();
|
||
}
|
||
|
||
config
|
||
}
|
||
|
||
/// Toast customization saved for built-in themes in the config file.
|
||
fn builtin_toast_config(appearance: &AppearanceConfig) -> (bool, [Color; 9]) {
|
||
let preference = theme::Preference::parse(&appearance.theme).unwrap_or_default();
|
||
|
||
(
|
||
appearance.toast.enabled,
|
||
appearance.toast.colors(preference),
|
||
)
|
||
}
|
||
|
||
/// Resolves the saved theme selection to its live theme and colors. The final
|
||
/// flag reports that a selected custom theme could not be found, in which case
|
||
/// the app falls back to the built-in dark theme.
|
||
fn resolve_theme(
|
||
appearance: &AppearanceConfig,
|
||
custom_themes: &[CustomTheme],
|
||
) -> (
|
||
ThemeChoice,
|
||
theme::Preference,
|
||
[Color; 5],
|
||
bool,
|
||
[Color; 9],
|
||
bool,
|
||
) {
|
||
if let Some(id) = &appearance.custom_theme {
|
||
if let Some(theme) = custom_themes.iter().find(|theme| theme.id == *id) {
|
||
return (
|
||
ThemeChoice::Custom {
|
||
id: theme.id.clone(),
|
||
name: theme.name.clone(),
|
||
},
|
||
theme.based_on,
|
||
theme.colors,
|
||
theme.custom_toasts,
|
||
theme.toast_colors,
|
||
false,
|
||
);
|
||
}
|
||
|
||
let preference = theme::Preference::Dark;
|
||
let (custom_toasts, toast_colors) = builtin_toast_config(appearance);
|
||
|
||
return (
|
||
ThemeChoice::BuiltIn(preference),
|
||
preference,
|
||
builtin_colors(preference),
|
||
custom_toasts,
|
||
toast_colors,
|
||
true,
|
||
);
|
||
}
|
||
|
||
let preference = theme::Preference::parse(&appearance.theme).unwrap_or_default();
|
||
let (custom_toasts, toast_colors) = builtin_toast_config(appearance);
|
||
|
||
(
|
||
ThemeChoice::BuiltIn(preference),
|
||
preference,
|
||
builtin_colors(preference),
|
||
custom_toasts,
|
||
toast_colors,
|
||
false,
|
||
)
|
||
}
|
||
|
||
/// Warning shown when the saved custom theme is no longer on disk.
|
||
fn missing_theme_notification(name: Option<&str>) -> notifications::Notification {
|
||
let message = match name {
|
||
Some(name) => {
|
||
format!("The theme \"{name}\" is missing. Switched to the Dark theme.")
|
||
}
|
||
None => "The selected custom theme is missing. Switched to the Dark theme.".to_owned(),
|
||
};
|
||
|
||
notifications::Notification::new(notifications::NotificationKind::Warning, message)
|
||
.title("Theme unavailable")
|
||
.persistent()
|
||
}
|
||
|
||
/// 0.5s total: 250ms fading out plus 250ms fading in.
|
||
fn new_fade_animation() -> Animation<bool> {
|
||
Animation::new(true).duration(Duration::from_millis(250))
|
||
}
|
||
|
||
/// Fade used by the tab close icon when the tab is hovered or left.
|
||
fn new_tab_close_animation() -> Animation<bool> {
|
||
Animation::new(false).duration(Duration::from_millis(750))
|
||
}
|
||
|
||
/// Commits the draft settings to the running state.
|
||
fn apply_settings(state: &mut Moorly) {
|
||
state.show_start_tab = state.show_start_tab_draft;
|
||
state.fade_settings = state.fade_settings_draft;
|
||
state.hide_tab_close = state.hide_tab_close_draft;
|
||
|
||
state.saved_theme = state.theme;
|
||
state.saved_theme_choice = state.theme_choice.clone();
|
||
state.saved_colors = match &state.saved_theme_choice {
|
||
ThemeChoice::BuiltIn(preference) => builtin_colors(*preference),
|
||
ThemeChoice::Custom { id, .. } => state
|
||
.custom_themes
|
||
.iter()
|
||
.find(|theme| theme.id == *id)
|
||
.map(|theme| theme.colors)
|
||
.unwrap_or_else(|| builtin_colors(state.theme)),
|
||
};
|
||
state.saved_shortcuts = state.shortcuts.clone();
|
||
|
||
if !state.fade_settings {
|
||
if let Some(pending) = state.pending_settings_section.take() {
|
||
state.settings_section = pending;
|
||
}
|
||
state.fade_animation = new_fade_animation();
|
||
}
|
||
}
|
||
|
||
/// Discards the drafts, including the previewed theme selection.
|
||
fn undo_settings(state: &mut Moorly) {
|
||
state.show_start_tab_draft = state.show_start_tab;
|
||
state.fade_settings_draft = state.fade_settings;
|
||
state.hide_tab_close_draft = state.hide_tab_close;
|
||
state.shortcuts = state.saved_shortcuts.clone();
|
||
state.shortcut_capture = None;
|
||
state.theme_choice = state.saved_theme_choice.clone();
|
||
state.theme = state.saved_theme;
|
||
state.colors = state.saved_colors;
|
||
|
||
let (custom_toasts, toast_colors) = match &state.saved_theme_choice {
|
||
ThemeChoice::BuiltIn(_) => (state.builtin_custom_toasts, state.builtin_toast_colors),
|
||
ThemeChoice::Custom { id, .. } => state
|
||
.custom_themes
|
||
.iter()
|
||
.find(|theme| theme.id == *id)
|
||
.map(|theme| (theme.custom_toasts, theme.toast_colors))
|
||
.unwrap_or((state.builtin_custom_toasts, state.builtin_toast_colors)),
|
||
};
|
||
|
||
state.custom_toasts = custom_toasts;
|
||
state.toast_colors = toast_colors;
|
||
}
|
||
|
||
fn save_config(state: &Moorly) {
|
||
// Never let the unit tests overwrite the developer's real settings.
|
||
if cfg!(test) {
|
||
return;
|
||
}
|
||
|
||
let Some(path) = config_path() else {
|
||
return;
|
||
};
|
||
|
||
if let Some(parent) = path.parent() {
|
||
let _ = std::fs::create_dir_all(parent);
|
||
}
|
||
|
||
if let Ok(text) = toml::to_string_pretty(&config_file(state)) {
|
||
let _ = std::fs::write(path, text);
|
||
}
|
||
}
|
||
|
||
/// The committed settings, laid out one table per settings section.
|
||
fn config_file(state: &Moorly) -> ConfigFile {
|
||
ConfigFile {
|
||
general: GeneralConfig {
|
||
fade_settings: state.fade_settings,
|
||
},
|
||
startup: StartupConfig {
|
||
show_start_tab: state.show_start_tab,
|
||
},
|
||
appearance: AppearanceConfig {
|
||
theme: state.saved_theme.as_str().to_owned(),
|
||
custom_theme: match &state.saved_theme_choice {
|
||
ThemeChoice::Custom { id, .. } => Some(id.clone()),
|
||
ThemeChoice::BuiltIn(_) => None,
|
||
},
|
||
custom_theme_name: match &state.saved_theme_choice {
|
||
ThemeChoice::Custom { name, .. } => Some(name.clone()),
|
||
ThemeChoice::BuiltIn(_) => None,
|
||
},
|
||
hide_tab_close: state.hide_tab_close,
|
||
toast: ToastFile::from_colors(state.builtin_custom_toasts, &state.builtin_toast_colors),
|
||
},
|
||
shortcuts: ShortcutConfig {
|
||
settings: state
|
||
.saved_shortcuts
|
||
.settings
|
||
.as_ref()
|
||
.map(ToString::to_string)
|
||
.unwrap_or_default(),
|
||
quit: state
|
||
.saved_shortcuts
|
||
.quit
|
||
.as_ref()
|
||
.map(ToString::to_string)
|
||
.unwrap_or_default(),
|
||
command_palette: state
|
||
.saved_shortcuts
|
||
.command_palette
|
||
.as_ref()
|
||
.map(ToString::to_string)
|
||
.unwrap_or_default(),
|
||
},
|
||
}
|
||
}
|
||
|
||
impl Default for Moorly {
|
||
fn default() -> Self {
|
||
let config = load_config();
|
||
let custom_themes = load_custom_themes();
|
||
let (theme_choice, theme, colors, custom_toasts, toast_colors, theme_missing) =
|
||
resolve_theme(&config.appearance, &custom_themes);
|
||
let (builtin_custom_toasts, builtin_toast_palette) =
|
||
builtin_toast_config(&config.appearance);
|
||
let show_start_tab = config.startup.show_start_tab;
|
||
let fade_settings = config.general.fade_settings;
|
||
let hide_tab_close = config.appearance.hide_tab_close;
|
||
let shortcuts = Shortcuts {
|
||
settings: Shortcut::parse(&config.shortcuts.settings),
|
||
quit: Shortcut::parse(&config.shortcuts.quit),
|
||
command_palette: Shortcut::parse(&config.shortcuts.command_palette),
|
||
};
|
||
let mut notifications = notifications::NotificationManager::default();
|
||
|
||
if theme_missing {
|
||
notifications.add(missing_theme_notification(
|
||
config.appearance.custom_theme_name.as_deref(),
|
||
));
|
||
}
|
||
|
||
Self {
|
||
windows: HashMap::new(),
|
||
window_order: Vec::new(),
|
||
main_window: None,
|
||
focused_window: None,
|
||
drag: None,
|
||
theme,
|
||
saved_theme: theme,
|
||
theme_choice: theme_choice.clone(),
|
||
saved_theme_choice: theme_choice,
|
||
custom_themes,
|
||
theme_name_dialog: None,
|
||
theme_signature: themes_signature(),
|
||
shortcuts: shortcuts.clone(),
|
||
saved_shortcuts: shortcuts,
|
||
shortcut_capture: None,
|
||
settings_section: SettingsSection::default(),
|
||
pending_settings_section: None,
|
||
show_start_tab,
|
||
show_start_tab_draft: show_start_tab,
|
||
fade_settings,
|
||
fade_settings_draft: fade_settings,
|
||
hide_tab_close,
|
||
hide_tab_close_draft: hide_tab_close,
|
||
advanced_open: false,
|
||
colors,
|
||
saved_colors: colors,
|
||
custom_toasts,
|
||
toast_colors,
|
||
builtin_custom_toasts,
|
||
builtin_toast_colors: builtin_toast_palette,
|
||
open_color_picker: None,
|
||
open_toast_color_picker: None,
|
||
fade_animation: new_fade_animation(),
|
||
hovered_tab: None,
|
||
tab_close_fades: HashMap::new(),
|
||
profile_filter: String::new(),
|
||
profile_folders: load_profiles(),
|
||
selected: None,
|
||
checked: HashSet::new(),
|
||
trash_open: false,
|
||
trash_entries: Vec::new(),
|
||
trash_checked: HashSet::new(),
|
||
transfer: None,
|
||
confirm_delete: false,
|
||
hovered_folder: None,
|
||
add_menu_open: false,
|
||
folder_dialog: None,
|
||
profile_dialog: None,
|
||
dir_picker: None,
|
||
next_blank_tab: 1,
|
||
notifications,
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Debug, Clone)]
|
||
enum Message {
|
||
WindowEvent(window::Id, window::Event),
|
||
PointerPressed(window::Id),
|
||
PointerMoved(window::Id, Point),
|
||
PointerReleased(window::Id),
|
||
PointerLeft(window::Id),
|
||
DragTick,
|
||
ToggleMenu(window::Id),
|
||
CloseMenu(window::Id),
|
||
ToggleTabsSubmenu(window::Id),
|
||
AddTab(window::Id),
|
||
CloseActiveTab(window::Id),
|
||
CloseOtherTabs(window::Id),
|
||
ToggleCommandPalette(window::Id),
|
||
CloseCommandPalette(window::Id),
|
||
CommandPaletteChanged(window::Id, String),
|
||
CommandPaletteUp(window::Id),
|
||
CommandPaletteDown(window::Id),
|
||
RunSelectedCommand(window::Id),
|
||
RunCommand(window::Id, Command),
|
||
SelectTheme(ThemeOption),
|
||
OpenThemeNameDialog,
|
||
ThemeNameChanged(String),
|
||
ConfirmThemeName,
|
||
CancelThemeName,
|
||
SaveTheme,
|
||
UndoTheme,
|
||
ReloadThemes,
|
||
SelectTab(window::Id, Tab),
|
||
CloseTab(window::Id, Tab),
|
||
SelectSettingsSection(SettingsSection),
|
||
SetShowStartTab(bool),
|
||
SetFadeSettings(bool),
|
||
SetHideTabClose(bool),
|
||
ToggleAdvanced,
|
||
SetCustomToasts(bool),
|
||
OpenColorPicker(ColorOption),
|
||
SubmitColor(ColorOption, Color),
|
||
OpenToastColorPicker(ToastColorOption),
|
||
SubmitToastColor(ToastColorOption, Color),
|
||
CancelColorPicker,
|
||
SaveSettings,
|
||
UndoChanges,
|
||
Notification(notifications::Message),
|
||
NotificationTick(Instant),
|
||
ShowNotificationDemo,
|
||
Frame(Instant),
|
||
ProfileFilterChanged(String),
|
||
ClearProfileFilter,
|
||
ToggleAddMenu,
|
||
CloseAddMenu,
|
||
ToggleFolder(usize),
|
||
HoverFolder(Option<usize>),
|
||
HoverTab {
|
||
tab: Tab,
|
||
hovered: bool,
|
||
},
|
||
SelectProfile {
|
||
folder: usize,
|
||
profile: usize,
|
||
},
|
||
ToggleChecked(Selection),
|
||
DeselectAll,
|
||
RestoreFromTrash,
|
||
ToggleTrashChecked(usize),
|
||
RestoreSelected,
|
||
CloseTrash,
|
||
CopyChecked,
|
||
MoveChecked,
|
||
DeleteChecked,
|
||
TransferFolderSelected(FolderChoice),
|
||
ConfirmTransfer,
|
||
CancelTransfer,
|
||
ConfirmDelete,
|
||
CancelDelete,
|
||
OpenProfileDialog,
|
||
ProfileNameChanged(String),
|
||
ProfileKindSelected(ProfileKind),
|
||
ProfileFolderSelected(FolderChoice),
|
||
SessionEndSelected(SessionEnd),
|
||
ProfileHostChanged(String),
|
||
ProfilePortChanged(String),
|
||
ProfileUsernameChanged(String),
|
||
AuthMethodSelected(AuthMethod),
|
||
ProfilePasswordChanged(String),
|
||
TogglePasswordVisibility,
|
||
ProfileStartPathChanged(String),
|
||
ProfilePrivateKeyChanged(String),
|
||
OpenDirectoryPicker,
|
||
OpenPrivateKeyPicker,
|
||
DirPickerEnter(PathBuf),
|
||
DirPickerSelect(PathBuf),
|
||
DirPickerUp,
|
||
ConfirmDirectoryPicker,
|
||
CancelDirectoryPicker,
|
||
ConfirmProfile,
|
||
CancelProfile,
|
||
OpenFolderDialog,
|
||
FolderNameChanged(String),
|
||
ConfirmFolder,
|
||
CancelFolder,
|
||
Ignore,
|
||
OpenShortcutCapture(ShortcutAction),
|
||
CancelShortcut,
|
||
ClearShortcut(ShortcutAction),
|
||
DefaultShortcut(ShortcutAction),
|
||
ApplyShortcut,
|
||
CaptureKey {
|
||
key: keyboard::Key,
|
||
modifiers: keyboard::Modifiers,
|
||
},
|
||
TabsScrolled(window::Id, scrollable::Viewport),
|
||
ScrollTabs(window::Id, mouse::ScrollDelta),
|
||
ScrollTabsBy(window::Id, f32),
|
||
Quit,
|
||
}
|
||
|
||
fn update(state: &mut Moorly, message: Message) -> Task<Message> {
|
||
match message {
|
||
Message::WindowEvent(window, event) => {
|
||
return window_event(state, window, event);
|
||
}
|
||
Message::PointerPressed(window) => {
|
||
state.focused_window = Some(window);
|
||
let pending = if state.drag.is_some() {
|
||
finish_drag(state, window)
|
||
} else {
|
||
Task::none()
|
||
};
|
||
start_tab_drag(state, window);
|
||
return pending;
|
||
}
|
||
Message::PointerMoved(window, position) => {
|
||
if let Some(state) = state.windows.get_mut(&window) {
|
||
state.pointer = Some(position);
|
||
}
|
||
|
||
if state
|
||
.drag
|
||
.as_ref()
|
||
.is_some_and(|drag| drag.window == window)
|
||
{
|
||
let detach = position.y > MENUBAR_HEIGHT + 12.0;
|
||
if let Some(drag) = state.drag.as_mut() {
|
||
drag.pointer = position;
|
||
drag.detach = detach;
|
||
drag.moved = drag.moved
|
||
|| (position.x - drag.origin.x).abs() > 4.0
|
||
|| (position.y - drag.origin.y).abs() > 4.0;
|
||
}
|
||
if state.drag.as_ref().is_some_and(|drag| drag.moved)
|
||
&& let Some(delta) = drag_scroll_delta(state)
|
||
{
|
||
return scroll_tabs_by(state, window, delta);
|
||
}
|
||
}
|
||
}
|
||
Message::PointerReleased(window) => return finish_drag(state, window),
|
||
Message::PointerLeft(window) => {
|
||
if let Some(drag) = state.drag.as_mut()
|
||
&& drag.window == window
|
||
{
|
||
drag.detach = true;
|
||
}
|
||
}
|
||
Message::DragTick => {
|
||
if let Some(delta) = drag_scroll_delta(state) {
|
||
let window = state.drag.as_ref().unwrap().window;
|
||
return scroll_tabs_by(state, window, delta);
|
||
}
|
||
}
|
||
Message::ToggleMenu(window) => {
|
||
if let Some(state) = state.windows.get_mut(&window) {
|
||
state.menu_open = !state.menu_open;
|
||
state.tabs_submenu_open = false;
|
||
}
|
||
}
|
||
Message::CloseMenu(window) => {
|
||
if let Some(state) = state.windows.get_mut(&window) {
|
||
state.menu_open = false;
|
||
state.tabs_submenu_open = false;
|
||
}
|
||
}
|
||
Message::ToggleTabsSubmenu(window) => {
|
||
if let Some(state) = state.windows.get_mut(&window) {
|
||
state.tabs_submenu_open = !state.tabs_submenu_open;
|
||
}
|
||
}
|
||
Message::AddTab(window) => {
|
||
let tab = Tab::Blank(state.next_blank_tab);
|
||
state.next_blank_tab += 1;
|
||
|
||
if let Some(state) = state.windows.get_mut(&window) {
|
||
state.tabs.push(tab);
|
||
state.active_tab = Some(tab);
|
||
state.menu_open = false;
|
||
state.tabs_submenu_open = false;
|
||
}
|
||
|
||
return scroll_tabs_to_end(state, window);
|
||
}
|
||
Message::CloseActiveTab(window) => {
|
||
let active = state
|
||
.windows
|
||
.get(&window)
|
||
.and_then(|state| state.active_tab);
|
||
if let Some(tab) = active {
|
||
close_tab(state, window, tab);
|
||
}
|
||
if let Some(state) = state.windows.get_mut(&window) {
|
||
state.menu_open = false;
|
||
state.tabs_submenu_open = false;
|
||
}
|
||
|
||
return Task::batch([
|
||
reveal_active_tab(state, window),
|
||
close_window_if_empty(state, window),
|
||
]);
|
||
}
|
||
Message::CloseOtherTabs(window) => {
|
||
let active = state
|
||
.windows
|
||
.get(&window)
|
||
.and_then(|state| state.active_tab);
|
||
|
||
if let Some(state) = state.windows.get_mut(&window) {
|
||
match active {
|
||
Some(active) => state.tabs.retain(|tab| *tab == active),
|
||
None => state.tabs.clear(),
|
||
}
|
||
state.menu_open = false;
|
||
state.tabs_submenu_open = false;
|
||
}
|
||
|
||
if active != Some(Tab::Settings) {
|
||
state.settings_section = SettingsSection::default();
|
||
}
|
||
|
||
return close_window_if_empty(state, window);
|
||
}
|
||
Message::ToggleCommandPalette(window) => {
|
||
let Some(window_state) = state.windows.get_mut(&window) else {
|
||
return Task::none();
|
||
};
|
||
|
||
if window_state.command_palette_open {
|
||
close_command_palette(state, window);
|
||
} else {
|
||
window_state.command_palette_open = true;
|
||
window_state.command_palette_query.clear();
|
||
window_state.command_palette_selected = 0;
|
||
return operation::focus(window_state.command_palette_input.clone());
|
||
}
|
||
}
|
||
Message::CloseCommandPalette(window) => close_command_palette(state, window),
|
||
Message::CommandPaletteChanged(window, query) => {
|
||
if let Some(window_state) = state.windows.get_mut(&window)
|
||
&& window_state.command_palette_open
|
||
{
|
||
window_state.command_palette_query = query;
|
||
window_state.command_palette_selected = 0;
|
||
}
|
||
}
|
||
Message::CommandPaletteUp(window) => {
|
||
if let Some(window_state) = state.windows.get_mut(&window)
|
||
&& window_state.command_palette_open
|
||
{
|
||
window_state.command_palette_selected =
|
||
window_state.command_palette_selected.saturating_sub(1);
|
||
}
|
||
}
|
||
Message::CommandPaletteDown(window) => {
|
||
let query = state
|
||
.windows
|
||
.get(&window)
|
||
.filter(|window_state| window_state.command_palette_open)
|
||
.map(|window_state| window_state.command_palette_query.clone());
|
||
|
||
if let Some(query) = query {
|
||
let last = Command::matching(state, window, &query)
|
||
.len()
|
||
.saturating_sub(1);
|
||
|
||
if let Some(window_state) = state.windows.get_mut(&window) {
|
||
window_state.command_palette_selected =
|
||
(window_state.command_palette_selected + 1).min(last);
|
||
}
|
||
}
|
||
}
|
||
Message::RunSelectedCommand(window) => {
|
||
let command = state
|
||
.windows
|
||
.get(&window)
|
||
.filter(|window_state| window_state.command_palette_open)
|
||
.and_then(|window_state| {
|
||
Command::matching(state, window, &window_state.command_palette_query)
|
||
.get(window_state.command_palette_selected)
|
||
.copied()
|
||
});
|
||
|
||
if let Some(command) = command {
|
||
return update(state, Message::RunCommand(window, command));
|
||
}
|
||
}
|
||
Message::RunCommand(window, command) => {
|
||
let tab = state
|
||
.windows
|
||
.get(&window)
|
||
.and_then(|window_state| window_state.active_tab);
|
||
close_command_palette(state, window);
|
||
|
||
match command {
|
||
Command::Settings => {
|
||
return update(state, Message::SelectTab(window, Tab::Settings));
|
||
}
|
||
Command::Close => {
|
||
return update(state, Message::CloseActiveTab(window));
|
||
}
|
||
Command::Move => {
|
||
if let Some(tab) = tab {
|
||
return detach_tab(state, window, tab, None);
|
||
}
|
||
}
|
||
Command::MoveToWindow(destination) => {
|
||
if let Some(tab) = tab {
|
||
move_tab_to_window(state, window, destination, tab);
|
||
return close_window_if_empty(state, window);
|
||
}
|
||
}
|
||
Command::FocusWindow(id) => {
|
||
state.focused_window = Some(id);
|
||
return window::gain_focus(id);
|
||
}
|
||
Command::FocusTab(id, tab) => {
|
||
state.focused_window = Some(id);
|
||
return Task::batch([
|
||
update(state, Message::SelectTab(id, tab)),
|
||
window::gain_focus(id),
|
||
]);
|
||
}
|
||
Command::Exit => {
|
||
return update(state, Message::Quit);
|
||
}
|
||
}
|
||
}
|
||
Message::SelectTheme(option) => {
|
||
if let ThemeOption::Theme { choice, .. } = option {
|
||
apply_theme_choice(state, choice);
|
||
}
|
||
}
|
||
Message::OpenThemeNameDialog => {
|
||
state.theme_name_dialog = Some(String::new());
|
||
return operation::focus(THEME_NAME_INPUT);
|
||
}
|
||
Message::ThemeNameChanged(value) => {
|
||
if let Some(draft) = state.theme_name_dialog.as_mut() {
|
||
*draft = value.chars().take(100).collect();
|
||
}
|
||
}
|
||
Message::ConfirmThemeName => {
|
||
let Some(name) = state
|
||
.theme_name_dialog
|
||
.as_deref()
|
||
.map(str::trim)
|
||
.filter(|name| !name.is_empty())
|
||
.map(str::to_owned)
|
||
else {
|
||
return Task::none();
|
||
};
|
||
|
||
let based_on = match &state.theme_choice {
|
||
ThemeChoice::BuiltIn(preference) => *preference,
|
||
ThemeChoice::Custom { id, .. } => state
|
||
.custom_themes
|
||
.iter()
|
||
.find(|theme| theme.id == *id)
|
||
.map(|theme| theme.based_on)
|
||
.unwrap_or(state.theme),
|
||
};
|
||
|
||
let id = uuid::Uuid::new_v4().to_string();
|
||
|
||
if write_custom_theme(
|
||
&id,
|
||
&name,
|
||
based_on,
|
||
&state.colors,
|
||
state.custom_toasts,
|
||
&state.toast_colors,
|
||
)
|
||
.is_none()
|
||
{
|
||
return Task::none();
|
||
}
|
||
|
||
state.custom_themes = load_custom_themes();
|
||
state.theme_signature = themes_signature();
|
||
state.theme_name_dialog = None;
|
||
state.theme_choice = ThemeChoice::Custom { id, name };
|
||
state.theme = based_on;
|
||
|
||
// Creating a theme is a separate action, so it is persisted
|
||
// immediately instead of waiting for the settings bar.
|
||
state.saved_theme = based_on;
|
||
state.saved_theme_choice = state.theme_choice.clone();
|
||
state.saved_colors = state.colors;
|
||
save_config(state);
|
||
}
|
||
Message::CancelThemeName => state.theme_name_dialog = None,
|
||
Message::SaveTheme => {
|
||
if let ThemeChoice::Custom { id, name } = &state.theme_choice
|
||
&& let Some(theme) = state.custom_themes.iter().find(|theme| theme.id == *id)
|
||
{
|
||
let based_on = theme.based_on;
|
||
|
||
if write_custom_theme(
|
||
id,
|
||
name,
|
||
based_on,
|
||
&state.colors,
|
||
state.custom_toasts,
|
||
&state.toast_colors,
|
||
)
|
||
.is_some()
|
||
{
|
||
if let Some(theme) =
|
||
state.custom_themes.iter_mut().find(|theme| theme.id == *id)
|
||
{
|
||
theme.colors = state.colors;
|
||
theme.custom_toasts = state.custom_toasts;
|
||
theme.toast_colors = state.toast_colors;
|
||
}
|
||
|
||
if matches!(
|
||
&state.saved_theme_choice,
|
||
ThemeChoice::Custom { id: saved, .. } if saved == id
|
||
) {
|
||
state.saved_colors = state.colors;
|
||
}
|
||
|
||
state.theme_signature = themes_signature();
|
||
}
|
||
}
|
||
}
|
||
Message::UndoTheme => {
|
||
if let ThemeChoice::Custom { id, .. } = &state.theme_choice
|
||
&& let Some(theme) = state.custom_themes.iter().find(|theme| theme.id == *id)
|
||
{
|
||
state.theme = theme.based_on;
|
||
state.colors = theme.colors;
|
||
state.custom_toasts = theme.custom_toasts;
|
||
state.toast_colors = theme.toast_colors;
|
||
|
||
if matches!(
|
||
&state.saved_theme_choice,
|
||
ThemeChoice::Custom { id: saved, .. } if saved == id
|
||
) {
|
||
state.saved_theme = theme.based_on;
|
||
state.saved_colors = theme.colors;
|
||
}
|
||
}
|
||
}
|
||
Message::ReloadThemes => {
|
||
let signature = themes_signature();
|
||
|
||
if signature != state.theme_signature {
|
||
let selected_id = match &state.theme_choice {
|
||
ThemeChoice::Custom { id, .. } => Some(id.clone()),
|
||
ThemeChoice::BuiltIn(_) => None,
|
||
};
|
||
let old_theme = selected_id.as_ref().and_then(|id| {
|
||
state
|
||
.custom_themes
|
||
.iter()
|
||
.find(|theme| theme.id == *id)
|
||
.cloned()
|
||
});
|
||
let had_no_edits = old_theme
|
||
.as_ref()
|
||
.map(|theme| {
|
||
theme.colors == state.colors
|
||
&& theme.custom_toasts == state.custom_toasts
|
||
&& theme.toast_colors == state.toast_colors
|
||
})
|
||
.unwrap_or(true);
|
||
|
||
state.custom_themes = load_custom_themes();
|
||
state.theme_signature = signature;
|
||
|
||
if let Some(id) = selected_id {
|
||
if let Some(theme) = state.custom_themes.iter().find(|theme| theme.id == id) {
|
||
state.theme_choice = ThemeChoice::Custom {
|
||
id: id.clone(),
|
||
name: theme.name.clone(),
|
||
};
|
||
|
||
if had_no_edits {
|
||
state.theme = theme.based_on;
|
||
state.colors = theme.colors;
|
||
state.custom_toasts = theme.custom_toasts;
|
||
state.toast_colors = theme.toast_colors;
|
||
}
|
||
|
||
if matches!(
|
||
&state.saved_theme_choice,
|
||
ThemeChoice::Custom { id: saved, .. } if saved == &id
|
||
) {
|
||
state.saved_theme = theme.based_on;
|
||
state.saved_colors = theme.colors;
|
||
}
|
||
} else {
|
||
let missing_name = match &state.theme_choice {
|
||
ThemeChoice::Custom { name, .. } => Some(name.clone()),
|
||
ThemeChoice::BuiltIn(_) => None,
|
||
};
|
||
|
||
state.theme = theme::Preference::Dark;
|
||
state.theme_choice = ThemeChoice::BuiltIn(state.theme);
|
||
state.colors = builtin_colors(state.theme);
|
||
state.custom_toasts = state.builtin_custom_toasts;
|
||
state.toast_colors = state.builtin_toast_colors;
|
||
|
||
if matches!(
|
||
&state.saved_theme_choice,
|
||
ThemeChoice::Custom { id: saved, .. } if saved == &id
|
||
) {
|
||
state.saved_theme = state.theme;
|
||
state.saved_theme_choice = state.theme_choice.clone();
|
||
state.saved_colors = state.colors;
|
||
}
|
||
|
||
state
|
||
.notifications
|
||
.add(missing_theme_notification(missing_name.as_deref()));
|
||
}
|
||
}
|
||
}
|
||
}
|
||
Message::SelectTab(window, tab) => {
|
||
let Some(window_state) = state.windows.get_mut(&window) else {
|
||
return Task::none();
|
||
};
|
||
let is_new = !window_state.tabs.contains(&tab);
|
||
if is_new {
|
||
window_state.tabs.push(tab);
|
||
}
|
||
window_state.active_tab = Some(tab);
|
||
window_state.menu_open = false;
|
||
window_state.tabs_submenu_open = false;
|
||
|
||
// New tabs land at the end, so bring that end into view.
|
||
if is_new {
|
||
return scroll_tabs_to_end(state, window);
|
||
}
|
||
}
|
||
Message::CloseTab(window, tab) => {
|
||
let was_active = close_tab(state, window, tab);
|
||
|
||
return Task::batch([
|
||
if was_active {
|
||
reveal_active_tab(state, window)
|
||
} else {
|
||
Task::none()
|
||
},
|
||
close_window_if_empty(state, window),
|
||
]);
|
||
}
|
||
Message::SelectSettingsSection(section) => {
|
||
if section == state.settings_section && state.pending_settings_section.is_none() {
|
||
// Already showing this section.
|
||
} else if !state.fade_settings {
|
||
state.settings_section = section;
|
||
state.pending_settings_section = None;
|
||
state.fade_animation = new_fade_animation();
|
||
} else if section == state.settings_section {
|
||
// Clicking the current section cancels a fade to another one.
|
||
state.pending_settings_section = None;
|
||
state.fade_animation.go_mut(true, Instant::now());
|
||
} else {
|
||
state.pending_settings_section = Some(section);
|
||
state.fade_animation.go_mut(false, Instant::now());
|
||
}
|
||
}
|
||
Message::SetShowStartTab(value) => state.show_start_tab_draft = value,
|
||
Message::SetFadeSettings(value) => state.fade_settings_draft = value,
|
||
Message::SetHideTabClose(value) => state.hide_tab_close_draft = value,
|
||
Message::ToggleAdvanced => state.advanced_open = !state.advanced_open,
|
||
Message::SetCustomToasts(value) => {
|
||
state.custom_toasts = value;
|
||
|
||
if !value {
|
||
state.open_toast_color_picker = None;
|
||
}
|
||
|
||
if matches!(state.theme_choice, ThemeChoice::BuiltIn(_)) {
|
||
state.builtin_custom_toasts = value;
|
||
save_config(state);
|
||
}
|
||
}
|
||
Message::OpenColorPicker(option) => {
|
||
state.open_color_picker = Some(option);
|
||
state.open_toast_color_picker = None;
|
||
}
|
||
Message::SubmitColor(option, color) => {
|
||
state.colors[option.index()] = color;
|
||
state.open_color_picker = None;
|
||
}
|
||
Message::OpenToastColorPicker(option) => {
|
||
state.open_toast_color_picker = Some(option);
|
||
state.open_color_picker = None;
|
||
}
|
||
Message::SubmitToastColor(option, color) => {
|
||
state.toast_colors[option.index()] = color;
|
||
state.open_toast_color_picker = None;
|
||
|
||
if matches!(state.theme_choice, ThemeChoice::BuiltIn(_)) {
|
||
state.builtin_toast_colors = state.toast_colors;
|
||
save_config(state);
|
||
}
|
||
}
|
||
Message::CancelColorPicker => {
|
||
state.open_color_picker = None;
|
||
state.open_toast_color_picker = None;
|
||
}
|
||
Message::SaveSettings => {
|
||
apply_settings(state);
|
||
save_config(state);
|
||
}
|
||
Message::UndoChanges => undo_settings(state),
|
||
Message::Notification(action) => match action {
|
||
notifications::Message::Dismiss(id) => state.notifications.dismiss(id),
|
||
},
|
||
Message::NotificationTick(now) => state.notifications.remove_expired(now),
|
||
Message::ShowNotificationDemo => {
|
||
use notifications::{Notification, NotificationKind};
|
||
|
||
state.notifications.add(
|
||
Notification::new(NotificationKind::Info, "This is a timed info notification.")
|
||
.title("Info"),
|
||
);
|
||
state.notifications.add(
|
||
Notification::new(
|
||
NotificationKind::Success,
|
||
"The operation completed successfully.",
|
||
)
|
||
.title("Success")
|
||
.timed(Duration::from_secs(8)),
|
||
);
|
||
state.notifications.add(
|
||
Notification::new(
|
||
NotificationKind::Warning,
|
||
"This warning stays until you dismiss it.",
|
||
)
|
||
.title("Persistent warning")
|
||
.persistent(),
|
||
);
|
||
state.notifications.add(
|
||
Notification::new(
|
||
NotificationKind::Error,
|
||
"This error is persistent as well.\nUse the close button to dismiss it.",
|
||
)
|
||
.title("Persistent error")
|
||
.persistent(),
|
||
);
|
||
}
|
||
Message::Frame(now) => {
|
||
if !state.fade_animation.is_animating(now)
|
||
&& !state.fade_animation.value()
|
||
&& let Some(pending) = state.pending_settings_section.take()
|
||
{
|
||
state.settings_section = pending;
|
||
state.fade_animation.go_mut(true, now);
|
||
}
|
||
}
|
||
Message::ProfileFilterChanged(value) => state.profile_filter = value,
|
||
Message::ClearProfileFilter => state.profile_filter.clear(),
|
||
Message::ToggleAddMenu => state.add_menu_open = !state.add_menu_open,
|
||
Message::CloseAddMenu => state.add_menu_open = false,
|
||
Message::ToggleFolder(index) => {
|
||
if let Some(folder) = state.profile_folders.get_mut(index) {
|
||
folder.expanded = !folder.expanded;
|
||
}
|
||
state.selected = Some(Selection::Folder(index));
|
||
}
|
||
Message::HoverFolder(folder) => state.hovered_folder = folder,
|
||
Message::HoverTab { tab, hovered } => {
|
||
let now = Instant::now();
|
||
|
||
if hovered {
|
||
state.hovered_tab = Some(tab);
|
||
|
||
for (key, animation) in &mut state.tab_close_fades {
|
||
if *key != tab {
|
||
animation.go_mut(false, now);
|
||
}
|
||
}
|
||
|
||
state
|
||
.tab_close_fades
|
||
.entry(tab)
|
||
.or_insert_with(new_tab_close_animation)
|
||
.go_mut(true, now);
|
||
} else if state.hovered_tab == Some(tab) {
|
||
state.hovered_tab = None;
|
||
|
||
for animation in state.tab_close_fades.values_mut() {
|
||
animation.go_mut(false, now);
|
||
}
|
||
}
|
||
}
|
||
Message::SelectProfile { folder, profile } => {
|
||
state.selected = Some(Selection::Profile { folder, profile });
|
||
}
|
||
Message::ToggleChecked(item) => {
|
||
if !state.checked.remove(&item) {
|
||
state.checked.insert(item);
|
||
}
|
||
}
|
||
Message::DeselectAll => state.checked.clear(),
|
||
Message::RestoreFromTrash => {
|
||
state.trash_entries = load_trash_entries();
|
||
state.trash_checked.clear();
|
||
state.trash_open = true;
|
||
}
|
||
Message::ToggleTrashChecked(index) => {
|
||
if !state.trash_checked.remove(&index) {
|
||
state.trash_checked.insert(index);
|
||
}
|
||
}
|
||
Message::RestoreSelected => restore_trash_items(state),
|
||
Message::CloseTrash => {
|
||
state.trash_open = false;
|
||
state.trash_checked.clear();
|
||
}
|
||
Message::CopyChecked => {
|
||
if !state.checked.is_empty() {
|
||
let destination = state
|
||
.selected
|
||
.and_then(|selection| match selection {
|
||
Selection::Folder(index) => Some(index),
|
||
Selection::Profile { folder, .. } => Some(folder),
|
||
})
|
||
.unwrap_or(0);
|
||
state.transfer = Some(TransferDialog {
|
||
mode: TransferMode::Copy,
|
||
destination,
|
||
});
|
||
}
|
||
}
|
||
Message::MoveChecked => {
|
||
if !state.checked.is_empty() {
|
||
let destination = state
|
||
.selected
|
||
.and_then(|selection| match selection {
|
||
Selection::Folder(index) => Some(index),
|
||
Selection::Profile { folder, .. } => Some(folder),
|
||
})
|
||
.unwrap_or(0);
|
||
state.transfer = Some(TransferDialog {
|
||
mode: TransferMode::Move,
|
||
destination,
|
||
});
|
||
}
|
||
}
|
||
Message::DeleteChecked => {
|
||
if !state.checked.is_empty() {
|
||
state.confirm_delete = true;
|
||
}
|
||
}
|
||
Message::TransferFolderSelected(choice) => {
|
||
if let Some(transfer) = state.transfer.as_mut() {
|
||
transfer.destination = choice.index;
|
||
}
|
||
}
|
||
Message::ConfirmTransfer => {
|
||
if let Some(transfer) = state.transfer.clone() {
|
||
apply_transfer(state, transfer.mode, transfer.destination);
|
||
}
|
||
}
|
||
Message::CancelTransfer => state.transfer = None,
|
||
Message::ConfirmDelete => apply_delete(state),
|
||
Message::CancelDelete => state.confirm_delete = false,
|
||
Message::OpenProfileDialog => {
|
||
let folder = match state.selected {
|
||
Some(Selection::Folder(index)) => index,
|
||
Some(Selection::Profile { folder, .. }) => folder,
|
||
None => state
|
||
.profile_folders
|
||
.iter()
|
||
.position(|folder| folder.path == DEFAULT_PROFILE_FOLDER)
|
||
.unwrap_or(0),
|
||
};
|
||
state.add_menu_open = false;
|
||
state.profile_dialog = Some(ProfileDraft::new(folder));
|
||
return operation::focus(PROFILE_NAME_INPUT);
|
||
}
|
||
Message::ProfileNameChanged(value) => {
|
||
if let Some(draft) = state.profile_dialog.as_mut() {
|
||
draft.name = value.chars().take(150).collect();
|
||
}
|
||
}
|
||
Message::ProfileKindSelected(kind) => {
|
||
if let Some(draft) = state.profile_dialog.as_mut() {
|
||
draft.kind = kind;
|
||
}
|
||
}
|
||
Message::ProfileFolderSelected(choice) => {
|
||
if let Some(draft) = state.profile_dialog.as_mut() {
|
||
draft.folder = choice.index;
|
||
}
|
||
}
|
||
Message::SessionEndSelected(session_end) => {
|
||
if let Some(draft) = state.profile_dialog.as_mut() {
|
||
draft.session_end = session_end;
|
||
}
|
||
}
|
||
Message::ProfileHostChanged(value) => {
|
||
if let Some(draft) = state.profile_dialog.as_mut() {
|
||
draft.host = value;
|
||
}
|
||
}
|
||
Message::ProfilePortChanged(value) => {
|
||
let valid = value.chars().all(|c| c.is_ascii_digit())
|
||
&& (value.is_empty() || value.parse::<u32>().is_ok_and(|port| port <= 65534));
|
||
|
||
if valid {
|
||
if let Some(draft) = state.profile_dialog.as_mut() {
|
||
draft.port = value;
|
||
}
|
||
}
|
||
}
|
||
Message::ProfileUsernameChanged(value) => {
|
||
if let Some(draft) = state.profile_dialog.as_mut() {
|
||
draft.username = value;
|
||
}
|
||
}
|
||
Message::AuthMethodSelected(auth) => {
|
||
if let Some(draft) = state.profile_dialog.as_mut() {
|
||
draft.auth = auth;
|
||
}
|
||
}
|
||
Message::ProfilePasswordChanged(value) => {
|
||
if let Some(draft) = state.profile_dialog.as_mut() {
|
||
draft.password = value;
|
||
}
|
||
}
|
||
Message::TogglePasswordVisibility => {
|
||
if let Some(draft) = state.profile_dialog.as_mut() {
|
||
draft.password_visible = !draft.password_visible;
|
||
}
|
||
}
|
||
Message::ProfileStartPathChanged(value) => {
|
||
if let Some(draft) = state.profile_dialog.as_mut() {
|
||
draft.start_path = value;
|
||
}
|
||
}
|
||
Message::ProfilePrivateKeyChanged(value) => {
|
||
if let Some(draft) = state.profile_dialog.as_mut() {
|
||
draft.private_key = value;
|
||
}
|
||
}
|
||
Message::OpenDirectoryPicker => {
|
||
let path = state
|
||
.profile_dialog
|
||
.as_ref()
|
||
.map(|draft| resolve_start_path(&draft.start_path))
|
||
.filter(|path| path.is_dir())
|
||
.unwrap_or_else(home_dir);
|
||
|
||
state.dir_picker = Some(DirPicker::open(path, false, PickerTarget::StartPath));
|
||
}
|
||
Message::OpenPrivateKeyPicker => {
|
||
let typed = state
|
||
.profile_dialog
|
||
.as_ref()
|
||
.map(|draft| resolve_start_path(&draft.private_key))
|
||
.unwrap_or_default();
|
||
|
||
let directory = if typed.is_dir() {
|
||
typed
|
||
} else {
|
||
typed
|
||
.parent()
|
||
.filter(|path| path.is_dir())
|
||
.map(PathBuf::from)
|
||
.unwrap_or_else(home_dir)
|
||
};
|
||
|
||
state.dir_picker = Some(DirPicker::open(directory, true, PickerTarget::PrivateKey));
|
||
}
|
||
Message::DirPickerEnter(path) => {
|
||
if let Some(picker) = state.dir_picker.as_mut() {
|
||
picker.navigate(path);
|
||
}
|
||
}
|
||
Message::DirPickerSelect(path) => {
|
||
if let Some(picker) = state.dir_picker.as_mut() {
|
||
picker.selected = Some(path);
|
||
}
|
||
}
|
||
Message::DirPickerUp => {
|
||
if let Some(picker) = state.dir_picker.as_mut() {
|
||
if let Some(parent) = picker.path.parent().map(PathBuf::from) {
|
||
picker.navigate(parent);
|
||
}
|
||
}
|
||
}
|
||
Message::ConfirmDirectoryPicker => {
|
||
if let Some(picker) = state.dir_picker.take() {
|
||
let value = match picker.target {
|
||
PickerTarget::StartPath => Some(picker.path.clone()),
|
||
PickerTarget::PrivateKey => picker.selected.clone(),
|
||
};
|
||
|
||
if let (Some(value), Some(draft)) = (value, state.profile_dialog.as_mut()) {
|
||
let value = value.to_string_lossy().into_owned();
|
||
match picker.target {
|
||
PickerTarget::StartPath => draft.start_path = value,
|
||
PickerTarget::PrivateKey => draft.private_key = value,
|
||
}
|
||
}
|
||
}
|
||
}
|
||
Message::CancelDirectoryPicker => state.dir_picker = None,
|
||
Message::ConfirmProfile => {
|
||
let Some(draft) = state.profile_dialog.as_ref() else {
|
||
return Task::none();
|
||
};
|
||
|
||
if !draft.valid() {
|
||
return Task::none();
|
||
}
|
||
|
||
let folder_index = draft
|
||
.folder
|
||
.min(state.profile_folders.len().saturating_sub(1));
|
||
let Some(folder_path) = state
|
||
.profile_folders
|
||
.get(folder_index)
|
||
.map(|folder| folder.path.clone())
|
||
else {
|
||
return Task::none();
|
||
};
|
||
let mut profile = Profile {
|
||
name: draft.name.trim().to_owned(),
|
||
kind: draft.kind,
|
||
session_end: draft.session_end,
|
||
host: draft.host.trim().to_owned(),
|
||
port: draft.port.clone(),
|
||
username: draft.username.trim().to_owned(),
|
||
auth: draft.auth,
|
||
password: draft.password.clone(),
|
||
start_path: draft.start_path.clone(),
|
||
private_key: draft.private_key.clone(),
|
||
file: None,
|
||
};
|
||
|
||
profile.file = write_profile(&profile, &folder_path);
|
||
save_folders(&state.profile_folders);
|
||
|
||
let Some(folder) = state.profile_folders.get_mut(folder_index) else {
|
||
return Task::none();
|
||
};
|
||
|
||
folder.profiles.push(profile);
|
||
folder.expanded = true;
|
||
state.selected = Some(Selection::Profile {
|
||
folder: folder_index,
|
||
profile: folder.profiles.len() - 1,
|
||
});
|
||
state.profile_dialog = None;
|
||
}
|
||
Message::CancelProfile => state.profile_dialog = None,
|
||
Message::OpenFolderDialog => {
|
||
state.add_menu_open = false;
|
||
state.folder_dialog = Some(String::new());
|
||
return operation::focus(FOLDER_NAME_INPUT);
|
||
}
|
||
Message::FolderNameChanged(value) => {
|
||
if let Some(draft) = state.folder_dialog.as_mut() {
|
||
*draft = value;
|
||
}
|
||
}
|
||
Message::ConfirmFolder => {
|
||
let Some(name) = state
|
||
.folder_dialog
|
||
.as_deref()
|
||
.map(str::trim)
|
||
.filter(|name| !name.is_empty())
|
||
.map(str::to_owned)
|
||
else {
|
||
return Task::none();
|
||
};
|
||
|
||
let path = normalize_folder_path(&name);
|
||
let index = ensure_folder(&mut state.profile_folders, &path);
|
||
state.checked.clear();
|
||
state.selected = Some(Selection::Folder(index));
|
||
state.folder_dialog = None;
|
||
save_folders(&state.profile_folders);
|
||
}
|
||
Message::CancelFolder => state.folder_dialog = None,
|
||
Message::Ignore => {}
|
||
Message::OpenShortcutCapture(action) => {
|
||
state.shortcut_capture = Some(ShortcutCapture {
|
||
action,
|
||
candidate: None,
|
||
error: None,
|
||
});
|
||
}
|
||
Message::CancelShortcut => state.shortcut_capture = None,
|
||
Message::ClearShortcut(action) => {
|
||
state.shortcuts.set(action, None);
|
||
state.shortcut_capture = None;
|
||
}
|
||
Message::DefaultShortcut(action) => {
|
||
state
|
||
.shortcuts
|
||
.set(action, Shortcuts::default().get(action).cloned());
|
||
state.shortcut_capture = None;
|
||
}
|
||
Message::ApplyShortcut => apply_shortcut(state),
|
||
Message::CaptureKey { key, modifiers } => match key {
|
||
keyboard::Key::Named(keyboard::key::Named::Escape) => {
|
||
state.shortcut_capture = None;
|
||
}
|
||
keyboard::Key::Named(keyboard::key::Named::Enter) => apply_shortcut(state),
|
||
keyboard::Key::Named(
|
||
keyboard::key::Named::Control
|
||
| keyboard::key::Named::Shift
|
||
| keyboard::key::Named::Alt,
|
||
) => {}
|
||
_ => {
|
||
if let Some(capture) = state.shortcut_capture.as_mut() {
|
||
match Shortcut::from_key(&key, modifiers) {
|
||
Some(shortcut) => {
|
||
capture.candidate = Some(shortcut);
|
||
capture.error = None;
|
||
}
|
||
None => {
|
||
capture.candidate = None;
|
||
capture.error = Some("Use Ctrl or Alt plus a key.".to_owned());
|
||
}
|
||
}
|
||
}
|
||
}
|
||
},
|
||
Message::TabsScrolled(window, viewport) => {
|
||
if let Some(window_state) = state.windows.get_mut(&window) {
|
||
window_state.tab_offset = viewport.absolute_offset().x;
|
||
}
|
||
}
|
||
Message::ScrollTabs(window, delta) => {
|
||
let amount = match delta {
|
||
mouse::ScrollDelta::Lines { y, .. } => y * 60.0,
|
||
mouse::ScrollDelta::Pixels { x, y } => x + y,
|
||
};
|
||
return scroll_tabs_by(state, window, amount);
|
||
}
|
||
Message::ScrollTabsBy(window, amount) => {
|
||
return scroll_tabs_by(state, window, amount);
|
||
}
|
||
Message::Quit => std::process::exit(0),
|
||
}
|
||
|
||
Task::none()
|
||
}
|
||
|
||
fn close_command_palette(state: &mut Moorly, window: window::Id) {
|
||
if let Some(window_state) = state.windows.get_mut(&window) {
|
||
window_state.command_palette_open = false;
|
||
window_state.command_palette_query.clear();
|
||
window_state.command_palette_selected = 0;
|
||
}
|
||
}
|
||
|
||
/// Commits the captured shortcut if it is valid and unused.
|
||
fn apply_shortcut(state: &mut Moorly) {
|
||
let Some(capture) = state.shortcut_capture.as_ref() else {
|
||
return;
|
||
};
|
||
let action = capture.action;
|
||
|
||
let Some(candidate) = capture.candidate.clone() else {
|
||
if let Some(capture) = state.shortcut_capture.as_mut() {
|
||
capture.error = Some("Press a key combination first.".to_owned());
|
||
}
|
||
return;
|
||
};
|
||
|
||
if let Some(name) = state.shortcuts.conflict(&candidate, action) {
|
||
if let Some(capture) = state.shortcut_capture.as_mut() {
|
||
capture.error = Some(format!("Already used by {name}."));
|
||
}
|
||
return;
|
||
}
|
||
|
||
state.shortcuts.set(action, Some(candidate));
|
||
state.shortcut_capture = None;
|
||
}
|
||
|
||
fn window_event(state: &mut Moorly, window: window::Id, event: window::Event) -> Task<Message> {
|
||
match event {
|
||
window::Event::Opened { position, size } => {
|
||
if let Some(window_state) = state.windows.get_mut(&window) {
|
||
window_state.size = size;
|
||
if position.is_some() {
|
||
window_state.position = position;
|
||
}
|
||
}
|
||
}
|
||
window::Event::Moved(position) => {
|
||
if let Some(window_state) = state.windows.get_mut(&window) {
|
||
window_state.position = Some(position);
|
||
}
|
||
}
|
||
window::Event::Resized(size) => {
|
||
if let Some(window_state) = state.windows.get_mut(&window) {
|
||
window_state.size = size;
|
||
}
|
||
}
|
||
window::Event::Focused => state.focused_window = Some(window),
|
||
window::Event::CloseRequested => {
|
||
remove_window(state, window);
|
||
|
||
if state.windows.is_empty() {
|
||
return iced::exit();
|
||
}
|
||
|
||
return window::close(window);
|
||
}
|
||
window::Event::Closed => {
|
||
remove_window(state, window);
|
||
|
||
if state.windows.is_empty() {
|
||
return iced::exit();
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
|
||
Task::none()
|
||
}
|
||
|
||
fn remove_window(state: &mut Moorly, window: window::Id) {
|
||
state.windows.remove(&window);
|
||
state.window_order.retain(|id| *id != window);
|
||
|
||
if state.main_window == Some(window) {
|
||
state.main_window = None;
|
||
}
|
||
if state.focused_window == Some(window) {
|
||
state.focused_window = state.window_order.first().copied();
|
||
}
|
||
if state
|
||
.drag
|
||
.as_ref()
|
||
.is_some_and(|drag| drag.window == window)
|
||
{
|
||
state.drag = None;
|
||
}
|
||
}
|
||
|
||
/// Width the tab strip gets after the scroll buttons and hamburger.
|
||
fn tab_strip_width(window_width: f32) -> f32 {
|
||
(window_width
|
||
- TAB_STRIP_LEFT
|
||
- MENUBAR_RIGHT_PADDING
|
||
- 2.0 * SCROLL_BUTTON_WIDTH
|
||
- HAMBURGER_WIDTH
|
||
- 3.0 * TAB_SPACING)
|
||
.max(0.0)
|
||
}
|
||
|
||
struct TabStripMetrics {
|
||
viewport: f32,
|
||
width: f32,
|
||
step: f32,
|
||
content: f32,
|
||
offset: f32,
|
||
}
|
||
|
||
fn tab_strip_metrics(window_state: &WindowState) -> TabStripMetrics {
|
||
let viewport = tab_strip_width(window_state.size.width);
|
||
let count = window_state.tabs.len();
|
||
let width = tab_width(viewport, count);
|
||
let step = width + TAB_SPACING;
|
||
let content = if count == 0 {
|
||
0.0
|
||
} else {
|
||
step * count as f32 - TAB_SPACING
|
||
};
|
||
let offset = window_state.tab_offset.min((content - viewport).max(0.0));
|
||
|
||
TabStripMetrics {
|
||
viewport,
|
||
width,
|
||
step,
|
||
content,
|
||
offset,
|
||
}
|
||
}
|
||
|
||
/// Index of the tab under `point`, if the point is inside the tab strip.
|
||
fn tab_index_at(state: &Moorly, window: window::Id, point: Point) -> Option<usize> {
|
||
let window_state = state.windows.get(&window)?;
|
||
|
||
if window_state.tabs.is_empty()
|
||
|| point.y < 0.0
|
||
|| point.y > MENUBAR_HEIGHT
|
||
|| point.x < TAB_STRIP_LEFT
|
||
{
|
||
return None;
|
||
}
|
||
|
||
let metrics = tab_strip_metrics(window_state);
|
||
if metrics.viewport <= 0.0 || point.x > TAB_STRIP_LEFT + metrics.viewport {
|
||
return None;
|
||
}
|
||
|
||
let relative = point.x - TAB_STRIP_LEFT + metrics.offset;
|
||
|
||
if relative < 0.0 || relative > metrics.content {
|
||
return None;
|
||
}
|
||
|
||
Some(((relative / metrics.step).floor() as usize).min(window_state.tabs.len() - 1))
|
||
}
|
||
|
||
/// Gap the dragged tab would be inserted into: `0` is before the first tab,
|
||
/// `tabs.len()` is after the last one.
|
||
fn tab_gap_index(state: &Moorly, window: window::Id, x: f32) -> Option<usize> {
|
||
let window_state = state.windows.get(&window)?;
|
||
if window_state.tabs.is_empty() {
|
||
return Some(0);
|
||
}
|
||
|
||
let metrics = tab_strip_metrics(window_state);
|
||
let relative = x - TAB_STRIP_LEFT + metrics.offset;
|
||
let mut gap = window_state.tabs.len();
|
||
|
||
for index in 0..window_state.tabs.len() {
|
||
let midpoint = index as f32 * metrics.step + metrics.width / 2.0;
|
||
if relative < midpoint {
|
||
gap = index;
|
||
break;
|
||
}
|
||
}
|
||
|
||
Some(gap)
|
||
}
|
||
|
||
fn start_tab_drag(state: &mut Moorly, window: window::Id) {
|
||
state.drag = None;
|
||
|
||
let Some((pointer, menu_open)) = state
|
||
.windows
|
||
.get(&window)
|
||
.map(|window_state| (window_state.pointer, window_state.menu_open))
|
||
else {
|
||
return;
|
||
};
|
||
|
||
if menu_open {
|
||
return;
|
||
}
|
||
|
||
let Some(pointer) = pointer else {
|
||
return;
|
||
};
|
||
let Some(index) = tab_index_at(state, window, pointer) else {
|
||
return;
|
||
};
|
||
let Some(window_state) = state.windows.get(&window) else {
|
||
return;
|
||
};
|
||
|
||
state.drag = Some(TabDrag {
|
||
window,
|
||
tab: window_state.tabs[index],
|
||
origin: pointer,
|
||
pointer,
|
||
moved: false,
|
||
detach: false,
|
||
});
|
||
}
|
||
|
||
fn apply_tab_move(state: &mut Moorly, window: window::Id, tab: Tab, gap: usize) {
|
||
let Some(window_state) = state.windows.get_mut(&window) else {
|
||
return;
|
||
};
|
||
let Some(current) = window_state.tabs.iter().position(|open| *open == tab) else {
|
||
return;
|
||
};
|
||
|
||
// Removing the tab collapses its own slot, so gaps after it shift left.
|
||
let target = if current < gap { gap - 1 } else { gap };
|
||
if target == current {
|
||
return;
|
||
}
|
||
|
||
window_state.tabs.remove(current);
|
||
window_state.tabs.insert(target, tab);
|
||
}
|
||
|
||
/// Scroll delta for auto-scrolling while a tab is dragged near an edge.
|
||
fn drag_scroll_delta(state: &Moorly) -> Option<f32> {
|
||
let drag = state.drag.as_ref()?;
|
||
if drag.detach || !drag.moved {
|
||
return None;
|
||
}
|
||
|
||
let window_state = state.windows.get(&drag.window)?;
|
||
let metrics = tab_strip_metrics(window_state);
|
||
if window_state.tabs.is_empty()
|
||
|| metrics.viewport <= 0.0
|
||
|| metrics.content <= metrics.viewport
|
||
{
|
||
return None;
|
||
}
|
||
|
||
let x = drag.pointer.x;
|
||
let left = TAB_STRIP_LEFT;
|
||
let right = left + metrics.viewport;
|
||
|
||
if x < left + DRAG_EDGE {
|
||
let amount = ((left + DRAG_EDGE - x) / DRAG_EDGE).clamp(0.0, 1.0);
|
||
return Some(-DRAG_SCROLL_SPEED * amount);
|
||
}
|
||
|
||
if x > right - DRAG_EDGE {
|
||
let amount = ((x - (right - DRAG_EDGE)) / DRAG_EDGE).clamp(0.0, 1.0);
|
||
return Some(DRAG_SCROLL_SPEED * amount);
|
||
}
|
||
|
||
None
|
||
}
|
||
|
||
// ponytail: window geometry is enough for X11/Windows drops. Wayland does not
|
||
// expose window positions, so there a drop only moves tabs when the release is
|
||
// routed directly to the destination window.
|
||
fn window_at(state: &Moorly, except: window::Id, point: Point) -> Option<window::Id> {
|
||
state.windows.iter().find_map(|(id, window_state)| {
|
||
if *id == except {
|
||
return None;
|
||
}
|
||
|
||
let position = window_state.position?;
|
||
Rectangle::new(position, window_state.size)
|
||
.contains(point)
|
||
.then_some(*id)
|
||
})
|
||
}
|
||
|
||
fn drop_targets(state: &Moorly, source: window::Id) -> Vec<(window::Id, String)> {
|
||
state
|
||
.window_order
|
||
.iter()
|
||
.filter(|id| **id != source && state.windows.contains_key(id))
|
||
.map(|id| (*id, window_title(state, *id)))
|
||
.collect()
|
||
}
|
||
|
||
fn drop_panel_rect(window_state: &WindowState, count: usize) -> Rectangle {
|
||
let width = DROP_PANEL_WIDTH.min((window_state.size.width - 24.0).max(120.0));
|
||
let height = DROP_PANEL_PADDING * 2.0
|
||
+ DROP_HEADER_HEIGHT
|
||
+ count as f32 * (DROP_ROW_HEIGHT + DROP_ROW_GAP);
|
||
let x = ((window_state.size.width - width) / 2.0).max(0.0);
|
||
let y = MENUBAR_HEIGHT + 8.0;
|
||
|
||
Rectangle::new(Point::new(x, y), Size::new(width, height))
|
||
}
|
||
|
||
fn drop_target_index(state: &Moorly, source: window::Id, point: Point) -> Option<usize> {
|
||
let window_state = state.windows.get(&source)?;
|
||
let targets = drop_targets(state, source);
|
||
if targets.is_empty() {
|
||
return None;
|
||
}
|
||
|
||
let rect = drop_panel_rect(window_state, targets.len());
|
||
if !rect.contains(point) {
|
||
return None;
|
||
}
|
||
|
||
let row_top = rect.y + DROP_PANEL_PADDING + DROP_HEADER_HEIGHT + DROP_ROW_GAP;
|
||
if point.y < row_top {
|
||
return None;
|
||
}
|
||
|
||
let index = ((point.y - row_top) / (DROP_ROW_HEIGHT + DROP_ROW_GAP)).floor() as usize;
|
||
(index < targets.len()).then_some(index)
|
||
}
|
||
|
||
fn drop_target_at(state: &Moorly, source: window::Id, point: Point) -> Option<window::Id> {
|
||
let index = drop_target_index(state, source, point)?;
|
||
drop_targets(state, source).get(index).map(|(id, _)| *id)
|
||
}
|
||
|
||
fn move_tab_to_window(state: &mut Moorly, source: window::Id, destination: window::Id, tab: Tab) {
|
||
let Some(source_state) = state.windows.get_mut(&source) else {
|
||
return;
|
||
};
|
||
let Some(index) = source_state.tabs.iter().position(|open| *open == tab) else {
|
||
return;
|
||
};
|
||
source_state.tabs.remove(index);
|
||
|
||
if source_state.active_tab == Some(tab) {
|
||
source_state.active_tab = source_state
|
||
.tabs
|
||
.get(index)
|
||
.or_else(|| source_state.tabs.last())
|
||
.copied();
|
||
}
|
||
|
||
if let Some(destination_state) = state.windows.get_mut(&destination) {
|
||
if !destination_state.tabs.contains(&tab) {
|
||
destination_state.tabs.push(tab);
|
||
}
|
||
destination_state.active_tab = Some(tab);
|
||
}
|
||
|
||
state.focused_window = Some(destination);
|
||
}
|
||
|
||
/// Moves a tab into a brand-new window positioned where it was dropped.
|
||
fn detach_tab(
|
||
state: &mut Moorly,
|
||
source: window::Id,
|
||
tab: Tab,
|
||
global: Option<Point>,
|
||
) -> Task<Message> {
|
||
let Some(source_state) = state.windows.get_mut(&source) else {
|
||
return Task::none();
|
||
};
|
||
let Some(index) = source_state.tabs.iter().position(|open| *open == tab) else {
|
||
return Task::none();
|
||
};
|
||
source_state.tabs.remove(index);
|
||
|
||
if source_state.active_tab == Some(tab) {
|
||
source_state.active_tab = source_state
|
||
.tabs
|
||
.get(index)
|
||
.or_else(|| source_state.tabs.last())
|
||
.copied();
|
||
}
|
||
|
||
let size = Size::new(900.0, 600.0);
|
||
let position =
|
||
global.map(|point| Point::new((point.x - 100.0).max(0.0), (point.y - 20.0).max(0.0)));
|
||
let settings = window::Settings {
|
||
size,
|
||
position: position.map_or(window::Position::Default, window::Position::Specific),
|
||
exit_on_close_request: false,
|
||
..window::Settings::default()
|
||
};
|
||
let (id, open) = window::open(settings);
|
||
state
|
||
.windows
|
||
.insert(id, WindowState::with_tab(tab, size, position));
|
||
state.window_order.push(id);
|
||
state.focused_window = Some(id);
|
||
|
||
Task::batch([
|
||
open.map(|_| Message::Ignore),
|
||
close_window_if_empty(state, source),
|
||
])
|
||
}
|
||
|
||
fn finish_drag(state: &mut Moorly, released_in: window::Id) -> Task<Message> {
|
||
let Some(drag) = state.drag.take() else {
|
||
return Task::none();
|
||
};
|
||
let source = drag.window;
|
||
let tab = drag.tab;
|
||
|
||
if !drag.moved
|
||
|| !state
|
||
.windows
|
||
.get(&source)
|
||
.is_some_and(|window_state| window_state.tabs.contains(&tab))
|
||
{
|
||
return Task::none();
|
||
}
|
||
|
||
// Dropping directly into another window is the cross-window move path.
|
||
if released_in != source && state.windows.contains_key(&released_in) {
|
||
move_tab_to_window(state, source, released_in, tab);
|
||
return close_window_if_empty(state, source);
|
||
}
|
||
|
||
let Some(window_state) = state.windows.get(&source) else {
|
||
return Task::none();
|
||
};
|
||
let outside = drag.pointer.x < 0.0
|
||
|| drag.pointer.y < 0.0
|
||
|| drag.pointer.x > window_state.size.width
|
||
|| drag.pointer.y > window_state.size.height;
|
||
|
||
// On Wayland the window under the pointer is unknowable, so the user can
|
||
// drop onto the in-window target list instead.
|
||
if (drag.detach || outside)
|
||
&& let Some(destination) = drop_target_at(state, source, drag.pointer)
|
||
{
|
||
move_tab_to_window(state, source, destination, tab);
|
||
return close_window_if_empty(state, source);
|
||
}
|
||
|
||
let global = window_state
|
||
.position
|
||
.map(|position| Point::new(position.x + drag.pointer.x, position.y + drag.pointer.y));
|
||
|
||
if drag.detach || outside {
|
||
if let Some(global) = global
|
||
&& let Some(destination) = window_at(state, source, global)
|
||
{
|
||
move_tab_to_window(state, source, destination, tab);
|
||
return close_window_if_empty(state, source);
|
||
}
|
||
|
||
return detach_tab(state, source, tab, global);
|
||
}
|
||
|
||
if let Some(gap) = tab_gap_index(state, source, drag.pointer.x) {
|
||
apply_tab_move(state, source, tab, gap);
|
||
}
|
||
|
||
Task::none()
|
||
}
|
||
|
||
fn close_window_if_empty(state: &mut Moorly, window: window::Id) -> Task<Message> {
|
||
if !state
|
||
.windows
|
||
.get(&window)
|
||
.is_some_and(|window_state| window_state.tabs.is_empty())
|
||
{
|
||
return Task::none();
|
||
}
|
||
|
||
remove_window(state, window);
|
||
|
||
if state.windows.is_empty() {
|
||
return iced::exit();
|
||
}
|
||
|
||
window::close(window)
|
||
}
|
||
|
||
fn scroll_tabs_by(state: &Moorly, window: window::Id, x: f32) -> Task<Message> {
|
||
let Some(window_state) = state.windows.get(&window) else {
|
||
return Task::none();
|
||
};
|
||
|
||
operation::scroll_by(
|
||
window_state.scroll_id.clone(),
|
||
operation::AbsoluteOffset { x, y: 0.0 },
|
||
)
|
||
}
|
||
|
||
fn scroll_tabs_to_end(state: &Moorly, window: window::Id) -> Task<Message> {
|
||
let Some(window_state) = state.windows.get(&window) else {
|
||
return Task::none();
|
||
};
|
||
|
||
operation::snap_to(
|
||
window_state.scroll_id.clone(),
|
||
operation::RelativeOffset::END,
|
||
)
|
||
}
|
||
|
||
/// Removes a tab and keeps the selection sensible: the next tab on the right
|
||
/// takes over, falling back to the new last tab. Returns whether the active
|
||
/// tab was the one closed.
|
||
fn close_tab(state: &mut Moorly, window: window::Id, tab: Tab) -> bool {
|
||
let was_active = {
|
||
let Some(window_state) = state.windows.get_mut(&window) else {
|
||
return false;
|
||
};
|
||
let Some(index) = window_state.tabs.iter().position(|open| *open == tab) else {
|
||
return false;
|
||
};
|
||
let was_active = window_state.active_tab == Some(tab);
|
||
window_state.tabs.remove(index);
|
||
|
||
if was_active {
|
||
window_state.active_tab = window_state
|
||
.tabs
|
||
.get(index)
|
||
.or_else(|| window_state.tabs.last())
|
||
.copied();
|
||
}
|
||
|
||
was_active
|
||
};
|
||
|
||
// Drop the tab's page state along with the tab itself.
|
||
if tab == Tab::Settings {
|
||
state.settings_section = SettingsSection::default();
|
||
}
|
||
|
||
was_active
|
||
}
|
||
|
||
/// Estimated scroll delta that brings the active tab into view, or `None`
|
||
/// when it already is (or the strip does not overflow).
|
||
fn tab_reveal_delta(state: &Moorly, window: window::Id) -> Option<f32> {
|
||
let window_state = state.windows.get(&window)?;
|
||
let index = window_state
|
||
.active_tab
|
||
.and_then(|active| window_state.tabs.iter().position(|tab| *tab == active))?;
|
||
|
||
if window_state.tabs.is_empty() {
|
||
return None;
|
||
}
|
||
|
||
let metrics = tab_strip_metrics(window_state);
|
||
if metrics.viewport <= 0.0 || metrics.content <= metrics.viewport {
|
||
return None;
|
||
}
|
||
|
||
let start = index as f32 * metrics.step;
|
||
let visible_start = metrics.offset;
|
||
let visible_end = metrics.offset + metrics.viewport;
|
||
|
||
if start >= visible_start && start + metrics.width <= visible_end {
|
||
return None;
|
||
}
|
||
|
||
let target = (start - (metrics.viewport - metrics.width) / 2.0).max(0.0);
|
||
Some(target - metrics.offset)
|
||
}
|
||
|
||
fn reveal_active_tab(state: &Moorly, window: window::Id) -> Task<Message> {
|
||
match tab_reveal_delta(state, window) {
|
||
Some(delta) => scroll_tabs_by(state, window, delta),
|
||
None => Task::none(),
|
||
}
|
||
}
|
||
|
||
fn hamburger(
|
||
open: bool,
|
||
text_color: Color,
|
||
window: window::Id,
|
||
) -> iced::widget::Button<'static, Message> {
|
||
let icon: Element<'static, Message> = if open {
|
||
stack![
|
||
text("☰").size(14),
|
||
container(text("X").size(11).color(theme::DANGER))
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.align_x(Alignment::End)
|
||
.align_y(Alignment::Start),
|
||
]
|
||
.into()
|
||
} else {
|
||
text("☰").size(14).into()
|
||
};
|
||
|
||
button(icon)
|
||
.on_press(Message::ToggleMenu(window))
|
||
.width(HAMBURGER_WIDTH)
|
||
.padding([2, 8])
|
||
.style(move |theme, status| theme::menubar_button(theme, status, text_color))
|
||
}
|
||
|
||
/// Shortens a title to `MAX_TAB_TITLE` characters, ellipsizing the rest.
|
||
fn fit_title(title: &str) -> String {
|
||
if title.chars().count() <= MAX_TAB_TITLE {
|
||
return title.to_owned();
|
||
}
|
||
|
||
let mut fitted: String = title.chars().take(MAX_TAB_TITLE - 3).collect();
|
||
fitted.push_str("...");
|
||
fitted
|
||
}
|
||
|
||
/// Width that lets the strip show as many tabs as possible, between the
|
||
/// minimum and maximum tab widths.
|
||
fn tab_width(available: f32, count: usize) -> f32 {
|
||
let count = count as f32;
|
||
|
||
if count == 0.0 || available <= 0.0 {
|
||
return TAB_MAX_WIDTH;
|
||
}
|
||
|
||
let available = available - TAB_SPACING * (count - 1.0);
|
||
(available / count).clamp(TAB_MIN_WIDTH, TAB_MAX_WIDTH)
|
||
}
|
||
|
||
fn tab_shell(
|
||
content: Element<'static, Message>,
|
||
active: bool,
|
||
width: f32,
|
||
active_bg: Color,
|
||
inactive_bg: Color,
|
||
outline: Color,
|
||
) -> Element<'static, Message> {
|
||
let tab = container(content)
|
||
.width(width)
|
||
.height(Length::Fill)
|
||
.align_y(Alignment::Center)
|
||
.style(move |theme| theme::tab(theme, active, active_bg, inactive_bg));
|
||
|
||
// Draw the active outline as three separate edges so there is no bottom
|
||
// border to blend away.
|
||
if active {
|
||
let top = container(space::horizontal())
|
||
.width(Length::Fill)
|
||
.height(1.0)
|
||
.style(move |theme| theme::tab_outline(theme, outline));
|
||
|
||
let left = container(space::vertical())
|
||
.width(1.0)
|
||
.height(Length::Fill)
|
||
.style(move |theme| theme::tab_outline(theme, outline));
|
||
|
||
let right = container(
|
||
container(space::vertical())
|
||
.width(1.0)
|
||
.height(Length::Fill)
|
||
.style(move |theme| theme::tab_outline(theme, outline)),
|
||
)
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.align_x(Alignment::End);
|
||
|
||
stack![tab, top, left, right].into()
|
||
} else {
|
||
tab.into()
|
||
}
|
||
}
|
||
|
||
fn tab_view(
|
||
window: window::Id,
|
||
tab: Tab,
|
||
active: bool,
|
||
hide_close: bool,
|
||
close_opacity: f32,
|
||
width: f32,
|
||
colors: [Color; 5],
|
||
) -> Element<'static, Message> {
|
||
let title = tab.title();
|
||
let padding = Padding::new(10.0);
|
||
let text_color = colors[ColorOption::Text.index()];
|
||
let active_bg = colors[ColorOption::MainBackground.index()];
|
||
let inactive_bg = colors[ColorOption::SidebarBackground.index()];
|
||
let outline = colors[ColorOption::ActiveTabOutline.index()];
|
||
|
||
let title_button = button(
|
||
container(text(fit_title(&title)).size(15))
|
||
.width(Length::Fill)
|
||
.align_x(Alignment::Center),
|
||
)
|
||
.on_press(Message::SelectTab(window, tab))
|
||
.padding(padding)
|
||
.width(Length::Fill)
|
||
.clip(true)
|
||
.style(move |theme, status| {
|
||
let mut style = button::text(theme, status);
|
||
style.text_color = if active {
|
||
text_color
|
||
} else {
|
||
text_color.scale_alpha(0.6)
|
||
};
|
||
style
|
||
});
|
||
|
||
let close_icon = |padding: Padding| {
|
||
button(text("×").size(15))
|
||
.on_press(Message::CloseTab(window, tab))
|
||
.padding(padding)
|
||
.style(move |theme, status| {
|
||
let mut style = button::text(theme, status);
|
||
style.text_color = text_color;
|
||
style.text_color.a = close_opacity;
|
||
style
|
||
})
|
||
};
|
||
|
||
let tab_element = if hide_close {
|
||
let tab = tab_shell(
|
||
title_button.into(),
|
||
active,
|
||
width,
|
||
active_bg,
|
||
inactive_bg,
|
||
outline,
|
||
);
|
||
|
||
if close_opacity <= 0.01 {
|
||
tab
|
||
} else {
|
||
let close =
|
||
container(close_icon(Padding::new(4.0))).style(move |_theme: &iced::Theme| {
|
||
let mut background = if active { active_bg } else { inactive_bg };
|
||
background.a = close_opacity;
|
||
|
||
container::Style {
|
||
background: Some(background.into()),
|
||
border: Border {
|
||
color: Color::TRANSPARENT,
|
||
width: 0.0,
|
||
radius: 4.0.into(),
|
||
},
|
||
..container::Style::default()
|
||
}
|
||
});
|
||
|
||
let overlay = container(close)
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.align_x(Alignment::End)
|
||
.align_y(Alignment::Center)
|
||
.padding(Padding::ZERO.right(12.0));
|
||
|
||
stack![tab, overlay]
|
||
.width(width)
|
||
.height(Length::Fill)
|
||
.into()
|
||
}
|
||
} else {
|
||
tab_shell(
|
||
row![title_button, close_icon(Padding::new(10.0))]
|
||
.spacing(0)
|
||
.align_y(Alignment::Center)
|
||
.into(),
|
||
active,
|
||
width,
|
||
active_bg,
|
||
inactive_bg,
|
||
outline,
|
||
)
|
||
};
|
||
|
||
let content = mouse_area(tab_element)
|
||
.on_enter(Message::HoverTab { tab, hovered: true })
|
||
.on_exit(Message::HoverTab {
|
||
tab,
|
||
hovered: false,
|
||
});
|
||
|
||
tooltip(
|
||
content,
|
||
container(text(title).size(11)).padding(4),
|
||
tooltip::Position::Bottom,
|
||
)
|
||
.into()
|
||
}
|
||
|
||
/// Floating copy of the dragged tab that follows the pointer.
|
||
fn drag_ghost(
|
||
state: &Moorly,
|
||
window: window::Id,
|
||
colors: [Color; 5],
|
||
) -> Option<Element<'static, Message>> {
|
||
let drag = state
|
||
.drag
|
||
.as_ref()
|
||
.filter(|drag| drag.window == window && drag.moved)?;
|
||
let window_state = state.windows.get(&window)?;
|
||
|
||
let x =
|
||
(drag.pointer.x + 12.0).clamp(0.0, (window_state.size.width - DRAG_GHOST_WIDTH).max(0.0));
|
||
let y =
|
||
(drag.pointer.y + 12.0).clamp(0.0, (window_state.size.height - DRAG_GHOST_HEIGHT).max(0.0));
|
||
|
||
let text_color = colors[ColorOption::Text.index()];
|
||
let mut background = colors[ColorOption::MainBackground.index()];
|
||
background.a = 0.9;
|
||
let outline = colors[ColorOption::ActiveTabOutline.index()];
|
||
|
||
let ghost = container(
|
||
text(fit_title(&drag.tab.title()))
|
||
.size(14)
|
||
.color(text_color),
|
||
)
|
||
.width(DRAG_GHOST_WIDTH)
|
||
.height(DRAG_GHOST_HEIGHT)
|
||
.padding([5, 10])
|
||
.align_y(Alignment::Center)
|
||
.style(move |_| container::Style {
|
||
background: Some(background.into()),
|
||
border: Border {
|
||
color: outline,
|
||
width: 1.0,
|
||
radius: 6.0.into(),
|
||
},
|
||
shadow: Shadow {
|
||
color: Color::BLACK.scale_alpha(0.35),
|
||
offset: Vector::new(0.0, 4.0),
|
||
blur_radius: 10.0,
|
||
},
|
||
text_color: Some(text_color),
|
||
..container::Style::default()
|
||
});
|
||
|
||
Some(
|
||
container(ghost)
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.align_x(Alignment::Start)
|
||
.align_y(Alignment::Start)
|
||
.padding(Padding {
|
||
top: y,
|
||
left: x,
|
||
right: 0.0,
|
||
bottom: 0.0,
|
||
})
|
||
.into(),
|
||
)
|
||
}
|
||
|
||
/// Vertical marker showing where the dragged tab will be inserted on release.
|
||
fn tab_drop_bar(
|
||
state: &Moorly,
|
||
window: window::Id,
|
||
colors: [Color; 5],
|
||
) -> Option<Element<'static, Message>> {
|
||
let drag = state
|
||
.drag
|
||
.as_ref()
|
||
.filter(|drag| drag.window == window && drag.moved && !drag.detach)?;
|
||
let window_state = state.windows.get(&window)?;
|
||
|
||
let outside = drag.pointer.x < 0.0
|
||
|| drag.pointer.y < 0.0
|
||
|| drag.pointer.x > window_state.size.width
|
||
|| drag.pointer.y > window_state.size.height;
|
||
if outside || window_state.tabs.is_empty() {
|
||
return None;
|
||
}
|
||
|
||
let metrics = tab_strip_metrics(window_state);
|
||
if metrics.viewport <= 0.0 {
|
||
return None;
|
||
}
|
||
|
||
let gap = tab_gap_index(state, window, drag.pointer.x)?;
|
||
let content_x = if gap == 0 {
|
||
0.0
|
||
} else if gap >= window_state.tabs.len() {
|
||
metrics.content
|
||
} else {
|
||
gap as f32 * metrics.step - TAB_SPACING / 2.0
|
||
};
|
||
let x = TAB_STRIP_LEFT + content_x - metrics.offset;
|
||
|
||
if x < TAB_STRIP_LEFT || x > TAB_STRIP_LEFT + metrics.viewport {
|
||
return None;
|
||
}
|
||
|
||
let accent = colors[ColorOption::Accent.index()];
|
||
let bar = container(space::horizontal())
|
||
.width(2.0)
|
||
.height(MENUBAR_HEIGHT - 12.0)
|
||
.style(move |_| container::Style {
|
||
background: Some(accent.into()),
|
||
border: Border {
|
||
color: Color::TRANSPARENT,
|
||
width: 0.0,
|
||
radius: 1.0.into(),
|
||
},
|
||
..container::Style::default()
|
||
});
|
||
|
||
Some(
|
||
container(bar)
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.align_x(Alignment::Start)
|
||
.align_y(Alignment::Start)
|
||
.padding(Padding {
|
||
top: 6.0,
|
||
left: x - 1.0,
|
||
right: 0.0,
|
||
bottom: 0.0,
|
||
})
|
||
.into(),
|
||
)
|
||
}
|
||
|
||
/// In-window list of other windows to drop a dragged tab onto. This is the
|
||
/// cross-window path that works on Wayland, where window positions are hidden.
|
||
fn drop_panel(
|
||
state: &Moorly,
|
||
window: window::Id,
|
||
colors: [Color; 5],
|
||
) -> Option<Element<'static, Message>> {
|
||
let drag = state.drag.as_ref().filter(|drag| drag.window == window)?;
|
||
let window_state = state.windows.get(&window)?;
|
||
let outside = drag.pointer.x < 0.0
|
||
|| drag.pointer.y < 0.0
|
||
|| drag.pointer.x > window_state.size.width
|
||
|| drag.pointer.y > window_state.size.height;
|
||
|
||
if !drag.detach && !outside {
|
||
return None;
|
||
}
|
||
|
||
let targets = drop_targets(state, window);
|
||
if targets.is_empty() {
|
||
return None;
|
||
}
|
||
|
||
let rect = drop_panel_rect(window_state, targets.len());
|
||
let hovered = drop_target_index(state, window, drag.pointer);
|
||
let text_color = colors[ColorOption::Text.index()];
|
||
let background = colors[ColorOption::SidebarBackground.index()];
|
||
let outline = colors[ColorOption::ActiveTabOutline.index()];
|
||
let accent = colors[ColorOption::Accent.index()];
|
||
|
||
let mut rows = column![].spacing(DROP_ROW_GAP).width(Length::Fill);
|
||
|
||
for (index, (_, title)) in targets.iter().enumerate() {
|
||
let selected = hovered == Some(index);
|
||
rows = rows.push(
|
||
container(text(fit_title(title)).size(13).color(text_color))
|
||
.width(Length::Fill)
|
||
.height(DROP_ROW_HEIGHT)
|
||
.padding([0, 8])
|
||
.align_y(Alignment::Center)
|
||
.style(move |_| container::Style {
|
||
background: Some(
|
||
if selected {
|
||
accent.scale_alpha(0.35)
|
||
} else {
|
||
background
|
||
}
|
||
.into(),
|
||
),
|
||
border: Border {
|
||
color: outline.scale_alpha(0.4),
|
||
width: if selected { 1.0 } else { 0.0 },
|
||
radius: 4.0.into(),
|
||
},
|
||
..container::Style::default()
|
||
}),
|
||
);
|
||
}
|
||
|
||
let header = container(
|
||
text("Move to window")
|
||
.size(12)
|
||
.color(text_color.scale_alpha(0.7)),
|
||
)
|
||
.width(Length::Fill)
|
||
.height(DROP_HEADER_HEIGHT)
|
||
.align_y(Alignment::Center)
|
||
.padding([0, 8]);
|
||
|
||
let panel = container(column![header, rows].spacing(DROP_ROW_GAP))
|
||
.width(rect.width)
|
||
.padding(DROP_PANEL_PADDING)
|
||
.style(move |_| container::Style {
|
||
background: Some(background.into()),
|
||
border: Border {
|
||
color: outline,
|
||
width: 1.0,
|
||
radius: 8.0.into(),
|
||
},
|
||
shadow: Shadow {
|
||
color: Color::BLACK.scale_alpha(0.35),
|
||
offset: Vector::new(0.0, 6.0),
|
||
blur_radius: 16.0,
|
||
},
|
||
text_color: Some(text_color),
|
||
..container::Style::default()
|
||
});
|
||
|
||
Some(
|
||
container(panel)
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.align_x(Alignment::Start)
|
||
.align_y(Alignment::Start)
|
||
.padding(Padding {
|
||
top: rect.y,
|
||
left: rect.x,
|
||
right: 0.0,
|
||
bottom: 0.0,
|
||
})
|
||
.into(),
|
||
)
|
||
}
|
||
|
||
/// Theme selection as a right-aligned drop list.
|
||
fn theme_picker(state: &Moorly) -> Element<'_, Message> {
|
||
let mut options = Vec::new();
|
||
let mut custom: Vec<&CustomTheme> = state.custom_themes.iter().collect();
|
||
custom.sort_by(|left, right| left.name.to_lowercase().cmp(&right.name.to_lowercase()));
|
||
|
||
for theme in custom {
|
||
let choice = ThemeChoice::Custom {
|
||
id: theme.id.clone(),
|
||
name: theme.name.clone(),
|
||
};
|
||
|
||
options.push(ThemeOption::Theme {
|
||
selected: choice == state.theme_choice,
|
||
choice,
|
||
});
|
||
}
|
||
|
||
if !state.custom_themes.is_empty() {
|
||
options.push(ThemeOption::Separator);
|
||
}
|
||
|
||
for preference in theme::Preference::ALL {
|
||
let choice = ThemeChoice::BuiltIn(preference);
|
||
|
||
options.push(ThemeOption::Theme {
|
||
selected: choice == state.theme_choice,
|
||
choice,
|
||
});
|
||
}
|
||
|
||
let selected = options
|
||
.iter()
|
||
.find(|option| matches!(option, ThemeOption::Theme { selected: true, .. }))
|
||
.cloned();
|
||
|
||
row![
|
||
text("Themes").size(16),
|
||
space::horizontal(),
|
||
pick_list(options, selected, Message::SelectTheme).width(200),
|
||
]
|
||
.spacing(8)
|
||
.align_y(Alignment::Center)
|
||
.into()
|
||
}
|
||
|
||
/// Collapsible area for future advanced appearance settings.
|
||
fn advanced_panel(state: &Moorly) -> Element<'_, Message> {
|
||
let glyph = if state.advanced_open { "▴" } else { "▾" };
|
||
let header = button(
|
||
row![
|
||
text("Advanced customization"),
|
||
space::horizontal(),
|
||
text(glyph),
|
||
]
|
||
.width(Length::Fill)
|
||
.align_y(Alignment::Center),
|
||
)
|
||
.on_press(Message::ToggleAdvanced)
|
||
.width(Length::Fill)
|
||
.padding([6, 0])
|
||
.style(button::text);
|
||
|
||
let mut panel = column![header].spacing(8).width(Length::Fill);
|
||
|
||
if state.advanced_open {
|
||
let mut rows = column![].spacing(8).width(Length::Fill);
|
||
|
||
for option in ColorOption::ALL {
|
||
rows = rows.push(color_row(state, option));
|
||
}
|
||
|
||
rows = rows.push(rule::horizontal(1));
|
||
rows = rows.push(
|
||
row![
|
||
text("Custom toaster colors"),
|
||
space::horizontal(),
|
||
toggler(state.custom_toasts).on_toggle(Message::SetCustomToasts),
|
||
]
|
||
.align_y(Alignment::Center),
|
||
);
|
||
|
||
if state.custom_toasts {
|
||
for option in ToastColorOption::ALL {
|
||
rows = rows.push(toast_color_row(state, option));
|
||
}
|
||
}
|
||
|
||
let actions = match &state.theme_choice {
|
||
ThemeChoice::BuiltIn(_) => row![
|
||
space::horizontal(),
|
||
button("Save as new theme")
|
||
.on_press(Message::OpenThemeNameDialog)
|
||
.padding([6, 12])
|
||
.style(theme::positive_option),
|
||
],
|
||
ThemeChoice::Custom { .. } => row![
|
||
space::horizontal(),
|
||
button("Save")
|
||
.on_press(Message::SaveTheme)
|
||
.padding([6, 12])
|
||
.style(theme::positive_option),
|
||
button("Save as new")
|
||
.on_press(Message::OpenThemeNameDialog)
|
||
.padding([6, 12])
|
||
.style(theme::outlined_option),
|
||
button("Undo")
|
||
.on_press(Message::UndoTheme)
|
||
.padding([6, 12])
|
||
.style(theme::outlined_option),
|
||
],
|
||
}
|
||
.spacing(8)
|
||
.align_y(Alignment::Center);
|
||
|
||
rows = rows.push(actions);
|
||
panel = panel.push(rows);
|
||
}
|
||
|
||
container(panel)
|
||
.width(Length::Fill)
|
||
.padding(8)
|
||
.style(theme::advanced_frame)
|
||
.into()
|
||
}
|
||
|
||
/// One theme color option: label on the left, clickable swatch on the right.
|
||
fn color_row(state: &Moorly, option: ColorOption) -> Element<'_, Message> {
|
||
color_swatch_row(
|
||
option.label(),
|
||
state.colors[option.index()],
|
||
state.open_color_picker == Some(option),
|
||
Message::OpenColorPicker(option),
|
||
move |color| Message::SubmitColor(option, color),
|
||
)
|
||
}
|
||
|
||
/// One custom-toast color option, using the same swatch control as the theme.
|
||
fn toast_color_row(state: &Moorly, option: ToastColorOption) -> Element<'_, Message> {
|
||
color_swatch_row(
|
||
option.label(),
|
||
state.toast_colors[option.index()],
|
||
state.open_toast_color_picker == Some(option),
|
||
Message::OpenToastColorPicker(option),
|
||
move |color| Message::SubmitToastColor(option, color),
|
||
)
|
||
}
|
||
|
||
fn color_swatch_row<'a>(
|
||
label: &'static str,
|
||
color: Color,
|
||
open: bool,
|
||
on_open: Message,
|
||
on_submit: impl Fn(Color) -> Message + 'static,
|
||
) -> Element<'a, Message> {
|
||
let swatch = container(space::horizontal())
|
||
.width(24)
|
||
.height(24)
|
||
.style(move |_| container::Style {
|
||
background: Some(color.into()),
|
||
border: Border {
|
||
color: theme::ADVANCED_BORDER,
|
||
width: 1.0,
|
||
radius: 3.0.into(),
|
||
},
|
||
..container::Style::default()
|
||
});
|
||
|
||
let button = button(swatch)
|
||
.on_press(on_open)
|
||
.padding(3)
|
||
.style(button::text);
|
||
|
||
let picker = iced_aw::color_picker(open, color, button, Message::CancelColorPicker, on_submit);
|
||
|
||
row![text(label), space::horizontal(), picker]
|
||
.align_y(Alignment::Center)
|
||
.into()
|
||
}
|
||
|
||
/// Shortcut bindings list.
|
||
fn shortcuts_panel(state: &Moorly) -> Element<'_, Message> {
|
||
let mut panel = column![
|
||
shortcut_row(
|
||
ShortcutAction::Settings,
|
||
state.shortcuts.get(ShortcutAction::Settings),
|
||
),
|
||
shortcut_row(
|
||
ShortcutAction::Quit,
|
||
state.shortcuts.get(ShortcutAction::Quit)
|
||
),
|
||
shortcut_row(
|
||
ShortcutAction::CommandPalette,
|
||
state.shortcuts.get(ShortcutAction::CommandPalette),
|
||
),
|
||
]
|
||
.spacing(8);
|
||
|
||
match &state.shortcut_capture {
|
||
Some(capture) => panel = panel.push(shortcut_capture_panel(capture)),
|
||
None => {
|
||
panel = panel.push(text("Press ... to change a shortcut.").size(12));
|
||
}
|
||
}
|
||
|
||
panel.into()
|
||
}
|
||
|
||
/// One read-only binding row with buttons to clear or rebind it.
|
||
fn shortcut_row(action: ShortcutAction, shortcut: Option<&Shortcut>) -> Element<'static, Message> {
|
||
let value = shortcut.map(ToString::to_string).unwrap_or_default();
|
||
|
||
// No `on_input`: the field only displays the binding.
|
||
let field = text_input("None", &value).width(180).padding(6);
|
||
|
||
row![
|
||
container(text(action.label())).width(120),
|
||
field,
|
||
button("Default")
|
||
.on_press(Message::DefaultShortcut(action))
|
||
.style(theme::outlined_option),
|
||
button("None")
|
||
.on_press(Message::ClearShortcut(action))
|
||
.style(theme::outlined_option),
|
||
button("...")
|
||
.on_press(Message::OpenShortcutCapture(action))
|
||
.style(theme::outlined_option),
|
||
]
|
||
.spacing(8)
|
||
.align_y(Alignment::Center)
|
||
.into()
|
||
}
|
||
|
||
/// Popover shown while a new shortcut is being recorded.
|
||
fn shortcut_capture_panel(capture: &ShortcutCapture) -> Element<'_, Message> {
|
||
let preview = capture
|
||
.candidate
|
||
.as_ref()
|
||
.map(ToString::to_string)
|
||
.unwrap_or_else(|| "Press a key combination".to_owned());
|
||
|
||
let mut panel = column![
|
||
text(format!(
|
||
"Enter a new shortcut for {}",
|
||
capture.action.label()
|
||
))
|
||
.size(12),
|
||
container(text(preview).size(16))
|
||
.width(Length::Fill)
|
||
.padding([6, 10])
|
||
.style(theme::settings_frame),
|
||
]
|
||
.spacing(6);
|
||
|
||
if let Some(error) = &capture.error {
|
||
panel = panel.push(text(error).size(12).color(theme::DANGER));
|
||
}
|
||
|
||
panel = panel.push(
|
||
row![
|
||
button("Apply")
|
||
.on_press(Message::ApplyShortcut)
|
||
.style(theme::outlined_option),
|
||
button("Cancel")
|
||
.on_press(Message::CancelShortcut)
|
||
.style(theme::outlined_option),
|
||
]
|
||
.spacing(6),
|
||
);
|
||
|
||
container(panel)
|
||
.width(280)
|
||
.padding(10)
|
||
.style(theme::menu)
|
||
.into()
|
||
}
|
||
|
||
fn profile_action_button<'a>(
|
||
glyph: &'a str,
|
||
tip: &'a str,
|
||
message: Message,
|
||
enabled: bool,
|
||
danger: bool,
|
||
) -> Element<'a, Message> {
|
||
let glyph = text(glyph).size(16);
|
||
let glyph = if danger {
|
||
glyph.color(theme::DANGER.scale_alpha(if enabled { 1.0 } else { 0.4 }))
|
||
} else {
|
||
glyph
|
||
};
|
||
|
||
let button = button(glyph)
|
||
.on_press_maybe(enabled.then_some(message))
|
||
.padding([6, 10])
|
||
.style(theme::outlined_option);
|
||
|
||
tooltip(
|
||
button,
|
||
container(text(tip).size(11)).padding(4),
|
||
tooltip::Position::Top,
|
||
)
|
||
.into()
|
||
}
|
||
|
||
fn profiles_panel(state: &Moorly, show_add: bool) -> Element<'_, Message> {
|
||
let field = text_input("Filter", &state.profile_filter)
|
||
.on_input(Message::ProfileFilterChanged)
|
||
.padding(Padding {
|
||
top: 6.0,
|
||
right: 32.0,
|
||
bottom: 6.0,
|
||
left: 28.0,
|
||
})
|
||
.style(theme::filter_field)
|
||
.width(Length::Fill);
|
||
|
||
let search = container(text("⌕").size(24))
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.align_x(Alignment::Start)
|
||
.align_y(Alignment::Center)
|
||
.padding(Padding::ZERO.left(9.0));
|
||
|
||
let mut filter = stack![field, search].width(Length::Fill);
|
||
|
||
if !state.profile_filter.is_empty() {
|
||
let clear = container(
|
||
button(text("✕").size(15))
|
||
.on_press(Message::ClearProfileFilter)
|
||
.padding([2, 4])
|
||
.style(button::text),
|
||
)
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.align_x(Alignment::End)
|
||
.align_y(Alignment::Center)
|
||
.padding(Padding::ZERO.right(6.0));
|
||
|
||
filter = filter.push(clear);
|
||
}
|
||
|
||
let add_button = button(
|
||
row![text("+").size(16), text("Add"), text("▾").size(12)]
|
||
.spacing(6)
|
||
.align_y(Alignment::Center),
|
||
)
|
||
.on_press(Message::ToggleAddMenu)
|
||
.padding([6, 10])
|
||
.style(theme::outlined_option);
|
||
|
||
let filter_row = if show_add {
|
||
row![filter, add_button]
|
||
.spacing(12)
|
||
.align_y(Alignment::Center)
|
||
.width(Length::Fill)
|
||
} else {
|
||
row![filter].width(Length::Fill)
|
||
};
|
||
|
||
let has_checked = !state.checked.is_empty();
|
||
let actions = row![
|
||
profile_action_button(
|
||
"✕",
|
||
"Deselect all",
|
||
Message::DeselectAll,
|
||
has_checked,
|
||
false
|
||
),
|
||
profile_action_button("⧉", "Copy to", Message::CopyChecked, has_checked, false),
|
||
profile_action_button("➜", "Move to", Message::MoveChecked, has_checked, false),
|
||
profile_action_button("🗑", "Delete", Message::DeleteChecked, has_checked, true),
|
||
space::horizontal(),
|
||
profile_action_button(
|
||
"🗑↗",
|
||
"Restore from trash",
|
||
Message::RestoreFromTrash,
|
||
true,
|
||
false
|
||
),
|
||
]
|
||
.spacing(6)
|
||
.width(Length::Fill);
|
||
|
||
let mut list = column![].width(Length::Fill);
|
||
for (index, folder) in state.profile_folders.iter().enumerate() {
|
||
if index > 0 {
|
||
list = list.push(rule::horizontal(1));
|
||
}
|
||
list = list.push(profile_folder_row(
|
||
index,
|
||
folder,
|
||
state.selected,
|
||
&state.checked,
|
||
state.hovered_folder,
|
||
show_add,
|
||
));
|
||
}
|
||
|
||
let list = container(scrollable(list).width(Length::Fill).height(Length::Fill))
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.style(theme::settings_frame);
|
||
|
||
let base = column![filter_row]
|
||
.spacing(12)
|
||
.width(Length::Fill)
|
||
.height(Length::Fill);
|
||
|
||
let base = if show_add { base.push(actions) } else { base };
|
||
let base = base.push(list);
|
||
|
||
let dialog_open = state.folder_dialog.is_some()
|
||
|| state.profile_dialog.is_some()
|
||
|| state.transfer.is_some()
|
||
|| state.trash_open
|
||
|| state.confirm_delete
|
||
|| state.dir_picker.is_some();
|
||
|
||
if !show_add && !dialog_open {
|
||
return stack![base].into();
|
||
}
|
||
|
||
if !state.add_menu_open && !dialog_open {
|
||
return stack![base].into();
|
||
}
|
||
|
||
// Clicking anywhere outside the open layer dismisses it.
|
||
let backdrop = mouse_area(
|
||
container(space::horizontal())
|
||
.width(Length::Fill)
|
||
.height(Length::Fill),
|
||
)
|
||
.on_press(if state.dir_picker.is_some() {
|
||
Message::CancelDirectoryPicker
|
||
} else if state.trash_open {
|
||
Message::CloseTrash
|
||
} else if state.folder_dialog.is_some() {
|
||
Message::CancelFolder
|
||
} else if state.transfer.is_some() {
|
||
Message::CancelTransfer
|
||
} else if state.confirm_delete {
|
||
Message::CancelDelete
|
||
} else if state.profile_dialog.is_some() {
|
||
Message::CancelProfile
|
||
} else {
|
||
Message::CloseAddMenu
|
||
});
|
||
|
||
let mut layers = stack![base, backdrop];
|
||
|
||
if show_add && state.add_menu_open {
|
||
let menu = container(
|
||
column![
|
||
button(
|
||
row![text("👤").size(14), text("Profile")]
|
||
.spacing(8)
|
||
.align_y(Alignment::Center),
|
||
)
|
||
.on_press(Message::OpenProfileDialog)
|
||
.width(Length::Fill)
|
||
.padding([6, 10])
|
||
.style(button::text),
|
||
button(
|
||
row![text("📁").size(14), text("Folder")]
|
||
.spacing(8)
|
||
.align_y(Alignment::Center),
|
||
)
|
||
.on_press(Message::OpenFolderDialog)
|
||
.width(Length::Fill)
|
||
.padding([6, 10])
|
||
.style(button::text),
|
||
]
|
||
.width(Length::Fill),
|
||
)
|
||
.width(120)
|
||
.padding(4)
|
||
.style(theme::menu);
|
||
|
||
// ponytail: fixed offset under the filter row; keep in sync with its height.
|
||
let menu_layer = container(menu)
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.align_x(Alignment::End)
|
||
.align_y(Alignment::Start)
|
||
.padding(Padding::ZERO.top(44.0));
|
||
|
||
layers = layers.push(menu_layer);
|
||
}
|
||
|
||
if let Some(draft) = &state.folder_dialog {
|
||
let dialog = container(
|
||
column![
|
||
text("New folder").size(14),
|
||
text_input("Folder name", draft)
|
||
.id(FOLDER_NAME_INPUT)
|
||
.on_input(Message::FolderNameChanged)
|
||
.on_submit(Message::ConfirmFolder)
|
||
.padding(6)
|
||
.style(theme::filter_field)
|
||
.width(Length::Fill),
|
||
text("Use / to nest folders, e.g. Work/Production").size(11),
|
||
row![
|
||
space::horizontal(),
|
||
button("Cancel")
|
||
.on_press(Message::CancelFolder)
|
||
.style(theme::danger_option),
|
||
button("Add")
|
||
.on_press_maybe(
|
||
(!draft.trim().is_empty()).then_some(Message::ConfirmFolder)
|
||
)
|
||
.style(theme::positive_option),
|
||
]
|
||
.spacing(8),
|
||
]
|
||
.spacing(10)
|
||
.width(Length::Fill),
|
||
)
|
||
.width(260)
|
||
.padding(12)
|
||
.style(theme::menu);
|
||
|
||
// Swallow clicks on the dialog surface so only the backdrop outside it
|
||
// dismisses the dialog.
|
||
let dialog = mouse_area(dialog).on_press(Message::Ignore);
|
||
|
||
let dialog_layer = container(dialog)
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.align_x(Alignment::Center)
|
||
.align_y(Alignment::Center);
|
||
|
||
layers = layers.push(dialog_layer);
|
||
}
|
||
|
||
if state.trash_open {
|
||
let dialog = trash_dialog_view(state);
|
||
let dialog = mouse_area(dialog).on_press(Message::Ignore);
|
||
|
||
let dialog_layer = container(dialog)
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.align_x(Alignment::Center)
|
||
.align_y(Alignment::Center);
|
||
|
||
layers = layers.push(dialog_layer);
|
||
}
|
||
|
||
if let Some(transfer) = &state.transfer {
|
||
let dialog = transfer_dialog_view(transfer, &state.profile_folders);
|
||
let dialog = mouse_area(dialog).on_press(Message::Ignore);
|
||
|
||
let dialog_layer = container(dialog)
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.align_x(Alignment::Center)
|
||
.align_y(Alignment::Center);
|
||
|
||
layers = layers.push(dialog_layer);
|
||
}
|
||
|
||
if state.confirm_delete {
|
||
let dialog = container(
|
||
column![
|
||
text("Delete selected items?").size(14),
|
||
text(format!(
|
||
"{} selected item(s) will be moved to the trash and can be restored later.",
|
||
state.checked.len()
|
||
))
|
||
.size(12),
|
||
row![
|
||
space::horizontal(),
|
||
button("Cancel")
|
||
.on_press(Message::CancelDelete)
|
||
.style(theme::outlined_option),
|
||
button("Delete")
|
||
.on_press(Message::ConfirmDelete)
|
||
.style(theme::danger_option),
|
||
]
|
||
.spacing(8),
|
||
]
|
||
.spacing(10)
|
||
.width(Length::Fill),
|
||
)
|
||
.width(320)
|
||
.padding(12)
|
||
.style(theme::menu);
|
||
|
||
let dialog = mouse_area(dialog).on_press(Message::Ignore);
|
||
|
||
let dialog_layer = container(dialog)
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.align_x(Alignment::Center)
|
||
.align_y(Alignment::Center);
|
||
|
||
layers = layers.push(dialog_layer);
|
||
}
|
||
|
||
if let Some(draft) = &state.profile_dialog {
|
||
let dialog = profile_dialog_view(draft, &state.profile_folders);
|
||
let dialog = mouse_area(dialog).on_press(Message::Ignore);
|
||
|
||
let dialog_layer = container(dialog)
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.align_x(Alignment::Center)
|
||
.align_y(Alignment::Center);
|
||
|
||
layers = layers.push(dialog_layer);
|
||
}
|
||
|
||
if let Some(picker) = &state.dir_picker {
|
||
let dialog = directory_picker_view(picker);
|
||
let dialog = mouse_area(dialog).on_press(Message::Ignore);
|
||
|
||
let dialog_layer = container(dialog)
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.align_x(Alignment::Center)
|
||
.align_y(Alignment::Center);
|
||
|
||
layers = layers.push(dialog_layer);
|
||
}
|
||
|
||
layers.into()
|
||
}
|
||
|
||
/// Folder/file browser used by the Terminal start path and SSH private key.
|
||
fn directory_picker_view(picker: &DirPicker) -> Element<'_, Message> {
|
||
let mut entries = column![].width(Length::Fill);
|
||
|
||
if picker.path.parent().is_some() {
|
||
entries = entries.push(
|
||
button(row![text("📁").size(14), text("..")].spacing(8))
|
||
.on_press(Message::DirPickerUp)
|
||
.width(Length::Fill)
|
||
.padding([6, 8])
|
||
.style(button::text),
|
||
);
|
||
}
|
||
|
||
for path in &picker.entries {
|
||
let is_dir = path.is_dir();
|
||
let name = path
|
||
.file_name()
|
||
.map(|name| name.to_string_lossy().into_owned())
|
||
.unwrap_or_else(|| path.display().to_string());
|
||
|
||
let glyph = if is_dir { "📁" } else { "📄" };
|
||
let message = if is_dir {
|
||
Message::DirPickerEnter(path.clone())
|
||
} else {
|
||
Message::DirPickerSelect(path.clone())
|
||
};
|
||
let selected = picker.selected.as_ref() == Some(path);
|
||
|
||
entries = entries.push(
|
||
button(
|
||
row![text(glyph).size(14), text(name)]
|
||
.spacing(8)
|
||
.align_y(Alignment::Center),
|
||
)
|
||
.on_press(message)
|
||
.width(Length::Fill)
|
||
.padding([6, 8])
|
||
.style(move |theme, status| theme::selectable_row(theme, status, selected)),
|
||
);
|
||
}
|
||
|
||
let listing = container(scrollable(entries).width(Length::Fill).height(Length::Fill))
|
||
.width(Length::Fill)
|
||
.height(240)
|
||
.style(theme::settings_frame);
|
||
|
||
let title = if picker.files {
|
||
"Select private key"
|
||
} else {
|
||
"Select folder"
|
||
};
|
||
|
||
let mut content = column![
|
||
text(title).size(16),
|
||
text(picker.path.display().to_string()).size(12),
|
||
listing,
|
||
]
|
||
.spacing(10)
|
||
.width(Length::Fill);
|
||
|
||
if let Some(selected) = &picker.selected {
|
||
content = content.push(text(selected.display().to_string()).size(12));
|
||
}
|
||
|
||
if let Some(error) = &picker.error {
|
||
content = content.push(text(error).size(12).color(theme::DANGER));
|
||
}
|
||
|
||
content = content.push(
|
||
row![
|
||
space::horizontal(),
|
||
button("Cancel")
|
||
.on_press(Message::CancelDirectoryPicker)
|
||
.style(theme::danger_option),
|
||
button("Select")
|
||
.on_press_maybe(
|
||
picker
|
||
.can_confirm()
|
||
.then_some(Message::ConfirmDirectoryPicker)
|
||
)
|
||
.style(theme::positive_option),
|
||
]
|
||
.spacing(8),
|
||
);
|
||
|
||
container(content)
|
||
.width(520)
|
||
.padding(16)
|
||
.style(theme::menu)
|
||
.into()
|
||
}
|
||
|
||
/// The add-profile dialog: details on the left, type-specific view on the right.
|
||
/// Dialog listing everything currently in the `.trash` folder.
|
||
fn trash_dialog_view(state: &Moorly) -> Element<'_, Message> {
|
||
let restore_enabled = !state.trash_checked.is_empty();
|
||
let header = row![
|
||
button("Restore selected")
|
||
.on_press_maybe(restore_enabled.then_some(Message::RestoreSelected))
|
||
.style(theme::positive_option),
|
||
space::horizontal(),
|
||
button("Close")
|
||
.on_press(Message::CloseTrash)
|
||
.style(theme::outlined_option),
|
||
]
|
||
.spacing(8)
|
||
.width(Length::Fill);
|
||
|
||
let columns = row![
|
||
text("Name").size(11).width(Length::Fixed(200.0)),
|
||
text("Previous path").size(11).width(Length::Fixed(220.0)),
|
||
text("Deleted").size(11).width(Length::Fixed(160.0)),
|
||
]
|
||
.spacing(8)
|
||
.padding([4, 0]);
|
||
|
||
let mut rows = column![columns].spacing(2).width(Length::Fill);
|
||
|
||
for (index, entry) in state.trash_entries.iter().enumerate() {
|
||
let checked = state.trash_checked.contains(&index);
|
||
let glyph = if entry.is_folder() {
|
||
"🗀\u{fe0e}"
|
||
} else {
|
||
"👤"
|
||
};
|
||
let previous_path = if entry.previous_path().is_empty() {
|
||
"—"
|
||
} else {
|
||
entry.previous_path()
|
||
};
|
||
|
||
rows = rows.push(
|
||
row![
|
||
checkbox(checked)
|
||
.size(16)
|
||
.on_toggle(move |_| Message::ToggleTrashChecked(index)),
|
||
container(
|
||
row![text(glyph).size(13), text(entry.name()).size(13)]
|
||
.spacing(6)
|
||
.align_y(Alignment::Center)
|
||
)
|
||
.width(Length::Fixed(200.0)),
|
||
text(previous_path).size(12).width(Length::Fixed(220.0)),
|
||
text(entry.deleted()).size(12).width(Length::Fixed(160.0)),
|
||
]
|
||
.spacing(8)
|
||
.align_y(Alignment::Center)
|
||
.padding([4, 0]),
|
||
);
|
||
}
|
||
|
||
if state.trash_entries.is_empty() {
|
||
rows = rows.push(container(text("Trash is empty.").size(13)).padding([8, 0]));
|
||
}
|
||
|
||
let listing = container(scrollable(rows).width(Length::Fill).height(Length::Fill))
|
||
.width(Length::Fill)
|
||
.height(360)
|
||
.style(theme::settings_frame);
|
||
|
||
container(
|
||
column![text("Trash").size(16), header, listing]
|
||
.spacing(10)
|
||
.width(Length::Fill),
|
||
)
|
||
.width(720)
|
||
.padding(16)
|
||
.style(theme::menu)
|
||
.into()
|
||
}
|
||
|
||
/// Folder picker used by the "Copy to" and "Move to" actions.
|
||
fn transfer_dialog_view<'a>(
|
||
transfer: &TransferDialog,
|
||
folders: &'a [ProfileFolder],
|
||
) -> Element<'a, Message> {
|
||
let choices: Vec<FolderChoice> = folders
|
||
.iter()
|
||
.enumerate()
|
||
.map(|(index, folder)| FolderChoice {
|
||
index,
|
||
name: folder.path.clone(),
|
||
})
|
||
.collect();
|
||
let selected = choices.get(transfer.destination).cloned();
|
||
|
||
container(
|
||
column![
|
||
text(transfer.mode.label()).size(14),
|
||
pick_list(choices, selected, Message::TransferFolderSelected).width(Length::Fill),
|
||
row![
|
||
space::horizontal(),
|
||
button("Cancel")
|
||
.on_press(Message::CancelTransfer)
|
||
.style(theme::outlined_option),
|
||
button(transfer.mode.action())
|
||
.on_press(Message::ConfirmTransfer)
|
||
.style(theme::positive_option),
|
||
]
|
||
.spacing(8),
|
||
]
|
||
.spacing(10)
|
||
.width(Length::Fill),
|
||
)
|
||
.width(320)
|
||
.padding(12)
|
||
.style(theme::menu)
|
||
.into()
|
||
}
|
||
|
||
fn profile_dialog_view<'a>(
|
||
draft: &'a ProfileDraft,
|
||
folders: &'a [ProfileFolder],
|
||
) -> Element<'a, Message> {
|
||
let title = if draft.name.trim().is_empty() {
|
||
"New profile"
|
||
} else {
|
||
draft.name.as_str()
|
||
};
|
||
|
||
let choices: Vec<FolderChoice> = folders
|
||
.iter()
|
||
.enumerate()
|
||
.map(|(index, folder)| FolderChoice {
|
||
index,
|
||
name: folder.path.clone(),
|
||
})
|
||
.collect();
|
||
let selected_folder = choices.get(draft.folder).cloned();
|
||
|
||
let left = column![
|
||
text(title).size(18),
|
||
column![
|
||
text("Name").size(12),
|
||
text_input("Profile name", &draft.name)
|
||
.id(PROFILE_NAME_INPUT)
|
||
.on_input(Message::ProfileNameChanged)
|
||
.padding(6)
|
||
.style(theme::filter_field)
|
||
.width(Length::Fill),
|
||
]
|
||
.spacing(4),
|
||
column![
|
||
text("Folder").size(12),
|
||
pick_list(choices, selected_folder, Message::ProfileFolderSelected).width(Length::Fill),
|
||
]
|
||
.spacing(4),
|
||
row![
|
||
column![
|
||
text("When a session ends").size(13),
|
||
text("Only close the tab when session is explicitly terminated").size(10),
|
||
]
|
||
.spacing(2)
|
||
.width(Length::Fill),
|
||
pick_list(
|
||
SessionEnd::ALL,
|
||
Some(draft.session_end),
|
||
Message::SessionEndSelected,
|
||
)
|
||
.width(110),
|
||
]
|
||
.spacing(10)
|
||
.align_y(Alignment::Center),
|
||
]
|
||
.spacing(14)
|
||
.width(260);
|
||
|
||
let mut kind_picker = row![].spacing(6);
|
||
for kind in ProfileKind::ALL {
|
||
let item = button(text(kind.label()))
|
||
.on_press(Message::ProfileKindSelected(kind))
|
||
.padding([6, 10]);
|
||
|
||
kind_picker = kind_picker.push(if kind == draft.kind {
|
||
item.style(theme::selected_option)
|
||
} else {
|
||
item.style(theme::outlined_option)
|
||
});
|
||
}
|
||
|
||
let right = column![kind_picker, profile_kind_view(draft)]
|
||
.spacing(14)
|
||
.width(Length::Fill);
|
||
|
||
let body = row![left, right]
|
||
.spacing(24)
|
||
.align_y(Alignment::Start)
|
||
.width(Length::Fill);
|
||
|
||
let buttons = row![
|
||
space::horizontal(),
|
||
button("Cancel")
|
||
.on_press(Message::CancelProfile)
|
||
.style(theme::danger_option),
|
||
button("Add")
|
||
.on_press_maybe(draft.valid().then_some(Message::ConfirmProfile))
|
||
.style(theme::positive_option),
|
||
]
|
||
.spacing(8);
|
||
|
||
container(column![body, buttons].spacing(16).width(Length::Fill))
|
||
.width(720)
|
||
.padding(16)
|
||
.style(theme::menu)
|
||
.into()
|
||
}
|
||
|
||
/// Right-hand side of the profile dialog for the selected profile type.
|
||
fn profile_kind_view(draft: &ProfileDraft) -> Element<'_, Message> {
|
||
match draft.kind {
|
||
ProfileKind::Terminal => {
|
||
let field = text_input("Start path", &draft.start_path)
|
||
.on_input(Message::ProfileStartPathChanged)
|
||
.padding(Padding {
|
||
top: 6.0,
|
||
right: 40.0,
|
||
bottom: 6.0,
|
||
left: 8.0,
|
||
})
|
||
.style(theme::filter_field)
|
||
.width(Length::Fill);
|
||
|
||
let browse = container(
|
||
button("...")
|
||
.on_press(Message::OpenDirectoryPicker)
|
||
.padding([2, 6])
|
||
.style(|theme, status| theme::selectable_row(theme, status, false)),
|
||
)
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.align_x(Alignment::End)
|
||
.align_y(Alignment::Center)
|
||
.padding(Padding::ZERO.right(6.0));
|
||
|
||
column![
|
||
text("Terminal").size(18),
|
||
column![
|
||
text("Start path").size(12),
|
||
stack![field, browse].width(Length::Fill),
|
||
]
|
||
.spacing(4),
|
||
]
|
||
.spacing(12)
|
||
.into()
|
||
}
|
||
ProfileKind::PowerShell => text("PowerShell").size(18).into(),
|
||
ProfileKind::Ssh => {
|
||
let host_port = row![
|
||
column![
|
||
text("Host").size(12),
|
||
text_input("Hostname or IP", &draft.host)
|
||
.on_input(Message::ProfileHostChanged)
|
||
.padding(6)
|
||
.style(theme::filter_field)
|
||
.width(Length::Fill),
|
||
]
|
||
.spacing(4)
|
||
.width(292),
|
||
space::horizontal(),
|
||
column![
|
||
text("Port").size(12),
|
||
text_input("22", &draft.port)
|
||
.on_input(Message::ProfilePortChanged)
|
||
.padding(6)
|
||
.style(theme::filter_field)
|
||
.width(Length::Fill),
|
||
]
|
||
.spacing(4)
|
||
.width(64),
|
||
]
|
||
.spacing(12);
|
||
|
||
let username = column![
|
||
text("Username").size(12),
|
||
text_input("Username", &draft.username)
|
||
.on_input(Message::ProfileUsernameChanged)
|
||
.padding(6)
|
||
.style(theme::filter_field)
|
||
.width(Length::Fill),
|
||
]
|
||
.spacing(4)
|
||
.width(292);
|
||
|
||
let mut auth_buttons = row![].spacing(6).width(Length::Fill);
|
||
for auth in AuthMethod::ALL {
|
||
let item = button(
|
||
column![text(auth.glyph()).size(18), text(auth.label()).size(11),]
|
||
.spacing(2)
|
||
.align_x(Alignment::Center)
|
||
.width(Length::Fill),
|
||
)
|
||
.on_press(Message::AuthMethodSelected(auth))
|
||
.width(Length::Fill)
|
||
.padding([13, 4]);
|
||
|
||
auth_buttons = auth_buttons.push(if auth == draft.auth {
|
||
item.style(theme::selected_option)
|
||
} else {
|
||
item.style(theme::outlined_option)
|
||
});
|
||
}
|
||
|
||
let mut content = column![
|
||
text("SSH Connection").size(18),
|
||
host_port,
|
||
username,
|
||
auth_buttons,
|
||
]
|
||
.spacing(12);
|
||
|
||
if draft.auth == AuthMethod::Password {
|
||
content = content.push(password_field(draft));
|
||
}
|
||
|
||
if draft.auth == AuthMethod::Key {
|
||
content = content.push(private_key_field(draft));
|
||
}
|
||
|
||
content.into()
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Password label and masked field with an eye toggle.
|
||
fn password_field(draft: &ProfileDraft) -> Element<'_, Message> {
|
||
let field = text_input("Password", &draft.password)
|
||
.secure(!draft.password_visible)
|
||
.on_input(Message::ProfilePasswordChanged)
|
||
.padding(Padding {
|
||
top: 6.0,
|
||
right: 32.0,
|
||
bottom: 6.0,
|
||
left: 8.0,
|
||
})
|
||
.style(theme::filter_field)
|
||
.width(Length::Fill);
|
||
|
||
let eye_icon: Element<'_, Message> = if draft.password_visible {
|
||
text("👁").size(16).into()
|
||
} else {
|
||
// Eye with a line across it, rather than an ambiguous curve.
|
||
stack![
|
||
text("👁").size(16),
|
||
container(
|
||
rule::horizontal(1).style(|theme: &iced::Theme| iced::widget::rule::Style {
|
||
color: theme.extended_palette().background.base.text,
|
||
radius: 0.0.into(),
|
||
fill_mode: iced::widget::rule::FillMode::Full,
|
||
snap: true,
|
||
}),
|
||
)
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.align_y(Alignment::Center),
|
||
]
|
||
.into()
|
||
};
|
||
|
||
let eye_button = button(eye_icon)
|
||
.on_press(Message::TogglePasswordVisibility)
|
||
.padding([2, 4]);
|
||
|
||
let eye_button = if draft.password_visible {
|
||
eye_button.style(theme::revealed_eye)
|
||
} else {
|
||
eye_button.style(button::text)
|
||
};
|
||
|
||
let eye = container(eye_button)
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.align_x(Alignment::End)
|
||
.align_y(Alignment::Center)
|
||
.padding(Padding::ZERO.right(6.0));
|
||
|
||
column![
|
||
text("Password").size(12),
|
||
stack![field, eye].width(Length::Fill),
|
||
]
|
||
.spacing(4)
|
||
.into()
|
||
}
|
||
|
||
/// Private key label and file field with a browse button.
|
||
fn private_key_field(draft: &ProfileDraft) -> Element<'_, Message> {
|
||
let field = text_input("Private key", &draft.private_key)
|
||
.on_input(Message::ProfilePrivateKeyChanged)
|
||
.padding(Padding {
|
||
top: 6.0,
|
||
right: 40.0,
|
||
bottom: 6.0,
|
||
left: 8.0,
|
||
})
|
||
.style(theme::filter_field)
|
||
.width(Length::Fill);
|
||
|
||
let browse = container(
|
||
button("...")
|
||
.on_press(Message::OpenPrivateKeyPicker)
|
||
.padding([2, 6])
|
||
.style(|theme, status| theme::selectable_row(theme, status, false)),
|
||
)
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.align_x(Alignment::End)
|
||
.align_y(Alignment::Center)
|
||
.padding(Padding::ZERO.right(6.0));
|
||
|
||
column![
|
||
text("Private Key").size(12),
|
||
stack![field, browse].width(Length::Fill),
|
||
]
|
||
.spacing(4)
|
||
.into()
|
||
}
|
||
|
||
/// One folder heading followed by its profiles. Clicking the heading toggles
|
||
/// the profile list; clicking a row selects it.
|
||
fn profile_folder_row<'a>(
|
||
index: usize,
|
||
folder: &'a ProfileFolder,
|
||
selected: Option<Selection>,
|
||
checked: &'a HashSet<Selection>,
|
||
hovered: Option<usize>,
|
||
show_checks: bool,
|
||
) -> Element<'a, Message> {
|
||
let is_selected = selected == Some(Selection::Folder(index));
|
||
let expanded = folder.expanded;
|
||
let indent = folder.depth() as f32 * 18.0;
|
||
|
||
let folder_glyph = if folder.untracked {
|
||
if expanded {
|
||
"🗁\u{fe0e}"
|
||
} else {
|
||
"🗀\u{fe0e}"
|
||
}
|
||
} else if expanded {
|
||
"📂"
|
||
} else {
|
||
"📁"
|
||
};
|
||
|
||
let glyph = text(folder_glyph).size(14);
|
||
let glyph = if folder.untracked {
|
||
glyph.color(theme::UNTRACKED_FOLDER)
|
||
} else {
|
||
glyph
|
||
};
|
||
|
||
let mut name = text(folder.name.as_str()).size(14);
|
||
if folder.untracked {
|
||
name = name.font(Font {
|
||
style: font::Style::Italic,
|
||
..Font::DEFAULT
|
||
});
|
||
}
|
||
|
||
let mut heading_content = row![glyph, name, space::horizontal()]
|
||
.spacing(8)
|
||
.align_y(Alignment::Center)
|
||
.width(Length::Fill);
|
||
|
||
if is_selected || hovered == Some(index) {
|
||
heading_content = heading_content.push(
|
||
button(text("⋮").size(16))
|
||
.on_press(Message::Ignore)
|
||
.padding([2, 6])
|
||
.style(button::text),
|
||
);
|
||
}
|
||
|
||
let heading = button(heading_content)
|
||
.on_press(Message::ToggleFolder(index))
|
||
.width(Length::Fill)
|
||
.padding(Padding {
|
||
top: 8.0,
|
||
right: 10.0,
|
||
bottom: 8.0,
|
||
left: if show_checks { 0.0 } else { 10.0 + indent },
|
||
})
|
||
.style(move |theme, status| {
|
||
let mut style = theme::selectable_row(theme, status, is_selected);
|
||
if !expanded {
|
||
style.text_color = style.text_color.scale_alpha(0.6);
|
||
}
|
||
style
|
||
});
|
||
|
||
let heading = mouse_area(heading)
|
||
.on_enter(Message::HoverFolder(Some(index)))
|
||
.on_exit(Message::HoverFolder(None));
|
||
|
||
let folder_checked = checked.contains(&Selection::Folder(index));
|
||
|
||
let heading: Element<'_, Message> = if show_checks {
|
||
let folder_checkbox: Element<'_, Message> = if folder.path == DEFAULT_PROFILE_FOLDER {
|
||
container(space::horizontal())
|
||
.width(16)
|
||
.padding(Padding {
|
||
top: 8.0,
|
||
right: 6.0,
|
||
bottom: 8.0,
|
||
left: 10.0 + indent,
|
||
})
|
||
.into()
|
||
} else {
|
||
container(
|
||
checkbox(folder_checked)
|
||
.size(16)
|
||
.on_toggle(move |_| Message::ToggleChecked(Selection::Folder(index))),
|
||
)
|
||
.padding(Padding {
|
||
top: 8.0,
|
||
right: 6.0,
|
||
bottom: 8.0,
|
||
left: 10.0 + indent,
|
||
})
|
||
.into()
|
||
};
|
||
|
||
row![folder_checkbox, heading]
|
||
.align_y(Alignment::Center)
|
||
.width(Length::Fill)
|
||
.into()
|
||
} else {
|
||
heading.into()
|
||
};
|
||
|
||
let mut rows = column![heading].width(Length::Fill);
|
||
|
||
if expanded {
|
||
for (profile_index, profile) in folder.profiles.iter().enumerate() {
|
||
let profile_selected = selected
|
||
== Some(Selection::Profile {
|
||
folder: index,
|
||
profile: profile_index,
|
||
});
|
||
let profile_checked = checked.contains(&Selection::Profile {
|
||
folder: index,
|
||
profile: profile_index,
|
||
});
|
||
let profile_row = button(
|
||
row![text("👤").size(13), text(profile.name.as_str()).size(13)]
|
||
.spacing(8)
|
||
.align_y(Alignment::Center),
|
||
)
|
||
.on_press(Message::SelectProfile {
|
||
folder: index,
|
||
profile: profile_index,
|
||
})
|
||
.width(Length::Fill)
|
||
.padding(Padding {
|
||
top: 4.0,
|
||
right: 26.0,
|
||
bottom: 4.0,
|
||
left: if show_checks { 0.0 } else { 26.0 + indent },
|
||
})
|
||
.style(move |theme, status| theme::selectable_row(theme, status, profile_selected));
|
||
|
||
if show_checks {
|
||
let profile_checkbox =
|
||
container(checkbox(profile_checked).size(16).on_toggle(move |_| {
|
||
Message::ToggleChecked(Selection::Profile {
|
||
folder: index,
|
||
profile: profile_index,
|
||
})
|
||
}))
|
||
.padding(Padding {
|
||
top: 4.0,
|
||
right: 6.0,
|
||
bottom: 4.0,
|
||
left: 26.0 + indent,
|
||
});
|
||
|
||
rows = rows.push(
|
||
row![profile_checkbox, profile_row]
|
||
.align_y(Alignment::Center)
|
||
.width(Length::Fill),
|
||
);
|
||
} else {
|
||
rows = rows.push(profile_row);
|
||
}
|
||
}
|
||
}
|
||
|
||
rows.into()
|
||
}
|
||
|
||
/// Landing tab: the profile listing with a shortcut to the Settings page.
|
||
fn start_page(state: &Moorly, window: window::Id) -> Element<'_, Message> {
|
||
responsive(move |size| {
|
||
// Half the window and 60% of its height, with sensible minimums.
|
||
let width = (size.width * 0.5).max(400.0);
|
||
let list_height = (size.height * 0.6).max(300.0);
|
||
|
||
let settings = button(
|
||
row![text("⚙\u{fe0e}").size(16), text("Settings")]
|
||
.spacing(6)
|
||
.align_y(Alignment::Center),
|
||
)
|
||
.on_press(Message::SelectTab(window, Tab::Settings))
|
||
.padding([6, 12])
|
||
.style(theme::outlined_option);
|
||
|
||
container(
|
||
container(
|
||
column![
|
||
container(profiles_panel(state, false))
|
||
.width(Length::Fill)
|
||
.height(list_height),
|
||
settings,
|
||
]
|
||
.spacing(12)
|
||
.width(Length::Fill)
|
||
.align_x(Alignment::Center),
|
||
)
|
||
.width(width)
|
||
.padding(12)
|
||
.style(theme::settings_frame),
|
||
)
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.align_x(Alignment::Center)
|
||
.padding(16)
|
||
.into()
|
||
})
|
||
.into()
|
||
}
|
||
|
||
/// General settings that are edited as a draft until saved.
|
||
fn general_panel(state: &Moorly) -> Element<'_, Message> {
|
||
row![
|
||
text("Fade In/Fade out animation"),
|
||
space::horizontal(),
|
||
toggler(state.fade_settings_draft).on_toggle(Message::SetFadeSettings),
|
||
]
|
||
.align_y(Alignment::Center)
|
||
.into()
|
||
}
|
||
|
||
/// Startup settings that are edited as a draft until saved.
|
||
fn startup_panel(state: &Moorly) -> Element<'_, Message> {
|
||
row![
|
||
text("Show Start tab at startup"),
|
||
space::horizontal(),
|
||
toggler(state.show_start_tab_draft).on_toggle(Message::SetShowStartTab),
|
||
]
|
||
.align_y(Alignment::Center)
|
||
.into()
|
||
}
|
||
|
||
/// Appearance settings that are edited as a draft until saved.
|
||
fn appearance_panel(state: &Moorly) -> Element<'_, Message> {
|
||
column![
|
||
theme_picker(state),
|
||
advanced_panel(state),
|
||
row![
|
||
text("Hide tab close icon"),
|
||
space::horizontal(),
|
||
toggler(state.hide_tab_close_draft).on_toggle(Message::SetHideTabClose),
|
||
]
|
||
.align_y(Alignment::Center),
|
||
]
|
||
.spacing(12)
|
||
.into()
|
||
}
|
||
|
||
fn settings_page(state: &Moorly) -> Element<'_, Message> {
|
||
let accent = state.colors[ColorOption::Accent.index()];
|
||
let text_color = state.colors[ColorOption::Text.index()];
|
||
let main_background = state.colors[ColorOption::MainBackground.index()];
|
||
|
||
let menu_item = |section: SettingsSection| {
|
||
let label = container(text(section.label()))
|
||
.width(Length::Fill)
|
||
.align_x(Alignment::Start);
|
||
let item = button(label)
|
||
.on_press(Message::SelectSettingsSection(section))
|
||
.width(Length::Fill)
|
||
.padding([6, 10]);
|
||
|
||
if section == state.settings_section {
|
||
item.style(move |theme, status| theme::settings_active(theme, status, accent))
|
||
} else {
|
||
item.style(move |theme, status| theme::menubar_button(theme, status, text_color))
|
||
}
|
||
};
|
||
|
||
let menu =
|
||
container(column(SettingsSection::ALL.map(|section| menu_item(section).into())).spacing(2))
|
||
.width(160)
|
||
.height(Length::Fill)
|
||
.padding(8);
|
||
|
||
let scrolls = state.settings_section != SettingsSection::Profiles;
|
||
|
||
// Leave room for the overlay scrollbar so right-aligned controls do not
|
||
// move or get covered when it appears.
|
||
let mut content = column![]
|
||
.spacing(12)
|
||
.width(Length::Fill)
|
||
.padding(Padding::ZERO.right(if scrolls { 12.0 } else { 0.0 }));
|
||
content = content.push(text(state.settings_section.label()).size(18));
|
||
if state.settings_section == SettingsSection::General {
|
||
content = content.push(general_panel(state));
|
||
}
|
||
if state.settings_section == SettingsSection::Startup {
|
||
content = content.push(startup_panel(state));
|
||
}
|
||
if state.settings_section == SettingsSection::Appearance {
|
||
content = content.push(appearance_panel(state));
|
||
}
|
||
if state.settings_section == SettingsSection::Shortcuts {
|
||
content = content.push(shortcuts_panel(state));
|
||
}
|
||
if state.settings_section == SettingsSection::Profiles {
|
||
content = content.push(profiles_panel(state, true));
|
||
}
|
||
|
||
let body: Element<'_, Message> = if scrolls {
|
||
scrollable(content)
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.into()
|
||
} else {
|
||
content.into()
|
||
};
|
||
|
||
let content = container(body)
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.padding(16);
|
||
|
||
// Fade the content pane to the frame background, swap sections at
|
||
// full opacity, then fade back in.
|
||
let now = Instant::now();
|
||
let fading = state.fade_animation.is_animating(now) || !state.fade_animation.value();
|
||
let fade = state.fade_animation.interpolate(0.0, 1.0, now);
|
||
let content: Element<'_, Message> = if fading {
|
||
let overlay = container(space::horizontal())
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.style(move |_| {
|
||
let mut color = main_background;
|
||
color.a = 1.0 - fade;
|
||
|
||
container::Style {
|
||
background: Some(color.into()),
|
||
..container::Style::default()
|
||
}
|
||
});
|
||
|
||
stack![content, overlay]
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.into()
|
||
} else {
|
||
content.into()
|
||
};
|
||
|
||
let frame = row![menu, content].width(Length::Fill).height(Length::Fill);
|
||
|
||
let dirty = state.show_start_tab_draft != state.show_start_tab
|
||
|| state.fade_settings_draft != state.fade_settings
|
||
|| state.hide_tab_close_draft != state.hide_tab_close
|
||
|| state.theme_choice != state.saved_theme_choice
|
||
|| state.shortcuts != state.saved_shortcuts;
|
||
|
||
let page: Element<'_, Message> = if dirty {
|
||
let bar = container(
|
||
row![
|
||
text("There is unsaved changes"),
|
||
space::horizontal(),
|
||
button(
|
||
row![text("✓"), text("Save changes")]
|
||
.spacing(6)
|
||
.align_y(Alignment::Center),
|
||
)
|
||
.on_press(Message::SaveSettings)
|
||
.padding([6, 12])
|
||
.style(theme::positive_option),
|
||
button(
|
||
row![text("↶"), text("Undo changes")]
|
||
.spacing(6)
|
||
.align_y(Alignment::Center),
|
||
)
|
||
.on_press(Message::UndoChanges)
|
||
.padding([6, 12])
|
||
.style(theme::outlined_option),
|
||
]
|
||
.spacing(8)
|
||
.align_y(Alignment::Center),
|
||
)
|
||
.width(Length::Fill)
|
||
.padding([8, 12])
|
||
.style(theme::settings_bar);
|
||
|
||
let bar_layer = container(bar)
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.align_y(Alignment::End);
|
||
|
||
stack![frame, bar_layer]
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.into()
|
||
} else {
|
||
frame.into()
|
||
};
|
||
|
||
if let Some(draft) = &state.theme_name_dialog {
|
||
let dialog = container(
|
||
column![
|
||
text("Save as new theme").size(14),
|
||
text_input("Theme name", draft)
|
||
.id(THEME_NAME_INPUT)
|
||
.on_input(Message::ThemeNameChanged)
|
||
.on_submit(Message::ConfirmThemeName)
|
||
.padding(6)
|
||
.style(theme::filter_field)
|
||
.width(Length::Fill),
|
||
row![
|
||
space::horizontal(),
|
||
button("Cancel")
|
||
.on_press(Message::CancelThemeName)
|
||
.style(theme::outlined_option),
|
||
button("Save")
|
||
.on_press_maybe(
|
||
(!draft.trim().is_empty()).then_some(Message::ConfirmThemeName)
|
||
)
|
||
.style(theme::positive_option),
|
||
]
|
||
.spacing(8),
|
||
]
|
||
.spacing(10)
|
||
.width(Length::Fill),
|
||
)
|
||
.width(320)
|
||
.padding(12)
|
||
.style(theme::menu);
|
||
|
||
let dialog = mouse_area(dialog).on_press(Message::Ignore);
|
||
let dialog_layer = container(dialog)
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.align_x(Alignment::Center)
|
||
.align_y(Alignment::Center);
|
||
let backdrop = mouse_area(
|
||
container(space::horizontal())
|
||
.width(Length::Fill)
|
||
.height(Length::Fill),
|
||
)
|
||
.on_press(Message::CancelThemeName);
|
||
|
||
stack![page, backdrop, dialog_layer].into()
|
||
} else {
|
||
page
|
||
}
|
||
}
|
||
|
||
/// A left-aligned menu row with an optional right-aligned shortcut. The
|
||
/// vertical bar and shortcut live inside the same clickable button.
|
||
fn menu_item(
|
||
label: &'static str,
|
||
shortcut: Option<String>,
|
||
message: Message,
|
||
) -> iced::widget::Button<'static, Message> {
|
||
menu_item_with_glyph(None, label, shortcut, message)
|
||
}
|
||
|
||
fn menu_item_with_glyph(
|
||
glyph: Option<&'static str>,
|
||
label: &'static str,
|
||
shortcut: Option<String>,
|
||
message: Message,
|
||
) -> iced::widget::Button<'static, Message> {
|
||
let mut content = row![]
|
||
.width(Length::Fill)
|
||
.align_y(Alignment::Center)
|
||
.spacing(6);
|
||
|
||
if let Some(glyph) = glyph {
|
||
content = content.push(text(glyph).size(16));
|
||
}
|
||
|
||
content = content.push(text(label));
|
||
|
||
if let Some(shortcut) = shortcut {
|
||
content = content
|
||
.push(space::horizontal())
|
||
.push(container(rule::vertical(1)).height(12).padding([0, 6]))
|
||
.push(text(shortcut).size(11));
|
||
}
|
||
|
||
button(content)
|
||
.on_press(message)
|
||
.width(Length::Fill)
|
||
.height(MENU_ITEM_HEIGHT)
|
||
.padding([4, 8])
|
||
.style(button::text)
|
||
}
|
||
|
||
/// Vertical offset of the Tabs row inside the menu column, so the chevron
|
||
/// column can place its `◀ |` alongside it. Keep in sync with the layout.
|
||
fn tabs_row_top() -> f32 {
|
||
let mut top = MENU_ITEM_HEIGHT + 4.0;
|
||
|
||
if cfg!(debug_assertions) {
|
||
top += MENU_ITEM_HEIGHT + 4.0;
|
||
}
|
||
|
||
top
|
||
}
|
||
|
||
/// Vertical offset of the Tabs row from the top of the menu panel, so the
|
||
/// submenu can start at the same height.
|
||
fn tabs_submenu_top() -> f32 {
|
||
MENU_PADDING + HAMBURGER_ROW_HEIGHT + 2.0 + tabs_row_top()
|
||
}
|
||
|
||
fn scroll_button(
|
||
symbol: &'static str,
|
||
delta: f32,
|
||
enabled: bool,
|
||
text_color: Color,
|
||
window: window::Id,
|
||
) -> iced::widget::Button<'static, Message> {
|
||
button(text(symbol).size(17))
|
||
.on_press_maybe(enabled.then_some(Message::ScrollTabsBy(window, delta)))
|
||
.width(SCROLL_BUTTON_WIDTH)
|
||
.padding([0, 6])
|
||
.style(move |theme, status| theme::menubar_button(theme, status, text_color))
|
||
}
|
||
|
||
/// Whether the tab strip can still scroll left/right.
|
||
fn tab_scroll_limits(state: &Moorly, window: window::Id) -> (bool, bool) {
|
||
let Some(window_state) = state.windows.get(&window) else {
|
||
return (false, false);
|
||
};
|
||
|
||
if window_state.tabs.is_empty() {
|
||
return (false, false);
|
||
}
|
||
|
||
let metrics = tab_strip_metrics(window_state);
|
||
let max_offset = (metrics.content - metrics.viewport).max(0.0);
|
||
let offset = window_state.tab_offset.min(max_offset);
|
||
(offset > 0.5, offset < max_offset - 0.5)
|
||
}
|
||
|
||
fn main_view(state: &Moorly, window: window::Id) -> Element<'_, Message> {
|
||
let Some(window_state) = state.windows.get(&window) else {
|
||
return container(space::horizontal())
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.into();
|
||
};
|
||
|
||
// Tab strip: size tabs to the strip's current width so as many as
|
||
// possible fit before scrolling starts.
|
||
let tabs = window_state.tabs.clone();
|
||
let active_tab = window_state.active_tab;
|
||
let menu_open = window_state.menu_open;
|
||
let tabs_submenu_open = window_state.tabs_submenu_open;
|
||
let scroll_id = window_state.scroll_id.clone();
|
||
let hide_close = state.hide_tab_close;
|
||
let colors = state.colors;
|
||
let text_color = colors[ColorOption::Text.index()];
|
||
let main_background = colors[ColorOption::MainBackground.index()];
|
||
let sidebar_background = colors[ColorOption::SidebarBackground.index()];
|
||
let now = Instant::now();
|
||
let close_opacities: HashMap<Tab, f32> = tabs
|
||
.iter()
|
||
.map(|tab| {
|
||
let opacity = if hide_close {
|
||
state
|
||
.tab_close_fades
|
||
.get(tab)
|
||
.map(|animation| animation.interpolate(0.0, 1.0, now))
|
||
.unwrap_or(0.0)
|
||
} else {
|
||
1.0
|
||
};
|
||
|
||
(*tab, opacity)
|
||
})
|
||
.collect();
|
||
|
||
let tab_strip = responsive(move |size| {
|
||
let width = tab_width(size.width, tabs.len());
|
||
let mut tab_row = row![].spacing(TAB_SPACING).height(Length::Fill);
|
||
|
||
for &tab in &tabs {
|
||
tab_row = tab_row.push(tab_view(
|
||
window,
|
||
tab,
|
||
active_tab == Some(tab),
|
||
hide_close,
|
||
close_opacities.get(&tab).copied().unwrap_or(0.0),
|
||
width,
|
||
colors,
|
||
));
|
||
}
|
||
|
||
let tab_strip = scrollable(tab_row)
|
||
.direction(scrollable::Direction::Horizontal(
|
||
scrollable::Scrollbar::hidden(),
|
||
))
|
||
.id(scroll_id.clone())
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.on_scroll(move |viewport| Message::TabsScrolled(window, viewport));
|
||
|
||
// Convert vertical wheel input into horizontal tab-strip scrolling.
|
||
mouse_area(tab_strip)
|
||
.on_scroll(move |delta| Message::ScrollTabs(window, delta))
|
||
.into()
|
||
});
|
||
|
||
let (can_scroll_left, can_scroll_right) = tab_scroll_limits(state, window);
|
||
|
||
let mut bar = row![
|
||
tab_strip,
|
||
scroll_button("◀", -TAB_SCROLL_STEP, can_scroll_left, text_color, window),
|
||
scroll_button("▶", TAB_SCROLL_STEP, can_scroll_right, text_color, window),
|
||
]
|
||
.spacing(2)
|
||
.align_y(Alignment::Center);
|
||
|
||
if menu_open {
|
||
// The dropdown draws the close button over this spot.
|
||
bar = bar.push(space::horizontal().width(HAMBURGER_WIDTH));
|
||
} else {
|
||
bar = bar.push(hamburger(false, text_color, window));
|
||
}
|
||
|
||
let menubar = container(bar)
|
||
.width(Length::Fill)
|
||
.height(MENUBAR_HEIGHT)
|
||
.align_y(Alignment::Center)
|
||
.padding(Padding {
|
||
top: 0.0,
|
||
right: MENUBAR_RIGHT_PADDING,
|
||
bottom: 0.0,
|
||
left: TAB_STRIP_LEFT,
|
||
})
|
||
.style(move |theme| theme::menubar(theme, sidebar_background));
|
||
|
||
let main_area: Element<'_, Message> = match active_tab {
|
||
Some(Tab::Start) => start_page(state, window),
|
||
Some(Tab::Settings) => settings_page(state),
|
||
_ => container(column![])
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.into(),
|
||
};
|
||
|
||
let main_area = container(main_area)
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.style(move |_| container::Style {
|
||
background: Some(main_background.into()),
|
||
text_color: Some(text_color),
|
||
..container::Style::default()
|
||
});
|
||
|
||
let base = column![menubar, main_area];
|
||
let ghost = drag_ghost(state, window, colors);
|
||
let drop_bar = tab_drop_bar(state, window, colors);
|
||
let drop_panel = drop_panel(state, window, colors);
|
||
|
||
if !menu_open {
|
||
// Keep the root a `stack` so the tab strip's scroll state survives
|
||
// opening/closing the menu.
|
||
let mut root = stack![base];
|
||
|
||
if let Some(ghost) = ghost {
|
||
root = root.push(ghost);
|
||
}
|
||
if let Some(drop_bar) = drop_bar {
|
||
root = root.push(drop_bar);
|
||
}
|
||
if let Some(drop_panel) = drop_panel {
|
||
root = root.push(drop_panel);
|
||
}
|
||
|
||
return root.into();
|
||
}
|
||
|
||
let menu_items = column![].spacing(4);
|
||
|
||
let settings_shortcut = state
|
||
.shortcuts
|
||
.get(ShortcutAction::Settings)
|
||
.map(ToString::to_string);
|
||
let quit_shortcut = state
|
||
.shortcuts
|
||
.get(ShortcutAction::Quit)
|
||
.map(ToString::to_string);
|
||
|
||
let mut menu_items = menu_items.push(menu_item_with_glyph(
|
||
Some("⚙\u{fe0e}"),
|
||
"Settings",
|
||
settings_shortcut,
|
||
Message::SelectTab(window, Tab::Settings),
|
||
));
|
||
|
||
if cfg!(debug_assertions) {
|
||
menu_items = menu_items.push(menu_item(
|
||
"temp Add Tab",
|
||
Some("Ctrl+Shift+T".to_owned()),
|
||
Message::AddTab(window),
|
||
));
|
||
}
|
||
|
||
let menu_items = menu_items
|
||
.push(menu_item("Tabs", None, Message::ToggleTabsSubmenu(window)))
|
||
.push(rule::horizontal(1))
|
||
.push(menu_item("Quit", quit_shortcut, Message::Quit))
|
||
.width(Length::Fill);
|
||
|
||
// The `◀ |` marker owns its own column; menu rows start to its right.
|
||
let tabs_marker = container(column![
|
||
space::vertical().height(tabs_row_top()),
|
||
container(
|
||
row![
|
||
text("◀").size(16),
|
||
container(rule::vertical(1)).height(12).padding([0, 6]),
|
||
]
|
||
.align_y(Alignment::Center),
|
||
)
|
||
.height(MENU_ITEM_HEIGHT)
|
||
.padding(Padding::ZERO.top(4.0))
|
||
.align_y(Alignment::Start),
|
||
])
|
||
.width(24);
|
||
|
||
let menu = container(
|
||
column![
|
||
container(hamburger(true, text_color, window))
|
||
.width(Length::Fill)
|
||
.height(HAMBURGER_ROW_HEIGHT)
|
||
.align_x(Alignment::End)
|
||
.align_y(Alignment::Center),
|
||
row![tabs_marker, menu_items].align_y(Alignment::Start),
|
||
]
|
||
.spacing(2),
|
||
)
|
||
.width(220)
|
||
.padding(MENU_PADDING)
|
||
.style(theme::menu);
|
||
|
||
let tabs_submenu = container(
|
||
column![
|
||
menu_item(
|
||
"Close Active Tab",
|
||
Some("Ctrl+Shift+W".to_owned()),
|
||
Message::CloseActiveTab(window),
|
||
),
|
||
menu_item(
|
||
"Close all other tabs",
|
||
None,
|
||
Message::CloseOtherTabs(window),
|
||
),
|
||
]
|
||
.spacing(4),
|
||
)
|
||
.width(220)
|
||
.padding(MENU_PADDING)
|
||
.style(theme::menu);
|
||
|
||
// Push the submenu down so its first row starts level with the Tabs row.
|
||
let tabs_submenu =
|
||
container(tabs_submenu).padding(Padding::ZERO.top(tabs_submenu_top() - MENU_PADDING));
|
||
|
||
let mut dropdown_row = row![].spacing(0).align_y(Alignment::Start);
|
||
if tabs_submenu_open {
|
||
dropdown_row = dropdown_row.push(tabs_submenu);
|
||
}
|
||
dropdown_row = dropdown_row.push(menu);
|
||
|
||
let dropdown = container(dropdown_row)
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.align_x(Alignment::End)
|
||
.align_y(Alignment::Start)
|
||
.padding(Padding::ZERO.right(8.0));
|
||
|
||
// Clicking anywhere outside the dropdown dismisses it.
|
||
let backdrop = mouse_area(
|
||
container(space::horizontal())
|
||
.width(Length::Fill)
|
||
.height(Length::Fill),
|
||
)
|
||
.on_press(Message::CloseMenu(window));
|
||
|
||
let mut root = stack![base, backdrop, dropdown]
|
||
.width(Length::Fill)
|
||
.height(Length::Fill);
|
||
|
||
if let Some(ghost) = ghost {
|
||
root = root.push(ghost);
|
||
}
|
||
if let Some(drop_bar) = drop_bar {
|
||
root = root.push(drop_bar);
|
||
}
|
||
if let Some(drop_panel) = drop_panel {
|
||
root = root.push(drop_panel);
|
||
}
|
||
|
||
root.into()
|
||
}
|
||
|
||
/// One command row: name over description, with the Enter hint on the
|
||
/// selected row.
|
||
fn command_palette_item(
|
||
state: &Moorly,
|
||
window: window::Id,
|
||
command: Command,
|
||
selected: bool,
|
||
) -> Element<'static, Message> {
|
||
let details = column![
|
||
text(command.label(state)).size(16),
|
||
text(command.description(state)).size(12),
|
||
]
|
||
.spacing(2);
|
||
|
||
let mut content = row![details.width(Length::Fill)]
|
||
.align_y(Alignment::Center)
|
||
.height(Length::Fill);
|
||
|
||
if selected {
|
||
content = content.push(
|
||
container(text("Enter").size(11))
|
||
.height(Length::Fill)
|
||
.align_y(Alignment::Center)
|
||
.padding([0, 8])
|
||
.style(|theme: &iced::Theme| {
|
||
let palette = theme.extended_palette();
|
||
|
||
container::Style {
|
||
border: Border {
|
||
color: palette.background.strong.color,
|
||
width: 1.0,
|
||
radius: 4.0.into(),
|
||
},
|
||
..container::Style::default()
|
||
}
|
||
}),
|
||
);
|
||
}
|
||
|
||
button(content)
|
||
.on_press(Message::RunCommand(window, command))
|
||
.width(Length::Fill)
|
||
.height(52)
|
||
.padding([4, 10])
|
||
.style(move |theme, status| theme::selectable_row(theme, status, selected))
|
||
.into()
|
||
}
|
||
|
||
/// Top-of-window command palette field and matching command list.
|
||
fn command_palette_layer(state: &Moorly, window: window::Id) -> Option<Element<'_, Message>> {
|
||
let window_state = state.windows.get(&window)?;
|
||
if !window_state.command_palette_open {
|
||
return None;
|
||
}
|
||
|
||
let field = text_input("Type a command...", &window_state.command_palette_query)
|
||
.id(window_state.command_palette_input.clone())
|
||
.on_input(move |query| Message::CommandPaletteChanged(window, query))
|
||
.padding([10, 12])
|
||
.style(theme::filter_field)
|
||
.width(Length::Fill);
|
||
|
||
let matches = Command::matching(state, window, &window_state.command_palette_query);
|
||
let selected = window_state
|
||
.command_palette_selected
|
||
.min(matches.len().saturating_sub(1));
|
||
|
||
let mut list = column![].spacing(2);
|
||
if matches.is_empty() {
|
||
list = list.push(container(text("No matching commands").size(12)).padding(8));
|
||
} else {
|
||
for (index, command) in matches.into_iter().enumerate() {
|
||
list = list.push(command_palette_item(
|
||
state,
|
||
window,
|
||
command,
|
||
index == selected,
|
||
));
|
||
}
|
||
}
|
||
|
||
let panel = container(column![field, list].spacing(6))
|
||
.width(560)
|
||
.padding(6)
|
||
.style(theme::menu);
|
||
|
||
Some(
|
||
container(panel)
|
||
.width(Length::Fill)
|
||
.height(Length::Fill)
|
||
.align_x(Alignment::Center)
|
||
.align_y(Alignment::Start)
|
||
.padding(Padding::ZERO.top(8.0))
|
||
.into(),
|
||
)
|
||
}
|
||
|
||
/// The application content with the notification stack rendered above it.
|
||
fn view(state: &Moorly, window: window::Id) -> Element<'_, Message> {
|
||
let content = main_view(state, window);
|
||
let palette = command_palette_layer(state, window);
|
||
|
||
if state.notifications.is_empty() && palette.is_none() {
|
||
return content;
|
||
}
|
||
|
||
let mut root = stack![content];
|
||
|
||
if !state.notifications.is_empty() {
|
||
let toasts = state
|
||
.notifications
|
||
.view(
|
||
Instant::now(),
|
||
state
|
||
.custom_toasts
|
||
.then(|| notifications::ToastColors::from_array(state.toast_colors)),
|
||
)
|
||
.map(Message::Notification);
|
||
|
||
root = root.push(toasts);
|
||
}
|
||
|
||
if let Some(palette) = palette {
|
||
root = root.push(palette);
|
||
}
|
||
|
||
root.width(Length::Fill).height(Length::Fill).into()
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::{Message, Moorly, Tab, theme, update};
|
||
use iced::keyboard;
|
||
|
||
fn test_window() -> iced::window::Id {
|
||
static WINDOW: std::sync::OnceLock<iced::window::Id> = std::sync::OnceLock::new();
|
||
|
||
*WINDOW.get_or_init(iced::window::Id::unique)
|
||
}
|
||
|
||
fn window_state(state: &Moorly) -> &super::WindowState {
|
||
&state.windows[&test_window()]
|
||
}
|
||
|
||
fn window_state_mut(state: &mut Moorly) -> &mut super::WindowState {
|
||
state.windows.get_mut(&test_window()).unwrap()
|
||
}
|
||
|
||
fn state() -> Moorly {
|
||
let window = test_window();
|
||
let window_state = super::WindowState::new(false, iced::Size::new(1024.0, 768.0));
|
||
|
||
Moorly {
|
||
windows: [(window, window_state)].into_iter().collect(),
|
||
window_order: vec![window],
|
||
main_window: Some(window),
|
||
focused_window: Some(window),
|
||
drag: None,
|
||
theme: theme::Preference::default(),
|
||
saved_theme: theme::Preference::default(),
|
||
theme_choice: super::ThemeChoice::BuiltIn(theme::Preference::default()),
|
||
saved_theme_choice: super::ThemeChoice::BuiltIn(theme::Preference::default()),
|
||
custom_themes: Vec::new(),
|
||
theme_name_dialog: None,
|
||
theme_signature: Vec::new(),
|
||
shortcuts: super::Shortcuts::default(),
|
||
saved_shortcuts: super::Shortcuts::default(),
|
||
shortcut_capture: None,
|
||
settings_section: super::SettingsSection::default(),
|
||
pending_settings_section: None,
|
||
show_start_tab: true,
|
||
show_start_tab_draft: true,
|
||
fade_settings: true,
|
||
fade_settings_draft: true,
|
||
hide_tab_close: true,
|
||
hide_tab_close_draft: true,
|
||
advanced_open: false,
|
||
colors: super::DEFAULT_COLORS,
|
||
saved_colors: super::DEFAULT_COLORS,
|
||
custom_toasts: false,
|
||
toast_colors: super::builtin_toast_colors(theme::Preference::default()),
|
||
builtin_custom_toasts: false,
|
||
builtin_toast_colors: super::builtin_toast_colors(theme::Preference::default()),
|
||
open_color_picker: None,
|
||
open_toast_color_picker: None,
|
||
fade_animation: super::new_fade_animation(),
|
||
hovered_tab: None,
|
||
tab_close_fades: Default::default(),
|
||
profile_filter: String::new(),
|
||
profile_folders: vec![super::ProfileFolder::default_folder()],
|
||
selected: None,
|
||
checked: super::HashSet::new(),
|
||
trash_open: false,
|
||
trash_entries: Vec::new(),
|
||
trash_checked: super::HashSet::new(),
|
||
transfer: None,
|
||
confirm_delete: false,
|
||
hovered_folder: None,
|
||
add_menu_open: false,
|
||
folder_dialog: None,
|
||
profile_dialog: None,
|
||
dir_picker: None,
|
||
next_blank_tab: 1,
|
||
notifications: super::notifications::NotificationManager::default(),
|
||
}
|
||
}
|
||
|
||
fn profile(name: &str) -> super::Profile {
|
||
super::Profile {
|
||
name: name.to_owned(),
|
||
kind: super::ProfileKind::Ssh,
|
||
session_end: super::SessionEnd::Auto,
|
||
host: String::new(),
|
||
port: "22".to_owned(),
|
||
username: String::new(),
|
||
auth: super::AuthMethod::Password,
|
||
password: String::new(),
|
||
start_path: String::new(),
|
||
private_key: String::new(),
|
||
file: None,
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn start_tab_follows_the_saved_setting() {
|
||
let (state, _) = super::boot();
|
||
let window = state.windows.keys().next().copied().unwrap();
|
||
let expected = state.show_start_tab.then_some(Tab::Start);
|
||
|
||
assert_eq!(
|
||
state.windows[&window].tabs,
|
||
expected.into_iter().collect::<Vec<_>>()
|
||
);
|
||
assert_eq!(state.windows[&window].active_tab, expected);
|
||
assert_eq!(Tab::Start.title(), "Start");
|
||
}
|
||
|
||
#[test]
|
||
fn fade_starts_visible_and_ends_hidden() {
|
||
let start = iced::time::Instant::now();
|
||
let mut fade = super::new_fade_animation();
|
||
|
||
assert_eq!(fade.interpolate(0.0, 1.0, start), 1.0);
|
||
|
||
fade.go_mut(false, start);
|
||
assert!(fade.interpolate(0.0, 1.0, start) > 0.99);
|
||
assert!(fade.interpolate(0.0, 1.0, start + iced::time::Duration::from_millis(250)) < 0.01);
|
||
}
|
||
|
||
#[test]
|
||
fn section_switch_waits_for_the_fade_out() {
|
||
let mut state = state();
|
||
state.settings_section = super::SettingsSection::General;
|
||
|
||
let _ = update(
|
||
&mut state,
|
||
Message::SelectSettingsSection(super::SettingsSection::Startup),
|
||
);
|
||
assert_eq!(state.settings_section, super::SettingsSection::General);
|
||
assert_eq!(
|
||
state.pending_settings_section,
|
||
Some(super::SettingsSection::Startup)
|
||
);
|
||
assert!(
|
||
state
|
||
.fade_animation
|
||
.is_animating(iced::time::Instant::now())
|
||
);
|
||
|
||
let later = iced::time::Instant::now() + iced::time::Duration::from_secs(1);
|
||
let _ = update(&mut state, Message::Frame(later));
|
||
assert_eq!(state.settings_section, super::SettingsSection::Startup);
|
||
assert_eq!(state.pending_settings_section, None);
|
||
}
|
||
|
||
#[test]
|
||
fn startup_changes_wait_for_save_or_undo() {
|
||
let mut state = state();
|
||
|
||
let _ = update(&mut state, Message::SetShowStartTab(false));
|
||
assert!(state.show_start_tab);
|
||
assert!(!state.show_start_tab_draft);
|
||
|
||
let _ = update(&mut state, Message::UndoChanges);
|
||
assert_eq!(state.show_start_tab_draft, state.show_start_tab);
|
||
|
||
let _ = update(&mut state, Message::SetShowStartTab(false));
|
||
super::apply_settings(&mut state);
|
||
assert!(!state.show_start_tab);
|
||
assert_eq!(state.show_start_tab_draft, state.show_start_tab);
|
||
}
|
||
|
||
#[test]
|
||
fn hiding_tab_close_waits_for_save_or_undo() {
|
||
let mut state = state();
|
||
|
||
let _ = update(&mut state, Message::SetHideTabClose(false));
|
||
assert!(state.hide_tab_close);
|
||
assert!(!state.hide_tab_close_draft);
|
||
|
||
let _ = update(&mut state, Message::UndoChanges);
|
||
assert_eq!(state.hide_tab_close_draft, state.hide_tab_close);
|
||
|
||
let _ = update(&mut state, Message::SetHideTabClose(false));
|
||
super::apply_settings(&mut state);
|
||
assert!(!state.hide_tab_close);
|
||
assert_eq!(state.hide_tab_close_draft, state.hide_tab_close);
|
||
}
|
||
|
||
#[test]
|
||
fn theme_selection_waits_for_save_or_undo() {
|
||
let mut state = state();
|
||
let dark = super::ThemeOption::Theme {
|
||
choice: super::ThemeChoice::BuiltIn(theme::Preference::Dark),
|
||
selected: false,
|
||
};
|
||
|
||
let _ = update(&mut state, Message::SelectTheme(dark.clone()));
|
||
assert_eq!(state.theme, theme::Preference::Dark);
|
||
assert_eq!(state.saved_theme, theme::Preference::System);
|
||
assert_ne!(state.theme_choice, state.saved_theme_choice);
|
||
|
||
let _ = update(&mut state, Message::UndoChanges);
|
||
assert_eq!(state.theme, theme::Preference::System);
|
||
assert_eq!(state.theme_choice, state.saved_theme_choice);
|
||
|
||
let _ = update(&mut state, Message::SelectTheme(dark));
|
||
super::apply_settings(&mut state);
|
||
assert_eq!(state.saved_theme, theme::Preference::Dark);
|
||
assert_eq!(state.saved_theme_choice, state.theme_choice);
|
||
}
|
||
|
||
#[test]
|
||
fn config_is_written_as_sectioned_toml() {
|
||
let mut state = state();
|
||
state.fade_settings = false;
|
||
state.show_start_tab = false;
|
||
state.hide_tab_close = false;
|
||
state.saved_theme = theme::Preference::Dark;
|
||
state.saved_theme_choice = super::ThemeChoice::BuiltIn(theme::Preference::Dark);
|
||
state.builtin_custom_toasts = true;
|
||
state.builtin_toast_colors[super::ToastColorOption::Info.index()] =
|
||
iced::Color::from_rgb8(1, 2, 3);
|
||
|
||
let text = toml::to_string_pretty(&super::config_file(&state)).unwrap();
|
||
let parsed: toml::Value = toml::from_str(&text).unwrap();
|
||
|
||
assert!(text.contains("[general]\nfade_settings = false"));
|
||
assert!(text.contains("[startup]\nshow_start_tab = false"));
|
||
assert!(text.contains("[appearance]\ntheme = \"dark\""));
|
||
assert!(text.contains("[appearance.toast]"));
|
||
assert!(text.contains("[shortcuts]"));
|
||
assert_eq!(parsed["general"]["fade_settings"].as_bool(), Some(false));
|
||
assert_eq!(parsed["appearance"]["theme"].as_str(), Some("dark"));
|
||
assert_eq!(
|
||
parsed["appearance"]["toast"]["enabled"].as_bool(),
|
||
Some(true)
|
||
);
|
||
assert_eq!(
|
||
parsed["appearance"]["toast"]["info"].as_str(),
|
||
Some("#010203")
|
||
);
|
||
assert_eq!(parsed["shortcuts"]["settings"].as_str(), Some("Ctrl+,"));
|
||
|
||
state.saved_theme_choice = super::ThemeChoice::Custom {
|
||
id: "abc".to_owned(),
|
||
name: "Mine".to_owned(),
|
||
};
|
||
let text = toml::to_string_pretty(&super::config_file(&state)).unwrap();
|
||
assert!(text.contains("custom_theme = \"abc\""));
|
||
assert!(text.contains("custom_theme_name = \"Mine\""));
|
||
}
|
||
|
||
#[test]
|
||
fn missing_custom_theme_falls_back_to_dark() {
|
||
let appearance = super::AppearanceConfig {
|
||
theme: "light".to_owned(),
|
||
custom_theme: Some("gone".to_owned()),
|
||
..super::AppearanceConfig::default()
|
||
};
|
||
|
||
let (choice, preference, _, _, _, missing) = super::resolve_theme(&appearance, &[]);
|
||
|
||
assert!(missing);
|
||
assert_eq!(preference, theme::Preference::Dark);
|
||
assert_eq!(choice, super::ThemeChoice::BuiltIn(theme::Preference::Dark));
|
||
}
|
||
|
||
#[test]
|
||
fn shortcut_changes_wait_for_save_or_undo() {
|
||
let mut state = state();
|
||
let _ = update(
|
||
&mut state,
|
||
Message::OpenShortcutCapture(super::ShortcutAction::Settings),
|
||
);
|
||
let _ = update(
|
||
&mut state,
|
||
press(
|
||
keyboard::Key::Character("k".into()),
|
||
keyboard::Modifiers::CTRL | keyboard::Modifiers::SHIFT,
|
||
),
|
||
);
|
||
let _ = update(&mut state, Message::ApplyShortcut);
|
||
|
||
assert_eq!(
|
||
state.shortcuts.settings.as_ref().map(ToString::to_string),
|
||
Some("Ctrl+Shift+K".to_owned())
|
||
);
|
||
assert_eq!(
|
||
state
|
||
.saved_shortcuts
|
||
.settings
|
||
.as_ref()
|
||
.map(ToString::to_string),
|
||
Some("Ctrl+,".to_owned())
|
||
);
|
||
|
||
super::apply_settings(&mut state);
|
||
assert_eq!(state.saved_shortcuts, state.shortcuts);
|
||
}
|
||
|
||
#[test]
|
||
fn notification_demo_adds_all_types() {
|
||
let mut state = state();
|
||
let _ = update(&mut state, Message::ShowNotificationDemo);
|
||
|
||
assert_eq!(state.notifications.len(), 4);
|
||
}
|
||
|
||
#[test]
|
||
fn long_titles_are_ellipsized_to_max_width() {
|
||
assert_eq!(super::fit_title("Settings"), "Settings");
|
||
assert_eq!(super::fit_title(&"a".repeat(20)), "a".repeat(20));
|
||
|
||
let fitted = super::fit_title(&"a".repeat(30));
|
||
assert_eq!(fitted, format!("{}...", "a".repeat(17)));
|
||
assert_eq!(fitted.chars().count(), 20);
|
||
}
|
||
|
||
#[test]
|
||
fn tab_width_fits_the_strip_within_bounds() {
|
||
assert_eq!(super::tab_width(0.0, 2), super::TAB_MAX_WIDTH);
|
||
assert_eq!(super::tab_width(1000.0, 2), super::TAB_MAX_WIDTH);
|
||
assert_eq!(super::tab_width(500.0, 10), super::TAB_MIN_WIDTH);
|
||
|
||
let width = super::tab_width(500.0, 3);
|
||
assert!((width - (500.0 - 2.0 * super::TAB_SPACING) / 3.0).abs() < 0.01);
|
||
}
|
||
|
||
#[test]
|
||
fn theme_colors_round_trip_through_hex() {
|
||
let color = iced::Color::from_rgb8(0x12, 0x34, 0x56);
|
||
|
||
assert_eq!(super::color_to_hex(color), "#123456");
|
||
assert_eq!(super::color_from_hex("#123456"), Some(color));
|
||
assert_eq!(
|
||
super::color_from_hex("#12345680"),
|
||
Some(iced::Color::from_rgba8(0x12, 0x34, 0x56, 128.0 / 255.0))
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn theme_file_only_stores_changed_colors() {
|
||
let mut colors = super::DEFAULT_COLORS;
|
||
colors[super::ColorOption::Accent.index()] = iced::Color::from_rgb8(1, 2, 3);
|
||
|
||
let file = super::ThemeFile::from_colors(
|
||
"Test theme".to_owned(),
|
||
theme::Preference::Dark,
|
||
&colors,
|
||
&super::DEFAULT_COLORS,
|
||
true,
|
||
&super::builtin_toast_colors(theme::Preference::Dark),
|
||
);
|
||
let text = toml::to_string(&file).unwrap();
|
||
|
||
assert!(text.contains("name = \"Test theme\""));
|
||
assert!(text.contains("based_on = \"dark\""));
|
||
assert!(text.contains("accent = \"#010203\""));
|
||
assert!(!text.contains("active_tab_outline"));
|
||
assert!(text.contains("[toast]"));
|
||
assert!(text.contains("enabled = true"));
|
||
assert!(text.contains("background = \"#"));
|
||
assert!(file.toast.enabled);
|
||
|
||
let loaded = file.colors(theme::Preference::Dark);
|
||
assert_eq!(
|
||
loaded[super::ColorOption::Accent.index()],
|
||
iced::Color::from_rgb8(1, 2, 3)
|
||
);
|
||
assert_eq!(
|
||
loaded[super::ColorOption::Text.index()],
|
||
super::DEFAULT_COLORS[super::ColorOption::Text.index()]
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn color_picker_updates_the_swatch_and_closes() {
|
||
let mut state = state();
|
||
let option = super::ColorOption::Accent;
|
||
let color = iced::Color::from_rgb(0.1, 0.2, 0.3);
|
||
|
||
let _ = update(&mut state, Message::OpenColorPicker(option));
|
||
assert_eq!(state.open_color_picker, Some(option));
|
||
|
||
let _ = update(&mut state, Message::SubmitColor(option, color));
|
||
assert_eq!(state.colors[option.index()], color);
|
||
assert_eq!(state.open_color_picker, None);
|
||
}
|
||
|
||
#[test]
|
||
fn toaster_color_picker_updates_only_toast_colors() {
|
||
let mut state = state();
|
||
// A custom theme keeps edits out of the config file and in the theme file.
|
||
state.theme_choice = super::ThemeChoice::Custom {
|
||
id: "test".to_owned(),
|
||
name: "Test".to_owned(),
|
||
};
|
||
let option = super::ToastColorOption::Info;
|
||
let color = iced::Color::from_rgb(0.4, 0.5, 0.6);
|
||
|
||
let _ = update(&mut state, Message::SetCustomToasts(true));
|
||
let _ = update(&mut state, Message::OpenToastColorPicker(option));
|
||
assert_eq!(state.open_toast_color_picker, Some(option));
|
||
|
||
let _ = update(&mut state, Message::SubmitToastColor(option, color));
|
||
assert_eq!(state.toast_colors[option.index()], color);
|
||
assert_eq!(state.open_toast_color_picker, None);
|
||
assert_eq!(state.colors, super::DEFAULT_COLORS);
|
||
|
||
let _ = update(&mut state, Message::SetCustomToasts(false));
|
||
assert!(!state.custom_toasts);
|
||
}
|
||
|
||
#[test]
|
||
fn builtin_toast_config_is_loaded_from_toml() {
|
||
let config: super::ConfigFile = toml::from_str(
|
||
r##"
|
||
[appearance]
|
||
theme = "dark"
|
||
|
||
[appearance.toast]
|
||
enabled = true
|
||
info = "#010203"
|
||
"##,
|
||
)
|
||
.unwrap();
|
||
|
||
let (enabled, colors) = super::builtin_toast_config(&config.appearance);
|
||
|
||
assert!(enabled);
|
||
assert_eq!(
|
||
colors[super::ToastColorOption::Info.index()],
|
||
iced::Color::from_rgb8(1, 2, 3)
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn theme_file_round_trips_toast_settings() {
|
||
let mut toast = super::builtin_toast_colors(theme::Preference::Dark);
|
||
toast[super::ToastColorOption::Background.index()] = iced::Color::from_rgb8(1, 2, 3);
|
||
|
||
let file = super::ThemeFile::from_colors(
|
||
"Test theme".to_owned(),
|
||
theme::Preference::Dark,
|
||
&super::DEFAULT_COLORS,
|
||
&super::DEFAULT_COLORS,
|
||
true,
|
||
&toast,
|
||
);
|
||
let text = toml::to_string_pretty(&file).unwrap();
|
||
let loaded: super::ThemeFile = toml::from_str(&text).unwrap();
|
||
|
||
assert!(loaded.toast.enabled);
|
||
assert_eq!(
|
||
loaded.toast.colors(theme::Preference::Dark)
|
||
[super::ToastColorOption::Background.index()],
|
||
iced::Color::from_rgb8(1, 2, 3)
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn tab_close_fades_in_and_out() {
|
||
let mut state = state();
|
||
let tab = Tab::Start;
|
||
|
||
let _ = update(&mut state, Message::HoverTab { tab, hovered: true });
|
||
|
||
let later = iced::time::Instant::now() + iced::time::Duration::from_secs(1);
|
||
let fade = state.tab_close_fades.get(&tab).unwrap();
|
||
assert!(fade.interpolate(0.0, 1.0, later) > 0.99);
|
||
|
||
let _ = update(
|
||
&mut state,
|
||
Message::HoverTab {
|
||
tab,
|
||
hovered: false,
|
||
},
|
||
);
|
||
|
||
let end = iced::time::Instant::now() + iced::time::Duration::from_secs(2);
|
||
let fade = state.tab_close_fades.get(&tab).unwrap();
|
||
assert!(fade.interpolate(0.0, 1.0, end) < 0.01);
|
||
}
|
||
|
||
#[test]
|
||
fn tab_scroll_buttons_follow_the_viewport() {
|
||
let mut state = state();
|
||
let window = test_window();
|
||
{
|
||
let window_state = window_state_mut(&mut state);
|
||
// 315px window => 200px strip; five tabs overflow at the min width.
|
||
window_state.size = iced::Size::new(315.0, 768.0);
|
||
window_state.tabs = (1..=5).map(Tab::Blank).collect();
|
||
}
|
||
|
||
window_state_mut(&mut state).tab_offset = 0.0;
|
||
assert_eq!(super::tab_scroll_limits(&state, window), (false, true));
|
||
|
||
window_state_mut(&mut state).tab_offset = 150.0;
|
||
assert_eq!(super::tab_scroll_limits(&state, window), (true, true));
|
||
|
||
window_state_mut(&mut state).tab_offset = 310.0;
|
||
assert_eq!(super::tab_scroll_limits(&state, window), (true, false));
|
||
}
|
||
|
||
#[test]
|
||
fn add_tab_appends_a_new_blank_tab() {
|
||
let mut state = state();
|
||
let window = test_window();
|
||
let _ = update(&mut state, Message::SelectTab(window, Tab::Settings));
|
||
let _ = update(&mut state, Message::AddTab(window));
|
||
let _ = update(&mut state, Message::AddTab(window));
|
||
|
||
let window_state = window_state(&state);
|
||
assert_eq!(
|
||
window_state.tabs,
|
||
vec![Tab::Settings, Tab::Blank(1), Tab::Blank(2)]
|
||
);
|
||
assert_eq!(window_state.active_tab, Some(Tab::Blank(2)));
|
||
assert_eq!(window_state.tabs[1].title(), "temp 1");
|
||
assert_eq!(window_state.tabs[2].title(), "temp 2");
|
||
}
|
||
|
||
#[test]
|
||
fn revealing_active_tab_only_scrolls_when_needed() {
|
||
let mut state = state();
|
||
let window = test_window();
|
||
{
|
||
let window_state = window_state_mut(&mut state);
|
||
// 515px window => 400px strip; ten tabs overflow at the min width.
|
||
window_state.size = iced::Size::new(515.0, 768.0);
|
||
window_state.tabs = (1..=10).map(Tab::Blank).collect();
|
||
window_state.active_tab = Some(Tab::Blank(10));
|
||
}
|
||
|
||
window_state_mut(&mut state).tab_offset = 620.0;
|
||
assert_eq!(super::tab_reveal_delta(&state, window), None);
|
||
|
||
window_state_mut(&mut state).tab_offset = 0.0;
|
||
assert!(super::tab_reveal_delta(&state, window).unwrap() > 0.0);
|
||
}
|
||
|
||
#[test]
|
||
fn close_other_tabs_keeps_only_the_active_one() {
|
||
let mut state = state();
|
||
let window = test_window();
|
||
let _ = update(&mut state, Message::SelectTab(window, Tab::Settings));
|
||
let _ = update(&mut state, Message::AddTab(window));
|
||
let _ = update(&mut state, Message::AddTab(window));
|
||
|
||
let _ = update(&mut state, Message::CloseOtherTabs(window));
|
||
let window_state = window_state(&state);
|
||
assert_eq!(window_state.tabs, vec![Tab::Blank(2)]);
|
||
assert_eq!(window_state.active_tab, Some(Tab::Blank(2)));
|
||
}
|
||
|
||
#[test]
|
||
fn close_active_tab_shortcut_closes_selected_tab() {
|
||
let mut state = state();
|
||
let window = test_window();
|
||
let _ = update(&mut state, Message::SelectTab(window, Tab::Settings));
|
||
let _ = update(&mut state, Message::AddTab(window));
|
||
|
||
let _ = update(&mut state, Message::CloseActiveTab(window));
|
||
let window_state = window_state(&state);
|
||
assert_eq!(window_state.tabs, vec![Tab::Settings]);
|
||
assert_eq!(window_state.active_tab, Some(Tab::Settings));
|
||
}
|
||
|
||
#[test]
|
||
fn closing_selects_the_next_tab_then_the_last() {
|
||
let mut state = state();
|
||
let window = test_window();
|
||
let _ = update(&mut state, Message::SelectTab(window, Tab::Settings));
|
||
let _ = update(&mut state, Message::AddTab(window));
|
||
let _ = update(&mut state, Message::AddTab(window));
|
||
|
||
let _ = update(&mut state, Message::SelectTab(window, Tab::Blank(1)));
|
||
let _ = update(&mut state, Message::CloseTab(window, Tab::Blank(1)));
|
||
assert_eq!(window_state(&state).active_tab, Some(Tab::Blank(2)));
|
||
|
||
let _ = update(&mut state, Message::CloseTab(window, Tab::Blank(2)));
|
||
assert_eq!(window_state(&state).active_tab, Some(Tab::Settings));
|
||
}
|
||
|
||
#[test]
|
||
fn closing_the_last_tab_unloads_the_window() {
|
||
let mut state = state();
|
||
let window = test_window();
|
||
let _ = update(&mut state, Message::SelectTab(window, Tab::Settings));
|
||
assert_eq!(window_state(&state).tabs, vec![Tab::Settings]);
|
||
assert_eq!(window_state(&state).active_tab, Some(Tab::Settings));
|
||
|
||
let _ = update(
|
||
&mut state,
|
||
Message::SelectSettingsSection(super::SettingsSection::Startup),
|
||
);
|
||
let _ = update(&mut state, Message::CloseTab(window, Tab::Settings));
|
||
assert!(!state.windows.contains_key(&window));
|
||
assert!(state.window_order.is_empty());
|
||
assert_eq!(state.settings_section, super::SettingsSection::General);
|
||
}
|
||
|
||
#[test]
|
||
fn dragging_reorders_tabs_and_moving_the_last_tab_closes_the_window() {
|
||
let mut state = state();
|
||
let window = test_window();
|
||
let _ = update(&mut state, Message::SelectTab(window, Tab::Settings));
|
||
let _ = update(&mut state, Message::AddTab(window));
|
||
let _ = update(&mut state, Message::AddTab(window));
|
||
|
||
// 1024px window => 909px strip => 230px tabs with 2px gaps.
|
||
state.drag = Some(super::TabDrag {
|
||
window,
|
||
tab: Tab::Settings,
|
||
origin: iced::Point::new(10.0, 20.0),
|
||
pointer: iced::Point::new(585.0, 20.0),
|
||
moved: true,
|
||
detach: false,
|
||
});
|
||
|
||
// The move is pending until release.
|
||
assert_eq!(
|
||
window_state(&state).tabs,
|
||
vec![Tab::Settings, Tab::Blank(1), Tab::Blank(2)]
|
||
);
|
||
assert_eq!(super::tab_gap_index(&state, window, 585.0), Some(3));
|
||
|
||
let _ = super::finish_drag(&mut state, window);
|
||
assert_eq!(
|
||
window_state(&state).tabs,
|
||
vec![Tab::Blank(1), Tab::Blank(2), Tab::Settings]
|
||
);
|
||
|
||
let destination = iced::window::Id::unique();
|
||
state.windows.insert(
|
||
destination,
|
||
super::WindowState::with_tab(Tab::Blank(9), iced::Size::new(800.0, 600.0), None),
|
||
);
|
||
state.window_order.push(destination);
|
||
|
||
let source = window_state_mut(&mut state);
|
||
source.tabs = vec![Tab::Settings];
|
||
source.active_tab = Some(Tab::Settings);
|
||
|
||
super::move_tab_to_window(&mut state, window, destination, Tab::Settings);
|
||
let _ = super::close_window_if_empty(&mut state, window);
|
||
|
||
assert!(!state.windows.contains_key(&window));
|
||
assert_eq!(state.windows[&destination].active_tab, Some(Tab::Settings));
|
||
assert_eq!(
|
||
super::window_title(&state, destination),
|
||
"Settings - Moorly"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn drop_panel_selects_the_window_under_the_pointer() {
|
||
let mut state = state();
|
||
let source = test_window();
|
||
let destination = iced::window::Id::unique();
|
||
state.windows.insert(
|
||
destination,
|
||
super::WindowState::with_tab(Tab::Blank(9), iced::Size::new(800.0, 600.0), None),
|
||
);
|
||
state.window_order.push(destination);
|
||
|
||
let rect = super::drop_panel_rect(window_state(&state), 1);
|
||
let row_y = rect.y
|
||
+ super::DROP_PANEL_PADDING
|
||
+ super::DROP_HEADER_HEIGHT
|
||
+ super::DROP_ROW_GAP
|
||
+ super::DROP_ROW_HEIGHT / 2.0;
|
||
let point = iced::Point::new(rect.x + 10.0, row_y);
|
||
|
||
assert_eq!(
|
||
super::drop_target_at(&state, source, point),
|
||
Some(destination)
|
||
);
|
||
assert_eq!(
|
||
super::drop_target_at(&state, source, iced::Point::new(0.0, 0.0)),
|
||
None
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn dragging_near_an_edge_requests_autoscroll() {
|
||
let mut state = state();
|
||
let window = test_window();
|
||
window_state_mut(&mut state).tabs = (1..=20).map(Tab::Blank).collect();
|
||
|
||
let viewport = super::tab_strip_width(1024.0);
|
||
state.drag = Some(super::TabDrag {
|
||
window,
|
||
tab: Tab::Blank(1),
|
||
origin: iced::Point::new(10.0, 20.0),
|
||
pointer: iced::Point::new(super::TAB_STRIP_LEFT + viewport - 2.0, 20.0),
|
||
moved: true,
|
||
detach: false,
|
||
});
|
||
assert!(super::drag_scroll_delta(&state).unwrap() > 0.0);
|
||
|
||
state.drag.as_mut().unwrap().pointer = iced::Point::new(6.0, 20.0);
|
||
assert!(super::drag_scroll_delta(&state).unwrap() < 0.0);
|
||
}
|
||
|
||
#[test]
|
||
fn shortcuts_round_trip_through_text() {
|
||
let shortcut = super::Shortcut::parse("ctrl+shift+k").unwrap();
|
||
assert_eq!(shortcut.to_string(), "Ctrl+Shift+K");
|
||
assert_eq!(
|
||
super::Shortcut::parse("Ctrl+,").unwrap().to_string(),
|
||
"Ctrl+,"
|
||
);
|
||
assert_eq!(
|
||
super::Shortcut::parse("Ctrl+Shift+Space")
|
||
.unwrap()
|
||
.to_string(),
|
||
"Ctrl+Shift+Space"
|
||
);
|
||
assert_eq!(super::Shortcut::parse("Ctrl+"), None);
|
||
assert_eq!(super::Shortcut::parse("Hyper+K"), None);
|
||
}
|
||
|
||
#[test]
|
||
fn space_shortcuts_match_the_space_key() {
|
||
let shortcut = super::Shortcut::parse("Ctrl+Shift+Space").unwrap();
|
||
|
||
assert!(shortcut.matches(
|
||
&keyboard::Key::Named(keyboard::key::Named::Space),
|
||
keyboard::Modifiers::CTRL | keyboard::Modifiers::SHIFT,
|
||
));
|
||
}
|
||
|
||
#[test]
|
||
fn command_palette_toggles_and_closes() {
|
||
let mut state = state();
|
||
let window = test_window();
|
||
|
||
let _ = update(&mut state, Message::ToggleCommandPalette(window));
|
||
assert!(window_state(&state).command_palette_open);
|
||
|
||
let _ = update(&mut state, Message::ToggleCommandPalette(window));
|
||
assert!(!window_state(&state).command_palette_open);
|
||
|
||
let _ = update(&mut state, Message::ToggleCommandPalette(window));
|
||
let _ = update(&mut state, Message::CloseCommandPalette(window));
|
||
assert!(!window_state(&state).command_palette_open);
|
||
}
|
||
|
||
#[test]
|
||
fn command_palette_fuzzy_matches_and_runs_settings() {
|
||
assert!(super::fuzzy_match("Settings", "stg"));
|
||
assert!(super::fuzzy_match("Settings", ""));
|
||
assert!(!super::fuzzy_match("Settings", "xyz"));
|
||
|
||
let mut state = state();
|
||
let window = test_window();
|
||
let _ = update(&mut state, Message::ToggleCommandPalette(window));
|
||
let _ = update(
|
||
&mut state,
|
||
Message::CommandPaletteChanged(window, "sett".to_owned()),
|
||
);
|
||
|
||
assert_eq!(
|
||
super::Command::matching(&state, window, "sett"),
|
||
vec![super::Command::Settings]
|
||
);
|
||
assert_eq!(
|
||
super::Command::matching(&state, window, "exit"),
|
||
vec![super::Command::Exit]
|
||
);
|
||
|
||
let _ = update(&mut state, Message::RunSelectedCommand(window));
|
||
|
||
assert_eq!(window_state(&state).active_tab, Some(Tab::Settings));
|
||
assert!(!window_state(&state).command_palette_open);
|
||
}
|
||
|
||
#[test]
|
||
fn command_palette_close_closes_the_active_tab() {
|
||
let mut state = state();
|
||
let window = test_window();
|
||
window_state_mut(&mut state).tabs = vec![Tab::Settings, Tab::Blank(1)];
|
||
window_state_mut(&mut state).active_tab = Some(Tab::Settings);
|
||
|
||
let _ = update(&mut state, Message::ToggleCommandPalette(window));
|
||
let _ = update(
|
||
&mut state,
|
||
Message::CommandPaletteChanged(window, "close".to_owned()),
|
||
);
|
||
let _ = update(&mut state, Message::RunSelectedCommand(window));
|
||
|
||
assert_eq!(window_state(&state).tabs, vec![Tab::Blank(1)]);
|
||
assert_eq!(window_state(&state).active_tab, Some(Tab::Blank(1)));
|
||
assert!(!window_state(&state).command_palette_open);
|
||
}
|
||
|
||
#[test]
|
||
fn move_command_detaches_the_active_tab_to_a_new_window() {
|
||
let mut state = state();
|
||
let window = test_window();
|
||
window_state_mut(&mut state).tabs = vec![Tab::Settings, Tab::Blank(1)];
|
||
window_state_mut(&mut state).active_tab = Some(Tab::Settings);
|
||
|
||
let _ = update(&mut state, Message::ToggleCommandPalette(window));
|
||
let _ = update(
|
||
&mut state,
|
||
Message::CommandPaletteChanged(window, "move".to_owned()),
|
||
);
|
||
let _ = update(&mut state, Message::RunSelectedCommand(window));
|
||
|
||
assert_eq!(state.windows.len(), 2);
|
||
let detached = *state.window_order.last().unwrap();
|
||
assert_eq!(state.windows[&detached].active_tab, Some(Tab::Settings));
|
||
assert_eq!(window_state(&state).active_tab, Some(Tab::Blank(1)));
|
||
}
|
||
|
||
#[test]
|
||
fn move_command_lists_windows_and_moves_to_the_selected_one() {
|
||
let mut state = state();
|
||
let window = test_window();
|
||
let destination = iced::window::Id::unique();
|
||
state.windows.insert(
|
||
destination,
|
||
super::WindowState::with_tab(Tab::Blank(9), iced::Size::new(800.0, 600.0), None),
|
||
);
|
||
state.window_order.push(destination);
|
||
window_state_mut(&mut state).tabs = vec![Tab::Settings, Tab::Blank(1)];
|
||
window_state_mut(&mut state).active_tab = Some(Tab::Settings);
|
||
|
||
assert_eq!(
|
||
super::Command::matching(&state, window, "move"),
|
||
vec![
|
||
super::Command::Move,
|
||
super::Command::MoveToWindow(destination)
|
||
]
|
||
);
|
||
|
||
let _ = update(&mut state, Message::ToggleCommandPalette(window));
|
||
let _ = update(
|
||
&mut state,
|
||
Message::CommandPaletteChanged(window, "move".to_owned()),
|
||
);
|
||
let _ = update(&mut state, Message::CommandPaletteDown(window));
|
||
let _ = update(&mut state, Message::RunSelectedCommand(window));
|
||
|
||
assert_eq!(window_state(&state).tabs, vec![Tab::Blank(1)]);
|
||
assert_eq!(state.windows[&destination].active_tab, Some(Tab::Settings));
|
||
}
|
||
|
||
#[test]
|
||
fn command_palette_focuses_a_matching_window() {
|
||
let mut state = state();
|
||
let window = test_window();
|
||
let destination = iced::window::Id::unique();
|
||
state.windows.insert(
|
||
destination,
|
||
super::WindowState::with_tab(Tab::Blank(9), iced::Size::new(800.0, 600.0), None),
|
||
);
|
||
state.window_order.push(destination);
|
||
|
||
assert_eq!(
|
||
super::Command::matching(&state, window, "temp 9"),
|
||
vec![
|
||
super::Command::FocusWindow(destination),
|
||
super::Command::FocusTab(destination, Tab::Blank(9))
|
||
]
|
||
);
|
||
|
||
let _ = update(&mut state, Message::ToggleCommandPalette(window));
|
||
let _ = update(
|
||
&mut state,
|
||
Message::CommandPaletteChanged(window, "temp 9".to_owned()),
|
||
);
|
||
let _ = update(&mut state, Message::RunSelectedCommand(window));
|
||
|
||
assert_eq!(state.focused_window, Some(destination));
|
||
}
|
||
|
||
#[test]
|
||
fn command_palette_focuses_a_matching_tab_in_its_window() {
|
||
let mut state = state();
|
||
let window = test_window();
|
||
let destination = iced::window::Id::unique();
|
||
let mut destination_state =
|
||
super::WindowState::with_tab(Tab::Blank(9), iced::Size::new(800.0, 600.0), None);
|
||
destination_state.tabs.push(Tab::Settings);
|
||
state.windows.insert(destination, destination_state);
|
||
state.window_order.push(destination);
|
||
|
||
assert_eq!(
|
||
super::Command::matching(&state, window, "settings"),
|
||
vec![
|
||
super::Command::Settings,
|
||
super::Command::FocusTab(destination, Tab::Settings)
|
||
]
|
||
);
|
||
|
||
let _ = update(&mut state, Message::ToggleCommandPalette(window));
|
||
let _ = update(
|
||
&mut state,
|
||
Message::CommandPaletteChanged(window, "settings".to_owned()),
|
||
);
|
||
let _ = update(&mut state, Message::CommandPaletteDown(window));
|
||
let _ = update(&mut state, Message::RunSelectedCommand(window));
|
||
|
||
assert_eq!(state.focused_window, Some(destination));
|
||
assert_eq!(state.windows[&destination].active_tab, Some(Tab::Settings));
|
||
}
|
||
|
||
fn press(key: keyboard::Key, modifiers: keyboard::Modifiers) -> Message {
|
||
Message::CaptureKey { key, modifiers }
|
||
}
|
||
|
||
#[test]
|
||
fn changing_the_settings_shortcut_rebinds_it() {
|
||
let mut state = state();
|
||
let _ = update(
|
||
&mut state,
|
||
Message::OpenShortcutCapture(super::ShortcutAction::Settings),
|
||
);
|
||
let _ = update(
|
||
&mut state,
|
||
press(
|
||
keyboard::Key::Character("k".into()),
|
||
keyboard::Modifiers::CTRL | keyboard::Modifiers::SHIFT,
|
||
),
|
||
);
|
||
assert_eq!(
|
||
state
|
||
.shortcut_capture
|
||
.as_ref()
|
||
.unwrap()
|
||
.candidate
|
||
.as_ref()
|
||
.unwrap()
|
||
.to_string(),
|
||
"Ctrl+Shift+K"
|
||
);
|
||
|
||
let _ = update(&mut state, Message::ApplyShortcut);
|
||
|
||
assert_eq!(
|
||
state.shortcuts.settings.as_ref().map(ToString::to_string),
|
||
Some("Ctrl+Shift+K".to_owned())
|
||
);
|
||
assert!(state.shortcut_capture.is_none());
|
||
}
|
||
|
||
#[test]
|
||
fn conflicting_shortcuts_are_rejected() {
|
||
let mut state = state();
|
||
let _ = update(
|
||
&mut state,
|
||
Message::OpenShortcutCapture(super::ShortcutAction::Settings),
|
||
);
|
||
let _ = update(
|
||
&mut state,
|
||
press(
|
||
keyboard::Key::Character("w".into()),
|
||
keyboard::Modifiers::CTRL | keyboard::Modifiers::SHIFT,
|
||
),
|
||
);
|
||
let _ = update(&mut state, Message::ApplyShortcut);
|
||
|
||
assert_eq!(
|
||
state.shortcuts.settings.as_ref().map(ToString::to_string),
|
||
Some("Ctrl+,".to_owned())
|
||
);
|
||
assert!(state.shortcut_capture.as_ref().unwrap().error.is_some());
|
||
}
|
||
|
||
#[test]
|
||
fn shortcuts_cannot_steal_each_others_keys() {
|
||
let mut state = state();
|
||
let _ = update(
|
||
&mut state,
|
||
Message::OpenShortcutCapture(super::ShortcutAction::Settings),
|
||
);
|
||
let _ = update(
|
||
&mut state,
|
||
press(
|
||
keyboard::Key::Character("q".into()),
|
||
keyboard::Modifiers::CTRL | keyboard::Modifiers::SHIFT,
|
||
),
|
||
);
|
||
let _ = update(&mut state, Message::ApplyShortcut);
|
||
|
||
assert_eq!(
|
||
state.shortcuts.settings.as_ref().map(ToString::to_string),
|
||
Some("Ctrl+,".to_owned())
|
||
);
|
||
assert_eq!(
|
||
state.shortcuts.quit.as_ref().map(ToString::to_string),
|
||
Some("Ctrl+Shift+Q".to_owned())
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn plain_keys_are_not_accepted_as_shortcuts() {
|
||
let mut state = state();
|
||
let _ = update(
|
||
&mut state,
|
||
Message::OpenShortcutCapture(super::ShortcutAction::Settings),
|
||
);
|
||
let _ = update(
|
||
&mut state,
|
||
press(
|
||
keyboard::Key::Character("k".into()),
|
||
keyboard::Modifiers::NONE,
|
||
),
|
||
);
|
||
|
||
assert!(state.shortcut_capture.as_ref().unwrap().candidate.is_none());
|
||
assert!(state.shortcut_capture.as_ref().unwrap().error.is_some());
|
||
}
|
||
|
||
#[test]
|
||
fn clearing_a_shortcut_removes_only_that_binding() {
|
||
let mut state = state();
|
||
let _ = update(
|
||
&mut state,
|
||
Message::ClearShortcut(super::ShortcutAction::Settings),
|
||
);
|
||
|
||
assert!(state.shortcuts.settings.is_none());
|
||
assert!(state.shortcuts.quit.is_some());
|
||
}
|
||
|
||
#[test]
|
||
fn restoring_a_shortcut_default_rebinds_it() {
|
||
let mut state = state();
|
||
let _ = update(
|
||
&mut state,
|
||
Message::ClearShortcut(super::ShortcutAction::Settings),
|
||
);
|
||
assert!(state.shortcuts.settings.is_none());
|
||
|
||
let _ = update(
|
||
&mut state,
|
||
Message::DefaultShortcut(super::ShortcutAction::Settings),
|
||
);
|
||
|
||
assert_eq!(
|
||
state.shortcuts.settings.as_ref().map(ToString::to_string),
|
||
Some("Ctrl+,".to_owned())
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn quit_has_a_default_shortcut() {
|
||
let state = state();
|
||
|
||
assert_eq!(
|
||
state.shortcuts.quit.as_ref().map(ToString::to_string),
|
||
Some("Ctrl+Shift+Q".to_owned())
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn profiles_start_with_an_ungrouped_map() {
|
||
let state = state();
|
||
|
||
assert_eq!(state.profile_folders.len(), 1);
|
||
assert_eq!(state.profile_folders[0].name, "Ungrouped");
|
||
assert!(state.profile_folders[0].profiles.is_empty());
|
||
}
|
||
|
||
#[test]
|
||
fn clicking_a_folder_toggles_its_profiles() {
|
||
let mut state = state();
|
||
assert!(state.profile_folders[0].expanded);
|
||
|
||
let _ = update(&mut state, Message::ToggleFolder(0));
|
||
assert!(!state.profile_folders[0].expanded);
|
||
assert_eq!(state.selected, Some(super::Selection::Folder(0)));
|
||
|
||
let _ = update(&mut state, Message::ToggleFolder(0));
|
||
assert!(state.profile_folders[0].expanded);
|
||
}
|
||
#[test]
|
||
fn add_menu_opens_the_folder_dialog() {
|
||
let mut state = state();
|
||
let _ = update(&mut state, Message::ToggleAddMenu);
|
||
assert!(state.add_menu_open);
|
||
|
||
let _ = update(&mut state, Message::OpenFolderDialog);
|
||
assert_eq!(state.folder_dialog.as_deref(), Some(""));
|
||
assert!(!state.add_menu_open);
|
||
|
||
let _ = update(&mut state, Message::FolderNameChanged("Work".to_owned()));
|
||
let _ = update(&mut state, Message::ConfirmFolder);
|
||
|
||
assert_eq!(state.profile_folders.len(), 2);
|
||
assert_eq!(state.profile_folders[1].name, "Work");
|
||
assert!(state.folder_dialog.is_none());
|
||
}
|
||
|
||
#[test]
|
||
fn cancelling_a_folder_does_not_add_it() {
|
||
let mut state = state();
|
||
let _ = update(&mut state, Message::OpenFolderDialog);
|
||
let _ = update(&mut state, Message::FolderNameChanged("Work".to_owned()));
|
||
let _ = update(&mut state, Message::CancelFolder);
|
||
|
||
assert_eq!(state.profile_folders.len(), 1);
|
||
assert!(state.folder_dialog.is_none());
|
||
}
|
||
|
||
#[test]
|
||
fn empty_folder_names_are_rejected() {
|
||
let mut state = state();
|
||
let _ = update(&mut state, Message::OpenFolderDialog);
|
||
let _ = update(&mut state, Message::FolderNameChanged(" ".to_owned()));
|
||
let _ = update(&mut state, Message::ConfirmFolder);
|
||
|
||
assert_eq!(state.profile_folders.len(), 1);
|
||
assert!(state.folder_dialog.is_some());
|
||
}
|
||
|
||
#[test]
|
||
fn adding_a_profile_opens_its_folder_and_selects_it() {
|
||
let mut state = state();
|
||
let _ = update(&mut state, Message::ToggleFolder(0));
|
||
assert!(!state.profile_folders[0].expanded);
|
||
|
||
let _ = update(&mut state, Message::OpenProfileDialog);
|
||
let _ = update(&mut state, Message::ProfileNameChanged("Server".to_owned()));
|
||
let _ = update(&mut state, Message::ConfirmProfile);
|
||
|
||
assert!(state.profile_folders[0].expanded);
|
||
assert_eq!(
|
||
state.selected,
|
||
Some(super::Selection::Profile {
|
||
folder: 0,
|
||
profile: 0,
|
||
})
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn profile_dialog_stores_the_entered_details() {
|
||
let mut state = state();
|
||
let _ = update(&mut state, Message::OpenProfileDialog);
|
||
let _ = update(&mut state, Message::ProfileNameChanged("Server".to_owned()));
|
||
let _ = update(
|
||
&mut state,
|
||
Message::ProfileHostChanged("example.com".to_owned()),
|
||
);
|
||
let _ = update(&mut state, Message::ProfilePortChanged("2222".to_owned()));
|
||
let _ = update(
|
||
&mut state,
|
||
Message::ProfileUsernameChanged("root".to_owned()),
|
||
);
|
||
let _ = update(
|
||
&mut state,
|
||
Message::ProfilePasswordChanged("hunter2".to_owned()),
|
||
);
|
||
let _ = update(
|
||
&mut state,
|
||
Message::ProfileKindSelected(super::ProfileKind::Ssh),
|
||
);
|
||
let _ = update(
|
||
&mut state,
|
||
Message::SessionEndSelected(super::SessionEnd::Reconnect),
|
||
);
|
||
let _ = update(&mut state, Message::ConfirmProfile);
|
||
|
||
let profile = &state.profile_folders[0].profiles[0];
|
||
assert_eq!(profile.name, "Server");
|
||
assert_eq!(profile.host, "example.com");
|
||
assert_eq!(profile.port, "2222");
|
||
assert_eq!(profile.username, "root");
|
||
assert_eq!(profile.password, "hunter2");
|
||
assert_eq!(profile.session_end, super::SessionEnd::Reconnect);
|
||
}
|
||
|
||
#[test]
|
||
fn auth_method_is_exclusive_and_password_visibility_toggles() {
|
||
let mut state = state();
|
||
let _ = update(&mut state, Message::OpenProfileDialog);
|
||
|
||
let _ = update(
|
||
&mut state,
|
||
Message::AuthMethodSelected(super::AuthMethod::Key),
|
||
);
|
||
assert_eq!(
|
||
state.profile_dialog.as_ref().unwrap().auth,
|
||
super::AuthMethod::Key
|
||
);
|
||
|
||
let _ = update(&mut state, Message::TogglePasswordVisibility);
|
||
assert!(state.profile_dialog.as_ref().unwrap().password_visible);
|
||
|
||
let _ = update(&mut state, Message::TogglePasswordVisibility);
|
||
assert!(!state.profile_dialog.as_ref().unwrap().password_visible);
|
||
}
|
||
|
||
#[test]
|
||
fn profile_port_only_accepts_0_to_65534() {
|
||
let mut state = state();
|
||
let _ = update(&mut state, Message::OpenProfileDialog);
|
||
|
||
let _ = update(&mut state, Message::ProfilePortChanged("65534".to_owned()));
|
||
assert_eq!(state.profile_dialog.as_ref().unwrap().port, "65534");
|
||
|
||
let _ = update(&mut state, Message::ProfilePortChanged("65535".to_owned()));
|
||
assert_eq!(state.profile_dialog.as_ref().unwrap().port, "65534");
|
||
|
||
let _ = update(&mut state, Message::ProfilePortChanged("abc".to_owned()));
|
||
assert_eq!(state.profile_dialog.as_ref().unwrap().port, "65534");
|
||
|
||
let _ = update(&mut state, Message::ProfilePortChanged(String::new()));
|
||
assert_eq!(state.profile_dialog.as_ref().unwrap().port, "");
|
||
}
|
||
|
||
#[test]
|
||
fn profile_names_are_limited_to_150_chars() {
|
||
let mut state = state();
|
||
let _ = update(&mut state, Message::OpenProfileDialog);
|
||
let _ = update(&mut state, Message::ProfileNameChanged("a".repeat(200)));
|
||
|
||
assert_eq!(
|
||
state.profile_dialog.as_ref().unwrap().name.chars().count(),
|
||
150
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn terminal_profiles_store_the_start_path() {
|
||
let mut state = state();
|
||
let _ = update(&mut state, Message::OpenProfileDialog);
|
||
|
||
let draft = state.profile_dialog.as_ref().unwrap();
|
||
if cfg!(windows) {
|
||
assert!(!draft.start_path.is_empty());
|
||
} else {
|
||
assert_eq!(draft.start_path, "~/");
|
||
}
|
||
|
||
let _ = update(
|
||
&mut state,
|
||
Message::ProfileKindSelected(super::ProfileKind::Terminal),
|
||
);
|
||
let _ = update(&mut state, Message::ProfileNameChanged("Term".to_owned()));
|
||
let _ = update(
|
||
&mut state,
|
||
Message::ProfileStartPathChanged("/tmp".to_owned()),
|
||
);
|
||
let _ = update(&mut state, Message::ConfirmProfile);
|
||
|
||
assert_eq!(state.profile_folders[0].profiles[0].start_path, "/tmp");
|
||
}
|
||
|
||
#[test]
|
||
fn directory_picker_lists_subdirectories() {
|
||
let stamp = std::time::SystemTime::now()
|
||
.duration_since(std::time::UNIX_EPOCH)
|
||
.unwrap()
|
||
.as_nanos();
|
||
let root = std::env::temp_dir().join(format!("moorly-test-{stamp}"));
|
||
let child = root.join("child");
|
||
std::fs::create_dir_all(&child).unwrap();
|
||
|
||
let picker = super::DirPicker::open(root.clone(), false, super::PickerTarget::StartPath);
|
||
assert_eq!(picker.entries, vec![child]);
|
||
assert!(picker.error.is_none());
|
||
|
||
std::fs::remove_dir_all(&root).unwrap();
|
||
}
|
||
|
||
#[test]
|
||
fn private_key_picker_selects_a_file() {
|
||
let stamp = std::time::SystemTime::now()
|
||
.duration_since(std::time::UNIX_EPOCH)
|
||
.unwrap()
|
||
.as_nanos();
|
||
let root = std::env::temp_dir().join(format!("moorly-key-test-{stamp}"));
|
||
std::fs::create_dir_all(&root).unwrap();
|
||
let key = root.join("id_test");
|
||
std::fs::write(&key, b"key").unwrap();
|
||
|
||
let mut picker =
|
||
super::DirPicker::open(root.clone(), true, super::PickerTarget::PrivateKey);
|
||
assert_eq!(picker.entries, vec![key.clone()]);
|
||
assert!(!picker.can_confirm());
|
||
|
||
picker.selected = Some(key.clone());
|
||
assert!(picker.can_confirm());
|
||
|
||
let mut state = state();
|
||
state.profile_dialog = Some(super::ProfileDraft::new(0));
|
||
state.dir_picker = Some(picker);
|
||
let _ = update(&mut state, Message::ConfirmDirectoryPicker);
|
||
|
||
assert_eq!(
|
||
state.profile_dialog.as_ref().unwrap().private_key,
|
||
key.to_string_lossy()
|
||
);
|
||
assert!(state.dir_picker.is_none());
|
||
|
||
std::fs::remove_dir_all(&root).unwrap();
|
||
}
|
||
|
||
#[test]
|
||
fn adding_a_folder_selects_it() {
|
||
let mut state = state();
|
||
let _ = update(&mut state, Message::OpenFolderDialog);
|
||
let _ = update(&mut state, Message::FolderNameChanged("Work".to_owned()));
|
||
let _ = update(&mut state, Message::ConfirmFolder);
|
||
|
||
assert_eq!(state.profile_folders[1].name, "Work");
|
||
assert_eq!(state.selected, Some(super::Selection::Folder(1)));
|
||
}
|
||
|
||
#[test]
|
||
fn checkboxes_toggle_and_clear() {
|
||
let mut state = state();
|
||
|
||
let _ = update(
|
||
&mut state,
|
||
Message::ToggleChecked(super::Selection::Folder(0)),
|
||
);
|
||
assert!(state.checked.contains(&super::Selection::Folder(0)));
|
||
|
||
let _ = update(
|
||
&mut state,
|
||
Message::ToggleChecked(super::Selection::Profile {
|
||
folder: 0,
|
||
profile: 0,
|
||
}),
|
||
);
|
||
assert_eq!(state.checked.len(), 2);
|
||
|
||
let _ = update(&mut state, Message::DeselectAll);
|
||
assert!(state.checked.is_empty());
|
||
}
|
||
|
||
#[test]
|
||
fn delete_removes_checked_profiles_and_folders() {
|
||
let mut state = state();
|
||
state.profile_folders = vec![
|
||
super::ProfileFolder::default_folder(),
|
||
super::ProfileFolder::from_path("Work".to_owned()),
|
||
super::ProfileFolder::from_path("Work/Sub".to_owned()),
|
||
];
|
||
state.profile_folders[0].profiles.push(profile("Loose"));
|
||
state.profile_folders[1].profiles.push(profile("Inside"));
|
||
state.profile_folders[2].profiles.push(profile("Nested"));
|
||
state.checked.insert(super::Selection::Profile {
|
||
folder: 0,
|
||
profile: 0,
|
||
});
|
||
state.checked.insert(super::Selection::Folder(1));
|
||
|
||
let _ = update(&mut state, Message::DeleteChecked);
|
||
assert!(state.confirm_delete);
|
||
let _ = update(&mut state, Message::ConfirmDelete);
|
||
|
||
assert!(state.checked.is_empty());
|
||
assert!(!state.confirm_delete);
|
||
assert!(
|
||
state
|
||
.profile_folders
|
||
.iter()
|
||
.all(|folder| folder.path != "Work")
|
||
);
|
||
|
||
// Unchecked children move up instead of going with the deleted folder.
|
||
let sub = state
|
||
.profile_folders
|
||
.iter()
|
||
.find(|folder| folder.path == "Sub")
|
||
.unwrap();
|
||
assert_eq!(sub.profiles.len(), 1);
|
||
assert_eq!(sub.profiles[0].name, "Nested");
|
||
|
||
let default = state
|
||
.profile_folders
|
||
.iter()
|
||
.find(|folder| folder.path == "Ungrouped")
|
||
.unwrap();
|
||
assert_eq!(default.profiles.len(), 1);
|
||
assert_eq!(default.profiles[0].name, "Inside");
|
||
}
|
||
|
||
#[test]
|
||
fn copy_and_move_transfer_checked_profiles() {
|
||
let mut state = state();
|
||
state.profile_folders = vec![
|
||
super::ProfileFolder::default_folder(),
|
||
super::ProfileFolder::from_path("Work".to_owned()),
|
||
];
|
||
state.profile_folders[0].profiles.push(profile("Source"));
|
||
state.checked.insert(super::Selection::Profile {
|
||
folder: 0,
|
||
profile: 0,
|
||
});
|
||
|
||
let _ = update(&mut state, Message::CopyChecked);
|
||
let _ = update(
|
||
&mut state,
|
||
Message::TransferFolderSelected(super::FolderChoice {
|
||
index: 1,
|
||
name: "Work".to_owned(),
|
||
}),
|
||
);
|
||
let _ = update(&mut state, Message::ConfirmTransfer);
|
||
|
||
assert_eq!(state.profile_folders[0].profiles.len(), 1);
|
||
assert_eq!(state.profile_folders[1].profiles.len(), 1);
|
||
assert_eq!(state.profile_folders[1].profiles[0].name, "Source");
|
||
|
||
state.checked.insert(super::Selection::Profile {
|
||
folder: 0,
|
||
profile: 0,
|
||
});
|
||
let _ = update(&mut state, Message::MoveChecked);
|
||
let _ = update(
|
||
&mut state,
|
||
Message::TransferFolderSelected(super::FolderChoice {
|
||
index: 1,
|
||
name: "Work".to_owned(),
|
||
}),
|
||
);
|
||
let _ = update(&mut state, Message::ConfirmTransfer);
|
||
|
||
assert!(state.profile_folders[0].profiles.is_empty());
|
||
assert_eq!(state.profile_folders[1].profiles.len(), 2);
|
||
}
|
||
|
||
#[test]
|
||
fn trash_restore_recreates_folders_and_profiles() {
|
||
let mut state = state();
|
||
state.profile_folders = vec![super::ProfileFolder::default_folder()];
|
||
let mut profile_file = super::ProfileFile::from_profile(&profile("Loose"), "Ungrouped");
|
||
profile_file.trash = Some(super::TrashInfo {
|
||
previous_path: "Ungrouped".to_owned(),
|
||
deleted: "2026-11-07 12:00:00".to_owned(),
|
||
});
|
||
state.trash_entries = vec![
|
||
super::TrashEntry::Folder(super::TrashFolder {
|
||
name: "Work".to_owned(),
|
||
previous_path: String::new(),
|
||
deleted: "2026-11-07 12:00:00".to_owned(),
|
||
}),
|
||
super::TrashEntry::Profile {
|
||
file: std::path::PathBuf::from("/nonexistent/trash.toml"),
|
||
profile: profile_file,
|
||
},
|
||
];
|
||
state.trash_checked.insert(0);
|
||
state.trash_checked.insert(1);
|
||
|
||
let _ = update(&mut state, Message::RestoreSelected);
|
||
|
||
assert!(state.trash_entries.is_empty());
|
||
assert_eq!(state.profile_folders[0].profiles.len(), 1);
|
||
assert_eq!(state.profile_folders[0].profiles[0].name, "Loose");
|
||
let work = state
|
||
.profile_folders
|
||
.iter()
|
||
.find(|folder| folder.path == "Work")
|
||
.unwrap();
|
||
assert!(work.profiles.is_empty());
|
||
}
|
||
|
||
#[test]
|
||
fn moving_a_folder_moves_its_subtree() {
|
||
let mut state = state();
|
||
state.profile_folders = vec![
|
||
super::ProfileFolder::default_folder(),
|
||
super::ProfileFolder::from_path("Work".to_owned()),
|
||
super::ProfileFolder::from_path("Home".to_owned()),
|
||
];
|
||
state.profile_folders[1].profiles.push(profile("Server"));
|
||
state.checked.insert(super::Selection::Folder(1));
|
||
|
||
let _ = update(&mut state, Message::MoveChecked);
|
||
let _ = update(
|
||
&mut state,
|
||
Message::TransferFolderSelected(super::FolderChoice {
|
||
index: 2,
|
||
name: "Home".to_owned(),
|
||
}),
|
||
);
|
||
let _ = update(&mut state, Message::ConfirmTransfer);
|
||
|
||
assert!(
|
||
state
|
||
.profile_folders
|
||
.iter()
|
||
.all(|folder| folder.path != "Work")
|
||
);
|
||
let moved = state
|
||
.profile_folders
|
||
.iter()
|
||
.find(|folder| folder.path == "Home/Work")
|
||
.unwrap();
|
||
assert_eq!(moved.profiles.len(), 1);
|
||
assert_eq!(moved.profiles[0].name, "Server");
|
||
}
|
||
|
||
#[test]
|
||
fn trash_timestamps_are_readable() {
|
||
assert_eq!(super::format_timestamp(0), "1970-01-01 00:00:00");
|
||
assert_eq!(
|
||
super::format_timestamp(1_700_000_000),
|
||
"2023-11-14 22:13:20"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn trash_entries_load_from_folders_and_profiles() {
|
||
let stamp = std::time::SystemTime::now()
|
||
.duration_since(std::time::UNIX_EPOCH)
|
||
.unwrap()
|
||
.as_nanos();
|
||
let root = std::env::temp_dir().join(format!("moorly-trash-test-{stamp}"));
|
||
std::fs::create_dir_all(&root).unwrap();
|
||
std::fs::write(
|
||
root.join("folders.toml"),
|
||
"[[folders]]\nname = \"Work\"\nprevious_path = \"\"\ndeleted = \"2026-11-07 12:00:00\"\n",
|
||
)
|
||
.unwrap();
|
||
|
||
let mut profile_file = super::ProfileFile::from_profile(&profile("Server"), "Work");
|
||
profile_file.trash = Some(super::TrashInfo {
|
||
previous_path: "Work".to_owned(),
|
||
deleted: "2026-11-07 12:01:00".to_owned(),
|
||
});
|
||
let text = toml::to_string_pretty(&profile_file).unwrap();
|
||
assert!(text.contains("[trash]"));
|
||
std::fs::write(root.join("Server.toml"), text).unwrap();
|
||
|
||
let entries = super::load_trash_entries_from(&root);
|
||
assert_eq!(entries.len(), 2);
|
||
|
||
let folder = entries.iter().find(|entry| entry.is_folder()).unwrap();
|
||
assert_eq!(folder.name(), "Work");
|
||
assert_eq!(folder.previous_path(), "");
|
||
assert_eq!(folder.deleted(), "2026-11-07 12:00:00");
|
||
|
||
let profile = entries.iter().find(|entry| !entry.is_folder()).unwrap();
|
||
assert_eq!(profile.name(), "Server");
|
||
assert_eq!(profile.previous_path(), "Work");
|
||
assert_eq!(profile.deleted(), "2026-11-07 12:01:00");
|
||
|
||
std::fs::remove_dir_all(&root).unwrap();
|
||
}
|
||
|
||
#[test]
|
||
fn profiles_load_nested_folders_and_create_missing_parents() {
|
||
let stamp = std::time::SystemTime::now()
|
||
.duration_since(std::time::UNIX_EPOCH)
|
||
.unwrap()
|
||
.as_nanos();
|
||
let root = std::env::temp_dir().join(format!("moorly-profiles-test-{stamp}"));
|
||
std::fs::create_dir_all(&root).unwrap();
|
||
std::fs::write(
|
||
root.join("folders.toml"),
|
||
"folders = [\"Work/Production\"]\n",
|
||
)
|
||
.unwrap();
|
||
std::fs::write(
|
||
root.join("Server.toml"),
|
||
"name = \"Server\"\nfolder = \"Work/Production\"\nhost = \"example.com\"\n",
|
||
)
|
||
.unwrap();
|
||
std::fs::write(
|
||
root.join("Orphan.toml"),
|
||
"name = \"Orphan\"\nfolder = \"Missing/Deep\"\nkind = \"terminal\"\n",
|
||
)
|
||
.unwrap();
|
||
|
||
let folders = super::load_profiles_from(&root);
|
||
let paths: Vec<&str> = folders.iter().map(|folder| folder.path.as_str()).collect();
|
||
|
||
assert!(paths.contains(&"Ungrouped"));
|
||
assert!(paths.contains(&"Work"));
|
||
assert!(paths.contains(&"Work/Production"));
|
||
assert!(paths.contains(&"Missing"));
|
||
assert!(paths.contains(&"Missing/Deep"));
|
||
assert!(
|
||
paths.iter().position(|path| *path == "Work")
|
||
< paths.iter().position(|path| *path == "Work/Production")
|
||
);
|
||
|
||
let production = folders
|
||
.iter()
|
||
.find(|folder| folder.path == "Work/Production")
|
||
.unwrap();
|
||
assert_eq!(production.profiles.len(), 1);
|
||
assert_eq!(production.profiles[0].name, "Server");
|
||
assert_eq!(production.profiles[0].host, "example.com");
|
||
assert!(!production.untracked);
|
||
|
||
let work = folders.iter().find(|folder| folder.path == "Work").unwrap();
|
||
assert!(!work.untracked);
|
||
|
||
let orphan = folders
|
||
.iter()
|
||
.find(|folder| folder.path == "Missing/Deep")
|
||
.unwrap();
|
||
assert_eq!(orphan.profiles[0].name, "Orphan");
|
||
assert!(orphan.untracked);
|
||
assert!(
|
||
folders
|
||
.iter()
|
||
.find(|folder| folder.path == "Missing")
|
||
.unwrap()
|
||
.untracked
|
||
);
|
||
|
||
super::write_folders_to(&root, &folders).unwrap();
|
||
let folders_text = std::fs::read_to_string(root.join("folders.toml")).unwrap();
|
||
assert!(folders_text.contains("\"Work/Production\""));
|
||
assert!(!folders_text.contains("Missing"));
|
||
|
||
std::fs::remove_dir_all(&root).unwrap();
|
||
}
|
||
|
||
#[test]
|
||
fn profile_files_store_the_folder_and_settings() {
|
||
let stamp = std::time::SystemTime::now()
|
||
.duration_since(std::time::UNIX_EPOCH)
|
||
.unwrap()
|
||
.as_nanos();
|
||
let root = std::env::temp_dir().join(format!("moorly-profile-file-test-{stamp}"));
|
||
let profile = super::Profile {
|
||
name: "Server/Test".to_owned(),
|
||
kind: super::ProfileKind::Ssh,
|
||
session_end: super::SessionEnd::Reconnect,
|
||
host: "example.com".to_owned(),
|
||
port: "2222".to_owned(),
|
||
username: "root".to_owned(),
|
||
auth: super::AuthMethod::Key,
|
||
password: "secret".to_owned(),
|
||
start_path: "/tmp".to_owned(),
|
||
private_key: "/keys/id".to_owned(),
|
||
file: None,
|
||
};
|
||
|
||
let path = super::write_profile_to(&root, &profile, "Work/Production").unwrap();
|
||
assert_eq!(path.file_name().unwrap(), "Server_Test.toml");
|
||
|
||
let text = std::fs::read_to_string(&path).unwrap();
|
||
assert!(text.contains("folder = \"Work/Production\""));
|
||
assert!(text.contains("kind = \"ssh\""));
|
||
assert!(text.contains("session_end = \"reconnect\""));
|
||
assert!(text.contains("host = \"example.com\""));
|
||
assert!(text.contains("private_key = \"/keys/id\""));
|
||
|
||
let duplicate = super::write_profile_to(&root, &profile, "Work/Production").unwrap();
|
||
assert_eq!(duplicate.file_name().unwrap(), "Server_Test-2.toml");
|
||
|
||
std::fs::remove_dir_all(&root).unwrap();
|
||
}
|
||
}
|