style: apply nightly rustfmt import grouping across the workspace

rustfmt.toml sets group_imports, imports_granularity and imports_layout,
which are nightly-only; agents formatted with stable rustfmt, which
ignored them. This is a formatting-only pass with `cargo +nightly fmt`.

Test Plan:
- cargo clippy --workspace --all-targets -- -D warnings
- cargo test --workspace
This commit is contained in:
ddidderr committed 2026-10-12 05:03:37 +02:00
1 parent 81d4119d85
commit 8bcb85a29a
259 files changed
+2495 -1547

No files matched your search

+5 -3
View File
@@ -3,9 +3,11 @@
//! ZIG/src/apprt/gtk/build/{blueprint,gresource}.zig. //! ZIG/src/apprt/gtk/build/{blueprint,gresource}.zig.
#![allow(clippy::unwrap_used)] #![allow(clippy::unwrap_used)]
use std::fmt::Write as _; use std::{
use std::path::{Path, PathBuf}; fmt::Write as _,
use std::process::Command; path::{Path, PathBuf},
process::Command,
};
const PREFIX: &str = "/com/mitchellh/ghostty"; const PREFIX: &str = "/com/mitchellh/ghostty";
const APP_ID: &str = "com.mitchellh.ghostty"; const APP_ID: &str = "com.mitchellh.ghostty";
+30 -14
View File
@@ -13,24 +13,40 @@
#![allow(unsafe_code)] // GL calls through glow #![allow(unsafe_code)] // GL calls through glow
use std::cell::{Cell, RefCell}; use std::{
use std::rc::Rc; cell::{Cell, RefCell},
use std::sync::Arc; rc::Rc,
use std::time::Duration; sync::Arc,
time::Duration,
use ghostty_apprt::action::{self, Action, Target};
use ghostty_apprt::runtime_api::{
AppMessage, CellSize, ClipboardError, CoreApp, CoreError, CoreSurface, DesiredFontSize,
InputEffect, KeyEvent, RtApp, RtSurface, SurfaceId,
}; };
use ghostty_apprt::structs::{
ClipboardRequest, ColorScheme, ContentScale, CursorPos, ImePos, SurfaceSize, use ghostty_apprt::{
action::{self, Action, Target},
runtime_api::{
AppMessage,
CellSize,
ClipboardError,
CoreApp,
CoreError,
CoreSurface,
DesiredFontSize,
InputEffect,
KeyEvent,
RtApp,
RtSurface,
SurfaceId,
},
structs::{ClipboardRequest, ColorScheme, ContentScale, CursorPos, ImePos, SurfaceSize},
}; };
use ghostty_apprt_gtk::app::App; use ghostty_apprt_gtk::app::App;
use ghostty_config::config::Config; use ghostty_config::config::Config;
use ghostty_input::binding::set::Value as BindingValue; use ghostty_input::{
use ghostty_input::binding::{self, Action as Binding}; Mods,
use ghostty_input::{Mods, MouseButton, MouseButtonState, ScrollMods}; MouseButton,
MouseButtonState,
ScrollMods,
binding::{self, Action as Binding, set::Value as BindingValue},
};
use glow::HasContext; use glow::HasContext;
fn confirm() -> bool { fn confirm() -> bool {
+6 -5
View File
@@ -7,14 +7,15 @@
//! app.terminate(); //! app.terminate();
//! ``` //! ```
use std::rc::Rc; use std::{rc::Rc, sync::Arc};
use std::sync::Arc;
use ghostty_apprt::action::{Action, Target}; use ghostty_apprt::{
use ghostty_apprt::ipc; action::{Action, Target},
ipc,
runtime_api::{CoreApp, SurfaceId, Waker},
};
use crate::class::application::{Application, RunError}; use crate::class::application::{Application, RunError};
use ghostty_apprt::runtime_api::{CoreApp, SurfaceId, Waker};
/// This is detected by the Renderer, in which case it sends a /// This is detected by the Renderer, in which case it sends a
/// `redraw_surface` message so that we can call `drawFrame` ourselves from /// `redraw_surface` message so that we can call `drawFrame` ourselves from
+1 -3
View File
@@ -1,8 +1,6 @@
//! Transient systemd scope creation over D-Bus (port of `apprt/gtk/cgroup.zig`). //! Transient systemd scope creation over D-Bus (port of `apprt/gtk/cgroup.zig`).
use gtk::gio; use gtk::{gio, glib, prelude::*};
use gtk::glib;
use gtk::prelude::*;
/// Properties for the transient scope. /// Properties for the transient scope.
#[derive(Debug, Clone, Copy, Default)] #[derive(Debug, Clone, Copy, Default)]
@@ -18,32 +18,41 @@
clippy::should_implement_trait clippy::should_implement_trait
)] )]
use std::cell::{Cell, OnceCell, Ref, RefCell, RefMut}; use std::{
use std::rc::Rc; cell::{Cell, OnceCell, Ref, RefCell, RefMut},
use std::sync::Arc; rc::Rc,
sync::Arc,
};
use adw::prelude::*; use adw::{prelude::*, subclass::prelude::*};
use adw::subclass::prelude::*; use ghostty_apprt::{
use ghostty_apprt::action::{self, Action, Target}; action::{self, Action, Target},
use ghostty_apprt::structs::ColorScheme; runtime_api::{AppMessage, CoreApp, RtApp, SurfaceId},
use ghostty_config::cli_args::ConfigField; structs::ColorScheme,
use ghostty_config::command::Command; };
use ghostty_config::config::Config as CoreConfig; use ghostty_config::{
use ghostty_config::types_b::{GtkSingleInstance, WindowTheme}; cli_args::ConfigField,
command::Command,
config::Config as CoreConfig,
types_b::{GtkSingleInstance, WindowTheme},
};
use ghostty_input::binding::Action as BindingAction; use ghostty_input::binding::Action as BindingAction;
use gtk::{gdk, gio, glib}; use gtk::{gdk, gio, glib};
use crate::class::close_confirmation_dialog::{self, CloseConfirmationDialog}; use crate::{
use crate::class::config::Config; class::{
use crate::class::config_errors_dialog::ConfigErrorsDialog; close_confirmation_dialog::{self, CloseConfirmationDialog},
use crate::class::global_shortcuts::GlobalShortcuts; config::Config,
use crate::class::split_tree::SplitTree; config_errors_dialog::ConfigErrorsDialog,
use crate::class::surface::{Size, Surface}; global_shortcuts::GlobalShortcuts,
use crate::class::tab::Tab; split_tree::SplitTree,
use crate::class::window::{SelectTab, TabOverrides, Window}; surface::{Size, Surface},
use crate::css::CssProviders; tab::Tab,
use crate::winproto; window::{SelectTab, TabOverrides, Window},
use ghostty_apprt::runtime_api::{AppMessage, CoreApp, RtApp, SurfaceId}; },
css::CssProviders,
winproto,
};
/// Errors from [`Application::run_loop`]. /// Errors from [`Application::run_loop`].
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
@@ -268,14 +277,26 @@ impl RtApp for AppRt {
} }
mod imp { mod imp {
use super::{ use adw::{prelude::*, subclass::prelude::*};
AppMessage, Cell, Config, ConfigErrorsDialog, CoreApp, CssProviders, GlobalShortcuts,
OnceCell, QuitTimer, Rc, RefCell, RtApp, glib, winproto,
};
use adw::prelude::*;
use adw::subclass::prelude::*;
use gtk::gio; use gtk::gio;
use super::{
AppMessage,
Cell,
Config,
ConfigErrorsDialog,
CoreApp,
CssProviders,
GlobalShortcuts,
OnceCell,
QuitTimer,
Rc,
RefCell,
RtApp,
glib,
winproto,
};
#[derive(Default)] #[derive(Default)]
pub struct Application { pub struct Application {
/// The libghostty App instance. /// The libghostty App instance.
@@ -826,7 +847,10 @@ impl Application {
fn sync_action_accelerators(&self) { fn sync_action_accelerators(&self) {
use ghostty_input::binding::action::{ use ghostty_input::binding::action::{
CloseTabMode, CopyToClipboard, InspectorMode, SplitDirection, CloseTabMode,
CopyToClipboard,
InspectorMode,
SplitDirection,
}; };
let a = |name: &str, action: BindingAction| self.sync_action_accelerator(name, &action); let a = |name: &str, action: BindingAction| self.sync_action_accelerator(name, &action);
a("app.quit", BindingAction::Quit); a("app.quit", BindingAction::Quit);
@@ -5,14 +5,15 @@
//! `clipboard-contents` (GtkTextBuffer), `blur`. Signals `confirm(bool)` and //! `clipboard-contents` (GtkTextBuffer), `blur`. Signals `confirm(bool)` and
//! `deny(bool)` (bool = "remember choice"). //! `deny(bool)` (bool = "remember choice").
use adw::prelude::*; use std::{
use adw::subclass::prelude::*; cell::{Cell, RefCell},
sync::OnceLock,
};
use adw::{prelude::*, subclass::prelude::*};
use ghostty_apprt::structs::ClipboardRequest; use ghostty_apprt::structs::ClipboardRequest;
use ghostty_os::i18n::tr; use ghostty_os::i18n::tr;
use gtk::glib; use gtk::{glib, glib::subclass::Signal};
use gtk::glib::subclass::Signal;
use std::cell::{Cell, RefCell};
use std::sync::OnceLock;
use super::dialog::{Dialog, DialogImpl}; use super::dialog::{Dialog, DialogImpl};
@@ -22,13 +23,25 @@ use super::dialog::{Dialog, DialogImpl};
pub struct ClipboardRequestBoxed(pub ClipboardRequest); pub struct ClipboardRequestBoxed(pub ClipboardRequest);
mod imp { mod imp {
use super::{
AdwAlertDialogImpl, AdwDialogImpl, Cell, ClipboardRequest, ClipboardRequestBoxed, Dialog,
DialogImpl, ObjectImpl, ObjectSubclass, OnceLock, RefCell, Signal, WidgetImpl, tr,
};
use adw::prelude::*; use adw::prelude::*;
use gtk::glib; use gtk::{glib, subclass::prelude::*};
use gtk::subclass::prelude::*;
use super::{
AdwAlertDialogImpl,
AdwDialogImpl,
Cell,
ClipboardRequest,
ClipboardRequestBoxed,
Dialog,
DialogImpl,
ObjectImpl,
ObjectSubclass,
OnceLock,
RefCell,
Signal,
WidgetImpl,
tr,
};
#[derive(Default, glib::Properties, gtk::CompositeTemplate)] #[derive(Default, glib::Properties, gtk::CompositeTemplate)]
#[properties(wrapper_type = super::ClipboardConfirmationDialog)] #[properties(wrapper_type = super::ClipboardConfirmationDialog)]
@@ -2,13 +2,11 @@
//! (`GhosttyCloseConfirmationDialog`). Property `target`; signals //! (`GhosttyCloseConfirmationDialog`). Property `target`; signals
//! `close-request` and `cancel`. //! `close-request` and `cancel`.
use adw::prelude::*; use std::{cell::Cell, sync::OnceLock};
use adw::subclass::prelude::*;
use adw::{prelude::*, subclass::prelude::*};
use ghostty_os::i18n::tr; use ghostty_os::i18n::tr;
use gtk::glib; use gtk::{glib, glib::subclass::Signal};
use gtk::glib::subclass::Signal;
use std::cell::Cell;
use std::sync::OnceLock;
use super::dialog::{Dialog, DialogImpl}; use super::dialog::{Dialog, DialogImpl};
@@ -47,13 +45,21 @@ impl Target {
} }
mod imp { mod imp {
use gtk::{glib, glib::prelude::*, subclass::prelude::*};
use super::{ use super::{
AdwAlertDialogImpl, AdwDialogImpl, Cell, Dialog, DialogImpl, ObjectImpl, ObjectSubclass, AdwAlertDialogImpl,
OnceLock, Signal, Target, WidgetImpl, AdwDialogImpl,
Cell,
Dialog,
DialogImpl,
ObjectImpl,
ObjectSubclass,
OnceLock,
Signal,
Target,
WidgetImpl,
}; };
use gtk::glib;
use gtk::glib::prelude::*;
use gtk::subclass::prelude::*;
#[derive(Default, glib::Properties, gtk::CompositeTemplate)] #[derive(Default, glib::Properties, gtk::CompositeTemplate)]
#[properties(wrapper_type = super::CloseConfirmationDialog)] #[properties(wrapper_type = super::CloseConfirmationDialog)]
@@ -5,22 +5,13 @@
//! keeps itself alive (a self-reference) from `new()` until its dialog is //! keeps itself alive (a self-reference) from `new()` until its dialog is
//! closed, like the Zig `refSink`/`unref` dance. //! closed, like the Zig `refSink`/`unref` dance.
use std::cell::RefCell; use std::{cell::RefCell, cmp::Ordering, sync::OnceLock};
use std::cmp::Ordering;
use std::sync::OnceLock;
use adw::prelude::*; use adw::{prelude::*, subclass::prelude::*};
use adw::subclass::prelude::*; use ghostty_input::{binding::Action as BindingAction, command::Command as InputCommand};
use ghostty_input::binding::Action as BindingAction; use gtk::{CompositeTemplate, TemplateChild, gio, glib, glib::subclass::Signal};
use ghostty_input::command::Command as InputCommand;
use gtk::glib;
use gtk::glib::subclass::Signal;
use gtk::{CompositeTemplate, TemplateChild, gio};
use super::application::Application; use super::{application::Application, config::Config, surface::Surface, window::Window};
use super::config::Config;
use super::surface::Surface;
use super::window::Window;
/// Boxed wrapper so a binding action can travel through the `trigger` /// Boxed wrapper so a binding action can travel through the `trigger`
/// signal (Zig passes `*const input.Binding.Action`). /// signal (Zig passes `*const input.Binding.Action`).
@@ -32,12 +23,19 @@ pub struct BoxedAction(pub BindingAction);
// Command (list item) // Command (list item)
mod command_imp { mod command_imp {
use super::{
BindingAction, Config, InputCommand, RefCell, Surface, ghostty_command_title_for_jump, glib,
};
use adw::prelude::*; use adw::prelude::*;
use gtk::glib::subclass::prelude::*; use gtk::glib::subclass::prelude::*;
use super::{
BindingAction,
Config,
InputCommand,
RefCell,
Surface,
ghostty_command_title_for_jump,
glib,
};
pub enum CommandData { pub enum CommandData {
Regular { Regular {
command: InputCommand, command: InputCommand,
@@ -276,14 +274,23 @@ fn is_action_supported_on_gtk(action: &BindingAction) -> bool {
// CommandPalette // CommandPalette
mod imp { mod imp {
use adw::{prelude::*, subclass::prelude::*};
use gtk::{gio, glib};
use super::{ use super::{
Application, BoxedAction, Command, CompositeTemplate, Config, OnceLock, Ordering, RefCell, Application,
Signal, TemplateChild, compare_commands, is_action_supported_on_gtk, BoxedAction,
Command,
CompositeTemplate,
Config,
OnceLock,
Ordering,
RefCell,
Signal,
TemplateChild,
compare_commands,
is_action_supported_on_gtk,
}; };
use adw::prelude::*;
use adw::subclass::prelude::*;
use gtk::gio;
use gtk::glib;
#[derive(Default, glib::Properties, CompositeTemplate)] #[derive(Default, glib::Properties, CompositeTemplate)]
#[properties(wrapper_type = super::CommandPalette)] #[properties(wrapper_type = super::CommandPalette)]
+8 -8
View File
@@ -3,19 +3,19 @@
//! Wraps a core config in a GObject so it can be reference counted and bound //! Wraps a core config in a GObject so it can be reference counted and bound
//! from blueprints (`diagnostics-buffer`, `has-diagnostics`). //! from blueprints (`diagnostics-buffer`, `has-diagnostics`).
use std::cell::RefCell; use std::{cell::RefCell, sync::Arc};
use std::sync::Arc;
use ghostty_config::config::Config as CoreConfig; use ghostty_config::config::Config as CoreConfig;
use gtk::glib; use gtk::{glib, glib::subclass::prelude::*};
use gtk::glib::subclass::prelude::*;
mod imp { mod imp {
use gtk::{
glib,
glib::{prelude::*, subclass::prelude::*},
prelude::TextBufferExt,
};
use super::{Arc, CoreConfig, RefCell}; use super::{Arc, CoreConfig, RefCell};
use gtk::glib;
use gtk::glib::prelude::*;
use gtk::glib::subclass::prelude::*;
use gtk::prelude::TextBufferExt;
#[derive(glib::Properties)] #[derive(glib::Properties)]
#[properties(wrapper_type = super::Config)] #[properties(wrapper_type = super::Config)]
@@ -2,25 +2,33 @@
//! //!
//! Property `config` (GhosttyConfig); signal `reload-config`. //! Property `config` (GhosttyConfig); signal `reload-config`.
use std::cell::RefCell; use std::{cell::RefCell, sync::OnceLock};
use adw::prelude::*; use adw::{prelude::*, subclass::prelude::*};
use adw::subclass::prelude::*; use gtk::{glib, glib::subclass::Signal};
use gtk::glib;
use gtk::glib::subclass::Signal;
use std::sync::OnceLock;
use super::config::Config; use super::{
use super::dialog::{Dialog, DialogImpl}; config::Config,
dialog::{Dialog, DialogImpl},
};
mod imp { mod imp {
use gtk::{glib, glib::prelude::*, subclass::prelude::*};
use super::{ use super::{
AdwAlertDialogImpl, AdwDialogImpl, Config, Dialog, DialogImpl, ObjectImpl, ObjectSubclass, AdwAlertDialogImpl,
ObjectSubclassExt, OnceLock, RefCell, Signal, WidgetImpl, AdwDialogImpl,
Config,
Dialog,
DialogImpl,
ObjectImpl,
ObjectSubclass,
ObjectSubclassExt,
OnceLock,
RefCell,
Signal,
WidgetImpl,
}; };
use gtk::glib;
use gtk::glib::prelude::*;
use gtk::subclass::prelude::*;
#[derive(Default, glib::Properties, gtk::CompositeTemplate)] #[derive(Default, glib::Properties, gtk::CompositeTemplate)]
#[properties(wrapper_type = super::ConfigErrorsDialog)] #[properties(wrapper_type = super::ConfigErrorsDialog)]
@@ -4,8 +4,7 @@
use gtk::glib; use gtk::glib;
mod imp { mod imp {
use gtk::glib; use gtk::{glib, subclass::prelude::*};
use gtk::subclass::prelude::*;
#[derive(Default, gtk::CompositeTemplate)] #[derive(Default, gtk::CompositeTemplate)]
#[template(resource = "/com/mitchellh/ghostty/ui/1.3/debug-warning.ui")] #[template(resource = "/com/mitchellh/ghostty/ui/1.3/debug-warning.ui")]
+1 -2
View File
@@ -4,8 +4,7 @@
//! `adw::MessageDialog` fallback is not needed). Subclasses implement //! `adw::MessageDialog` fallback is not needed). Subclasses implement
//! [`DialogImpl`] and may override `response` via `AlertDialogImpl`. //! [`DialogImpl`] and may override `response` via `AlertDialogImpl`.
use adw::prelude::*; use adw::{prelude::*, subclass::prelude::*};
use adw::subclass::prelude::*;
use gtk::glib; use gtk::glib;
mod imp { mod imp {
@@ -8,21 +8,28 @@
#![allow(deprecated)] // gio D-Bus signal_subscribe: replacement API is awkward for portal use #![allow(deprecated)] // gio D-Bus signal_subscribe: replacement API is awkward for portal use
use std::cell::{Cell, RefCell}; use std::{
use std::collections::HashMap; cell::{Cell, RefCell},
use std::sync::OnceLock; collections::HashMap,
sync::OnceLock,
};
use ghostty_input::binding::Action as BindingAction; use ghostty_input::binding::{Action as BindingAction, set::Value as BindingValue};
use ghostty_input::binding::set::Value as BindingValue; use gtk::{
use gtk::gio::{self, prelude::*}; gio::{self, prelude::*},
use gtk::glib::{self, subclass::Signal, subclass::prelude::*, variant::ObjectPath}; glib::{
self,
subclass::{Signal, prelude::*},
variant::ObjectPath,
},
};
use crate::class::config::Config; use crate::class::config::Config;
mod imp { mod imp {
use glib::{prelude::*, subclass::prelude::*};
use super::{BindingAction, Cell, Config, OnceLock, RefCell, Signal, gio, glib}; use super::{BindingAction, Cell, Config, OnceLock, RefCell, Signal, gio, glib};
use glib::prelude::*;
use glib::subclass::prelude::*;
#[derive(glib::Properties, Default)] #[derive(glib::Properties, Default)]
#[properties(wrapper_type = super::GlobalShortcuts)] #[properties(wrapper_type = super::GlobalShortcuts)]
@@ -9,15 +9,15 @@
//! cheaply in gtk-rs without a lot of class struct boilerplate, so subclasses //! cheaply in gtk-rs without a lot of class struct boilerplate, so subclasses
//! install the two hooks with [`ImguiWidget::set_hooks`] instead. //! install the two hooks with [`ImguiWidget::set_hooks`] instead.
use std::cell::{Cell, RefCell}; use std::{
use std::time::{Duration, Instant}; cell::{Cell, RefCell},
time::{Duration, Instant},
};
use adw::prelude::*; use adw::{prelude::*, subclass::prelude::*};
use adw::subclass::prelude::*;
use dear_imgui_glow::GlowRenderer; use dear_imgui_glow::GlowRenderer;
use ghostty_inspector::imgui::{Context, MouseButton, Ui}; use ghostty_inspector::imgui::{Context, MouseButton, Ui};
use gtk::glib::translate::IntoGlib; use gtk::{gdk, glib, glib::translate::IntoGlib};
use gtk::{gdk, glib};
use crate::key; use crate::key;
@@ -4,16 +4,16 @@
//! property activates the inspector on that surface's core surface and //! property activates the inspector on that surface's core surface and
//! clearing it deactivates it again. //! clearing it deactivates it again.
use std::cell::RefCell; use std::{cell::RefCell, rc::Rc};
use std::rc::Rc;
use adw::prelude::*; use adw::{prelude::*, subclass::prelude::*};
use adw::subclass::prelude::*;
use ghostty_apprt::runtime_api::CoreSurface; use ghostty_apprt::runtime_api::CoreSurface;
use gtk::glib; use gtk::glib;
use super::imgui_widget::{ImguiWidget, ImguiWidgetImpl}; use super::{
use super::surface::Surface; imgui_widget::{ImguiWidget, ImguiWidgetImpl},
surface::Surface,
};
glib::wrapper! { glib::wrapper! {
pub struct InspectorWidget(ObjectSubclass<imp::InspectorWidget>) pub struct InspectorWidget(ObjectSubclass<imp::InspectorWidget>)
@@ -2,13 +2,10 @@
//! //!
//! Window for displaying the Ghostty inspector. //! Window for displaying the Ghostty inspector.
use adw::prelude::*; use adw::{prelude::*, subclass::prelude::*};
use adw::subclass::prelude::*;
use gtk::glib; use gtk::glib;
use super::debug_warning::DebugWarning; use super::{debug_warning::DebugWarning, inspector_widget::InspectorWidget, surface::Surface};
use super::inspector_widget::InspectorWidget;
use super::surface::Surface;
glib::wrapper! { glib::wrapper! {
pub struct InspectorWindow(ObjectSubclass<imp::InspectorWindow>) pub struct InspectorWindow(ObjectSubclass<imp::InspectorWindow>)
@@ -7,8 +7,7 @@
//! Deviation: Zig's `ext.StringList` boxed type is replaced by `GStrv` //! Deviation: Zig's `ext.StringList` boxed type is replaced by `GStrv`
//! (`Vec<String>`) for the `tables` and `sequence` properties. //! (`Vec<String>`) for the `tables` and `sequence` properties.
use adw::prelude::*; use adw::{prelude::*, subclass::prelude::*};
use adw::subclass::prelude::*;
use gtk::glib; use gtk::glib;
glib::wrapper! { glib::wrapper! {
@@ -10,8 +10,7 @@
//! 2. Set the label with `set_label` //! 2. Set the label with `set_label`
//! 3. Schedule to show it with `schedule` //! 3. Schedule to show it with `schedule`
use adw::prelude::*; use adw::{prelude::*, subclass::prelude::*};
use adw::subclass::prelude::*;
use gtk::glib; use gtk::glib;
glib::wrapper! { glib::wrapper! {
@@ -5,10 +5,8 @@
use std::sync::OnceLock; use std::sync::OnceLock;
use adw::prelude::*; use adw::{prelude::*, subclass::prelude::*};
use adw::subclass::prelude::*; use gtk::{gdk, glib, glib::subclass::Signal};
use gtk::glib::subclass::Signal;
use gtk::{gdk, glib};
glib::wrapper! { glib::wrapper! {
pub struct SearchOverlay(ObjectSubclass<imp::SearchOverlay>) pub struct SearchOverlay(ObjectSubclass<imp::SearchOverlay>)
@@ -10,19 +10,29 @@
use std::cell::{Cell, RefCell}; use std::cell::{Cell, RefCell};
use adw::prelude::*; use adw::{prelude::*, subclass::prelude::*};
use adw::subclass::prelude::*;
use ghostty_datastruct::split_tree::{ use ghostty_datastruct::split_tree::{
Direction, Goto, Handle, Layout, Node, SplitError, SplitTree as DsSplitTree, SplitTreeView, Direction,
Goto,
Handle,
Layout,
Node,
SplitError,
SplitTree as DsSplitTree,
SplitTreeView,
};
use gtk::{
gio,
glib::{self, clone, subclass::Signal},
}; };
use gtk::gio;
use gtk::glib::{self, clone, subclass::Signal};
use half::f16; use half::f16;
use super::application::Application; use super::{
use super::close_confirmation_dialog::{CloseConfirmationDialog, Target as CloseTarget}; application::Application,
use super::surface::{Surface, SurfaceOverrides}; close_confirmation_dialog::{CloseConfirmationDialog, Target as CloseTarget},
use super::surface_scrolled_window::SurfaceScrolledWindow; surface::{Surface, SurfaceOverrides},
surface_scrolled_window::SurfaceScrolledWindow,
};
/// The split tree of surfaces (Zig: `Surface.Tree`). /// The split tree of surfaces (Zig: `Surface.Tree`).
pub type Tree = DsSplitTree<Surface>; pub type Tree = DsSplitTree<Surface>;
+71 -41
View File
@@ -8,47 +8,71 @@
//! into) is [`RtSurfaceHandle`], which implements [`ghostty_apprt::runtime_api::RtSurface`] //! into) is [`RtSurfaceHandle`], which implements [`ghostty_apprt::runtime_api::RtSurface`]
//! and holds only a weak reference to the widget. //! and holds only a weak reference to the widget.
use std::cell::{Cell, RefCell}; use std::{
use std::collections::HashMap; cell::{Cell, RefCell},
use std::io::Write as _; collections::HashMap,
use std::rc::Rc; io::Write as _,
use std::sync::OnceLock; rc::Rc,
sync::OnceLock,
use adw::prelude::*;
use adw::subclass::prelude::*;
use ghostty_apprt::action::{CommandFinished, Inspector, KeySequence, KeyTable, Readonly};
use ghostty_apprt::structs::{
Clipboard, ClipboardRequest, ContentScale, CursorPos, ImePos, SurfaceSize,
}; };
use ghostty_apprt::surface::{ChildExited, NewSurfaceContext, Scrollbar};
use ghostty_config::command::Command; use adw::{prelude::*, subclass::prelude::*};
use ghostty_config::config::Config as CoreConfig; use ghostty_apprt::{
use ghostty_config::path::Path as ConfigPath; action::{CommandFinished, Inspector, KeySequence, KeyTable, Readonly},
use ghostty_config::types_a::WorkingDirectory; runtime_api::{
use ghostty_config::types_b::{ ClipboardError,
BellFeatures, NotifyOnCommandFinish, ResizeOverlay as ResizeOverlayMode, ResizeOverlayPosition, CoreSurface,
DesiredFontSize,
InputEffect,
MIN_WINDOW_HEIGHT_CELLS,
MIN_WINDOW_WIDTH_CELLS,
RtSurface,
SurfaceId,
},
structs::{Clipboard, ClipboardRequest, ContentScale, CursorPos, ImePos, SurfaceSize},
surface::{ChildExited, NewSurfaceContext, Scrollbar},
};
use ghostty_config::{
command::Command,
config::Config as CoreConfig,
path::Path as ConfigPath,
types_a::WorkingDirectory,
types_b::{
BellFeatures,
NotifyOnCommandFinish,
ResizeOverlay as ResizeOverlayMode,
ResizeOverlayPosition,
},
}; };
use ghostty_input::{Action as KeyAction, Key, KeyEvent, Mods, MouseButton, MouseButtonState}; use ghostty_input::{Action as KeyAction, Key, KeyEvent, Mods, MouseButton, MouseButtonState};
use ghostty_vt::mouse_shape::MouseShape; use ghostty_vt::{
use ghostty_vt::osc::{ProgressReport, ProgressState}; mouse_shape::MouseShape,
use gtk::glib::subclass::Signal; osc::{ProgressReport, ProgressState},
use gtk::glib::translate::{FromGlib, IntoGlib}; };
use gtk::{gdk, gio, glib}; use gtk::{
gdk,
gio,
glib,
glib::{
subclass::Signal,
translate::{FromGlib, IntoGlib},
},
};
use crate::class::application::Application; use crate::{
use crate::class::clipboard_confirmation_dialog::ClipboardConfirmationDialog; class::{
use crate::class::config::Config; application::Application,
use crate::class::inspector_window::InspectorWindow; clipboard_confirmation_dialog::ClipboardConfirmationDialog,
use crate::class::key_state_overlay::KeyStateOverlay; config::Config,
use crate::class::resize_overlay::ResizeOverlay; inspector_window::InspectorWindow,
use crate::class::search_overlay::SearchOverlay; key_state_overlay::KeyStateOverlay,
use crate::class::surface_child_exited::SurfaceChildExited; resize_overlay::ResizeOverlay,
use crate::class::title_dialog::{self, TitleDialog}; search_overlay::SearchOverlay,
use crate::class::window::Window; surface_child_exited::SurfaceChildExited,
use crate::key as gtk_key; title_dialog::{self, TitleDialog},
use ghostty_apprt::runtime_api::{ window::Window,
ClipboardError, CoreSurface, DesiredFontSize, InputEffect, MIN_WINDOW_HEIGHT_CELLS, },
MIN_WINDOW_WIDTH_CELLS, RtSurface, SurfaceId, key as gtk_key,
}; };
/// Simple dimensions struct for the surface used by various properties /// Simple dimensions struct for the surface used by various properties
@@ -2268,12 +2292,18 @@ impl RtSurface for RtSurfaceHandle {
/// A namespace for our clipboard-related functions so Surface isn't SO large. /// A namespace for our clipboard-related functions so Surface isn't SO large.
mod clipboard { mod clipboard {
use adw::{prelude::*, subclass::prelude::ObjectSubclassIsExt};
use super::{ use super::{
Clipboard, ClipboardConfirmationDialog, ClipboardError, ClipboardRequest, Surface, gdk, Clipboard,
gio, glib, ClipboardConfirmationDialog,
ClipboardError,
ClipboardRequest,
Surface,
gdk,
gio,
glib,
}; };
use adw::prelude::*;
use adw::subclass::prelude::ObjectSubclassIsExt;
/// Set the clipboard contents. /// Set the clipboard contents.
pub(super) fn set( pub(super) fn set(
@@ -6,11 +6,9 @@
use std::sync::OnceLock; use std::sync::OnceLock;
use adw::prelude::*; use adw::{prelude::*, subclass::prelude::*};
use adw::subclass::prelude::*;
use ghostty_apprt::surface::ChildExited; use ghostty_apprt::surface::ChildExited;
use gtk::glib; use gtk::{glib, glib::subclass::Signal};
use gtk::glib::subclass::Signal;
/// Boxed wrapper so `ChildExited` can be a GObject property. /// Boxed wrapper so `ChildExited` can be a GObject property.
#[derive(Debug, Clone, Copy, PartialEq, Eq, glib::Boxed)] #[derive(Debug, Clone, Copy, PartialEq, Eq, glib::Boxed)]
@@ -11,8 +11,7 @@
//! `GtkWidget` (any `crate::class::surface::Surface` is accepted) and the //! `GtkWidget` (any `crate::class::surface::Surface` is accepted) and the
//! `config` property as `GObject` (a `crate::class::config::Config`). //! `config` property as `GObject` (a `crate::class::config::Config`).
use adw::prelude::*; use adw::{prelude::*, subclass::prelude::*};
use adw::subclass::prelude::*;
use gtk::glib; use gtk::glib;
glib::wrapper! { glib::wrapper! {
@@ -75,9 +74,10 @@ mod imp {
impl SurfaceScrolledWindow { impl SurfaceScrolledWindow {
#[template_callback(function)] #[template_callback(function)]
fn scrollbar_policy(config: Option<glib::Object>) -> gtk::PolicyType { fn scrollbar_policy(config: Option<glib::Object>) -> gtk::PolicyType {
use crate::class::config::Config;
use ghostty_config::types_b::Scrollbar; use ghostty_config::types_b::Scrollbar;
use crate::class::config::Config;
let Some(config) = config.and_then(|c| c.downcast::<Config>().ok()) else { let Some(config) = config.and_then(|c| c.downcast::<Config>().ok()) else {
return gtk::PolicyType::Automatic; return gtk::PolicyType::Automatic;
}; };
+12 -9
View File
@@ -5,17 +5,20 @@
use std::cell::RefCell; use std::cell::RefCell;
use adw::prelude::*; use adw::{prelude::*, subclass::prelude::*};
use adw::subclass::prelude::*;
use ghostty_apprt::surface::NewSurfaceContext; use ghostty_apprt::surface::NewSurfaceContext;
use gtk::gio; use gtk::{
use gtk::glib::{self, clone, subclass::Signal}; gio,
glib::{self, clone, subclass::Signal},
};
use super::application::Application; use super::{
use super::config::Config; application::Application,
use super::split_tree::{SplitTree, SurfaceTree}; config::Config,
use super::surface::{Surface, SurfaceOverrides}; split_tree::{SplitTree, SurfaceTree},
use super::title_dialog::{Target as TitleTarget, TitleDialog}; surface::{Surface, SurfaceOverrides},
title_dialog::{Target as TitleTarget, TitleDialog},
};
glib::wrapper! { glib::wrapper! {
pub struct Tab(ObjectSubclass<imp::Tab>) pub struct Tab(ObjectSubclass<imp::Tab>)
@@ -1,13 +1,14 @@
//! Port of apprt/gtk/class/title_dialog.zig (`GhosttyTitleDialog`). //! Port of apprt/gtk/class/title_dialog.zig (`GhosttyTitleDialog`).
//! Properties `target`, `initial-value`; signal `set(title: string)`. //! Properties `target`, `initial-value`; signal `set(title: string)`.
use adw::prelude::*; use std::{
use adw::subclass::prelude::*; cell::{Cell, RefCell},
sync::OnceLock,
};
use adw::{prelude::*, subclass::prelude::*};
use ghostty_os::i18n::tr; use ghostty_os::i18n::tr;
use gtk::glib; use gtk::{glib, glib::subclass::Signal};
use gtk::glib::subclass::Signal;
use std::cell::{Cell, RefCell};
use std::sync::OnceLock;
/// `GhosttyTitleDialogTarget`. /// `GhosttyTitleDialogTarget`.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, glib::Enum)] #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, glib::Enum)]
@@ -29,13 +30,20 @@ impl Target {
} }
mod imp { mod imp {
use gtk::{glib, glib::prelude::*, subclass::prelude::*};
use super::{ use super::{
AdwAlertDialogImpl, AdwDialogImpl, Cell, ObjectImpl, ObjectSubclass, OnceLock, RefCell, AdwAlertDialogImpl,
Signal, Target, WidgetImpl, AdwDialogImpl,
Cell,
ObjectImpl,
ObjectSubclass,
OnceLock,
RefCell,
Signal,
Target,
WidgetImpl,
}; };
use gtk::glib;
use gtk::glib::prelude::*;
use gtk::subclass::prelude::*;
#[derive(Default, glib::Properties, gtk::CompositeTemplate)] #[derive(Default, glib::Properties, gtk::CompositeTemplate)]
#[properties(wrapper_type = super::TitleDialog)] #[properties(wrapper_type = super::TitleDialog)]
+60 -28
View File
@@ -13,34 +13,51 @@
//! [`Surface`] object (Zig took the `*CoreSurface` and used //! [`Surface`] object (Zig took the `*CoreSurface` and used
//! `rt_surface.gobj()`); the core surface is looked up via `Surface::core()`. //! `rt_surface.gobj()`); the core surface is looked up via `Surface::core()`.
use std::cell::{Cell, RefCell}; use std::{
use std::rc::Rc; cell::{Cell, RefCell},
use std::time::Duration; rc::Rc,
time::Duration,
};
use adw::prelude::*; use adw::{prelude::*, subclass::prelude::*};
use adw::subclass::prelude::*;
use ghostty_apprt::surface::NewSurfaceContext; use ghostty_apprt::surface::NewSurfaceContext;
use ghostty_config::command::Command as ConfigCommand; use ghostty_config::{
use ghostty_config::types_a::WindowSubtitle; command::Command as ConfigCommand,
use ghostty_config::types_b::{ types_a::WindowSubtitle,
GtkTabsLocation, GtkTitlebarStyle, GtkToolbarStyle, WindowDecoration, WindowNewTabPosition, types_b::{
WindowShowTabBar, WindowTheme, GtkTabsLocation,
GtkTitlebarStyle,
GtkToolbarStyle,
WindowDecoration,
WindowNewTabPosition,
WindowShowTabBar,
WindowTheme,
},
}; };
use ghostty_input::binding::{Action as BindingAction, CloseTabMode}; use ghostty_input::binding::{Action as BindingAction, CloseTabMode};
use ghostty_os::i18n::tr; use ghostty_os::i18n::tr;
use gtk::glib::{self, clone}; use gtk::{
use gtk::{CompositeTemplate, TemplateChild, gio}; CompositeTemplate,
TemplateChild,
gio,
glib::{self, clone},
};
use super::application::Application; use super::{
use super::close_confirmation_dialog::{CloseConfirmationDialog, Target as CloseTarget}; application::Application,
use super::command_palette::CommandPalette; close_confirmation_dialog::{CloseConfirmationDialog, Target as CloseTarget},
use super::config::Config; command_palette::CommandPalette,
use super::debug_warning::DebugWarning; config::Config,
use super::split_tree::{SplitTree, SurfaceTree, Tree}; debug_warning::DebugWarning,
use super::surface::{Surface, SurfaceOverrides}; split_tree::{SplitTree, SurfaceTree, Tree},
use super::tab::Tab; surface::{Surface, SurfaceOverrides},
use crate::winproto::{self, WindowHost}; tab::Tab,
use crate::{adw_version, gtk_version}; };
use crate::{
adw_version,
gtk_version,
winproto::{self, WindowHost},
};
/// Which tab to select (Zig: `Window.SelectTab`). /// Which tab to select (Zig: `Window.SelectTab`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -108,15 +125,30 @@ impl WindowHost for Host {
} }
mod imp { mod imp {
use std::marker::PhantomData;
use adw::{prelude::*, subclass::prelude::*};
use super::{ use super::{
Cell, CommandPalette, CompositeTemplate, Config, DebugWarning, NewSurfaceContext, RefCell, Cell,
SplitTree, Surface, Tab, TabOverrides, TemplateChild, TitlebarStyle, Window as WindowObj, CommandPalette,
WindowDecoration, glib, gtk_version, CompositeTemplate,
Config,
DebugWarning,
NewSurfaceContext,
RefCell,
SplitTree,
Surface,
Tab,
TabOverrides,
TemplateChild,
TitlebarStyle,
Window as WindowObj,
WindowDecoration,
glib,
gtk_version,
}; };
use crate::winproto; use crate::winproto;
use adw::prelude::*;
use adw::subclass::prelude::*;
use std::marker::PhantomData;
#[derive(glib::Properties, CompositeTemplate)] #[derive(glib::Properties, CompositeTemplate)]
#[properties(wrapper_type = WindowObj)] #[properties(wrapper_type = WindowObj)]
+1 -3
View File
@@ -12,9 +12,7 @@
use std::fmt::Write as _; use std::fmt::Write as _;
use ghostty_config::config::Config; use ghostty_config::{config::Config, path::Path, types_b::WindowTheme};
use ghostty_config::path::Path;
use ghostty_config::types_b::WindowTheme;
use gtk::{gdk, glib, prelude::*}; use gtk::{gdk, glib, prelude::*};
/// Maximum size of a `gtk-custom-css` file. /// Maximum size of a `gtk-custom-css` file.
+3 -9
View File
@@ -36,17 +36,11 @@
//! with a few lowercase aliases (`enter`, `esc`, `up`, ...). Commands act on //! with a few lowercase aliases (`enter`, `esc`, `up`, ...). Commands act on
//! the active surface of the active window at the time they run. //! the active surface of the active window at the time they run.
use std::cell::RefCell; use std::{cell::RefCell, rc::Rc, time::Duration};
use std::rc::Rc;
use std::time::Duration;
use gtk::glib::translate::IntoGlib; use gtk::{gdk, glib, glib::translate::IntoGlib, prelude::*};
use gtk::prelude::*;
use gtk::{gdk, glib};
use crate::class::application::Application; use crate::class::{application::Application, surface::Surface, window::Window};
use crate::class::surface::Surface;
use crate::class::window::Window;
/// One parsed command. /// One parsed command.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
+1 -4
View File
@@ -1,9 +1,6 @@
//! GAction helpers (port of `apprt/gtk/ext/actions.zig`). //! GAction helpers (port of `apprt/gtk/ext/actions.zig`).
use gtk::gio; use gtk::{gio, glib, glib::prelude::*, prelude::*};
use gtk::glib;
use gtk::glib::prelude::*;
use gtk::prelude::*;
fn g_action_name_is_valid(name: &str) -> bool { fn g_action_name_is_valid(name: &str) -> bool {
!name.is_empty() !name.is_empty()
+1 -4
View File
@@ -6,12 +6,9 @@
pub mod actions; pub mod actions;
pub mod slice; pub mod slice;
use gtk::{glib, glib::prelude::*, prelude::*};
pub use slice::StringList; pub use slice::StringList;
use gtk::glib;
use gtk::glib::prelude::*;
use gtk::prelude::*;
/// Get the first ancestor of `widget` of type `T`. /// Get the first ancestor of `widget` of type `T`.
pub fn get_ancestor<T: IsA<gtk::Widget>>(widget: &impl IsA<gtk::Widget>) -> Option<T> { pub fn get_ancestor<T: IsA<gtk::Widget>>(widget: &impl IsA<gtk::Widget>) -> Option<T> {
widget.ancestor(T::static_type()).and_downcast::<T>() widget.ancestor(T::static_type()).and_downcast::<T>()
+2 -1
View File
@@ -20,9 +20,10 @@ impl StringList {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use gtk::glib::prelude::*; use gtk::glib::prelude::*;
use super::*;
#[test] #[test]
fn string_list_create_and_destroy() { fn string_list_create_and_destroy() {
let list = StringList::create(&["hello", "world"]); let list = StringList::create(&["hello", "world"]);
+1 -2
View File
@@ -7,8 +7,7 @@
//! `glow::Context::from_loader_function` need. Call it only while the GLArea //! `glow::Context::from_loader_function` need. Call it only while the GLArea
//! context is current. //! context is current.
use std::ffi::c_void; use std::{ffi::c_void, sync::OnceLock};
use std::sync::OnceLock;
fn epoxy() -> Option<&'static libloading::Library> { fn epoxy() -> Option<&'static libloading::Library> {
static LIB: OnceLock<Option<libloading::Library>> = OnceLock::new(); static LIB: OnceLock<Option<libloading::Library>> = OnceLock::new();
+1 -2
View File
@@ -1,7 +1,6 @@
//! Typed access to `GtkSettings` (port of `apprt/gtk/gsettings.zig`). //! Typed access to `GtkSettings` (port of `apprt/gtk/gsettings.zig`).
use gtk::glib; use gtk::{glib, prelude::*};
use gtk::prelude::*;
/// Settings keys we read (the GTK property names). /// Settings keys we read (the GTK property names).
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
+1 -3
View File
@@ -1,9 +1,7 @@
//! D-Bus helper for IPC (port of `apprt/gtk/ipc/DBus.zig`). //! D-Bus helper for IPC (port of `apprt/gtk/ipc/DBus.zig`).
use ghostty_apprt::ipc::{Error, Target}; use ghostty_apprt::ipc::{Error, Target};
use gtk::gio; use gtk::{gio, glib, prelude::*};
use gtk::glib;
use gtk::prelude::*;
/// A pending `org.gtk.Actions.Activate` call. /// A pending `org.gtk.Actions.Activate` call.
pub struct DBus { pub struct DBus {
+6 -7
View File
@@ -2,13 +2,12 @@
use std::fmt::Write as _; use std::fmt::Write as _;
use ghostty_input::binding::{Trigger, TriggerKey}; use ghostty_input::{
use ghostty_input::key::{Action, Key as K}; binding::{Trigger, TriggerKey},
use ghostty_input::key_mods::{ModSide, Mods}; key::{Action, Key as K},
use gtk::gdk; key_mods::{ModSide, Mods},
use gtk::gdk::prelude::DeviceExt; };
use gtk::glib::translate::IntoGlib; use gtk::{gdk, gdk::prelude::DeviceExt, glib::translate::IntoGlib, prelude::*};
use gtk::prelude::*;
/// Name of a keyval (`gdk.keyvalName`). /// Name of a keyval (`gdk.keyvalName`).
fn keyval_name(keyval: u32) -> Option<String> { fn keyval_name(keyval: u32) -> Option<String> {
+5 -4
View File
@@ -1,10 +1,11 @@
//! Parent post-fork hook creating the transient scope (port of //! Parent post-fork hook creating the transient scope (port of
//! `apprt/gtk/post_fork.zig`). //! `apprt/gtk/post_fork.zig`).
use ghostty_config::config::Config; use ghostty_config::{
use ghostty_config::types_b::{GtkSingleInstance, LinuxCgroup}; config::Config,
use gtk::gio; types_b::{GtkSingleInstance, LinuxCgroup},
use gtk::prelude::*; };
use gtk::{gio, prelude::*};
use crate::cgroup; use crate::cgroup;
+4 -2
View File
@@ -4,8 +4,10 @@
//! sleeps. The wait loop is shared with `ghostty-termio` via //! sleeps. The wait loop is shared with `ghostty-termio` via
//! `ghostty_os::cgroup::wait_for_scope`. //! `ghostty_os::cgroup::wait_for_scope`.
use ghostty_config::config::Config; use ghostty_config::{
use ghostty_config::types_b::{GtkSingleInstance, LinuxCgroup}; config::Config,
types_b::{GtkSingleInstance, LinuxCgroup},
};
use crate::cgroup; use crate::cgroup;
+1 -2
View File
@@ -2,8 +2,7 @@
//! already provides `glib::WeakRef<T>`; this wrapper keeps the Zig API //! already provides `glib::WeakRef<T>`; this wrapper keeps the Zig API
//! (`set`/`get`/`empty`). //! (`set`/`get`/`empty`).
use gtk::glib; use gtk::{glib, glib::prelude::*};
use gtk::glib::prelude::*;
/// A weak reference to a GObject of type `T`. /// A weak reference to a GObject of type `T`.
#[derive(Debug, Default)] #[derive(Debug, Default)]
+3 -7
View File
@@ -8,15 +8,11 @@
//! code held a `*ApprtWindow` pointer; here the window GObject implements //! code held a `*ApprtWindow` pointer; here the window GObject implements
//! [`WindowHost`] (a small, weak-referencing adapter), see below. //! [`WindowHost`] (a small, weak-referencing adapter), see below.
use std::rc::Rc; use std::{rc::Rc, sync::Arc};
use std::sync::Arc;
use gtk::gdk; use ghostty_config::{config::Config, types_b::WindowDecoration};
use gtk::prelude::*;
use ghostty_config::config::Config;
use ghostty_config::types_b::WindowDecoration;
use ghostty_input::Mods; use ghostty_input::Mods;
use gtk::{gdk, prelude::*};
pub mod noop; pub mod noop;
pub mod wayland; pub mod wayland;
@@ -3,10 +3,10 @@
use std::rc::Rc; use std::rc::Rc;
use ghostty_input::Mods;
use gtk::gdk; use gtk::gdk;
use super::{Result, WindowHost}; use super::{Result, WindowHost};
use ghostty_input::Mods;
#[derive(Debug, Default, Clone, Copy)] #[derive(Debug, Default, Clone, Copy)]
pub struct App; pub struct App;
@@ -17,42 +17,59 @@
//! first (or run with `LD_PRELOAD=libgtk4-layer-shell.so`). Without it, //! first (or run with `LD_PRELOAD=libgtk4-layer-shell.so`). Without it,
//! `layer_shell::is_supported()` is false and the quick terminal is disabled. //! `layer_shell::is_supported()` is false and the quick terminal is disabled.
use std::cell::RefCell; use std::{
use std::rc::Rc; cell::RefCell,
use std::sync::Arc; rc::Rc,
use std::sync::Mutex; sync::{
use std::sync::atomic::{AtomicBool, Ordering}; Arc,
Mutex,
use gdk4_wayland::WaylandDisplay; atomic::{AtomicBool, Ordering},
use gdk4_wayland::prelude::*; },
use gtk::gdk;
use gtk::glib;
use gtk::prelude::*;
use gtk4_layer_shell::{self as layer_shell, LayerShell};
use wayland_client::globals::{GlobalListContents, registry_queue_init};
use wayland_client::protocol::wl_registry::WlRegistry;
use wayland_client::protocol::wl_surface::WlSurface;
use wayland_client::{Connection, Dispatch, EventQueue, Proxy, QueueHandle};
use wayland_protocols::xdg::activation::v1::client::xdg_activation_token_v1::{
self, XdgActivationTokenV1,
}; };
use wayland_protocols::xdg::activation::v1::client::xdg_activation_v1::XdgActivationV1;
use wayland_protocols_plasma::blur::client::org_kde_kwin_blur::OrgKdeKwinBlur;
use wayland_protocols_plasma::blur::client::org_kde_kwin_blur_manager::OrgKdeKwinBlurManager;
use wayland_protocols_plasma::server_decoration::client::org_kde_kwin_server_decoration::OrgKdeKwinServerDecoration;
use wayland_protocols_plasma::server_decoration::client::org_kde_kwin_server_decoration_manager::{
self, OrgKdeKwinServerDecorationManager,
};
use wayland_protocols_plasma::slide::client::org_kde_kwin_slide::OrgKdeKwinSlide;
use wayland_protocols_plasma::slide::client::org_kde_kwin_slide_manager::OrgKdeKwinSlideManager;
use super::{Error, Result, WindowHost}; use gdk4_wayland::{WaylandDisplay, prelude::*};
use ghostty_config::config::Config; use ghostty_config::{
use ghostty_config::types_b::{ config::Config,
QuickTerminalDimensions, QuickTerminalKeyboardInteractivity, QuickTerminalLayer, types_b::{
QuickTerminalPosition, WindowDecoration, QuickTerminalDimensions,
QuickTerminalKeyboardInteractivity,
QuickTerminalLayer,
QuickTerminalPosition,
WindowDecoration,
},
}; };
use ghostty_input::Mods; use ghostty_input::Mods;
use gtk::{gdk, glib, prelude::*};
use gtk4_layer_shell::{self as layer_shell, LayerShell};
use wayland_client::{
Connection,
Dispatch,
EventQueue,
Proxy,
QueueHandle,
globals::{GlobalListContents, registry_queue_init},
protocol::{wl_registry::WlRegistry, wl_surface::WlSurface},
};
use wayland_protocols::xdg::activation::v1::client::{
xdg_activation_token_v1::{self, XdgActivationTokenV1},
xdg_activation_v1::XdgActivationV1,
};
use wayland_protocols_plasma::{
blur::client::{
org_kde_kwin_blur::OrgKdeKwinBlur,
org_kde_kwin_blur_manager::OrgKdeKwinBlurManager,
},
server_decoration::client::{
org_kde_kwin_server_decoration::OrgKdeKwinServerDecoration,
org_kde_kwin_server_decoration_manager::{self, OrgKdeKwinServerDecorationManager},
},
slide::client::{
org_kde_kwin_slide::OrgKdeKwinSlide,
org_kde_kwin_slide_manager::OrgKdeKwinSlideManager,
},
};
use super::{Error, Result, WindowHost};
/// `org_kde_kwin_server_decoration_manager.mode` values. /// `org_kde_kwin_server_decoration_manager.mode` values.
const DECO_NONE: u32 = 0; const DECO_NONE: u32 = 0;
+7 -8
View File
@@ -5,17 +5,16 @@
//! comments. //! comments.
#![allow(unsafe_code)] #![allow(unsafe_code)]
use std::ffi::{c_int, c_long, c_uchar, c_uint, c_ulong, c_void}; use std::{
use std::rc::Rc; ffi::{c_int, c_long, c_uchar, c_uint, c_ulong, c_void},
rc::Rc,
};
use gdk4_x11::x11::xlib; use gdk4_x11::{X11Display, X11Surface, x11::xlib};
use gdk4_x11::{X11Display, X11Surface}; use ghostty_input::Mods;
use gtk::gdk; use gtk::{gdk, glib, prelude::*};
use gtk::glib;
use gtk::prelude::*;
use super::{Error, Result, WindowHost}; use super::{Error, Result, WindowHost};
use ghostty_input::Mods;
// XKB bits we need that the `x11` crate doesn't expose (XKBlib.h / XKB.h). // XKB bits we need that the `x11` crate doesn't expose (XKBlib.h / XKB.h).
const XKB_MAJOR_VERSION: c_int = 1; const XKB_MAJOR_VERSION: c_int = 1;
+6 -6
View File
@@ -3,14 +3,14 @@
//! C-ABI plumbing (`C`, `CValue`, `cval`, `ghostty.h` sync tests) is not //! C-ABI plumbing (`C`, `CValue`, `cval`, `ghostty.h` sync tests) is not
//! ported; the enums keep their C integer discriminants via `as i32`. //! ported; the enums keep their C integer discriminants via `as i32`.
use crate::surface::{ChildExited, RendererHealth, Scrollbar};
use ghostty_config::config::Config;
use ghostty_config::types_b::Duration;
use ghostty_input::binding::Trigger;
use ghostty_vt::mouse_shape::MouseShape;
use ghostty_vt::osc::ProgressReport;
use std::sync::Arc; use std::sync::Arc;
use ghostty_config::{config::Config, types_b::Duration};
use ghostty_input::binding::Trigger;
use ghostty_vt::{mouse_shape::MouseShape, osc::ProgressReport};
use crate::surface::{ChildExited, RendererHealth, Scrollbar};
/// The target for an action. This is generally the thing that had focus /// The target for an action. This is generally the thing that had focus
/// while the action was made but the concept of "focus" is not guaranteed /// while the action was made but the concept of "focus" is not guaranteed
/// since actions can also be triggered by timers, scripts, etc. /// since actions can also be triggered by timers, scripts, etc.
+10 -2
View File
@@ -13,6 +13,14 @@ pub mod surface;
pub use action::{Action, Target}; pub use action::{Action, Target};
pub use structs::{ pub use structs::{
Clipboard, ClipboardContent, ClipboardRequest, ClipboardRequestType, ColorScheme, ContentScale, Clipboard,
CursorPos, ImePos, Selection, SurfaceSize, ClipboardContent,
ClipboardRequest,
ClipboardRequestType,
ColorScheme,
ContentScale,
CursorPos,
ImePos,
Selection,
SurfaceSize,
}; };
+14 -6
View File
@@ -15,16 +15,24 @@
//! //!
//! See `docs/rewrite/notes/ghostty-apprt-gtk.md` for the full spec. //! See `docs/rewrite/notes/ghostty-apprt-gtk.md` for the full spec.
use std::rc::Rc; use std::{rc::Rc, sync::Arc};
use std::sync::Arc;
use crate::action::{Action, Target};
use crate::structs::{
Clipboard, ClipboardRequest, ColorScheme, ContentScale, CursorPos, ImePos, SurfaceSize,
};
use ghostty_config::config::Config; use ghostty_config::config::Config;
use ghostty_input::{Mods, MouseButton, MouseButtonState, ScrollMods}; use ghostty_input::{Mods, MouseButton, MouseButtonState, ScrollMods};
use crate::{
action::{Action, Target},
structs::{
Clipboard,
ClipboardRequest,
ColorScheme,
ContentScale,
CursorPos,
ImePos,
SurfaceSize,
},
};
/// Identifier for a core surface (Zig: `*CoreSurface` pointer). Allocated by /// Identifier for a core surface (Zig: `*CoreSurface` pointer). Allocated by
/// this crate for each GTK surface; core stores it in its `Target::Surface`. /// this crate for each GTK surface; core stores it in its `Target::Surface`.
pub type SurfaceId = u64; pub type SurfaceId = u64;
+11 -9
View File
@@ -1,15 +1,16 @@
//! Port of `surface.zig`: messages sent from the core to a surface's apprt. //! Port of `surface.zig`: messages sent from the core to a surface's apprt.
use crate::structs::Clipboard;
use ghostty_config::config::Config;
use ghostty_config::types_a::WorkingDirectory;
use ghostty_datastruct::MessageData;
use ghostty_datastruct::blocking_queue::Timeout;
use ghostty_vt::mouse_shape::MouseShape;
use ghostty_vt::osc::ProgressReport;
use ghostty_vt::osc::color::ColoredTarget;
use std::sync::Arc; use std::sync::Arc;
use ghostty_config::{config::Config, types_a::WorkingDirectory};
use ghostty_datastruct::{MessageData, blocking_queue::Timeout};
use ghostty_vt::{
mouse_shape::MouseShape,
osc::{ProgressReport, color::ColoredTarget},
};
use crate::structs::Clipboard;
/// Represents a write request. Magic number comes from the max size /// Represents a write request. Magic number comes from the max size
/// we want this union to be. /// we want this union to be.
pub type WriteReq = MessageData<u8, 255>; pub type WriteReq = MessageData<u8, 255>;
@@ -233,9 +234,10 @@ pub fn new_config(config: &Config, context: NewSurfaceContext, prev_pwd: Option<
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use std::cell::RefCell; use std::cell::RefCell;
use super::*;
struct Rec(RefCell<Vec<(u32, bool)>>); struct Rec(RefCell<Vec<(u32, bool)>>);
impl AppMailbox<u32> for Rec { impl AppMailbox<u32> for Rec {
fn push_surface_message(&self, s: u32, m: Message, _t: Timeout) -> usize { fn push_surface_message(&self, s: u32, m: Message, _t: Timeout) -> usize {
+6 -4
View File
@@ -1,9 +1,11 @@
//! Minimal `--key=value` option parsing (the subset of `cli/args.zig` used by //! Minimal `--key=value` option parsing (the subset of `cli/args.zig` used by
//! the benchmark and synthetic CLIs). //! the benchmark and synthetic CLIs).
use std::collections::HashMap; use std::{
use std::fs::File; collections::HashMap,
use std::io::{self, Read}; fs::File,
use std::str::FromStr; io::{self, Read},
str::FromStr,
};
/// Parsed `--key[=value]` arguments. /// Parsed `--key[=value]` arguments.
#[derive(Debug, Default)] #[derive(Debug, Default)]
+7 -4
View File
@@ -1,7 +1,7 @@
//! The individual benchmarks (ports of `benchmark/*.zig`) and the CLI action //! The individual benchmarks (ports of `benchmark/*.zig`) and the CLI action
//! dispatch (`benchmark/cli.zig`). //! dispatch (`benchmark/cli.zig`).
use crate::args::{Args, data_file, read_short}; use std::{hint::black_box, io::Read};
use crate::benchmark::{Benchmark, BenchmarkFailed, Result, RunMode, RunResult, run};
use ghostty_terminal::{ use ghostty_terminal::{
point::{Coordinate, Point}, point::{Coordinate, Point},
render::RenderState, render::RenderState,
@@ -14,8 +14,11 @@ use ghostty_vt::{
stream::{Action, Handler, Stream}, stream::{Action, Handler, Stream},
utf8_decoder::Utf8Decoder, utf8_decoder::Utf8Decoder,
}; };
use std::hint::black_box;
use std::io::Read; use crate::{
args::{Args, data_file, read_short},
benchmark::{Benchmark, BenchmarkFailed, Result, RunMode, RunResult, run},
};
const CHUNK: usize = 4096; const CHUNK: usize = 4096;
@@ -1,11 +1,14 @@
//! `ghostty-synthetic +<ascii|utf8|osc> [--option=value ...]`: endless //! `ghostty-synthetic +<ascii|utf8|osc> [--option=value ...]`: endless
//! synthetic data on stdout (port of `synthetic/main.zig`). //! synthetic data on stdout (port of `synthetic/main.zig`).
use std::{
io::{BufWriter, Write},
process::ExitCode,
};
use ghostty_bench::{ use ghostty_bench::{
args::Args, args::Args,
synthetic::{OscStyle, Rng, run_ascii, run_osc, run_sgr, run_utf8}, synthetic::{OscStyle, Rng, run_ascii, run_osc, run_sgr, run_utf8},
}; };
use std::io::{BufWriter, Write};
use std::process::ExitCode;
fn run() -> Result<(), String> { fn run() -> Result<(), String> {
let argv: Vec<String> = std::env::args().skip(1).collect(); let argv: Vec<String> = std::env::args().skip(1).collect();
+2 -1
View File
@@ -1,7 +1,8 @@
//! `ghostty-bench +<action> [--option=value ...]` (port of `main_bench.zig`). //! `ghostty-bench +<action> [--option=value ...]` (port of `main_bench.zig`).
use ghostty_bench::{args::Args, benches};
use std::process::ExitCode; use std::process::ExitCode;
use ghostty_bench::{args::Args, benches};
fn main() -> ExitCode { fn main() -> ExitCode {
let argv: Vec<String> = std::env::args().skip(1).collect(); let argv: Vec<String> = std::env::args().skip(1).collect();
let mut action = None; let mut action = None;
+4 -2
View File
@@ -1,8 +1,9 @@
//! Synthetic data generators (port of `ZIG/src/synthetic`): random bytes, //! Synthetic data generators (port of `ZIG/src/synthetic`): random bytes,
//! UTF-8 and OSC sequences, used to feed the benchmarks. //! UTF-8 and OSC sequences, used to feed the benchmarks.
use ghostty_vt::string_encoding::url_percent_encode;
use std::io::{self, Write}; use std::io::{self, Write};
use ghostty_vt::string_encoding::url_percent_encode;
/// xoshiro256++ (what Zig's `std.Random.DefaultPrng` is). /// xoshiro256++ (what Zig's `std.Random.DefaultPrng` is).
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Rng { pub struct Rng {
@@ -666,9 +667,10 @@ fn finished(r: io::Result<usize>) -> io::Result<bool> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use ghostty_vt::osc::Parser; use ghostty_vt::osc::Parser;
use super::*;
const SEED: u64 = 0xC0FFEEEEEEEEEEEE; const SEED: u64 = 0xC0FFEEEEEEEEEEEE;
#[test] #[test]
+7 -2
View File
@@ -4,8 +4,13 @@ use std::fmt::Write as _;
use ghostty_config::cli_args::FieldKind; use ghostty_config::cli_args::FieldKind;
use crate::chunks_bash::{C0, C1, C2, C3, C4, C5, C6}; use crate::{
use crate::{actions, config_fields, join_names, join_packed}; actions,
chunks_bash::{C0, C1, C2, C3, C4, C5, C6},
config_fields,
join_names,
join_packed,
};
const COMPGEN_PREFIX: &str = "_compreply compgen -W \""; const COMPGEN_PREFIX: &str = "_compreply compgen -W \"";
const COMPGEN_SUFFIX: &str = "\" -- \"$cur\"; _add_spaces ;;"; const COMPGEN_SUFFIX: &str = "\" -- \"$cur\"; _add_spaces ;;";
+1 -3
View File
@@ -8,9 +8,7 @@
#![cfg_attr(test, allow(clippy::expect_used))] #![cfg_attr(test, allow(clippy::expect_used))]
use ghostty_cli::Action; use ghostty_cli::Action;
use ghostty_config::cli_args::FieldKind; use ghostty_config::{cli_args::FieldKind, config::Config, macros::ConfigStruct};
use ghostty_config::config::Config;
use ghostty_config::macros::ConfigStruct;
pub mod bash; pub mod bash;
pub mod fish; pub mod fish;
+1 -2
View File
@@ -5,8 +5,7 @@
//! +vim-ftdetect|+vim-ftplugin|+vim-compiler|+terminfo|+mdgen-ghostty-1| //! +vim-ftdetect|+vim-ftplugin|+vim-compiler|+terminfo|+mdgen-ghostty-1|
//! +mdgen-ghostty-5` //! +mdgen-ghostty-5`
use std::io::Write; use std::{io::Write, process::ExitCode};
use std::process::ExitCode;
use ghostty_build_data::Mode; use ghostty_build_data::Mode;
+4 -2
View File
@@ -1,7 +1,9 @@
//! Sublime syntax (also used by `bat`) (port of `extra/sublime.zig`). //! Sublime syntax (also used by `bat`) (port of `extra/sublime.zig`).
use crate::chunks_sublime::{C0, C1}; use crate::{
use crate::config_fields; chunks_sublime::{C0, C1},
config_fields,
};
#[must_use] #[must_use]
pub fn syntax() -> String { pub fn syntax() -> String {
+4 -2
View File
@@ -2,8 +2,10 @@
use std::fmt::Write as _; use std::fmt::Write as _;
use crate::chunks_vim::{C0, C1, C2, C3, C4}; use crate::{
use crate::config_fields; chunks_vim::{C0, C1, C2, C3, C4},
config_fields,
};
pub const FTDETECT: &str = C0; pub const FTDETECT: &str = C0;
pub const FTPLUGIN: &str = C1; pub const FTPLUGIN: &str = C1;
+7 -2
View File
@@ -4,8 +4,13 @@ use std::fmt::Write as _;
use ghostty_config::cli_args::FieldKind; use ghostty_config::cli_args::FieldKind;
use crate::chunks_zsh::{C0, C1, C2, C3}; use crate::{
use crate::{actions, config_fields, join_names, join_packed}; actions,
chunks_zsh::{C0, C1, C2, C3},
config_fields,
join_names,
join_packed,
};
const EQUALS_REQUIRED: &str = "=-:::"; const EQUALS_REQUIRED: &str = "=-:::";
+4 -2
View File
@@ -8,8 +8,10 @@
//! The version can be overridden with `GHOSTTY_VERSION_STRING` (Zig: //! The version can be overridden with `GHOSTTY_VERSION_STRING` (Zig:
//! `-Dversion-string`), which must be a semantic version. //! `-Dversion-string`), which must be a semantic version.
use std::path::{Path, PathBuf}; use std::{
use std::process::Command; path::{Path, PathBuf},
process::Command,
};
fn run(cmd: &str, args: &[&str], dir: &Path) -> Option<String> { fn run(cmd: &str, args: &[&str], dir: &Path) -> Option<String> {
let out = Command::new(cmd) let out = Command::new(cmd)
+2 -1
View File
@@ -104,9 +104,10 @@ where
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
#![allow(clippy::unwrap_used)] #![allow(clippy::unwrap_used)]
use super::*;
use ghostty_config::cli_args::split_args; use ghostty_config::cli_args::split_args;
use super::*;
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Plain { enum Plain {
Foo, Foo,
+11 -8
View File
@@ -5,17 +5,20 @@
//! joined with `\x01` and raw-deflate compressed into `boo_frames.deflate` //! joined with `\x01` and raw-deflate compressed into `boo_frames.deflate`
//! (the same format `framegen` produces for Zig's `framedata`). //! (the same format `framegen` produces for Zig's `framedata`).
use std::io::Read; use std::{
use std::time::{Duration, Instant}; io::Read,
time::{Duration, Instant},
};
use flate2::read::DeflateDecoder; use flate2::read::DeflateDecoder;
use ratatui::buffer::Buffer; use ratatui::{
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers}; buffer::Buffer,
use ratatui::layout::Rect; crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers},
use ratatui::style::{Color, Style}; layout::Rect,
style::{Color, Style},
};
use crate::error::Error; use crate::{error::Error, options::NoOptions as Options};
use crate::options::NoOptions as Options;
static FRAME_DATA: &[u8] = include_bytes!("boo_frames.deflate"); static FRAME_DATA: &[u8] = include_bytes!("boo_frames.deflate");
+5 -4
View File
@@ -4,14 +4,15 @@
//! Ghostty uses sentry for crash reporting; only the listing behaviour is //! Ghostty uses sentry for crash reporting; only the listing behaviour is
//! ported. //! ported.
use std::io::{IsTerminal, Write}; use std::{
use std::path::PathBuf; io::{IsTerminal, Write},
use std::time::{SystemTime, UNIX_EPOCH}; path::PathBuf,
time::{SystemTime, UNIX_EPOCH},
};
use ghostty_config::types_b::Duration; use ghostty_config::types_b::Duration;
use crate::error::Error; use crate::error::Error;
pub use crate::options::NoOptions as Options; pub use crate::options::NoOptions as Options;
/// A crash report file (Zig: `crash.Report`). /// A crash report file (Zig: `crash.Report`).
+1 -3
View File
@@ -1,12 +1,10 @@
//! `+edit-config` (ZIG/src/cli/edit_config.zig). //! `+edit-config` (ZIG/src/cli/edit_config.zig).
use std::io::Write; use std::{io::Write, os::unix::process::CommandExt};
use std::os::unix::process::CommandExt;
use ghostty_config::config::Config; use ghostty_config::config::Config;
use crate::error::Error; use crate::error::Error;
pub use crate::options::NoOptions as Options; pub use crate::options::NoOptions as Options;
/// The `edit-config` command opens the Ghostty configuration file in the /// The `edit-config` command opens the Ghostty configuration file in the
+7 -5
View File
@@ -3,8 +3,10 @@
use std::io::Write; use std::io::Write;
use crate::action::{ActionEnum, DetectError, SpecialCase, detect_iter}; use crate::{
use crate::error::Error; action::{ActionEnum, DetectError, SpecialCase, detect_iter},
error::Error,
};
/// Special commands that can be invoked via CLI flags. These are all /// Special commands that can be invoked via CLI flags. These are all
/// invoked by using `+<action>` as a CLI flag. The only exception is /// invoked by using `+<action>` as a CLI flag. The only exception is
@@ -117,8 +119,7 @@ impl Action {
/// Used by the build-data generator for shell completions. /// Used by the build-data generator for shell completions.
#[must_use] #[must_use]
pub fn option_fields(self) -> Vec<(&'static str, ghostty_config::cli_args::FieldKind)> { pub fn option_fields(self) -> Vec<(&'static str, ghostty_config::cli_args::FieldKind)> {
use ghostty_config::cli_args::FieldKind; use ghostty_config::{cli_args::FieldKind, macros::ConfigStruct};
use ghostty_config::macros::ConfigStruct;
fn of<T: ConfigStruct>() -> Vec<(&'static str, FieldKind)> { fn of<T: ConfigStruct>() -> Vec<(&'static str, FieldKind)> {
T::FIELDS T::FIELDS
.iter() .iter()
@@ -297,9 +298,10 @@ pub fn run_from_args(args: &[String]) -> Option<u8> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
#![allow(clippy::unwrap_used)] #![allow(clippy::unwrap_used)]
use super::*;
use ghostty_config::cli_args::split_args; use ghostty_config::cli_args::split_args;
use super::*;
fn detect_str(s: &str) -> Result<Option<Action>, DetectError> { fn detect_str(s: &str) -> Result<Option<Action>, DetectError> {
detect_iter::<Action, _, _>(split_args(s)) detect_iter::<Action, _, _>(split_args(s))
} }
+1 -2
View File
@@ -4,8 +4,7 @@ use std::io::Write;
use ghostty_config::config_struct; use ghostty_config::config_struct;
use crate::error::Error; use crate::{error::Error, ghostty::Action};
use crate::ghostty::Action;
config_struct! { config_struct! {
// Note that this options struct doesn't implement the `help` decl like other // Note that this options struct doesn't implement the `help` decl like other
+8 -4
View File
@@ -1,12 +1,16 @@
//! `+list-colors` (ZIG/src/cli/list_colors.zig). //! `+list-colors` (ZIG/src/cli/list_colors.zig).
use std::cmp::Ordering; use std::{
use std::io::{IsTerminal, Write}; cmp::Ordering,
io::{IsTerminal, Write},
};
use ghostty_config::config_struct; use ghostty_config::config_struct;
use crate::error::Error; use crate::{
use crate::tui::{self, Color, PrettySession, Style}; error::Error,
tui::{self, Color, PrettySession, Style},
};
config_struct! { config_struct! {
pub struct Options { pub struct Options {
+1 -2
View File
@@ -49,8 +49,7 @@ pub fn run(args: &[String]) -> Result<u8, Error> {
let mut opts = Options::default(); let mut opts = Options::default();
crate::parse_options(&mut opts, args)?; crate::parse_options(&mut opts, args)?;
use std::collections::HashMap; use std::{collections::HashMap, io::Write};
use std::io::Write;
// We'll be putting our fonts into a list categorized by family // We'll be putting our fonts into a list categorized by family
// so it is easier to read the output. // so it is easier to read the output.
+20 -10
View File
@@ -1,18 +1,28 @@
//! `+list-keybinds` (ZIG/src/cli/list_keybinds.zig), including its pretty //! `+list-keybinds` (ZIG/src/cli/list_keybinds.zig), including its pretty
//! (tty) output. //! (tty) output.
use std::cmp::Ordering; use std::{
use std::io::{IsTerminal, Write}; cmp::Ordering,
io::{IsTerminal, Write},
};
use ghostty_config::config::Config; use ghostty_config::{
use ghostty_config::config_struct; config::Config,
use ghostty_config::formatter::EntryFormatter; config_struct,
use ghostty_config::keybinds::Keybinds; formatter::EntryFormatter,
use ghostty_input::binding::set::{Set, Value}; keybinds::Keybinds,
use ghostty_input::binding::{Action as BindingAction, Trigger, TriggerKey}; };
use ghostty_input::binding::{
Action as BindingAction,
Trigger,
TriggerKey,
set::{Set, Value},
};
use crate::error::Error; use crate::{
use crate::tui::{self, Color, PrettySession, Style, gwidth}; error::Error,
tui::{self, Color, PrettySession, Style, gwidth},
};
config_struct! { config_struct! {
pub struct Options { pub struct Options {
+12 -8
View File
@@ -3,16 +3,20 @@
//! The non-interactive listing is a faithful port. The interactive preview //! The non-interactive listing is a faithful port. The interactive preview
//! (libvaxis in Zig) is implemented with ratatui + crossterm in [`preview`]. //! (libvaxis in Zig) is implemented with ratatui + crossterm in [`preview`].
use std::cmp::Ordering; use std::{
use std::fmt::Write as _; cmp::Ordering,
use std::io::{IsTerminal, Write}; fmt::Write as _,
io::{IsTerminal, Write},
};
use ghostty_config::config::Config; use ghostty_config::{
use ghostty_config::theme::{Location, LocationIterator}; config::Config,
use ghostty_config::{config_enum, config_struct}; config_enum,
config_struct,
theme::{Location, LocationIterator},
};
use crate::error::Error; use crate::{error::Error, tui};
use crate::tui;
pub mod preview; pub mod preview;
+30 -17
View File
@@ -13,22 +13,32 @@
//! termina cannot parse); it starts as light //! termina cannot parse); it starts as light
//! like the Zig code does, but `COLORFGBG` is used as a hint if set. //! like the Zig code does, but `COLORFGBG` is used as a hint if set.
use std::cell::RefCell; use std::{cell::RefCell, fmt::Write as _, io::Write};
use std::fmt::Write as _;
use std::io::Write;
use ghostty_config::config::Config; use ghostty_config::{config::Config, types_a::TerminalColor};
use ghostty_config::types_a::TerminalColor; use ratatui::{
use ratatui::Frame; Frame,
use ratatui::buffer::Buffer; buffer::Buffer,
use ratatui::crossterm::event::{ crossterm::event::{
Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent, MouseEventKind, Event,
KeyCode,
KeyEvent,
KeyEventKind,
KeyModifiers,
MouseButton,
MouseEvent,
MouseEventKind,
},
layout::{Position, Rect},
style::{Color, Modifier, Style},
}; };
use ratatui::layout::{Position, Rect};
use ratatui::style::{Color, Modifier, Style};
use super::{ use super::{
ColorScheme, SMALL_LIST_THRESHOLD, ThemeListElement, absolute_path, should_include_theme, ColorScheme,
SMALL_LIST_THRESHOLD,
ThemeListElement,
absolute_path,
should_include_theme,
}; };
use crate::error::Error; use crate::error::Error;
@@ -1667,10 +1677,12 @@ pub fn preview(themes: Vec<ThemeListElement>, theme_filter: ColorScheme) -> Resu
} }
fn run_loop(app: &mut Preview) -> Result<(), Error> { fn run_loop(app: &mut Preview) -> Result<(), Error> {
use ratatui::Terminal as RatTerminal; use ratatui::{Terminal as RatTerminal, backend::CrosstermBackend};
use ratatui::backend::CrosstermBackend; use termina::{
use termina::escape::csi::{Csi, DecPrivateMode, DecPrivateModeCode, Mode}; PlatformTerminal,
use termina::{PlatformTerminal, Terminal as _}; Terminal as _,
escape::csi::{Csi, DecPrivateMode, DecPrivateModeCode, Mode},
};
let mut tty = PlatformTerminal::new()?; let mut tty = PlatformTerminal::new()?;
tty.enter_raw_mode()?; tty.enter_raw_mode()?;
@@ -1753,9 +1765,10 @@ fn draw_frame(app: &mut Preview, f: &mut Frame<'_>) -> Option<Position> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
#![allow(clippy::unwrap_used)] #![allow(clippy::unwrap_used)]
use super::*;
use ghostty_config::theme::Location; use ghostty_config::theme::Location;
use super::*;
fn make_themes(dir: &std::path::Path, names: &[(&str, &str)]) -> Vec<ThemeListElement> { fn make_themes(dir: &std::path::Path, names: &[(&str, &str)]) -> Vec<ThemeListElement> {
names names
.iter() .iter()
+2 -1
View File
@@ -237,9 +237,10 @@ pub fn run(args: &[String]) -> Result<u8, Error> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
#![allow(clippy::unwrap_used)] #![allow(clippy::unwrap_used)]
use super::*;
use ghostty_config::cli_args::{VecIterator, parse}; use ghostty_config::cli_args::{VecIterator, parse};
use super::*;
fn parse_str(s: &str) -> Options { fn parse_str(s: &str) -> Options {
let mut opts = Options::default(); let mut opts = Options::default();
let mut it = VecIterator::from_str_args(s); let mut it = VecIterator::from_str_args(s);
+1 -3
View File
@@ -2,9 +2,7 @@
use std::io::Write; use std::io::Write;
use ghostty_config::config::Config; use ghostty_config::{config::Config, config_struct, file_formatter::FileFormatter};
use ghostty_config::config_struct;
use ghostty_config::file_formatter::FileFormatter;
use crate::error::Error; use crate::error::Error;
+14 -8
View File
@@ -1,13 +1,19 @@
//! `+show-face` (ZIG/src/cli/show_face.zig). //! `+show-face` (ZIG/src/cli/show_face.zig).
use ghostty_config::config::Config; use ghostty_config::{
use ghostty_config::diagnostics::Location; config::Config,
use ghostty_config::{config_enum, config_struct, diagnostics::DiagnosticList}; config_enum,
use ghostty_font::collection::EntryError; config_struct,
use ghostty_font::collection::GetFaceError; diagnostics::{DiagnosticList, Location},
use ghostty_font::face::DesiredSize; };
use ghostty_font::shared_grid_set::DerivedConfig; use ghostty_font::{
use ghostty_font::{self as font, SharedGrid, SharedGridSet}; self as font,
SharedGrid,
SharedGridSet,
collection::{EntryError, GetFaceError},
face::DesiredSize,
shared_grid_set::DerivedConfig,
};
use crate::error::Error; use crate::error::Error;
@@ -2,12 +2,14 @@
//! (ZIG/src/cli/ssh-cache/DiskCache.zig). The cache only stores metadata //! (ZIG/src/cli/ssh-cache/DiskCache.zig). The cache only stores metadata
//! (hostname, terminfo value, etc.) and does not store any sensitive data. //! (hostname, terminfo value, etc.) and does not store any sensitive data.
use std::collections::BTreeMap; use std::{
use std::fs::{File, OpenOptions}; collections::BTreeMap,
use std::io::{Read, Write}; fs::{File, OpenOptions},
use std::net::Ipv6Addr; io::{Read, Write},
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; net::Ipv6Addr,
use std::path::PathBuf; os::unix::fs::{OpenOptionsExt, PermissionsExt},
path::PathBuf,
};
use super::entry::{Entry, now_timestamp}; use super::entry::{Entry, now_timestamp};
+4 -2
View File
@@ -2,8 +2,10 @@
//! Our SSH entry cache stores which hosts we've sent our terminfo to so that //! Our SSH entry cache stores which hosts we've sent our terminfo to so that
//! we don't have to send it again. It doesn't store any sensitive information. //! we don't have to send it again. It doesn't store any sensitive information.
use std::fmt::Write as _; use std::{
use std::time::{SystemTime, UNIX_EPOCH}; fmt::Write as _,
time::{SystemTime, UNIX_EPOCH},
};
const S_PER_DAY: i64 = 86_400; const S_PER_DAY: i64 = 86_400;
+1 -2
View File
@@ -2,8 +2,7 @@
use std::io::Write; use std::io::Write;
use ghostty_config::config::Config; use ghostty_config::{config::Config, config_struct};
use ghostty_config::config_struct;
use crate::error::Error; use crate::error::Error;
+4 -2
View File
@@ -2,8 +2,10 @@
use std::io::{IsTerminal, Write}; use std::io::{IsTerminal, Write};
use crate::build_info::{self, BuildInfo}; use crate::{
use crate::error::Error; build_info::{self, BuildInfo},
error::Error,
};
/// The `version` command is used to display information about Ghostty. Recognized as /// The `version` command is used to display information about Ghostty. Recognized as
/// either `+version` or `--version`. /// either `+version` or `--version`.
+9 -6
View File
@@ -12,11 +12,13 @@
//! to a field and optionally provides diagnostics, compatibility handlers, //! to a field and optionally provides diagnostics, compatibility handlers,
//! a manual-parse hook and a `--help` hook. //! a manual-parse hook and a `--help` hook.
use crate::comma_splitter::CommaSplitter; use std::{fmt, io::BufRead};
use crate::diagnostics::{Diagnostic, DiagnosticList, Location};
use crate::formatter::EntryFormatter; use crate::{
use std::fmt; comma_splitter::CommaSplitter,
use std::io::BufRead; diagnostics::{Diagnostic, DiagnosticList, Location},
formatter::EntryFormatter,
};
/// For trimming /// For trimming
pub const WHITESPACE: &str = " \t"; pub const WHITESPACE: &str = " \t";
@@ -779,9 +781,10 @@ impl<R: BufRead> ArgIter for LineIterator<R> {
#[cfg(test)] #[cfg(test)]
#[allow(clippy::unwrap_used)] #[allow(clippy::unwrap_used)]
mod tests { mod tests {
use std::io::Cursor;
use super::*; use super::*;
use crate::{config_enum, config_packed, config_struct}; use crate::{config_enum, config_packed, config_struct};
use std::io::Cursor;
fn parse_str<T: CliTarget>(dst: &mut T, s: &str) -> Result<(), ArgError> { fn parse_str<T: CliTarget>(dst: &mut T, s: &str) -> Result<(), ArgError> {
let mut it = VecIterator::from_str_args(s); let mut it = VecIterator::from_str_args(s);
+5 -2
View File
@@ -1,9 +1,12 @@
//! A command to execute (port of `config/command.zig`). //! A command to execute (port of `config/command.zig`).
use crate::cli_args::{ArgError, ConfigField};
use crate::formatter::EntryFormatter;
use std::fmt; use std::fmt;
use crate::{
cli_args::{ArgError, ConfigField},
formatter::EntryFormatter,
};
/// A command to execute (argv0 and args). /// A command to execute (argv0 and args).
/// ///
/// A command is specified as a simple string such as "nvim a b c". /// A command is specified as a simple string such as "nvim a b c".
+21 -16
View File
@@ -4,22 +4,25 @@
//! invocation below with its exact name, type, default value and doc comment. //! invocation below with its exact name, type, default value and doc comment.
//! The doc comments are user-visible (`ghostty +show-config --docs`). //! The doc comments are user-visible (`ghostty +show-config --docs`).
use crate::cli_args::{self, ArgError, ArgIter, CliTarget};
use crate::command::Command;
use crate::conditional::{self, Conditional};
use crate::config_enum;
use crate::diagnostics::{Diagnostic, DiagnosticList};
use crate::io::RepeatableReadableIO;
use crate::key::Key;
use crate::keybinds::Keybinds;
use crate::macros::ConfigStruct;
use crate::metric_modifier::MetricModifier;
use crate::path::{Path, RepeatablePath};
use crate::repeatable_string_map::RepeatableStringMap;
use crate::types_a::*;
use crate::types_b::*;
use std::collections::HashSet; use std::collections::HashSet;
use crate::{
cli_args::{self, ArgError, ArgIter, CliTarget},
command::Command,
conditional::{self, Conditional},
config_enum,
diagnostics::{Diagnostic, DiagnosticList},
io::RepeatableReadableIO,
key::Key,
keybinds::Keybinds,
macros::ConfigStruct,
metric_modifier::MetricModifier,
path::{Path, RepeatablePath},
repeatable_string_map::RepeatableStringMap,
types_a::*,
types_b::*,
};
const NS_PER_S: u64 = 1_000_000_000; const NS_PER_S: u64 = 1_000_000_000;
const NS_PER_MS: u64 = 1_000_000; const NS_PER_MS: u64 = 1_000_000;
@@ -4820,10 +4823,12 @@ impl CliTarget for Config {
clippy::assert_is_empty clippy::assert_is_empty
)] )]
mod tests { mod tests {
use std::io::Cursor;
use ghostty_os::TempDir;
use super::*; use super::*;
use crate::cli_args::VecIterator; use crate::cli_args::VecIterator;
use ghostty_os::TempDir;
use std::io::Cursor;
fn it(args: &[&str]) -> VecIterator { fn it(args: &[&str]) -> VecIterator {
VecIterator::new(args.iter().map(|s| (*s).to_string()).collect()) VecIterator::new(args.iter().map(|s| (*s).to_string()).collect())
+2 -3
View File
@@ -1,9 +1,8 @@
//! Opening the config for editing (port of `config/edit.zig`). //! Opening the config for editing (port of `config/edit.zig`).
use std::{fs::OpenOptions, io, path::Path};
use crate::file_load; use crate::file_load;
use std::fs::OpenOptions;
use std::io;
use std::path::Path;
/// The path to the configuration that should be opened for editing. /// The path to the configuration that should be opened for editing.
/// ///
+6 -3
View File
@@ -1,11 +1,14 @@
//! `FileFormatter` (part of `config/formatter.zig`): outputs the config in a //! `FileFormatter` (part of `config/formatter.zig`): outputs the config in a
//! file-like format, identical to Ghostty's `+show-config`. //! file-like format, identical to Ghostty's `+show-config`.
use crate::config::Config;
use crate::key::Key;
use crate::macros::{ConfigStruct, help_string};
use std::fmt; use std::fmt;
use crate::{
config::Config,
key::Key,
macros::{ConfigStruct, help_string},
};
/// FileFormatter is a formatter implementation that outputs the /// FileFormatter is a formatter implementation that outputs the
/// config in a file-like format. This uses more generous whitespace, /// config in a file-like format. This uses more generous whitespace,
/// can include comments, etc. /// can include comments, etc.
+2 -1
View File
@@ -2,9 +2,10 @@
//! //!
//! macOS Application Support paths are not supported (Linux only). //! macOS Application Support paths are not supported (Linux only).
use ghostty_os::xdg;
use std::fs::File; use std::fs::File;
use ghostty_os::xdg;
/// Default path for the XDG home configuration file. /// Default path for the XDG home configuration file.
pub fn default_xdg_path() -> Result<String, xdg::Error> { pub fn default_xdg_path() -> Result<String, xdg::Error> {
xdg::config(&xdg::Options { xdg::config(&xdg::Options {
+2 -1
View File
@@ -1,9 +1,10 @@
//! Config formatting (port of `config/formatter.zig`). Output matches //! Config formatting (port of `config/formatter.zig`). Output matches
//! Ghostty's `+show-config`. //! Ghostty's `+show-config`.
use crate::cli_args::ConfigField;
use std::fmt; use std::fmt;
use crate::cli_args::ConfigField;
/// A single entry formatter for the given field name and writer. /// A single entry formatter for the given field name and writer.
pub struct EntryFormatter<'a> { pub struct EntryFormatter<'a> {
pub name: &'a str, pub name: &'a str,
+7 -3
View File
@@ -1,11 +1,15 @@
//! `ConfigField` implementations for types owned by `ghostty-input` //! `ConfigField` implementations for types owned by `ghostty-input`
//! (the input crate cannot depend on the config crate). //! (the input crate cannot depend on the config crate).
use crate::cli_args::{ArgError, ConfigField};
use crate::formatter::EntryFormatter;
use ghostty_input::{KeyRemapSet, OptionAsAlt};
use std::fmt; use std::fmt;
use ghostty_input::{KeyRemapSet, OptionAsAlt};
use crate::{
cli_args::{ArgError, ConfigField},
formatter::EntryFormatter,
};
impl ConfigField for KeyRemapSet { impl ConfigField for KeyRemapSet {
fn parse_cli(&mut self, value: Option<&str>) -> Result<(), ArgError> { fn parse_cli(&mut self, value: Option<&str>) -> Result<(), ArgError> {
self.parse_cli(value).map_err(|_| ArgError::InvalidValue) self.parse_cli(value).map_err(|_| ArgError::InvalidValue)
+6 -3
View File
@@ -1,10 +1,13 @@
//! Readable IO config values (port of `config/io.zig`). //! Readable IO config values (port of `config/io.zig`).
use crate::cli_args::{ArgError, ConfigField, split_tagged_union};
use crate::formatter::EntryFormatter;
use crate::string;
use std::fmt; use std::fmt;
use crate::{
cli_args::{ArgError, ConfigField, split_tagged_union},
formatter::EntryFormatter,
string,
};
/// ReadableIO is some kind of IO source that is readable. /// ReadableIO is some kind of IO source that is readable.
/// ///
/// It can be either a direct string or a filepath. The filepath will /// It can be either a direct string or a filepath. The filepath will
+28 -10
View File
@@ -1,17 +1,35 @@
//! Keybinds (port of `Config.Keybinds` from `config/Config.zig`). //! Keybinds (port of `Config.Keybinds` from `config/Config.zig`).
use crate::cli_args::{ArgError, ConfigField};
use crate::formatter::EntryFormatter;
use ghostty_input::binding::set::EntryFormatter as BindingEntryFormatter;
use ghostty_input::binding::set::Value;
use ghostty_input::binding::{
Action, AdjustSelection, CloseTabMode, CopyToClipboard, Flags, InspectorMode, Set,
SplitDirection, SplitFocusDirection, SplitResizeDirection, SplitResizeParameter, Trigger,
TriggerKey, WriteScreen,
};
use ghostty_input::{Key, Mods, ctrl_or_super};
use std::fmt; use std::fmt;
use ghostty_input::{
Key,
Mods,
binding::{
Action,
AdjustSelection,
CloseTabMode,
CopyToClipboard,
Flags,
InspectorMode,
Set,
SplitDirection,
SplitFocusDirection,
SplitResizeDirection,
SplitResizeParameter,
Trigger,
TriggerKey,
WriteScreen,
set::{EntryFormatter as BindingEntryFormatter, Value},
},
ctrl_or_super,
};
use crate::{
cli_args::{ArgError, ConfigField},
formatter::EntryFormatter,
};
/// The most recent binding target for `chain=` additions. /// The most recent binding target for `chain=` additions.
/// ///
/// This is intentionally tracked at the Keybinds level so that chains can /// This is intentionally tracked at the Keybinds level so that chains can
+5 -2
View File
@@ -3,10 +3,13 @@
//! The font crate depends on this crate (not the other way around), so the //! The font crate depends on this crate (not the other way around), so the
//! modifier type used by the `adjust-*` config options lives here. //! modifier type used by the `adjust-*` config options lives here.
use crate::cli_args::{ArgError, ConfigField};
use crate::formatter::EntryFormatter;
use std::fmt; use std::fmt;
use crate::{
cli_args::{ArgError, ConfigField},
formatter::EntryFormatter,
};
/// A modifier to apply to a metrics value. The modifier value represents /// A modifier to apply to a metrics value. The modifier value represents
/// a delta, so percent is a percentage to change, not a percentage of. /// a delta, so percent is a percentage to change, not a percentage of.
/// For example, "20%" is 20% larger, not 20% of the value. Likewise, /// For example, "20%" is 20% larger, not 20% of the value. Likewise,
+10 -5
View File
@@ -1,10 +1,15 @@
//! Path config values (port of `config/path.zig`). //! Path config values (port of `config/path.zig`).
use crate::cli_args::{ArgError, ConfigField}; use std::{
use crate::diagnostics::{Diagnostic, DiagnosticList}; fmt,
use crate::formatter::EntryFormatter; path::{Component, Path as StdPath, PathBuf},
use std::fmt; };
use std::path::{Component, Path as StdPath, PathBuf};
use crate::{
cli_args::{ArgError, ConfigField},
diagnostics::{Diagnostic, DiagnosticList},
formatter::EntryFormatter,
};
/// Path is like a string that represents a path value. The difference is that /// Path is like a string that represents a path value. The difference is that
/// when loading the configuration the value for this will be automatically /// when loading the configuration the value for this will be automatically
@@ -2,10 +2,13 @@
//! string map. This isn't called "StringMap" because I find that sometimes //! string map. This isn't called "StringMap" because I find that sometimes
//! leads to confusion that it _accepts_ a map such as JSON dict. //! leads to confusion that it _accepts_ a map such as JSON dict.
use crate::cli_args::{ArgError, ConfigField};
use crate::formatter::EntryFormatter;
use std::fmt; use std::fmt;
use crate::{
cli_args::{ArgError, ConfigField},
formatter::EntryFormatter,
};
/// std.ascii.whitespace /// std.ascii.whitespace
fn is_ascii_ws(c: char) -> bool { fn is_ascii_ws(c: char) -> bool {
matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0b' | '\x0c') matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0b' | '\x0c')
+2 -2
View File
@@ -3,9 +3,9 @@
//! Zig reads the resources dir from global state; here it is passed //! Zig reads the resources dir from global state; here it is passed
//! explicitly (`resources_dir`, the value of `ResourcesDir.app()`). //! explicitly (`resources_dir`, the value of `ResourcesDir.app()`).
use std::{fs::File, path::Path};
use crate::diagnostics::{Diagnostic, DiagnosticList}; use crate::diagnostics::{Diagnostic, DiagnosticList};
use std::fs::File;
use std::path::Path;
/// Location of possible themes. The order of this enum matters because it /// Location of possible themes. The order of this enum matters because it
/// defines the priority of theme search (from top to bottom). /// defines the priority of theme search (from top to bottom).
+11 -6
View File
@@ -2,14 +2,19 @@
//! enums, working directory, colors, palette, repeatable strings, word //! enums, working directory, colors, palette, repeatable strings, word
//! chars, font variation / codepoint maps, font style, links. //! chars, font variation / codepoint maps, font style, links.
use crate::cli_args::{ArgError, ConfigField, parse_int_base0, trim_ws};
use crate::clipboard_codepoint_map::{ClipboardCodepointMap, Entry as ClipboardEntry, Replacement};
use crate::font_types::{CodepointMap, CodepointMapEntry, Descriptor, Variation, VariationId};
use crate::formatter::EntryFormatter;
use crate::{config_enum, config_packed};
use ghostty_vt::color::{DEFAULT as DEFAULT_PALETTE, Palette as TermPalette, PaletteMask, Rgb};
use std::fmt; use std::fmt;
use ghostty_vt::color::{DEFAULT as DEFAULT_PALETTE, Palette as TermPalette, PaletteMask, Rgb};
use crate::{
cli_args::{ArgError, ConfigField, parse_int_base0, trim_ws},
clipboard_codepoint_map::{ClipboardCodepointMap, Entry as ClipboardEntry, Replacement},
config_enum,
config_packed,
font_types::{CodepointMap, CodepointMapEntry, Descriptor, Variation, VariationId},
formatter::EntryFormatter,
};
/// Write `name = value\n` for a string-ish value. /// Write `name = value\n` for a string-ish value.
fn write_str(f: &mut EntryFormatter<'_>, value: &str) -> fmt::Result { fn write_str(f: &mut EntryFormatter<'_>, value: &str) -> fmt::Result {
writeln!(f.writer, "{} = {}", f.name, value) writeln!(f.writer, "{} = {}", f.name, value)
+9 -4
View File
@@ -3,12 +3,17 @@
#![allow(clippy::format_push_string, clippy::single_match_else)] #![allow(clippy::format_push_string, clippy::single_match_else)]
use crate::cli_args::{ArgError, ConfigField, parse_auto_struct_with, parse_bool, trim_ws};
use crate::formatter::EntryFormatter;
use crate::{config_enum, config_packed};
use ghostty_input::binding::Action;
use std::fmt; use std::fmt;
use ghostty_input::binding::Action;
use crate::{
cli_args::{ArgError, ConfigField, parse_auto_struct_with, parse_bool, trim_ws},
config_enum,
config_packed,
formatter::EntryFormatter,
};
/// Write `name = <s>\n` (Zig: `formatEntry([]const u8, s)`). /// Write `name = <s>\n` (Zig: `formatEntry([]const u8, s)`).
fn fmt_str(f: &mut EntryFormatter<'_>, s: &str) -> fmt::Result { fn fmt_str(f: &mut EntryFormatter<'_>, s: &str) -> fmt::Result {
writeln!(f.writer, "{} = {}", f.name, s) writeln!(f.writer, "{} = {}", f.name, s)
+2 -1
View File
@@ -116,9 +116,10 @@ pub const REGEX: &str = concatcp!(
#[cfg(test)] #[cfg(test)]
#[allow(clippy::unwrap_used)] #[allow(clippy::unwrap_used)]
mod tests { mod tests {
use super::*;
use onig::Regex; use onig::Regex;
use super::*;
#[test] #[test]
fn url_regex() { fn url_regex() {
let re = Regex::new(REGEX).unwrap(); let re = Regex::new(REGEX).unwrap();
+27 -15
View File
@@ -11,26 +11,38 @@
//! app keeps weak references to them (the runtime owns the strong //! app keeps weak references to them (the runtime owns the strong
//! `Rc<dyn CoreSurface>`). //! `Rc<dyn CoreSurface>`).
use std::cell::{Cell, RefCell}; use std::{
use std::rc::{Rc, Weak}; cell::{Cell, RefCell},
use std::sync::Arc; rc::{Rc, Weak},
use std::time::Instant; sync::Arc,
time::Instant,
};
use crossbeam_channel::{Receiver, Sender, TrySendError}; use crossbeam_channel::{Receiver, Sender, TrySendError};
use ghostty_apprt::action::{Action as RtAction, QuitTimer, ReloadConfig, Target}; use ghostty_apprt::{
use ghostty_apprt::runtime_api::{ action::{Action as RtAction, QuitTimer, ReloadConfig, Target},
AppMessage, CellSize as RtCellSize, CoreApp, CoreError, CoreSurface, DesiredFontSize, RtApp, runtime_api::{
RtSurface, SurfaceId, Waker, AppMessage,
CellSize as RtCellSize,
CoreApp,
CoreError,
CoreSurface,
DesiredFontSize,
RtApp,
RtSurface,
SurfaceId,
Waker,
},
structs::ColorScheme,
surface::{AppMailbox, Message as SurfaceMessage},
}; };
use ghostty_apprt::structs::ColorScheme; use ghostty_config::{conditional, config::Config};
use ghostty_apprt::surface::{AppMailbox, Message as SurfaceMessage};
use ghostty_config::conditional;
use ghostty_config::config::Config;
use ghostty_datastruct::blocking_queue::Timeout; use ghostty_datastruct::blocking_queue::Timeout;
use ghostty_font::SharedGridSet; use ghostty_font::SharedGridSet;
use ghostty_input::KeyEvent; use ghostty_input::{
use ghostty_input::binding::set::Value as BindingValue; KeyEvent,
use ghostty_input::binding::{Action as BindingAction, Scope}; binding::{Action as BindingAction, Scope, set::Value as BindingValue},
};
use crate::surface::Surface; use crate::surface::Surface;
+2 -4
View File
@@ -5,11 +5,9 @@
//! the root binary before this is initialized, so what remains is: logging, //! the root binary before this is initialized, so what remains is: logging,
//! signal setup, rlimits and the resources directory. //! signal setup, rlimits and the resources directory.
use std::io::Write as _; use std::{io::Write as _, sync::OnceLock};
use std::sync::OnceLock;
use ghostty_os::file::Rlimit; use ghostty_os::{file::Rlimit, resourcesdir::ResourcesDir};
use ghostty_os::resourcesdir::ResourcesDir;
/// Where logging should go (Zig: `GlobalState.Logging`, a packed struct /// Where logging should go (Zig: `GlobalState.Logging`, a packed struct
/// parsed from `GHOSTTY_LOG`). /// parsed from `GHOSTTY_LOG`).
+66 -29
View File
@@ -2,42 +2,78 @@
//! `Search`, `searchCallback`, `dumpText`, `performBindingAction`, //! `Search`, `searchCallback`, `dumpText`, `performBindingAction`,
//! `closingAction`, `writeScreenFile`). //! `closingAction`, `writeScreenFile`).
use std::io::Write as _; use std::{io::Write as _, sync::Arc, thread::JoinHandle};
use std::sync::Arc;
use std::thread::JoinHandle;
use ghostty_apprt::action::{ use ghostty_apprt::{
Action as RtAction, CloseTabMode as RtCloseTabMode, FloatWindow, Fullscreen, action::{
GotoSplit as RtGotoSplit, GotoTab, GotoWindow as RtGotoWindow, Inspector as RtInspector, Action as RtAction,
KeyTable, MoveTab, OpenUrl, OpenUrlKind, PromptTitle, Readonly, ReloadConfig, CloseTabMode as RtCloseTabMode,
ResizeSplit as RtResizeSplit, ResizeSplitDirection, SecureInput, SetTitle, FloatWindow,
SplitDirection as RtSplit, StartSearch, Target, Fullscreen,
GotoSplit as RtGotoSplit,
GotoTab,
GotoWindow as RtGotoWindow,
Inspector as RtInspector,
KeyTable,
MoveTab,
OpenUrl,
OpenUrlKind,
PromptTitle,
Readonly,
ReloadConfig,
ResizeSplit as RtResizeSplit,
ResizeSplitDirection,
SecureInput,
SetTitle,
SplitDirection as RtSplit,
StartSearch,
Target,
},
runtime_api::{CoreError, RtApp, SurfaceId},
structs::{Clipboard, ClipboardRequest},
surface::Message as SurfaceMessage,
}; };
use ghostty_apprt::runtime_api::{CoreError, RtApp, SurfaceId};
use ghostty_apprt::structs::{Clipboard, ClipboardRequest};
use ghostty_apprt::surface::Message as SurfaceMessage;
use ghostty_config::types_a::NonNativeFullscreen; use ghostty_config::types_a::NonNativeFullscreen;
use ghostty_datastruct::blocking_queue::Timeout; use ghostty_datastruct::blocking_queue::Timeout;
use ghostty_input::binding::{ use ghostty_input::binding::{
Action, AdjustSelection, CloseTabMode, CrashThread, InspectorMode, NavigateSearch, Scope, Action,
SplitDirection, SplitFocusDirection, SplitResizeDirection, WriteScreen, WriteScreenAction, AdjustSelection,
CloseTabMode,
CrashThread,
InspectorMode,
NavigateSearch,
Scope,
SplitDirection,
SplitFocusDirection,
SplitResizeDirection,
WriteScreen,
WriteScreenAction,
WriteScreenFormat, WriteScreenFormat,
}; };
use ghostty_renderer::message::Message as RendererMessage; use ghostty_renderer::{
use ghostty_renderer::state::SharedState; message::Message as RendererMessage,
use ghostty_renderer::thread::Handle as RendererHandle; state::SharedState,
use ghostty_terminal::formatter::{self, Content, Format, ScreenFormatter}; thread::Handle as RendererHandle,
use ghostty_terminal::point::Tag;
use ghostty_terminal::screen::Scroll;
use ghostty_terminal::search::screen::Select;
use ghostty_terminal::search::thread::{
Event, Message as SearchMessage, Options as SearchOptions, TerminalLock, TerminalRef,
Thread as SearchThread,
}; };
use ghostty_terminal::selection::{Adjustment, Order, Selection}; use ghostty_terminal::{
use ghostty_terminal::terminal::{ScrollViewport, Terminal}; formatter::{self, Content, Format, ScreenFormatter},
use ghostty_termio::message::Message as IoMessage; point::Tag,
use ghostty_termio::{SharedStateExt, TerminalGuard}; screen::Scroll,
search::{
screen::Select,
thread::{
Event,
Message as SearchMessage,
Options as SearchOptions,
TerminalLock,
TerminalRef,
Thread as SearchThread,
},
},
selection::{Adjustment, Order, Selection},
terminal::{ScrollViewport, Terminal},
};
use ghostty_termio::{SharedStateExt, TerminalGuard, message::Message as IoMessage};
use super::Surface; use super::Surface;
use crate::app::Mailbox as AppMailbox; use crate::app::Mailbox as AppMailbox;
@@ -1172,9 +1208,10 @@ impl Surface {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use ghostty_terminal::terminal::Options; use ghostty_terminal::terminal::Options;
use super::*;
fn term(cols: u16, rows: u16) -> Terminal { fn term(cols: u16, rows: u16) -> Terminal {
Terminal::new(Options::new(cols, rows)).unwrap() Terminal::new(Options::new(cols, rows)).unwrap()
} }
+19 -16
View File
@@ -2,27 +2,30 @@
//! `copySelectionToClipboards`, clipboard requests, paste, OSC 52 and //! `copySelectionToClipboards`, clipboard requests, paste, OSC 52 and
//! desktop notifications). //! desktop notifications).
use std::hash::{Hash, Hasher}; use std::{
use std::rc::Rc; hash::{Hash, Hasher},
use std::sync::Arc; rc::Rc,
use std::time::{Duration, Instant}; sync::Arc,
time::{Duration, Instant},
};
use base64::Engine as _; use base64::{Engine as _, engine::general_purpose::STANDARD};
use base64::engine::general_purpose::STANDARD; use ghostty_apprt::{
use ghostty_apprt::action::{Action as RtAction, DesktopNotification}; action::{Action as RtAction, DesktopNotification},
use ghostty_apprt::runtime_api::ClipboardError; runtime_api::ClipboardError,
use ghostty_apprt::structs::{Clipboard, ClipboardRequest}; structs::{Clipboard, ClipboardRequest},
};
use ghostty_config::types_b::ClipboardAccess; use ghostty_config::types_b::ClipboardAccess;
use ghostty_input::binding::CopyToClipboard; use ghostty_input::{binding::CopyToClipboard, paste};
use ghostty_input::paste; use ghostty_terminal::{
use ghostty_terminal::formatter::{self, Format, ScreenFormatter}; formatter::{self, Format, ScreenFormatter},
use ghostty_terminal::selection::Selection; selection::Selection,
use ghostty_terminal::terminal::Terminal; terminal::Terminal,
};
use ghostty_termio::message::Message as IoMessage; use ghostty_termio::message::Message as IoMessage;
use ghostty_vt::modes::Mode; use ghostty_vt::modes::Mode;
use super::Surface; use super::{Surface, config::DerivedConfig};
use super::config::DerivedConfig;
/// `input.paste.Options.fromTerminal`. /// `input.paste.Options.fromTerminal`.
#[must_use] #[must_use]
+2 -4
View File
@@ -6,14 +6,12 @@
//! it so the fields keep their Zig names (`cfg.copy_on_select`, ...). The //! it so the fields keep their Zig names (`cfg.copy_on_select`, ...). The
//! few values that are *computed* in Zig live as fields of this struct. //! few values that are *computed* in Zig live as fields of this struct.
use std::ops::Deref; use std::{ops::Deref, sync::Arc};
use std::sync::Arc;
use ghostty_config::config::Config; use ghostty_config::config::Config;
use ghostty_input::link::{Action as LinkAction, Highlight}; use ghostty_input::link::{Action as LinkAction, Highlight};
use onig::Regex;
use ghostty_renderer::size::Padding; use ghostty_renderer::size::Padding;
use onig::Regex;
/// A link with its compiled regex (Zig: `DerivedConfig.Link`). /// A link with its compiled regex (Zig: `DerivedConfig.Link`).
pub struct Link { pub struct Link {
+2 -5
View File
@@ -5,11 +5,8 @@
use std::sync::Arc; use std::sync::Arc;
use ghostty_apprt::runtime_api::CoreError; use ghostty_apprt::runtime_api::CoreError;
use ghostty_inspector::Shared as Inspector; use ghostty_inspector::{Shared as Inspector, imgui::Ui, widgets::surface::SurfaceInfo};
use ghostty_inspector::imgui::Ui; use ghostty_renderer::{message::Message as RendererMessage, state::InspectorHook};
use ghostty_inspector::widgets::surface::SurfaceInfo;
use ghostty_renderer::message::Message as RendererMessage;
use ghostty_renderer::state::InspectorHook;
use ghostty_termio::message::Message as IoMessage; use ghostty_termio::message::Message as IoMessage;
use super::Surface; use super::Surface;
+17 -13
View File
@@ -11,20 +11,24 @@
//! time. A config change drops them anyway (`update_config` calls //! time. A config change drops them anyway (`update_config` calls
//! [`Surface::end_key_sequence`] and [`Surface::deactivate_all_key_tables`]). //! [`Surface::end_key_sequence`] and [`Surface::deactivate_all_key_tables`]).
use ghostty_apprt::action::{Action as RtAction, KeySequence, KeyTable}; use ghostty_apprt::{
use ghostty_apprt::runtime_api::{CoreError, InputEffect}; action::{Action as RtAction, KeySequence, KeyTable},
use ghostty_input::binding::set::Value; runtime_api::{CoreError, InputEffect},
use ghostty_input::binding::{Action as BindingAction, Flags, Scope, Set, Trigger, TriggerKey}; };
use ghostty_input::key_encode; use ghostty_input::{
use ghostty_input::{Action as KeyAction, Key, KeyEvent, Mods}; Action as KeyAction,
Key,
KeyEvent,
Mods,
binding::{Action as BindingAction, Flags, Scope, Set, Trigger, TriggerKey, set::Value},
key_encode,
};
use ghostty_inspector as inspector; use ghostty_inspector as inspector;
use ghostty_terminal::terminal::{MouseEvents, ScrollViewport, Terminal}; use ghostty_terminal::terminal::{MouseEvents, ScrollViewport, Terminal};
use ghostty_termio::message::Message as IoMessage; use ghostty_termio::message::Message as IoMessage;
use ghostty_vt::modes::Mode; use ghostty_vt::{modes::Mode, mouse_shape::MouseShape};
use ghostty_vt::mouse_shape::MouseShape;
use super::Surface; use super::{Surface, config::DerivedConfig};
use super::config::DerivedConfig;
/// The maximum number of key tables that can be active at any given time. /// The maximum number of key tables that can be active at any given time.
/// `activate_key_table` calls after this are ignored. /// `activate_key_table` calls after this are ignored.
@@ -1017,11 +1021,11 @@ impl Surface {
#[cfg(test)] #[cfg(test)]
#[allow(clippy::unwrap_used)] #[allow(clippy::unwrap_used)]
mod tests { mod tests {
use super::*; use ghostty_config::{cli_args::ConfigField, config::Config};
use ghostty_config::cli_args::ConfigField;
use ghostty_config::config::Config;
use ghostty_terminal::terminal::Options; use ghostty_terminal::terminal::Options;
use super::*;
fn cfg_with(binds: &[&str]) -> DerivedConfig { fn cfg_with(binds: &[&str]) -> DerivedConfig {
let mut c = Config::default(); let mut c = Config::default();
for b in binds { for b in binds {
+82 -48
View File
@@ -41,55 +41,90 @@ pub mod inspector;
pub mod keyboard; pub mod keyboard;
pub mod mouse; pub mod mouse;
use std::cell::{Cell, RefCell}; use std::{
use std::rc::Rc; cell::{Cell, RefCell},
use std::sync::Arc; rc::Rc,
use std::thread::JoinHandle; sync::Arc,
use std::time::{Duration as StdDuration, Instant}; thread::JoinHandle,
time::{Duration as StdDuration, Instant},
use ghostty_apprt::action::{
Action as RtAction, CellSize as ActionCellSize, ColorChange, ColorKind, CommandFinished,
ConfigChange, InitialSize, MouseVisibility, Pwd, ReloadConfig, SecureInput, SetTitle,
SizeLimit, Target,
};
use ghostty_apprt::runtime_api::{
ClipboardError, CoreError, CoreSurface, DesiredFontSize, InputEffect, RtApp, RtSurface,
SurfaceId,
};
use ghostty_apprt::structs::{
ClipboardRequest, ColorScheme, ContentScale, CursorPos, ImePos, SurfaceSize,
};
use ghostty_apprt::surface::{Mailbox as SurfaceMailboxImpl, Message};
use ghostty_config::conditional;
use ghostty_config::config::Config;
use ghostty_config::types_a::ConfirmCloseSurface;
use ghostty_datastruct::blocking_queue::Timeout;
use ghostty_font::face::DesiredSize;
use ghostty_font::metrics::Metrics;
use ghostty_font::shared_grid_set::{DerivedConfig as FontDerivedConfig, Key as FontGridKey};
use ghostty_input::{Mods, MouseButton, MouseButtonState, ScrollMods};
use ghostty_renderer::generic::Host as RendererHost;
use ghostty_renderer::message::{FontGridChange, Message as RendererMessage};
use ghostty_renderer::opengl::OpenGL;
use ghostty_renderer::options::Options as RendererOptions;
use ghostty_renderer::size::{CellSize, Coordinate, Padding, ScreenSize, Size};
use ghostty_renderer::state::{Preedit, PreeditCodepoint, State as RenderStateData};
use ghostty_renderer::thread::{Handle as RendererHandle, Running as RendererRunning};
use ghostty_renderer::{Health, Renderer};
use ghostty_terminal::page_list::Scrollbar;
use ghostty_terminal::point::Coordinate as PointCoordinate;
use ghostty_terminal::selection::Selection;
use ghostty_termio::exec;
use ghostty_termio::message::Message as IoMessage;
use ghostty_termio::{
Backend, DerivedConfig as IoDerivedConfig, Exec, Mailbox as IoMailbox, Options as IoOptions,
RendererMailbox, SharedState, SharedStateExt, TerminalGuard, Termio, Thread as IoThread,
Wakeup,
}; };
use crate::app::{AppState, Mailbox, Message as AppMessage};
use crate::global;
use config::DerivedConfig; use config::DerivedConfig;
use ghostty_apprt::{
action::{
Action as RtAction,
CellSize as ActionCellSize,
ColorChange,
ColorKind,
CommandFinished,
ConfigChange,
InitialSize,
MouseVisibility,
Pwd,
ReloadConfig,
SecureInput,
SetTitle,
SizeLimit,
Target,
},
runtime_api::{
ClipboardError,
CoreError,
CoreSurface,
DesiredFontSize,
InputEffect,
RtApp,
RtSurface,
SurfaceId,
},
structs::{ClipboardRequest, ColorScheme, ContentScale, CursorPos, ImePos, SurfaceSize},
surface::{Mailbox as SurfaceMailboxImpl, Message},
};
use ghostty_config::{conditional, config::Config, types_a::ConfirmCloseSurface};
use ghostty_datastruct::blocking_queue::Timeout;
use ghostty_font::{
face::DesiredSize,
metrics::Metrics,
shared_grid_set::{DerivedConfig as FontDerivedConfig, Key as FontGridKey},
};
use ghostty_input::{Mods, MouseButton, MouseButtonState, ScrollMods};
use ghostty_renderer::{
Health,
Renderer,
generic::Host as RendererHost,
message::{FontGridChange, Message as RendererMessage},
opengl::OpenGL,
options::Options as RendererOptions,
size::{CellSize, Coordinate, Padding, ScreenSize, Size},
state::{Preedit, PreeditCodepoint, State as RenderStateData},
thread::{Handle as RendererHandle, Running as RendererRunning},
};
use ghostty_terminal::{
page_list::Scrollbar,
point::Coordinate as PointCoordinate,
selection::Selection,
};
use ghostty_termio::{
Backend,
DerivedConfig as IoDerivedConfig,
Exec,
Mailbox as IoMailbox,
Options as IoOptions,
RendererMailbox,
SharedState,
SharedStateExt,
TerminalGuard,
Termio,
Thread as IoThread,
Wakeup,
exec,
message::Message as IoMessage,
};
use crate::{
app::{AppState, Mailbox, Message as AppMessage},
global,
};
/// Minimum window size in cells (Zig: `min_window_width_cells`). /// Minimum window size in cells (Zig: `min_window_width_cells`).
pub const MIN_WINDOW_WIDTH_CELLS: u32 = ghostty_apprt::runtime_api::MIN_WINDOW_WIDTH_CELLS; pub const MIN_WINDOW_WIDTH_CELLS: u32 = ghostty_apprt::runtime_api::MIN_WINDOW_WIDTH_CELLS;
@@ -793,8 +828,7 @@ impl Surface {
Message::ColorChange(change) => { Message::ColorChange(change) => {
// Notify our apprt, but don't send a mode 2031 DSR report // Notify our apprt, but don't send a mode 2031 DSR report
// because VT sequences were used to change the color. // because VT sequences were used to change the color.
use ghostty_vt::color::Dynamic as D; use ghostty_vt::{color::Dynamic as D, osc::color::Target};
use ghostty_vt::osc::color::Target;
let kind = match change.target { let kind = match change.target {
Target::Palette(v) => ColorKind::Palette(i32::from(v)), Target::Palette(v) => ColorKind::Palette(i32::from(v)),
Target::Dynamic(dyn_) => match dyn_ { Target::Dynamic(dyn_) => match dyn_ {
+35 -18
View File
@@ -8,24 +8,40 @@
use std::time::Instant; use std::time::Instant;
use ghostty_apprt::action::{Action as RtAction, MouseOverLink, OpenUrl, OpenUrlKind}; use ghostty_apprt::{
use ghostty_apprt::runtime_api::CoreError; action::{Action as RtAction, MouseOverLink, OpenUrl, OpenUrlKind},
use ghostty_apprt::structs::{Clipboard, ClipboardRequest, CursorPos}; runtime_api::CoreError,
use ghostty_config::types_a::LinkPreviews; structs::{Clipboard, ClipboardRequest, CursorPos},
use ghostty_config::types_b::{
CopyOnSelect, MouseShiftCapture as ConfigShiftCapture, RightClickAction,
}; };
use ghostty_input::link::{Action as LinkAction, Highlight}; use ghostty_config::{
use ghostty_input::{Mods, MouseButton, MouseButtonState, MousePressureStage, ScrollMods}; types_a::LinkPreviews,
use ghostty_renderer::size::{Coordinate as SizeCoordinate, CoordinateTag, Size, SurfaceCoord}; types_b::{CopyOnSelect, MouseShiftCapture as ConfigShiftCapture, RightClickAction},
use ghostty_renderer::state::State as RenderStateData; };
use ghostty_terminal::page_list::{Direction, PageList, Pin, TrackedPin}; use ghostty_input::{
use ghostty_terminal::point::{Coordinate as PointCoordinate, Point}; Mods,
use ghostty_terminal::screen::{Screen, SelectLine, SelectionString, SemanticClick}; MouseButton,
use ghostty_terminal::screen_set::Key as ScreenKey; MouseButtonState,
use ghostty_terminal::selection::Selection; MousePressureStage,
use ghostty_terminal::terminal::{ ScrollMods,
MouseEvents, MouseFormat, MouseShiftCapture as TerminalShiftCapture, ScrollViewport, Terminal, link::{Action as LinkAction, Highlight},
};
use ghostty_renderer::{
size::{Coordinate as SizeCoordinate, CoordinateTag, Size, SurfaceCoord},
state::State as RenderStateData,
};
use ghostty_terminal::{
page_list::{Direction, PageList, Pin, TrackedPin},
point::{Coordinate as PointCoordinate, Point},
screen::{Screen, SelectLine, SelectionString, SemanticClick},
screen_set::Key as ScreenKey,
selection::Selection,
terminal::{
MouseEvents,
MouseFormat,
MouseShiftCapture as TerminalShiftCapture,
ScrollViewport,
Terminal,
},
}; };
use ghostty_termio::message::Message as IoMessage; use ghostty_termio::message::Message as IoMessage;
use ghostty_vt::modes::Mode; use ghostty_vt::modes::Mode;
@@ -2239,10 +2255,11 @@ impl Drop for RenderOnDrop<'_> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use ghostty_renderer::size::{CellSize, Padding, ScreenSize}; use ghostty_renderer::size::{CellSize, Padding, ScreenSize};
use ghostty_terminal::screen::Options as ScreenOptions; use ghostty_terminal::screen::Options as ScreenOptions;
use super::*;
/// Our screen size is 10x5 cells that are 10x20 px, with 5px padding on /// Our screen size is 10x5 cells that are 10x20 px, with 5px padding on
/// all sides. /// all sides.
fn test_size() -> Size { fn test_size() -> Size {
+24 -15
View File
@@ -8,24 +8,33 @@
//! answering pending clipboard reads) while polling for conditions. //! answering pending clipboard reads) while polling for conditions.
#![allow(dead_code, clippy::unwrap_used, clippy::expect_used)] #![allow(dead_code, clippy::unwrap_used, clippy::expect_used)]
use std::cell::{Cell, RefCell}; use std::{
use std::collections::{HashMap, VecDeque}; cell::{Cell, RefCell},
use std::path::PathBuf; collections::{HashMap, VecDeque},
use std::rc::Rc; path::PathBuf,
use std::sync::Arc; rc::Rc,
use std::sync::atomic::{AtomicU64, Ordering}; sync::{
use std::time::{Duration, Instant}; Arc,
atomic::{AtomicU64, Ordering},
use ghostty_apprt::action::{Action, Target}; },
use ghostty_apprt::runtime_api::{ time::{Duration, Instant},
ClipboardError, CoreApp, InputEffect, RtApp, RtSurface, SurfaceId, Waker,
}; };
use ghostty_apprt::structs::{Clipboard, ClipboardRequest, ContentScale, CursorPos, SurfaceSize};
use ghostty_config::command::Command; use ghostty_apprt::{
use ghostty_config::config::Config; action::{Action, Target},
runtime_api::{ClipboardError, CoreApp, InputEffect, RtApp, RtSurface, SurfaceId, Waker},
structs::{Clipboard, ClipboardRequest, ContentScale, CursorPos, SurfaceSize},
};
use ghostty_config::{command::Command, config::Config};
use ghostty_core::{App, Surface}; use ghostty_core::{App, Surface};
use ghostty_input::{ use ghostty_input::{
Key, KeyEvent, Mods, MouseButton, MouseButtonState, ScrollMods, key::Action as KeyAction, Key,
KeyEvent,
Mods,
MouseButton,
MouseButtonState,
ScrollMods,
key::Action as KeyAction,
}; };
use ghostty_renderer::headless::Headless; use ghostty_renderer::headless::Headless;
+4 -2
View File
@@ -6,8 +6,10 @@ use std::fmt::Write as _;
mod common; mod common;
use common::*; use common::*;
use ghostty_apprt::action::{Action, GotoSplit, SplitDirection}; use ghostty_apprt::{
use ghostty_apprt::structs::Clipboard; action::{Action, GotoSplit, SplitDirection},
structs::Clipboard,
};
use ghostty_input::Key; use ghostty_input::Key;
#[test] #[test]
+1 -2
View File
@@ -5,8 +5,7 @@
mod common; mod common;
use common::*; use common::*;
use ghostty_apprt::action::Action; use ghostty_apprt::{action::Action, structs::Clipboard};
use ghostty_apprt::structs::Clipboard;
use ghostty_input::{Key, MouseButton}; use ghostty_input::{Key, MouseButton};
const L: MouseButton = MouseButton::Left; const L: MouseButton = MouseButton::Left;
+4 -2
View File
@@ -5,8 +5,10 @@
mod common; mod common;
use common::*; use common::*;
use ghostty_apprt::action::Action; use ghostty_apprt::{
use ghostty_apprt::structs::{Clipboard, SurfaceSize}; action::Action,
structs::{Clipboard, SurfaceSize},
};
use ghostty_input::Key; use ghostty_input::Key;
use ghostty_vt::osc::ProgressState; use ghostty_vt::osc::ProgressState;
@@ -1,9 +1,11 @@
//! Blocking queue implementation aimed primarily for message passing //! Blocking queue implementation aimed primarily for message passing
//! between threads (`blocking_queue.zig`). //! between threads (`blocking_queue.zig`).
use std::collections::VecDeque; use std::{
use std::sync::{Condvar, Mutex, MutexGuard, PoisonError}; collections::VecDeque,
use std::time::Duration; sync::{Condvar, Mutex, MutexGuard, PoisonError},
time::Duration,
};
/// The type we use for queue size types. /// The type we use for queue size types.
pub type Size = u32; pub type Size = u32;
@@ -179,9 +181,9 @@ impl<T, const CAPACITY: usize> Drop for DrainIterator<'_, T, CAPACITY> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::{sync::Arc, thread};
use super::*; use super::*;
use std::sync::Arc;
use std::thread;
#[test] #[test]
fn basic_push_and_pop() { fn basic_push_and_pop() {
+4 -2
View File
@@ -4,8 +4,10 @@
//! allocated entries; here the entries live in a slab and are linked by //! allocated entries; here the entries live in a slab and are linked by
//! index. //! index.
use std::collections::HashMap as StdHashMap; use std::{
use std::hash::{BuildHasher, Hash, RandomState}; collections::HashMap as StdHashMap,
hash::{BuildHasher, Hash, RandomState},
};
/// Create a HashMap for a key type that can be automatically hashed. /// Create a HashMap for a key type that can be automatically hashed.
/// If you want finer-grained control, use [`HashMap`] directly. /// If you want finer-grained control, use [`HashMap`] directly.
+2 -1
View File
@@ -20,9 +20,10 @@
//! parameters / `Allocator.Error`), the arena is replaced by a `Vec`, and the //! parameters / `Allocator.Error`), the arena is replaced by a `Vec`, and the
//! GObject boxed-type glue (`getGObjectType`) is left to the GTK crate. //! GObject boxed-type glue (`getGObjectType`) is left to the GTK crate.
use half::f16;
use std::fmt; use std::fmt;
use half::f16;
/// The requirements on the view type stored in a [`SplitTree`]. /// The requirements on the view type stored in a [`SplitTree`].
pub trait SplitTreeView: Clone { pub trait SplitTreeView: Clone {
/// Return a label that is used for the debug view. If this returns /// Return a label that is used for the debug view. If this returns
+4 -2
View File
@@ -14,8 +14,10 @@
//! that regions written INTO the atlas do not have to be square, only //! that regions written INTO the atlas do not have to be square, only
//! the full atlas texture itself. //! the full atlas texture itself.
use std::io::Write; use std::{
use std::sync::atomic::{AtomicUsize, Ordering}; io::Write,
sync::atomic::{AtomicUsize, Ordering},
};
/// The format of the texture data being written into the Atlas. This must be /// The format of the texture data being written into the Atlas. This must be
/// uniform for all textures in the Atlas. If you have some textures with /// uniform for all textures in the Atlas. If you have some textures with
+3 -3
View File
@@ -7,13 +7,13 @@
//! The canonical definition lives in `ghostty-config` (the `font-codepoint-map` //! The canonical definition lives in `ghostty-config` (the `font-codepoint-map`
//! option parses straight into it); it is re-exported here. //! option parses straight into it); it is re-exported here.
pub use ghostty_config::font_types::CodepointMap; pub use ghostty_config::font_types::{CodepointMap, CodepointMapEntry as Entry};
pub use ghostty_config::font_types::CodepointMapEntry as Entry;
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use ghostty_config::font_types::Descriptor; use ghostty_config::font_types::Descriptor;
use super::*;
fn desc(family: &str) -> Descriptor { fn desc(family: &str) -> Descriptor {
Descriptor { Descriptor {
family: Some(family.to_string()), family: Some(family.to_string()),
+18 -9
View File
@@ -10,13 +10,18 @@
use std::collections::HashMap; use std::collections::HashMap;
use crate::collection::{ use crate::{
AddOptions, Collection, Entry, GetFaceError, Index, PresentationMode, Special, Atlas,
CodepointMap,
Glyph,
Presentation,
SpriteFace,
Style,
collection::{AddOptions, Collection, Entry, GetFaceError, Index, PresentationMode, Special},
discovery::Discover,
face::{RenderOptions, freetype::RenderError as FaceRenderError},
sprite,
}; };
use crate::discovery::Discover;
use crate::face::{RenderOptions, freetype::RenderError as FaceRenderError};
use crate::sprite;
use crate::{Atlas, CodepointMap, Glyph, Presentation, SpriteFace, Style};
/// Packed array of booleans to indicate if a style is enabled or not. /// Packed array of booleans to indicate if a style is enabled or not.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -449,9 +454,13 @@ impl CodepointResolver {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::collection::{LoadOptions, SizeAdjustment}; use crate::{
use crate::face::{DesiredSize, Options}; Face,
use crate::{Face, Library, embedded}; Library,
collection::{LoadOptions, SizeAdjustment},
embedded,
face::{DesiredSize, Options},
};
fn add(c: &mut Collection, lib: &Library, data: &'static [u8], style: Style, pts: f32) { fn add(c: &mut Collection, lib: &Library, data: &'static [u8], style: Style, pts: f32) {
let size = if pts == 12.0 { let size = if pts == 12.0 {
+15 -6
View File
@@ -16,10 +16,17 @@
#![allow(clippy::collapsible_if, clippy::if_not_else, clippy::float_cmp)] #![allow(clippy::collapsible_if, clippy::if_not_else, clippy::float_cmp)]
use crate::config_types::{FontSyntheticStyle, FreetypeLoadFlags}; use crate::{
use crate::face::{self, DesiredSize}; DeferredFace,
use crate::metrics::{FaceMetrics, ModifierSet}; Face,
use crate::{DeferredFace, Face, Library, Metrics, Presentation, Style}; Library,
Metrics,
Presentation,
Style,
config_types::{FontSyntheticStyle, FreetypeLoadFlags},
face::{self, DesiredSize},
metrics::{FaceMetrics, ModifierSet},
};
/// The available faces we have. This shouldn't be modified manually. /// The available faces we have. This shouldn't be modified manually.
/// Instead, use the functions available on Collection. /// Instead, use the functions available on Collection.
@@ -1016,8 +1023,10 @@ impl Index {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::embedded; use crate::{
use crate::face::{DesiredSize, Options}; embedded,
face::{DesiredSize, Options},
};
fn opts_96(points: f32) -> Options { fn opts_96(points: f32) -> Options {
Options::new(DesiredSize { Options::new(DesiredSize {
+4 -2
View File
@@ -1,5 +1,7 @@
//! The config types consumed by the font engine. The canonical definitions //! The config types consumed by the font engine. The canonical definitions
//! live in `ghostty-config`; they are re-exported here for convenience. //! live in `ghostty-config`; they are re-exported here for convenience.
pub use ghostty_config::types_a::{FontShapingBreak, FontStyle, FontSyntheticStyle}; pub use ghostty_config::{
pub use ghostty_config::types_b::{FreetypeLoadFlags, GraphemeWidthMethod}; types_a::{FontShapingBreak, FontStyle, FontSyntheticStyle},
types_b::{FreetypeLoadFlags, GraphemeWidthMethod},
};
+7 -3
View File
@@ -7,9 +7,13 @@
//! //!
//! Port of `font/DeferredFace.zig` (fontconfig variant only). //! Port of `font/DeferredFace.zig` (fontconfig variant only).
use crate::face::{self, Options, Variation}; use crate::{
use crate::fontconfig as fc; Face,
use crate::{Face, Library, Presentation}; Library,
Presentation,
face::{self, Options, Variation},
fontconfig as fc,
};
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum LoadError { pub enum LoadError {
+6 -4
View File
@@ -3,10 +3,12 @@
use std::sync::Arc; use std::sync::Arc;
use crate::collection::Collection; use crate::{
use crate::deferred_face::{DeferredFace, Fontconfig as DeferredFontconfig}; collection::Collection,
use crate::face::Variation; deferred_face::{DeferredFace, Fontconfig as DeferredFontconfig},
use crate::fontconfig as fc; face::Variation,
fontconfig as fc,
};
/// Discover implementation for the compile options. /// Discover implementation for the compile options.
pub type Discover = Fontconfig; pub type Discover = Fontconfig;
+10 -6
View File
@@ -6,14 +6,18 @@
//! //!
//! Port of `font/face/freetype.zig`. //! Port of `font/face/freetype.zig`.
use std::ffi::CString; use std::{
use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; ffi::CString,
sync::{Arc, Mutex, MutexGuard, PoisonError},
};
use super::{DesiredSize, FontData, FreetypeLoadFlags, Options, RenderOptions, Variation}; use super::{DesiredSize, FontData, FreetypeLoadFlags, Options, RenderOptions, Variation};
use crate::atlas::{self, Atlas}; use crate::{
use crate::glyph::Glyph; atlas::{self, Atlas},
use crate::library::Library; glyph::Glyph,
use crate::metrics::FaceMetrics; library::Library,
metrics::FaceMetrics,
};
pub(crate) mod ft; pub(crate) mod ft;
mod resize; mod resize;
+4 -2
View File
@@ -8,8 +8,10 @@
// c_long is i64 on Linux but not everywhere; keep the casts portable. // c_long is i64 on Linux but not everywhere; keep the casts portable.
#![allow(clippy::unnecessary_cast)] #![allow(clippy::unnecessary_cast)]
use std::ffi::{CStr, c_int, c_long, c_uint, c_ulong, c_void}; use std::{
use std::ptr::{self, NonNull}; ffi::{CStr, c_int, c_long, c_uint, c_ulong, c_void},
ptr::{self, NonNull},
};
use freetype_sys as sys; use freetype_sys as sys;
+5 -3
View File
@@ -4,9 +4,11 @@
//! All raw FFI is confined to this module. //! All raw FFI is confined to this module.
#![allow(unsafe_code)] #![allow(unsafe_code)]
use std::ffi::{CStr, CString, c_int}; use std::{
use std::ptr::{self, NonNull}; ffi::{CStr, CString, c_int},
use std::sync::Arc; ptr::{self, NonNull},
sync::Arc,
};
use fontconfig_sys as sys; use fontconfig_sys as sys;
use fontconfig_sys::constants as fc; use fontconfig_sys::constants as fc;
-2
View File
@@ -29,7 +29,6 @@ pub mod sprite;
pub use atlas::Atlas; pub use atlas::Atlas;
pub use backend::{Backend, OPTIONS as options}; pub use backend::{Backend, OPTIONS as options};
pub use codepoint_map::CodepointMap; pub use codepoint_map::CodepointMap;
pub use codepoint_resolver::CodepointResolver; pub use codepoint_resolver::CodepointResolver;
pub use collection::Collection; pub use collection::Collection;
@@ -39,7 +38,6 @@ pub use face::Face;
pub use glyph::Glyph; pub use glyph::Glyph;
pub use library::Library; pub use library::Library;
pub use metrics::Metrics; pub use metrics::Metrics;
pub use shared_grid::SharedGrid; pub use shared_grid::SharedGrid;
pub use shared_grid_set::SharedGridSet; pub use shared_grid_set::SharedGridSet;
pub use sprite::{Face as SpriteFace, Sprite}; pub use sprite::{Face as SpriteFace, Sprite};
+1 -2
View File
@@ -1,7 +1,6 @@
//! Font metrics for the terminal grid. Port of `font/Metrics.zig`. //! Font metrics for the terminal grid. Port of `font/Metrics.zig`.
use std::collections::HashMap; use std::{collections::HashMap, str::FromStr};
use std::str::FromStr;
/// Metrics describing the terminal grid cell for a font. /// Metrics describing the terminal grid cell for a font.
#[derive(Debug, Clone, Copy, PartialEq)] #[derive(Debug, Clone, Copy, PartialEq)]
+2 -4
View File
@@ -6,8 +6,7 @@
//! Field names are in camelCase to match names in the spec. //! Field names are in camelCase to match names in the spec.
#![allow(non_snake_case)] #![allow(non_snake_case)]
use super::sfnt::Fixed; use super::{EndOfStream, Reader, sfnt::Fixed};
use super::{EndOfStream, Reader};
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Head { pub struct Head {
@@ -81,8 +80,7 @@ impl Head {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::embedded; use crate::{embedded, opentype::sfnt::Sfnt};
use crate::opentype::sfnt::Sfnt;
#[test] #[test]
fn head() { fn head() {
+1 -2
View File
@@ -70,8 +70,7 @@ impl Hhea {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::embedded; use crate::{embedded, opentype::sfnt::Sfnt};
use crate::opentype::sfnt::Sfnt;
#[test] #[test]
fn hhea() { fn hhea() {
+1 -2
View File
@@ -212,8 +212,7 @@ impl OS2 {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::embedded; use crate::{embedded, opentype::sfnt::Sfnt};
use crate::opentype::sfnt::Sfnt;
#[test] #[test]
fn os_2() { fn os_2() {
+6 -4
View File
@@ -4,8 +4,11 @@
//! - https://learn.microsoft.com/en-us/typography/opentype/spec/post //! - https://learn.microsoft.com/en-us/typography/opentype/spec/post
#![allow(non_snake_case)] #![allow(non_snake_case)]
use super::sfnt::{Fixed, Version16Dot16}; use super::{
use super::{EndOfStream, Reader}; EndOfStream,
Reader,
sfnt::{Fixed, Version16Dot16},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Post { pub struct Post {
@@ -44,8 +47,7 @@ impl Post {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::embedded; use crate::{embedded, opentype::sfnt::Sfnt};
use crate::opentype::sfnt::Sfnt;
#[test] #[test]
fn post() { fn post() {
+1 -2
View File
@@ -119,8 +119,7 @@ impl<'a> SVG<'a> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::embedded; use crate::{embedded, opentype::sfnt::Sfnt};
use crate::opentype::sfnt::Sfnt;
// NOTE: the Zig test obtains the table through `Face.copyTable`; we read // NOTE: the Zig test obtains the table through `Face.copyTable`; we read
// the same bytes through the SFNT directory (Face-based variant lives // the same bytes through the SFNT directory (Face-based variant lives
+7 -5
View File
@@ -3,14 +3,16 @@
//! The shaper implementation for the Linux backend is HarfBuzz //! The shaper implementation for the Linux backend is HarfBuzz
//! ([`crate::shaper::harfbuzz::Shaper`]). //! ([`crate::shaper::harfbuzz::Shaper`]).
pub use crate::shaper::cache::Cache;
pub use crate::shaper::feature::{DEFAULT_FEATURES, Feature, FeatureList};
pub use crate::shaper::run::{RunIterator, RunIteratorHook, RunOptions, TextRun};
pub use crate::shaper::{harfbuzz, noop};
/// Shaper implementation for our compile options (backend /// Shaper implementation for our compile options (backend
/// `fontconfig_freetype` => HarfBuzz). /// `fontconfig_freetype` => HarfBuzz).
pub use crate::shaper::harfbuzz::Shaper; pub use crate::shaper::harfbuzz::Shaper;
pub use crate::shaper::{
cache::Cache,
feature::{DEFAULT_FEATURES, Feature, FeatureList},
harfbuzz,
noop,
run::{RunIterator, RunIteratorHook, RunOptions, TextRun},
};
/// A cell is a single single within a terminal that should be rendered /// A cell is a single single within a terminal that should be rendered
/// for a shaping call. Note all terminal cells may be present; only /// for a shaping call. Note all terminal cells may be present; only
+20 -9
View File
@@ -11,9 +11,11 @@
//! prepare/add/finalize/shape sequence. //! prepare/add/finalize/shape sequence.
use super::hb; use super::hb;
use crate::face::freetype::Face; use crate::{
use crate::shape::{self, Cell, DEFAULT_FEATURES, FeatureList, TextRun}; face::freetype::Face,
use crate::shared_grid::SharedGrid; shape::{self, Cell, DEFAULT_FEATURES, FeatureList, TextRun},
shared_grid::SharedGrid,
};
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum ShapeError { pub enum ShapeError {
@@ -297,13 +299,22 @@ impl Shaper {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::face::{DesiredSize, FontData, Options}; use crate::{
use crate::shaper::run::{RunIterator, RunOptions}; Library,
use crate::shaper::test_util::{ embedded,
Term, TestFont, shape_all, test_shaper, test_shaper_with_discovered_font, face::{DesiredSize, FontData, Options},
test_shaper_with_font, shaper::{
run::{RunIterator, RunOptions},
test_util::{
Term,
TestFont,
shape_all,
test_shaper,
test_shaper_with_discovered_font,
test_shaper_with_font,
},
},
}; };
use crate::{Library, embedded};
fn text(s: &str) -> Vec<(u32, u32)> { fn text(s: &str) -> Vec<(u32, u32)> {
s.chars() s.chars()
+4 -2
View File
@@ -2,8 +2,10 @@
//! Each individual codepoint is mapped directly to the detected text run //! Each individual codepoint is mapped directly to the detected text run
//! font's glyph index. //! font's glyph index.
use crate::face::freetype::Face; use crate::{
use crate::shape::{self, Cell}; face::freetype::Face,
shape::{self, Cell},
};
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
struct Codepoint { struct Codepoint {
+10 -5
View File
@@ -12,12 +12,17 @@
use std::hash::{DefaultHasher, Hash, Hasher}; use std::hash::{DefaultHasher, Hash, Hasher};
use ghostty_config::types_a::FontShapingBreak; use ghostty_config::types_a::FontShapingBreak;
use ghostty_terminal::page::{Cell, ContentTag, Page, Wide}; use ghostty_terminal::{
use ghostty_terminal::style::{Color, Style as TermStyle}; page::{Cell, ContentTag, Page, Wide},
style::{Color, Style as TermStyle},
};
use crate::collection::Index; use crate::{
use crate::shared_grid::{Error as GridError, SharedGrid}; Presentation,
use crate::{Presentation, Style}; Style,
collection::Index,
shared_grid::{Error as GridError, SharedGrid},
};
/// The Kitty graphics unicode placeholder codepoint /// The Kitty graphics unicode placeholder codepoint
/// (`terminal.kitty.graphics.unicode.placeholder`). /// (`terminal.kitty.graphics.unicode.placeholder`).
+22 -12
View File
@@ -9,19 +9,29 @@
#![allow(clippy::collapsible_if)] #![allow(clippy::collapsible_if)]
use ghostty_terminal::page::Cell; use ghostty_terminal::{
use ghostty_terminal::point::{Coordinate, Point}; page::Cell,
use ghostty_terminal::screen::{Options, Screen}; point::{Coordinate, Point},
use ghostty_vt::color::Rgb; screen::{Options, Screen},
use ghostty_vt::sgr::Attribute; };
use ghostty_vt::{color::Rgb, sgr::Attribute};
use crate::codepoint_resolver::CodepointResolver; use crate::{
use crate::collection::{AddOptions, Collection, LoadOptions, SizeAdjustment}; Face,
use crate::discovery::{Descriptor, Fontconfig}; Library,
use crate::face::{DesiredSize, FontData, Options as FaceOptions}; SharedGrid,
use crate::shaper::harfbuzz::Shaper; Style,
use crate::shaper::run::{RunCell, RunIterator, RunOptions}; codepoint_resolver::CodepointResolver,
use crate::{Face, Library, SharedGrid, Style, embedded, shape}; collection::{AddOptions, Collection, LoadOptions, SizeAdjustment},
discovery::{Descriptor, Fontconfig},
embedded,
face::{DesiredSize, FontData, Options as FaceOptions},
shape,
shaper::{
harfbuzz::Shaper,
run::{RunCell, RunIterator, RunOptions},
},
};
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub(crate) enum TestFont { pub(crate) enum TestFont {
+22 -10
View File
@@ -19,14 +19,22 @@
#![allow(clippy::collapsible_if, clippy::if_not_else, clippy::float_cmp)] #![allow(clippy::collapsible_if, clippy::if_not_else, clippy::float_cmp)]
use std::collections::HashMap; use std::{
use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard}; collections::HashMap,
sync::{RwLock, RwLockReadGuard, RwLockWriteGuard},
};
use crate::atlas::{self, Atlas}; use crate::{
use crate::codepoint_resolver::{CodepointResolver, RenderGlyphError}; Glyph,
use crate::collection::{self, Collection, GetFaceError, Index, PresentationMode}; Metrics,
use crate::face::{Constraint, ConstraintSize, RenderOptions}; Presentation,
use crate::{Glyph, Metrics, Presentation, SpriteFace, Style}; SpriteFace,
Style,
atlas::{self, Atlas},
codepoint_resolver::{CodepointResolver, RenderGlyphError},
collection::{self, Collection, GetFaceError, Index, PresentationMode},
face::{Constraint, ConstraintSize, RenderOptions},
};
/// The size of a grid cell in pixels. /// The size of a grid cell in pixels.
// TODO(integration): replace with `renderer::CellSize` once the renderer // TODO(integration): replace with `renderer::CellSize` once the renderer
@@ -386,9 +394,13 @@ impl State {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::collection::{AddOptions, LoadOptions, SizeAdjustment}; use crate::{
use crate::face::{DesiredSize, Options}; Face,
use crate::{Face, Library, embedded}; Library,
collection::{AddOptions, LoadOptions, SizeAdjustment},
embedded,
face::{DesiredSize, Options},
};
fn test_grid(lib: &Library) -> SharedGrid { fn test_grid(lib: &Library) -> SharedGrid {
let mut c = Collection::new(); let mut c = Collection::new();
+30 -20
View File
@@ -8,28 +8,38 @@
//! This structure is thread-safe when the operations are documented //! This structure is thread-safe when the operations are documented
//! as thread-safe. //! as thread-safe.
use std::collections::HashMap; use std::{
use std::hash::{DefaultHasher, Hash, Hasher}; collections::HashMap,
use std::sync::{Arc, Mutex, MutexGuard}; hash::{DefaultHasher, Hash, Hasher},
sync::{Arc, Mutex, MutexGuard},
use ghostty_config::config::Config;
use ghostty_config::font_types::Variation;
use ghostty_config::font_types::VariationId;
use ghostty_config::types_a::{
FontStyle, FontSyntheticStyle, RepeatableCodepointMap, RepeatableFontVariation,
RepeatableString,
}; };
use ghostty_config::types_b::FreetypeLoadFlags;
use crate::codepoint_map::CodepointMap; use ghostty_config::{
use crate::codepoint_resolver::{CodepointResolver, StyleStatus}; config::Config,
use crate::collection::{self, AddOptions, Collection, LoadOptions, SizeAdjustment}; font_types::{Variation, VariationId},
use crate::discovery::{Descriptor, Discover, Fontconfig}; types_a::{
use crate::face::{self, DesiredSize, FontData}; FontStyle,
use crate::library::{Library, LibraryError}; FontSyntheticStyle,
use crate::metrics::{Key as MetricsKey, Modifier, ModifierSet}; RepeatableCodepointMap,
use crate::shared_grid::{self, SharedGrid}; RepeatableFontVariation,
use crate::{Face, Style, embedded}; RepeatableString,
},
types_b::FreetypeLoadFlags,
};
use crate::{
Face,
Style,
codepoint_map::CodepointMap,
codepoint_resolver::{CodepointResolver, StyleStatus},
collection::{self, AddOptions, Collection, LoadOptions, SizeAdjustment},
discovery::{Descriptor, Discover, Fontconfig},
embedded,
face::{self, DesiredSize, FontData},
library::{Library, LibraryError},
metrics::{Key as MetricsKey, Modifier, ModifierSet},
shared_grid::{self, SharedGrid},
};
/// Errors from [`SharedGridSet::ref_`]. /// Errors from [`SharedGridSet::ref_`].
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
+20 -4
View File
@@ -7,11 +7,27 @@
//! Port of `sprite/draw/block.zig`. //! Port of `sprite/draw/block.zig`.
use super::common::{ use super::common::{
Alignment, DrawFn, FIVE_EIGHTHS, Fraction, HALF, HAlign, ONE_EIGHTH, ONE_QUARTER, Quads, Range, Alignment,
SEVEN_EIGHTHS, Shade, THREE_EIGHTHS, THREE_QUARTERS, VAlign, fill, DrawFn,
FIVE_EIGHTHS,
Fraction,
HALF,
HAlign,
ONE_EIGHTH,
ONE_QUARTER,
Quads,
Range,
SEVEN_EIGHTHS,
Shade,
THREE_EIGHTHS,
THREE_QUARTERS,
VAlign,
fill,
};
use crate::{
metrics::Metrics,
sprite::canvas::{Canvas, Color, DrawError, Rect},
}; };
use crate::metrics::Metrics;
use crate::sprite::canvas::{Canvas, Color, DrawError, Rect};
pub const RANGES: &[Range] = &[Range { pub const RANGES: &[Range] = &[Range {
min: 0x2580, min: 0x2580,
+4 -2
View File
@@ -15,8 +15,10 @@
#![allow(clippy::needless_update)] #![allow(clippy::needless_update)]
use super::common::{Corner, DrawFn, Range, Thickness, hline, hline_middle, vline, vline_middle}; use super::common::{Corner, DrawFn, Range, Thickness, hline, hline_middle, vline, vline_middle};
use crate::metrics::Metrics; use crate::{
use crate::sprite::canvas::{Canvas, CapMode, Color, DrawError, Line, Path, Point, StrokeOptions}; metrics::Metrics,
sprite::canvas::{Canvas, CapMode, Color, DrawError, Line, Path, Point, StrokeOptions},
};
pub const RANGES: &[Range] = &[Range { pub const RANGES: &[Range] = &[Range {
min: 0x2500, min: 0x2500,
@@ -24,8 +24,10 @@
//! Port of `sprite/draw/braille.zig`. //! Port of `sprite/draw/braille.zig`.
use super::common::{DrawFn, Range}; use super::common::{DrawFn, Range};
use crate::metrics::Metrics; use crate::{
use crate::sprite::canvas::{Canvas, Color, DrawError}; metrics::Metrics,
sprite::canvas::{Canvas, Color, DrawError},
};
pub const RANGES: &[Range] = &[Range { pub const RANGES: &[Range] = &[Range {
min: 0x2800, min: 0x2800,
@@ -14,10 +14,14 @@
use std::f64::consts::PI; use std::f64::consts::PI;
use super::box_; use super::{
use super::common::{Corner, DrawFn, Edge, Range, Shade, Thickness, hline_middle, vline_middle}; box_,
use crate::metrics::Metrics; common::{Corner, DrawFn, Edge, Range, Shade, Thickness, hline_middle, vline_middle},
use crate::sprite::canvas::{Canvas, CapMode, Color, DrawError, Path, StrokeOptions}; };
use crate::{
metrics::Metrics,
sprite::canvas::{Canvas, CapMode, Color, DrawError, Path, StrokeOptions},
};
pub const RANGES: &[Range] = &[Range { pub const RANGES: &[Range] = &[Range {
min: 0xf5d0, min: 0xf5d0,
@@ -3,8 +3,10 @@
//! are generally applicable to multiple sets of glyphs //! are generally applicable to multiple sets of glyphs
//! rather than being single-use. Port of `sprite/draw/common.zig`. //! rather than being single-use. Port of `sprite/draw/common.zig`.
use crate::metrics::Metrics; use crate::{
use crate::sprite::canvas::{Canvas, Color, DrawError}; metrics::Metrics,
sprite::canvas::{Canvas, Color, DrawError},
};
/// A function that draws a glyph on the provided canvas. /// A function that draws a glyph on the provided canvas.
pub type DrawFn = fn( pub type DrawFn = fn(
@@ -14,8 +14,10 @@
//! Port of `sprite/draw/geometric_shapes.zig`. //! Port of `sprite/draw/geometric_shapes.zig`.
use super::common::{Corner, DrawFn, Range, Shade, Thickness}; use super::common::{Corner, DrawFn, Range, Shade, Thickness};
use crate::metrics::Metrics; use crate::{
use crate::sprite::canvas::{Canvas, CapMode, Color, DrawError, Path, StrokeOptions}; metrics::Metrics,
sprite::canvas::{Canvas, CapMode, Color, DrawError, Path, StrokeOptions},
};
pub const RANGES: &[Range] = &[ pub const RANGES: &[Range] = &[
Range { Range {
@@ -11,11 +11,13 @@
use std::f64::consts::SQRT_2; use std::f64::consts::SQRT_2;
use super::box_; use super::{
use super::common::{DrawFn, Range, Thickness}; box_,
use crate::metrics::Metrics; common::{DrawFn, Range, Thickness},
use crate::sprite::canvas::{ };
Canvas, CapMode, Color, DrawError, Path, Point, StrokeOptions, Triangle, use crate::{
metrics::Metrics,
sprite::canvas::{Canvas, CapMode, Color, DrawError, Path, Point, StrokeOptions, Triangle},
}; };
pub const RANGES: &[Range] = &[ pub const RANGES: &[Range] = &[
@@ -6,8 +6,10 @@
use std::f64::consts::{FRAC_1_SQRT_2, PI, TAU}; use std::f64::consts::{FRAC_1_SQRT_2, PI, TAU};
use crate::metrics::Metrics; use crate::{
use crate::sprite::canvas::{Canvas, CapMode, Color, DrawError, Path, Rect, StrokeOptions}; metrics::Metrics,
sprite::canvas::{Canvas, CapMode, Color, DrawError, Path, Rect, StrokeOptions},
};
pub fn underline( pub fn underline(
_cp: u32, _cp: u32,
@@ -3,16 +3,38 @@
//! //!
//! Port of `sprite/draw/symbols_for_legacy_computing.zig`. //! Port of `sprite/draw/symbols_for_legacy_computing.zig`.
use super::block; use super::{
use super::box_; block,
use super::common::{ box_,
Alignment, Corner, DrawFn, Edge, FIVE_EIGHTHS, Fraction, HALF, HAlign, ONE_EIGHTH, ONE_QUARTER, common::{
ONE_THIRD, Quads, Range, SEVEN_EIGHTHS, Shade, THREE_EIGHTHS, THREE_QUARTERS, TWO_THIRDS, Alignment,
Thickness, VAlign, fill, Corner,
DrawFn,
Edge,
FIVE_EIGHTHS,
Fraction,
HALF,
HAlign,
ONE_EIGHTH,
ONE_QUARTER,
ONE_THIRD,
Quads,
Range,
SEVEN_EIGHTHS,
Shade,
THREE_EIGHTHS,
THREE_QUARTERS,
TWO_THIRDS,
Thickness,
VAlign,
fill,
},
geometric_shapes as geo,
};
use crate::{
metrics::Metrics,
sprite::canvas::{Canvas, Color, DrawError, Line, Path, Point, Rect, StrokeOptions},
}; };
use super::geometric_shapes as geo;
use crate::metrics::Metrics;
use crate::sprite::canvas::{Canvas, Color, DrawError, Line, Path, Point, Rect, StrokeOptions};
const _: (f64, f64) = (ONE_THIRD, TWO_THIRDS); const _: (f64, f64) = (ONE_THIRD, TWO_THIRDS);
@@ -5,11 +5,15 @@
use std::sync::OnceLock; use std::sync::OnceLock;
use super::box_::{self, Lines, Style}; use super::{
use super::common::{Alignment, Corner, DrawFn, Fraction, Range, fill}; box_::{self, Lines, Style},
use super::symbols_for_legacy_computing as sflc; common::{Alignment, Corner, DrawFn, Fraction, Range, fill},
use crate::metrics::Metrics; symbols_for_legacy_computing as sflc,
use crate::sprite::canvas::{Canvas, CapMode, Color, DrawError, Path, StrokeOptions}; };
use crate::{
metrics::Metrics,
sprite::canvas::{Canvas, CapMode, Color, DrawError, Path, StrokeOptions},
};
pub const RANGES: &[Range] = &[ pub const RANGES: &[Range] = &[
Range { Range {
+21 -12
View File
@@ -15,19 +15,28 @@
use std::sync::OnceLock; use std::sync::OnceLock;
use super::Sprite; use super::{
use super::canvas::{Canvas, DrawError}; Sprite,
use super::draw::common::{DrawFn, Range}; canvas::{Canvas, DrawError},
use super::draw::{ draw::{
block, box_, braille, branch, geometric_shapes, powerline, special, block,
symbols_for_legacy_computing, symbols_for_legacy_computing_supplement, box_,
braille,
branch,
common::{DrawFn, Range},
geometric_shapes,
powerline,
special,
symbols_for_legacy_computing,
symbols_for_legacy_computing_supplement,
},
};
pub use crate::{Presentation, face::RenderOptions};
use crate::{
atlas::{self, Atlas},
glyph::Glyph,
metrics::Metrics,
}; };
use crate::atlas::{self, Atlas};
use crate::glyph::Glyph;
use crate::metrics::Metrics;
pub use crate::Presentation;
pub use crate::face::RenderOptions;
/// Errors from [`Face::render_glyph`]. /// Errors from [`Face::render_glyph`].
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+4 -2
View File
@@ -3,8 +3,10 @@
#![allow(clippy::needless_raw_string_hashes)] #![allow(clippy::needless_raw_string_hashes)]
use std::fmt; use std::{
use std::hash::{Hash, Hasher}; fmt,
hash::{Hash, Hasher},
};
use super::Error; use super::Error;
+27 -8
View File
@@ -4,19 +4,38 @@
pub mod action; pub mod action;
pub mod set; pub mod set;
use std::collections::hash_map::DefaultHasher; use std::{
use std::fmt; collections::hash_map::DefaultHasher,
use std::hash::{Hash, Hasher}; fmt,
hash::{Hash, Hasher},
};
pub use action::{ pub use action::{
Action, ActionKey, AdjustSelection, CloseTabMode, CopyToClipboard, CrashThread, CursorKey, Action,
GotoWindow, InspectorMode, NavigateSearch, Scope, SplitDirection, SplitFocusDirection, ActionKey,
SplitResizeDirection, SplitResizeParameter, WriteScreen, WriteScreenAction, WriteScreenFormat, AdjustSelection,
CloseTabMode,
CopyToClipboard,
CrashThread,
CursorKey,
GotoWindow,
InspectorMode,
NavigateSearch,
Scope,
SplitDirection,
SplitFocusDirection,
SplitResizeDirection,
SplitResizeParameter,
WriteScreen,
WriteScreenAction,
WriteScreenFormat,
}; };
pub use set::Set; pub use set::Set;
use crate::key; use crate::{
use crate::key_mods::{self, Mods}; key,
key_mods::{self, Mods},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] #[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum Error { pub enum Error {
+8 -4
View File
@@ -1,9 +1,13 @@
#![allow(clippy::unwrap_used)] #![allow(clippy::unwrap_used)]
use super::set::{AppendChainError, EntryFormatter, Value}; use super::{
use super::*; set::{AppendChainError, EntryFormatter, Value},
use crate::key::{Key, KeyEvent}; *,
use crate::key_mods::Mods; };
use crate::{
key::{Key, KeyEvent},
key_mods::Mods,
};
fn uni(c: char) -> Trigger { fn uni(c: char) -> Trigger {
Trigger { Trigger {
+11 -2
View File
@@ -3,8 +3,17 @@
use std::sync::OnceLock; use std::sync::OnceLock;
use crate::binding::{ use crate::binding::{
Action, CloseTabMode, CopyToClipboard, GotoWindow, InspectorMode, NavigateSearch, Action,
SplitDirection, SplitFocusDirection, WriteScreen, WriteScreenAction, WriteScreenFormat, CloseTabMode,
CopyToClipboard,
GotoWindow,
InspectorMode,
NavigateSearch,
SplitDirection,
SplitFocusDirection,
WriteScreen,
WriteScreenAction,
WriteScreenFormat,
}; };
/// A command is a named binding action that can be executed from /// A command is a named binding action that can be executed from
+3 -1
View File
@@ -21,6 +21,8 @@ pub use key_mods::{Mods, RemapSet as KeyRemapSet};
pub use keyboard::Layout as KeyboardLayout; pub use keyboard::Layout as KeyboardLayout;
pub use link::Link; pub use link::Link;
pub use mouse::{ pub use mouse::{
Button as MouseButton, ButtonState as MouseButtonState, PressureStage as MousePressureStage, Button as MouseButton,
ButtonState as MouseButtonState,
PressureStage as MousePressureStage,
ScrollMods, ScrollMods,
}; };
+4 -4
View File
@@ -3,8 +3,7 @@
use std::sync::{Mutex, MutexGuard, PoisonError}; use std::sync::{Mutex, MutexGuard, PoisonError};
use dear_imgui_rs::{ConfigFlags, Context, FontSource, StbTrueTypeFontData, Ui}; use dear_imgui_rs::{ConfigFlags, Context, FontSource, StbTrueTypeFontData, Ui};
use ghostty_renderer::overlay::Feature; use ghostty_renderer::{overlay::Feature, state::InspectorHook};
use ghostty_renderer::state::InspectorHook;
use ghostty_terminal::terminal::Terminal; use ghostty_terminal::terminal::Terminal;
use crate::widgets; use crate::widgets;
@@ -111,13 +110,14 @@ impl InspectorHook for Shared {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use crate::widgets::surface::SurfaceInfo;
use ghostty_input::{Action, Key, KeyEvent}; use ghostty_input::{Action, Key, KeyEvent};
use ghostty_renderer::size::{CellSize, Padding, ScreenSize, Size}; use ghostty_renderer::size::{CellSize, Padding, ScreenSize, Size};
use ghostty_terminal::terminal::Options; use ghostty_terminal::terminal::Options;
use ghostty_vt::stream::Stream; use ghostty_vt::stream::Stream;
use super::*;
use crate::widgets::surface::SurfaceInfo;
fn surface_info() -> SurfaceInfo { fn surface_info() -> SurfaceInfo {
SurfaceInfo { SurfaceInfo {
size: Size { size: Size {
+1 -2
View File
@@ -3,8 +3,7 @@
use std::collections::VecDeque; use std::collections::VecDeque;
use dear_imgui_rs::{InputTextFlags, TableColumnFlags, TableColumnWidth, TableFlags, Ui}; use dear_imgui_rs::{InputTextFlags, TableColumnFlags, TableColumnWidth, TableFlags, Ui};
use ghostty_input::binding::Action as BindingAction; use ghostty_input::{Action, Key, KeyEvent, Mods, binding::Action as BindingAction};
use ghostty_input::{Action, Key, KeyEvent, Mods};
/// The maximum number of recorded events (Zig: the ring grows by doubling up /// The maximum number of recorded events (Zig: the ring grows by doubling up
/// to this capacity, after which the oldest event is dropped). /// to this capacity, after which the oldest event is dropped).
+1 -2
View File
@@ -1,8 +1,7 @@
//! Page inspector (ZIG/src/inspector/widgets/page.zig). //! Page inspector (ZIG/src/inspector/widgets/page.zig).
use dear_imgui_rs::{ChildFlags, TableColumnFlags, TableColumnWidth, TableFlags, Ui}; use dear_imgui_rs::{ChildFlags, TableColumnFlags, TableColumnWidth, TableFlags, Ui};
use ghostty_terminal::hyperlink::HyperlinkId; use ghostty_terminal::{hyperlink::HyperlinkId, page::Page};
use ghostty_terminal::page::Page;
use super::{help_marker, style}; use super::{help_marker, style};
use crate::units::to_kibi_bytes; use crate::units::to_kibi_bytes;
@@ -1,12 +1,20 @@
//! PageList inspector (ZIG/src/inspector/widgets/pagelist.zig). //! PageList inspector (ZIG/src/inspector/widgets/pagelist.zig).
use dear_imgui_rs::{ use dear_imgui_rs::{
ComboBoxHeight, ComboBoxOptions, ItemHoveredFlags, MouseButton, StyleColor, TableFlags, ComboBoxHeight,
TreeNodeFlags, Ui, ComboBoxOptions,
ItemHoveredFlags,
MouseButton,
StyleColor,
TableFlags,
TreeNodeFlags,
Ui,
};
use ghostty_terminal::{
page_list::{PageList, Scroll, Scrollbar},
point::{Coordinate, Point, Tag},
style::DEFAULT_ID,
}; };
use ghostty_terminal::page_list::{PageList, Scroll, Scrollbar};
use ghostty_terminal::point::{Coordinate, Point, Tag};
use ghostty_terminal::style::DEFAULT_ID;
use super::{help_marker, page, style}; use super::{help_marker, page, style};
use crate::units::to_kibi_bytes; use crate::units::to_kibi_bytes;
@@ -1,10 +1,12 @@
//! Screen information (ZIG/src/inspector/widgets/screen.zig). //! Screen information (ZIG/src/inspector/widgets/screen.zig).
use dear_imgui_rs::{DockNodeFlags, TableFlags, TreeNodeFlags, Ui, WindowFlags}; use dear_imgui_rs::{DockNodeFlags, TableFlags, TreeNodeFlags, Ui, WindowFlags};
use ghostty_terminal::kitty::graphics_storage::ImageStorage; use ghostty_terminal::{
use ghostty_terminal::screen::{Cursor, Screen, SemanticClick, SemanticPrompt}; kitty::graphics_storage::ImageStorage,
use ghostty_terminal::screen_set::Key as ScreenKey; screen::{Cursor, Screen, SemanticClick, SemanticPrompt},
use ghostty_terminal::style::Style; screen_set::Key as ScreenKey,
style::Style,
};
use ghostty_vt::color::{DynamicPalette, Palette}; use ghostty_vt::color::{DynamicPalette, Palette};
use super::{help_marker, pagelist, style as style_widget}; use super::{help_marker, pagelist, style as style_widget};
@@ -3,9 +3,11 @@
use dear_imgui_rs::{DockNodeFlags, TableFlags, TreeNodeFlags, Ui, WindowFlags}; use dear_imgui_rs::{DockNodeFlags, TableFlags, TreeNodeFlags, Ui, WindowFlags};
use ghostty_renderer::size::{Coordinate, CoordinateTag, Size, SurfaceCoord}; use ghostty_renderer::size::{Coordinate, CoordinateTag, Size, SurfaceCoord};
use ghostty_terminal::page_list::Pin; use ghostty_terminal::{
use ghostty_terminal::point::{Coordinate as PointCoordinate, Tag}; page_list::Pin,
use ghostty_terminal::terminal::Terminal; point::{Coordinate as PointCoordinate, Tag},
terminal::Terminal,
};
use super::{key, renderer, terminal, termio}; use super::{key, renderer, terminal, termio};
use crate::dock::begin_window; use crate::dock::begin_window;
@@ -1,13 +1,25 @@
//! Terminal information (ZIG/src/inspector/widgets/terminal.zig). //! Terminal information (ZIG/src/inspector/widgets/terminal.zig).
use dear_imgui_rs::{ use dear_imgui_rs::{
ColorEditFlags, Condition, ItemHoveredFlags, StyleVar, TableColumnFlags, TableColumnWidth, ColorEditFlags,
TableFlags, TableRowFlags, Ui, WindowFlags, Condition,
ItemHoveredFlags,
StyleVar,
TableColumnFlags,
TableColumnWidth,
TableFlags,
TableRowFlags,
Ui,
WindowFlags,
};
use ghostty_terminal::{
screen_set::Key as ScreenKey,
terminal::{MouseShiftCapture, Terminal},
};
use ghostty_vt::{
color::{DynamicRgb, Palette},
modes::ENTRIES as MODE_ENTRIES,
}; };
use ghostty_terminal::screen_set::Key as ScreenKey;
use ghostty_terminal::terminal::{MouseShiftCapture, Terminal};
use ghostty_vt::color::{DynamicRgb, Palette};
use ghostty_vt::modes::ENTRIES as MODE_ENTRIES;
use super::{DetachableHeader, help_marker, screen, style::rgb_f32}; use super::{DetachableHeader, help_marker, screen, style::rgb_f32};
use crate::keys::tag_name; use crate::keys::tag_name;
+14 -8
View File
@@ -1,18 +1,24 @@
//! VT event stream inspector (ZIG/src/inspector/widgets/termio.zig). //! VT event stream inspector (ZIG/src/inspector/widgets/termio.zig).
use std::collections::VecDeque; use std::{collections::VecDeque, convert::Infallible, fmt::Write as _};
use std::convert::Infallible;
use std::fmt::Write as _;
use dear_imgui_rs::{ use dear_imgui_rs::{
FocusedFlags, Key, SelectableFlags, TableColumnFlags, TableColumnWidth, TableFlags, Ui, FocusedFlags,
Key,
SelectableFlags,
TableColumnFlags,
TableColumnWidth,
TableFlags,
Ui,
WindowFlags, WindowFlags,
}; };
use ghostty_terminal::terminal::{ScrollingRegion, Terminal}; use ghostty_terminal::terminal::{ScrollingRegion, Terminal};
use ghostty_vt::color::Palette; use ghostty_vt::{
use ghostty_vt::osc::{self, Command as OscCommand}; color::Palette,
use ghostty_vt::parser::Action as ParserAction; osc::{self, Command as OscCommand},
use ghostty_vt::stream::{Action as StreamAction, Handler, Stream as VtStream}; parser::Action as ParserAction,
stream::{Action as StreamAction, Handler, Stream as VtStream},
};
use super::screen::{CursorSnapshot, cursor_style, cursor_table}; use super::screen::{CursorSnapshot, cursor_style, cursor_table};
+2 -1
View File
@@ -26,9 +26,10 @@ pub fn set_retry_limit_in_search(param: &mut MatchParam, limit: u32) {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
#![allow(clippy::unwrap_used)] #![allow(clippy::unwrap_used)]
use super::*;
use onig::{Regex, SearchOptions}; use onig::{Regex, SearchOptions};
use super::*;
fn search(re: &Regex, text: &str, limit: Option<u32>) -> Result<Option<usize>, onig::Error> { fn search(re: &Regex, text: &str, limit: Option<u32>) -> Result<Option<usize>, onig::Error> {
let mut param = MatchParam::default(); let mut param = MatchParam::default();
if let Some(l) = limit { if let Some(l) = limit {
+6 -3
View File
@@ -1,5 +1,7 @@
use std::collections::HashMap; use std::{
use std::ffi::{OsStr, OsString}; collections::HashMap,
ffi::{OsStr, OsString},
};
use crate::flatpak::is_flatpak; use crate::flatpak::is_flatpak;
@@ -214,9 +216,10 @@ pub fn getenv_not_empty(key: &str) -> Option<String> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use std::os::unix::ffi::OsStringExt; use std::os::unix::ffi::OsStringExt;
use super::*;
#[test] #[test]
fn env_map_preserves_non_utf8() { fn env_map_preserves_non_utf8() {
let mut env = EnvMap::new(); let mut env = EnvMap::new();
+11 -6
View File
@@ -1,10 +1,15 @@
use std::collections::HashMap; use std::{
use std::os::fd::{AsFd, OwnedFd}; collections::HashMap,
use std::sync::{Arc, Condvar, Mutex}; os::fd::{AsFd, OwnedFd},
sync::{Arc, Condvar, Mutex},
};
use zbus::blocking::{Connection, MessageIterator}; use zbus::{
use zbus::zvariant::Fd; MatchRule,
use zbus::{MatchRule, message::Type as MessageType}; blocking::{Connection, MessageIterator},
message::Type as MessageType,
zvariant::Fd,
};
const BUS_NAME: &str = "org.freedesktop.Flatpak"; const BUS_NAME: &str = "org.freedesktop.Flatpak";
const OBJECT_PATH: &str = "/org/freedesktop/Flatpak/Development"; const OBJECT_PATH: &str = "/org/freedesktop/Flatpak/Development";
+10 -2
View File
@@ -48,8 +48,16 @@ pub(crate) mod testutil;
pub use dbus::launched_by_dbus_activation; pub use dbus::launched_by_dbus_activation;
pub use desktop::{DesktopEnvironment, desktop_environment, launched_from_desktop}; pub use desktop::{DesktopEnvironment, desktop_environment, launched_from_desktop};
pub use env::{ pub use env::{
EnvMap, append_env, append_env_always, append_env_os, filter_snap_paths, get_env_map, getenv, EnvMap,
getenv_not_empty, prepend_env, prepend_env_os, append_env,
append_env_always,
append_env_os,
filter_snap_paths,
get_env_map,
getenv,
getenv_not_empty,
prepend_env,
prepend_env_os,
}; };
pub use file::{Rlimit, alloc_tmp_dir, fix_max_files, restore_max_files}; pub use file::{Rlimit, alloc_tmp_dir, fix_max_files, restore_max_files};
pub use flatpak::{FlatpakHostCommand, is_flatpak}; pub use flatpak::{FlatpakHostCommand, is_flatpak};
+4 -2
View File
@@ -1,5 +1,7 @@
use std::io; use std::{
use std::process::{Command, Stdio}; io,
process::{Command, Stdio},
};
/// Kind of URL being opened (`apprt.action.OpenUrl.Kind`). On Linux the /// Kind of URL being opened (`apprt.action.OpenUrl.Kind`). On Linux the
/// kind is ignored by [`open`] (it only matters for macOS `open -t`). /// kind is ignored by [`open`] (it only matters for macOS `open -t`).
+5 -2
View File
@@ -47,10 +47,13 @@ pub fn get() -> std::io::Result<Entry> {
/// `Pty`) depends on this crate, so a minimal openpt/ptsname pair is opened /// `Pty`) depends on this crate, so a minimal openpt/ptsname pair is opened
/// here with rustix instead. Like Zig, only `shell` and `home` are filled in. /// here with rustix instead. Like Zig, only `shell` and `home` are filled in.
fn host_entry(name: &str) -> std::io::Result<Entry> { fn host_entry(name: &str) -> std::io::Result<Entry> {
use rustix::fs::{Mode, OFlags};
use rustix::pty::{OpenptFlags, grantpt, openpt, ptsname, unlockpt};
use std::io::Read; use std::io::Read;
use rustix::{
fs::{Mode, OFlags},
pty::{OpenptFlags, grantpt, openpt, ptsname, unlockpt},
};
let err = std::io::Error::from; let err = std::io::Error::from;
let master = let master =
openpt(OpenptFlags::RDWR | OpenptFlags::NOCTTY | OpenptFlags::CLOEXEC).map_err(err)?; openpt(OpenptFlags::RDWR | OpenptFlags::NOCTTY | OpenptFlags::CLOEXEC).map_err(err)?;
+1 -2
View File
@@ -1,5 +1,4 @@
use std::io; use std::{io, os::unix::fs::PermissionsExt};
use std::os::unix::fs::PermissionsExt;
/// Equivalent of `std.fs.max_path_bytes` on Linux. /// Equivalent of `std.fs.max_path_bytes` on Linux.
const MAX_PATH_BYTES: usize = 4096; const MAX_PATH_BYTES: usize = 4096;
+3 -3
View File
@@ -1,5 +1,4 @@
use std::io; use std::{io, os::fd::OwnedFd};
use std::os::fd::OwnedFd;
/// pipe() for POSIX. Sets CLOEXEC on the file descriptors. /// pipe() for POSIX. Sets CLOEXEC on the file descriptors.
/// Returns `(read, write)`. /// Returns `(read, write)`.
@@ -9,9 +8,10 @@ pub fn pipe() -> io::Result<(OwnedFd, OwnedFd)> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use std::io::{Read, Write}; use std::io::{Read, Write};
use super::*;
#[test] #[test]
fn pipe_roundtrip_cloexec() { fn pipe_roundtrip_cloexec() {
let (r, w) = pipe().unwrap(); let (r, w) = pipe().unwrap();
+1 -2
View File
@@ -1,5 +1,4 @@
use std::io; use std::{io, path::Path};
use std::path::Path;
use crate::path_join; use crate::path_join;
+4 -2
View File
@@ -1,5 +1,7 @@
use std::ffi::{CString, NulError}; use std::{
use std::io::{self, Write}; ffi::{CString, NulError},
io::{self, Write},
};
/// Builder for constructing space-separated shell command strings. /// Builder for constructing space-separated shell command strings.
#[derive(Debug, Default, Clone)] #[derive(Debug, Default, Clone)]
+4 -1
View File
@@ -4,5 +4,8 @@
//! vt cannot depend on os); this module re-exports it. //! vt cannot depend on os); this module re-exports it.
pub use ghostty_vt::string_encoding::{ pub use ghostty_vt::string_encoding::{
Error, printf_q_decode, url_percent_decode, url_percent_encode, Error,
printf_q_decode,
url_percent_decode,
url_percent_encode,
}; };
+9 -2
View File
@@ -70,7 +70,13 @@ pub fn launched_by_systemd() -> bool {
/// variable set and these functions essentially become a no-op. /// variable set and these functions essentially become a no-op.
pub mod notify { pub mod notify {
use rustix::net::{ use rustix::net::{
AddressFamily, SendFlags, SocketAddrUnix, SocketFlags, SocketType, connect, send, AddressFamily,
SendFlags,
SocketAddrUnix,
SocketFlags,
SocketType,
connect,
send,
socket_with, socket_with,
}; };
@@ -168,9 +174,10 @@ pub mod notify {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use std::os::unix::net::UnixDatagram; use std::os::unix::net::UnixDatagram;
use super::*;
#[test] #[test]
fn not_launched_without_env() { fn not_launched_without_env() {
temp_env::with_vars( temp_env::with_vars(
+5 -3
View File
@@ -1,9 +1,11 @@
//! Creates a temporary directory at runtime that can be safely used to //! Creates a temporary directory at runtime that can be safely used to
//! store temporary data and is destroyed on drop. //! store temporary data and is destroyed on drop.
use std::io; use std::{
use std::os::unix::fs::DirBuilderExt; io,
use std::path::{Path, PathBuf}; os::unix::fs::DirBuilderExt,
path::{Path, PathBuf},
};
use crate::file::alloc_tmp_dir; use crate::file::alloc_tmp_dir;
+1 -2
View File
@@ -1,8 +1,7 @@
//! URI parsing. Extends a faithful port of Zig's `std.Uri.parse` with the //! URI parsing. Extends a faithful port of Zig's `std.Uri.parse` with the
//! additional [`ParseOptions`] from `os/uri.zig`. //! additional [`ParseOptions`] from `os/uri.zig`.
use std::borrow::Cow; use std::{borrow::Cow, fmt::Write as _};
use std::fmt::Write as _;
#[derive(Debug, Clone, Copy, Default)] #[derive(Debug, Clone, Copy, Default)]
pub struct ParseOptions { pub struct ParseOptions {
+1 -2
View File
@@ -3,8 +3,7 @@
use std::ffi::CStr; use std::ffi::CStr;
use crate::env::getenv_not_empty; use crate::{env::getenv_not_empty, homedir, path_join};
use crate::{homedir, path_join};
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, Default)]
pub struct Options<'a> { pub struct Options<'a> {
+10 -5
View File
@@ -6,9 +6,11 @@
use ghostty_terminal::page::Cell as PageCell; use ghostty_terminal::page::Cell as PageCell;
use crate::cursor::Style as CursorStyle; use crate::{
use crate::opengl::shaders::{CellBg, CellText}; cursor::Style as CursorStyle,
use crate::size::{CellCountInt, GridSize}; opengl::shaders::{CellBg, CellText},
size::{CellCountInt, GridSize},
};
/// The possible cell content keys that exist. /// The possible cell content keys that exist.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -297,9 +299,12 @@ fn is_powerline(ch: u32) -> bool {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use ghostty_terminal::{
render::RenderState,
terminal::{Options, Terminal},
};
use super::*; use super::*;
use ghostty_terminal::render::RenderState;
use ghostty_terminal::terminal::{Options, Terminal};
fn fg(x: u16, y: u16) -> CellText { fn fg(x: u16, y: u16) -> CellText {
CellText { CellText {
+2 -1
View File
@@ -84,10 +84,11 @@ pub fn style(state: &RenderState, opts: StyleOptions) -> Option<Style> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use ghostty_terminal::terminal::{Options, ScrollViewport, Terminal}; use ghostty_terminal::terminal::{Options, ScrollViewport, Terminal};
use ghostty_vt::modes::Mode; use ghostty_vt::modes::Mode;
use super::*;
fn o(preedit: bool, focused: bool, blink_visible: bool) -> StyleOptions { fn o(preedit: bool, focused: bool, blink_visible: bool) -> StyleOptions {
StyleOptions { StyleOptions {
preedit, preedit,
+82 -44
View File
@@ -40,54 +40,91 @@
//! [`Renderer::display_unrealized`], dropping the `Renderer`) must run on the //! [`Renderer::display_unrealized`], dropping the `Renderer`) must run on the
//! thread with the GL context current. The renderer thread never does. //! thread with the GL context current. The renderer thread never does.
use std::collections::HashSet; use std::{
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; collections::HashSet,
use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; sync::{
use std::time::Instant; Arc,
Mutex,
MutexGuard,
PoisonError,
atomic::{AtomicBool, AtomicU8, Ordering},
},
time::Instant,
};
use ghostty_config::config::Config; use ghostty_config::{
use ghostty_config::path::Path as ConfigPath; config::Config,
use ghostty_config::types_a::{BoldColor, FontShapingBreak, TerminalColor, WindowPaddingColor}; path::Path as ConfigPath,
use ghostty_config::types_b::{ types_a::{BoldColor, FontShapingBreak, TerminalColor, WindowPaddingColor},
AlphaBlending, BackgroundBlur, BackgroundImageFit, BackgroundImagePosition, WindowColorspace, types_b::{
AlphaBlending,
BackgroundBlur,
BackgroundImageFit,
BackgroundImagePosition,
WindowColorspace,
},
};
use ghostty_font::{
Atlas,
Presentation,
SPRITE_INDEX,
SharedGrid,
Sprite,
Style as FontStyle,
face::{Constraint, ConstraintSize, RenderOptions},
nerd_font_attributes::get_constraint,
shape::{self, Cache as ShaperCache, RunIterator, RunOptions, TextRun},
shaper::run::RunCell,
}; };
use ghostty_font::face::{Constraint, ConstraintSize, RenderOptions};
use ghostty_font::nerd_font_attributes::get_constraint;
use ghostty_font::shape::{self, Cache as ShaperCache, RunIterator, RunOptions, TextRun};
use ghostty_font::shaper::run::RunCell;
use ghostty_font::{Atlas, Presentation, SPRITE_INDEX, SharedGrid, Sprite, Style as FontStyle};
use ghostty_input::Mods; use ghostty_input::Mods;
use ghostty_terminal::highlight::Flattened; use ghostty_terminal::{
use ghostty_terminal::page::{self, Cell as PageCell, Wide}; highlight::Flattened,
use ghostty_terminal::page_list::Scrollbar; page::{self, Cell as PageCell, Wide},
use ghostty_terminal::point::{Coordinate, Tag}; page_list::Scrollbar,
use ghostty_terminal::render::{Cursor as RenderCursor, Dirty, RenderState, Row as RenderRow}; point::{Coordinate, Tag},
use ghostty_terminal::style::{self, Style}; render::{Cursor as RenderCursor, Dirty, RenderState, Row as RenderRow},
use ghostty_terminal::terminal::ScrollViewport; style::{self, Style},
use ghostty_vt::color::Rgb; terminal::ScrollViewport,
use ghostty_vt::modes::Mode; };
use ghostty_vt::sgr::Underline; use ghostty_vt::{color::Rgb, modes::Mode, sgr::Underline};
use crate::backend::Health; use crate::{
use crate::cell::{self, Contents, Key as CellKey}; backend::Health,
use crate::cursor::{self, Style as CursorStyle}; cell::{self, Contents, Key as CellKey},
use crate::image::{self, Gpu}; cursor::{self, Style as CursorStyle},
use crate::link; image::{self, Gpu},
use crate::math; link,
use crate::opengl::buffer::Buffer; math,
use crate::opengl::gl::{self, Gl, Primitive}; opengl::{
use crate::opengl::render_pass::{Attachment, AttachmentTarget, Draw, Step}; self,
use crate::opengl::shaders::{ OpenGL,
BgImage, BgImageFit, BgImageInfo, BgImagePosition, Bools, CellBg, CellText, CellTextAtlas, Sampler,
PaddingExtend, Shaders, Uniforms, Target,
Texture,
buffer::Buffer,
gl::{self, Gl, Primitive},
render_pass::{Attachment, AttachmentTarget, Draw, Step},
shaders::{
BgImage,
BgImageFit,
BgImageInfo,
BgImagePosition,
Bools,
CellBg,
CellText,
CellTextAtlas,
PaddingExtend,
Shaders,
Uniforms,
},
},
options::Options,
overlay::{self, Overlay},
row::never_extend_bg,
shadertoy::{self, PathItem},
size::{CellSize, GridSize, Padding, Size},
state::{Preedit, SharedState},
}; };
use crate::opengl::{self, OpenGL, Sampler, Target, Texture};
use crate::options::Options;
use crate::overlay::{self, Overlay};
use crate::row::never_extend_bg;
use crate::shadertoy::{self, PathItem};
use crate::size::{CellSize, GridSize, Padding, Size};
use crate::state::{Preedit, SharedState};
/// The graphics API used by the renderer on Linux. /// The graphics API used by the renderer on Linux.
pub type GraphicsApi = OpenGL; pub type GraphicsApi = OpenGL;
@@ -3287,9 +3324,10 @@ impl DrawState {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use ghostty_config::types_a::Color as ConfigColor; use ghostty_config::types_a::Color as ConfigColor;
use super::*;
fn rgb(r: u8, g: u8, b: u8) -> Rgb { fn rgb(r: u8, g: u8, b: u8) -> Rgb {
Rgb { r, g, b } Rgb { r, g, b }
} }
+31 -18
View File
@@ -6,23 +6,34 @@
//! GL context) and uploaded to the GPU on the thread that owns the context //! GL context) and uploaded to the GPU on the thread that owns the context
//! (`State::upload`, called from `draw_frame`). //! (`State::upload`, called from `draw_frame`).
use std::collections::HashMap; use std::{collections::HashMap, time::Instant};
use std::time::Instant;
use ghostty_terminal::kitty::graphics_command::TransmissionFormat; use ghostty_terminal::{
use ghostty_terminal::kitty::graphics_storage::{ImageStorage, TerminalInfo}; kitty::{
use ghostty_terminal::kitty::{Image as KittyImage, unicode}; Image as KittyImage,
use ghostty_terminal::page_list::PageList; graphics_command::TransmissionFormat,
use ghostty_terminal::point::Tag; graphics_storage::{ImageStorage, TerminalInfo},
use ghostty_terminal::terminal::Terminal; unicode,
},
page_list::PageList,
point::Tag,
terminal::Terminal,
};
use crate::opengl::gl::{Gl, Primitive}; use crate::{
use crate::opengl::pipeline::Pipeline; opengl::{
use crate::opengl::render_pass::{Draw, RenderPass, Step}; Buffer,
use crate::opengl::shaders::Image as ImageVertex; Texture,
use crate::opengl::{Buffer, Texture, buffer, texture}; buffer,
use crate::overlay::Overlay; gl::{Gl, Primitive},
use crate::size::CellSize; pipeline::Pipeline,
render_pass::{Draw, RenderPass, Step},
shaders::Image as ImageVertex,
texture,
},
overlay::Overlay,
size::CellSize,
};
/// The GPU objects needed to upload and draw images. Built per frame from /// The GPU objects needed to upload and draw images. Built per frame from
/// the graphics API (the API itself is mutably borrowed by the frame while /// the graphics API (the API itself is mutably borrowed by the frame while
@@ -1062,9 +1073,11 @@ mod tests {
#[test] #[test]
fn kitty_update_builds_sorted_viewport_placements() { fn kitty_update_builds_sorted_viewport_placements() {
use ghostty_terminal::kitty::graphics_storage::{Location, Placement as KPlacement}; use ghostty_terminal::{
use ghostty_terminal::point::{Coordinate, Point}; kitty::graphics_storage::{Location, Placement as KPlacement},
use ghostty_terminal::terminal::Options; point::{Coordinate, Point},
terminal::Options,
};
let mut t = Terminal::new(Options::new(10, 10)).unwrap(); let mut t = Terminal::new(Options::new(10, 10)).unwrap();
t.width_px = 100; t.width_px = 100;
+7 -5
View File
@@ -2,10 +2,11 @@
use std::collections::HashSet; use std::collections::HashSet;
use ghostty_input::Mods; use ghostty_input::{
use ghostty_input::link::{Highlight, Link as InputLink}; Mods,
use ghostty_terminal::point::Coordinate; link::{Highlight, Link as InputLink},
use ghostty_terminal::render::RenderState; };
use ghostty_terminal::{point::Coordinate, render::RenderState};
use onig::{Regex, Region, SearchOptions}; use onig::{Regex, Region, SearchOptions};
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
@@ -155,10 +156,11 @@ impl Set {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use ghostty_input::link::Action; use ghostty_input::link::Action;
use ghostty_terminal::terminal::{Options, Terminal}; use ghostty_terminal::terminal::{Options, Terminal};
use super::*;
fn link(regex: &str, highlight: Highlight) -> InputLink { fn link(regex: &str, highlight: Highlight) -> InputLink {
InputLink { InputLink {
regex: regex.to_string(), regex: regex.to_string(),
+7 -6
View File
@@ -2,14 +2,15 @@
use std::sync::Arc; use std::sync::Arc;
use ghostty_config::config::Config; use ghostty_config::config::Config;
use ghostty_font::shared_grid_set::Key as SharedGridKey; use ghostty_font::{SharedGrid, SharedGridSet, shared_grid_set::Key as SharedGridKey};
use ghostty_font::{SharedGrid, SharedGridSet};
use ghostty_terminal::highlight::Flattened; use ghostty_terminal::highlight::Flattened;
use crate::generic::DerivedConfig as RendererDerivedConfig; use crate::{
use crate::link; generic::DerivedConfig as RendererDerivedConfig,
use crate::size::Size; link,
use crate::thread::DerivedConfig as ThreadDerivedConfig; size::Size,
thread::DerivedConfig as ThreadDerivedConfig,
};
/// The messages that can be sent to a renderer thread. /// The messages that can be sent to a renderer thread.
pub enum Message { pub enum Message {
+5 -3
View File
@@ -1,9 +1,11 @@
//! Wrapper for handling render frames (`opengl/Frame.zig`). //! Wrapper for handling render frames (`opengl/Frame.zig`).
use std::sync::Arc; use std::sync::Arc;
use super::OpenGL; use super::{
use super::render_pass::{Attachment, Options as RenderPassOptions, RenderPass}; OpenGL,
use super::target::Target; render_pass::{Attachment, Options as RenderPassOptions, RenderPass},
target::Target,
};
use crate::backend::Health; use crate::backend::Health;
/// Options for beginning a frame. /// Options for beginning a frame.
+7 -4
View File
@@ -13,8 +13,7 @@
//! * Pointer-carrying calls (`buffer_data`, `tex_image_2d`, ...) are only given //! * Pointer-carrying calls (`buffer_data`, `tex_image_2d`, ...) are only given
//! Rust slices, so lengths are always valid for the pointed memory. //! Rust slices, so lengths are always valid for the pointed memory.
use std::ffi::c_void; use std::{ffi::c_void, sync::Arc};
use std::sync::Arc;
use glow::HasContext; use glow::HasContext;
@@ -57,8 +56,12 @@ impl std::fmt::Debug for Gl {
// Re-exported raw handle types. // Re-exported raw handle types.
pub use glow::{ pub use glow::{
Buffer as RawBuffer, Framebuffer as RawFramebuffer, Program as RawProgram, Buffer as RawBuffer,
Renderbuffer as RawRenderbuffer, Sampler as RawSampler, Texture as RawTexture, Framebuffer as RawFramebuffer,
Program as RawProgram,
Renderbuffer as RawRenderbuffer,
Sampler as RawSampler,
Texture as RawTexture,
VertexArray as RawVertexArray, VertexArray as RawVertexArray,
}; };
+20 -12
View File
@@ -16,23 +16,31 @@ pub mod shaders;
pub mod target; pub mod target;
pub mod texture; pub mod texture;
use std::ffi::c_void; use std::{ffi::c_void, sync::Arc};
use std::sync::Arc;
use ghostty_font::atlas::{Atlas, Format as AtlasFormat}; use ghostty_font::atlas::{Atlas, Format as AtlasFormat};
pub use self::buffer::Buffer;
pub use self::frame::Frame;
pub use self::gl::Gl;
use self::gl::{ use self::gl::{
BufferTarget, BufferUsage, FramebufferTarget, InternalFormat, MagFilter, MinFilter, BufferTarget,
PixelFormat, TextureTarget, Wrap, BufferUsage,
FramebufferTarget,
InternalFormat,
MagFilter,
MinFilter,
PixelFormat,
TextureTarget,
Wrap,
};
pub use self::{
buffer::Buffer,
frame::Frame,
gl::Gl,
pipeline::Pipeline,
render_pass::RenderPass,
sampler::Sampler,
target::Target,
texture::Texture,
}; };
pub use self::pipeline::Pipeline;
pub use self::render_pass::RenderPass;
pub use self::sampler::Sampler;
pub use self::target::Target;
pub use self::texture::Texture;
use crate::shadertoy; use crate::shadertoy;
pub type GraphicsApi = OpenGL; pub type GraphicsApi = OpenGL;
@@ -1,6 +1,12 @@
//! Wrapper for handling render pipelines (`opengl/Pipeline.zig`). //! Wrapper for handling render pipelines (`opengl/Pipeline.zig`).
use super::gl::{ use super::gl::{
self, AttribType, FramebufferTarget, Gl, RawFramebuffer, RawProgram, RawVertexArray, self,
AttribType,
FramebufferTarget,
Gl,
RawFramebuffer,
RawProgram,
RawVertexArray,
}; };
/// Vertex step function. /// Vertex step function.
@@ -1,11 +1,11 @@
//! Wrapper for handling render passes (`opengl/RenderPass.zig`). //! Wrapper for handling render passes (`opengl/RenderPass.zig`).
use super::gl::{ use super::{
Attachment as GlAttachment, BufferTarget, FramebufferTarget, Gl, Primitive, RawBuffer, gl::{Attachment as GlAttachment, BufferTarget, FramebufferTarget, Gl, Primitive, RawBuffer},
pipeline::Pipeline,
sampler::Sampler,
target::Target,
texture::Texture,
}; };
use super::pipeline::Pipeline;
use super::sampler::Sampler;
use super::target::Target;
use super::texture::Texture;
/// What a color attachment renders into. /// What a color attachment renders into.
pub enum AttachmentTarget<'a> { pub enum AttachmentTarget<'a> {
@@ -1,8 +1,10 @@
//! Shader pipelines and GPU data layouts for OpenGL (`opengl/shaders.zig`). //! Shader pipelines and GPU data layouts for OpenGL (`opengl/shaders.zig`).
use bytemuck::{Pod, Zeroable}; use bytemuck::{Pod, Zeroable};
use super::gl::{self, AttribType, Gl}; use super::{
use super::pipeline::{Attribute, Options as PipelineOptions, Pipeline, StepFunction, Vertex}; gl::{self, AttribType, Gl},
pipeline::{Attribute, Options as PipelineOptions, Pipeline, StepFunction, Vertex},
};
use crate::math::Mat; use crate::math::Mat;
/// `shaders/glsl/common.glsl`, the only `#include`d file. /// `shaders/glsl/common.glsl`, the only `#include`d file.
@@ -464,9 +466,10 @@ impl Vertex for BgImage {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use core::mem::{offset_of, size_of}; use core::mem::{offset_of, size_of};
use super::*;
#[test] #[test]
fn uniforms_std140_layout() { fn uniforms_std140_layout() {
// Offsets from the std140 rules applied to the `Globals` block in // Offsets from the std140 rules applied to the `Globals` block in
+7 -1
View File
@@ -2,7 +2,13 @@
//! //!
//! In this case, an OpenGL renderbuffer-backed framebuffer. //! In this case, an OpenGL renderbuffer-backed framebuffer.
use super::gl::{ use super::gl::{
self, Attachment, FramebufferTarget, Gl, InternalFormat, RawFramebuffer, RawRenderbuffer, self,
Attachment,
FramebufferTarget,
Gl,
InternalFormat,
RawFramebuffer,
RawRenderbuffer,
}; };
/// Options for initializing a Target /// Options for initializing a Target
@@ -1,6 +1,14 @@
//! Wrapper for handling textures (`opengl/Texture.zig`). //! Wrapper for handling textures (`opengl/Texture.zig`).
use super::gl::{ use super::gl::{
self, Gl, InternalFormat, MagFilter, MinFilter, PixelFormat, RawTexture, TextureTarget, Wrap, self,
Gl,
InternalFormat,
MagFilter,
MinFilter,
PixelFormat,
RawTexture,
TextureTarget,
Wrap,
}; };
/// Options for initializing a texture. /// Options for initializing a texture.
+1 -2
View File
@@ -3,8 +3,7 @@ use std::sync::Arc;
use ghostty_font::SharedGrid; use ghostty_font::SharedGrid;
use crate::generic::Host; use crate::{generic::Host, size::Size};
use crate::size::Size;
/// Options for constructing a renderer. /// Options for constructing a renderer.
/// ///
+10 -5
View File
@@ -10,11 +10,15 @@
//! then get the resulting image with [`Overlay::pending_image`] to upload to //! then get the resulting image with [`Overlay::pending_image`] to upload to
//! the GPU. This works in concert with [`crate::image::State`]. //! the GPU. This works in concert with [`crate::image::State`].
use ghostty_terminal::page::{SemanticContent, SemanticPrompt}; use ghostty_terminal::{
use ghostty_terminal::render::RenderState; page::{SemanticContent, SemanticPrompt},
render::RenderState,
};
use crate::image::{Pending, PixelFormat}; use crate::{
use crate::size::{CellSize, Size}; image::{Pending, PixelFormat},
size::{CellSize, Size},
};
/// The colors we use for overlays. /// The colors we use for overlays.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -394,9 +398,10 @@ fn checked_i32(v: usize) -> Result<i32, Overflow> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use ghostty_terminal::terminal::{Options, Terminal};
use super::*; use super::*;
use crate::size::{Padding, ScreenSize}; use crate::size::{Padding, ScreenSize};
use ghostty_terminal::terminal::{Options, Terminal};
fn size(w: u32, h: u32) -> Size { fn size(w: u32, h: u32) -> Size {
Size { Size {
+6 -3
View File
@@ -1,7 +1,9 @@
//! Row heuristics for the renderer (`renderer/row.zig`). //! Row heuristics for the renderer (`renderer/row.zig`).
use ghostty_terminal::page::{Cell, ContentTag, Row, SemanticPrompt}; use ghostty_terminal::{
use ghostty_terminal::style::Style; page::{Cell, ContentTag, Row, SemanticPrompt},
style::Style,
};
use ghostty_vt::color::{Palette, Rgb}; use ghostty_vt::color::{Palette, Rgb};
/// Returns true if the row of this pin should never have its background /// Returns true if the row of this pin should never have its background
@@ -82,9 +84,10 @@ fn style_at(cell: Cell, styles: &[Style], x: usize) -> Style {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use ghostty_vt::color; use ghostty_vt::color;
use super::*;
const BG: Rgb = Rgb { r: 1, g: 2, b: 3 }; const BG: Rgb = Rgb { r: 1, g: 2, b: 3 };
#[test] #[test]
+10 -7
View File
@@ -8,14 +8,16 @@
//! `docs/rewrite/notes/ghostty-renderer-R1.md` for the (small) source //! `docs/rewrite/notes/ghostty-renderer-R1.md` for the (small) source
//! adaptations needed for naga's Vulkan-flavoured GLSL frontend. //! adaptations needed for naga's Vulkan-flavoured GLSL frontend.
use crate::shadertoy_sampler; use std::{io::Read, path::Path};
use std::io::Read;
use std::path::Path;
use bytemuck::{Pod, Zeroable}; use bytemuck::{Pod, Zeroable};
use naga::back::glsl as glsl_out; use naga::{
use naga::front::glsl as glsl_in; back::glsl as glsl_out,
use naga::valid::{Capabilities, ModuleInfo, ValidationFlags, Validator}; front::glsl as glsl_in,
valid::{Capabilities, ModuleInfo, ValidationFlags, Validator},
};
use crate::shadertoy_sampler;
/// The shadertoy prefix (declares the uniforms and the `main` entry point). /// The shadertoy prefix (declares the uniforms and the `main` entry point).
pub const PREFIX: &str = include_str!("../shaders/shadertoy_prefix.glsl"); pub const PREFIX: &str = include_str!("../shaders/shadertoy_prefix.glsl");
@@ -349,9 +351,10 @@ pub mod test_shaders {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use core::mem::{offset_of, size_of}; use core::mem::{offset_of, size_of};
use super::*;
#[test] #[test]
fn spirv() { fn spirv() {
let src = glsl_from_shader(TEST_CRT); let src = glsl_from_shader(TEST_CRT);
+1 -3
View File
@@ -3,9 +3,7 @@
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use ghostty_input::Mods; use ghostty_input::Mods;
use ghostty_terminal::point::Coordinate; use ghostty_terminal::{point::Coordinate, size::CellCountInt, terminal::Terminal};
use ghostty_terminal::size::CellCountInt;
use ghostty_terminal::terminal::Terminal;
use crate::overlay::Feature as OverlayFeature; use crate::overlay::Feature as OverlayFeature;
+10 -7
View File
@@ -31,17 +31,20 @@
//! The event loop (libxev in Zig) is replaced by a `crossbeam_channel::select!` //! The event loop (libxev in Zig) is replaced by a `crossbeam_channel::select!`
//! over the wakeup / stop / draw-now channels and the next timer deadline. //! over the wakeup / stop / draw-now channels and the next timer deadline.
use std::sync::Arc; use std::{
use std::time::{Duration, Instant}; sync::Arc,
time::{Duration, Instant},
};
use crossbeam_channel::{Receiver, Sender, bounded, never, select}; use crossbeam_channel::{Receiver, Sender, bounded, never, select};
use ghostty_config::config::Config; use ghostty_config::{config::Config, types_a::CustomShaderAnimation};
use ghostty_config::types_a::CustomShaderAnimation;
use ghostty_datastruct::blocking_queue::{BlockingQueue, Timeout}; use ghostty_datastruct::blocking_queue::{BlockingQueue, Timeout};
use crate::generic::{Host, Renderer}; use crate::{
use crate::message::Message; generic::{Host, Renderer},
use crate::state::SharedState; message::Message,
state::SharedState,
};
/// 120 FPS /// 120 FPS
pub const DRAW_INTERVAL: Duration = Duration::from_millis(8); pub const DRAW_INTERVAL: Duration = Duration::from_millis(8);
+38 -25
View File
@@ -8,17 +8,19 @@
// The EGL loader calls are `unsafe fn`s in khronos-egl (test-only usage). // The EGL loader calls are `unsafe fn`s in khronos-egl (test-only usage).
#![allow(unsafe_code, clippy::unwrap_used)] #![allow(unsafe_code, clippy::unwrap_used)]
use std::ffi::c_void; use std::{ffi::c_void, sync::Arc};
use std::sync::Arc;
use ghostty_renderer::opengl::buffer; use ghostty_renderer::{
use ghostty_renderer::opengl::gl::{Gl, Primitive}; opengl::{
use ghostty_renderer::opengl::render_pass::{Attachment, AttachmentTarget, Draw, Step}; AlphaBlending,
use ghostty_renderer::opengl::shaders::{ OpenGL,
BgImage, BgImageFit, BgImageInfo, BgImagePosition, CellText, Image, Uniforms, buffer,
gl::{Gl, Primitive},
render_pass::{Attachment, AttachmentTarget, Draw, Step},
shaders::{BgImage, BgImageFit, BgImageInfo, BgImagePosition, CellText, Image, Uniforms},
},
shadertoy,
}; };
use ghostty_renderer::opengl::{AlphaBlending, OpenGL};
use ghostty_renderer::shadertoy;
use khronos_egl as egl; use khronos_egl as egl;
// EGL_PLATFORM_SURFACELESS_MESA, falling back to the default display. // EGL_PLATFORM_SURFACELESS_MESA, falling back to the default display.
@@ -393,23 +395,34 @@ fn headless_invalid_shader_reports_compile_error() {
// Full renderer: Terminal -> RenderState -> generic renderer -> offscreen target // Full renderer: Terminal -> RenderState -> generic renderer -> offscreen target
mod full_renderer { mod full_renderer {
use super::*; use std::sync::{
use std::sync::Mutex; Mutex,
use std::sync::atomic::{AtomicUsize, Ordering}; atomic::{AtomicUsize, Ordering},
};
use ghostty_config::config::Config; use ghostty_config::{
use ghostty_config::types_a::Color as ConfigColor; config::Config,
use ghostty_config::types_b::AlphaBlending as ConfigBlending; types_a::Color as ConfigColor,
use ghostty_font::face::DesiredSize; types_b::AlphaBlending as ConfigBlending,
use ghostty_font::shared_grid_set::{DerivedConfig as FontDerivedConfig, SharedGridSet}; };
use ghostty_renderer::generic::{DerivedConfig, Host, Renderer}; use ghostty_font::{
use ghostty_renderer::options::Options; face::DesiredSize,
use ghostty_renderer::size::{CellSize, Padding, ScreenSize, Size}; shared_grid_set::{DerivedConfig as FontDerivedConfig, SharedGridSet},
use ghostty_renderer::state::State; };
use ghostty_terminal::page_list::Scrollbar; use ghostty_renderer::{
use ghostty_terminal::terminal::{Options as TermOptions, Terminal}; generic::{DerivedConfig, Host, Renderer},
options::Options,
size::{CellSize, Padding, ScreenSize, Size},
state::State,
};
use ghostty_terminal::{
page_list::Scrollbar,
terminal::{Options as TermOptions, Terminal},
};
use ghostty_vt::color::DynamicRgb; use ghostty_vt::color::DynamicRgb;
use super::*;
#[derive(Default)] #[derive(Default)]
struct TestHost { struct TestHost {
scrollbars: Mutex<Vec<Scrollbar>>, scrollbars: Mutex<Vec<Scrollbar>>,
@@ -781,10 +794,10 @@ mod full_renderer {
#[test] #[test]
fn headless_renderer_thread_updates_and_requests_draws() { fn headless_renderer_thread_updates_and_requests_draws() {
use ghostty_renderer::message::Message;
use ghostty_renderer::thread::Thread;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use ghostty_renderer::{message::Message, thread::Thread};
let Some(f) = Fixture::new("thread") else { let Some(f) = Fixture::new("thread") else {
return; return;
}; };
+8 -6
View File
@@ -8,6 +8,14 @@
//! into a small scratch buffer and measures it. //! into a small scratch buffer and measures it.
#![allow(clippy::too_many_arguments)] #![allow(clippy::too_many_arguments)]
use std::io::{self, Write};
use ghostty_vt::{
charsets::{Charset, Slots},
color::{Palette, Rgb},
modes::ENTRIES,
};
use crate::{ use crate::{
highlight::pin_page_iterator, highlight::pin_page_iterator,
hyperlink::HyperlinkId, hyperlink::HyperlinkId,
@@ -20,12 +28,6 @@ use crate::{
style::{Color, Style}, style::{Color, Style},
terminal::Terminal, terminal::Terminal,
}; };
use ghostty_vt::{
charsets::{Charset, Slots},
color::{Palette, Rgb},
modes::ENTRIES,
};
use std::io::{self, Write};
type Result<T> = io::Result<T>; type Result<T> = io::Result<T>;
@@ -1,6 +1,7 @@
use super::*;
use ghostty_vt::modes::Mode; use ghostty_vt::modes::Mode;
use super::*;
/// Format the screen with the given extras, returning output and pin map. /// Format the screen with the given extras, returning output and pin map.
fn screen_vt(t: &Terminal, mutate: impl FnOnce(&mut ScreenFormatter<'_>)) -> (String, Vec<Pin>) { fn screen_vt(t: &Terminal, mutate: impl FnOnce(&mut ScreenFormatter<'_>)) -> (String, Vec<Pin>) {
let mut pin_map: Vec<Pin> = Vec::new(); let mut pin_map: Vec<Pin> = Vec::new();
@@ -13,9 +13,9 @@
use ghostty_vt::kitty::graphics_command::{Command, Control, Display, Quiet, Response}; use ghostty_vt::kitty::graphics_command::{Command, Control, Display, Quiet, Response};
use super::graphics_image::{Error as ImageError, LoadingImage}; use super::{
use super::graphics_storage::{ graphics_image::{Error as ImageError, LoadingImage},
Error as StorageError, ImageStorage, Location, Placement, TerminalInfo, graphics_storage::{Error as StorageError, ImageStorage, Location, Placement, TerminalInfo},
}; };
use crate::page_list::{PageList, Pin}; use crate::page_list::{PageList, Pin};
@@ -466,9 +466,10 @@ fn encode_error(r: &mut Response, err: ImageError) {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use ghostty_vt::kitty::graphics_command::{Parser, TransmissionFormat};
use super::*; use super::*;
use crate::terminal::{Options, Terminal}; use crate::terminal::{Options, Terminal};
use ghostty_vt::kitty::graphics_command::{Parser, TransmissionFormat};
fn run(h: &mut Terminal, s: &str) -> Option<Response> { fn run(h: &mut Terminal, s: &str) -> Option<Response> {
let cmd = Parser::parse_string(s.as_bytes()).unwrap(); let cmd = Parser::parse_string(s.as_bytes()).unwrap();
@@ -3,14 +3,20 @@
//! [`LoadingImage`] is an image that is still being transmitted (possibly in //! [`LoadingImage`] is an image that is still being transmitted (possibly in
//! chunks). [`Image`] is a fully loaded and validated image. //! chunks). [`Image`] is a fully loaded and validated image.
use std::io::{Cursor, Read, Seek, SeekFrom}; use std::{
use std::os::unix::ffi::OsStrExt; io::{Cursor, Read, Seek, SeekFrom},
use std::os::unix::fs::FileExt; os::unix::{ffi::OsStrExt, fs::FileExt},
use std::path::Path; path::Path,
use std::time::Instant; time::Instant,
};
use ghostty_vt::kitty::graphics_command::{ use ghostty_vt::kitty::graphics_command::{
Command, Display, Quiet, TransmissionCompression, TransmissionFormat, TransmissionMedium, Command,
Display,
Quiet,
TransmissionCompression,
TransmissionFormat,
TransmissionMedium,
}; };
use crate::page_list::Pin; use crate::page_list::Pin;
@@ -138,8 +144,7 @@ impl LoadingImage {
/// Reads the data from a shared memory segment. /// Reads the data from a shared memory segment.
fn read_shared_memory(&mut self, offset: u32, size: u32, path: &[u8]) -> Result<(), Error> { fn read_shared_memory(&mut self, offset: u32, size: u32, path: &[u8]) -> Result<(), Error> {
use rustix::fs::Mode; use rustix::{fs::Mode, shm};
use rustix::shm;
let path_str = String::from_utf8_lossy(path); let path_str = String::from_utf8_lossy(path);
let fd = match shm::open(path, shm::OFlags::RDONLY, Mode::empty()) { let fd = match shm::open(path, shm::OFlags::RDONLY, Mode::empty()) {
@@ -565,9 +570,10 @@ pub struct Rect {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use ghostty_vt::kitty::graphics_command::{Control, Transmission}; use ghostty_vt::kitty::graphics_command::{Control, Transmission};
use super::*;
const RGB_NONE_20X15: &[u8] = const RGB_NONE_20X15: &[u8] =
include_bytes!("testdata/image-rgb-none-20x15-2147483647-raw.data"); include_bytes!("testdata/image-rgb-none-20x15-2147483647-raw.data");
const RGB_ZLIB_128X96: &[u8] = const RGB_ZLIB_128X96: &[u8] =
@@ -894,10 +900,10 @@ mod tests {
#[test] #[test]
fn image_load_shared_memory() { fn image_load_shared_memory() {
use rustix::fs::Mode;
use rustix::shm;
use std::io::Write; use std::io::Write;
use rustix::{fs::Mode, shm};
let name = format!("/ghostty-kitty-test-{}", std::process::id()); let name = format!("/ghostty-kitty-test-{}", std::process::id());
let fd = shm::open( let fd = shm::open(
name.as_str(), name.as_str(),
@@ -21,9 +21,11 @@ use std::collections::{BTreeMap, HashMap};
use ghostty_vt::kitty::graphics_command::Delete; use ghostty_vt::kitty::graphics_command::Delete;
use super::graphics_image::{Image, LoadingImage, Rect}; use super::graphics_image::{Image, LoadingImage, Rect};
use crate::page_list::{Overflow, PageList, TrackedPin}; use crate::{
use crate::point::{Coordinate, Point}; page_list::{Overflow, PageList, TrackedPin},
use crate::size::CellCountInt; point::{Coordinate, Point},
size::CellCountInt,
};
/// The subset of terminal state that the storage needs to read. /// The subset of terminal state that the storage needs to read.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
@@ -2,14 +2,18 @@
//! Kitty graphics protocol unicode placeholder, virtual placement feature //! Kitty graphics protocol unicode placeholder, virtual placement feature
//! (`ZIG/src/terminal/kitty/graphics_unicode.zig`). //! (`ZIG/src/terminal/kitty/graphics_unicode.zig`).
use super::graphics_image::Image; use super::{
use super::graphics_render::Placement as RenderPlacement; graphics_image::Image,
use super::graphics_storage::{ImageStorage, Location, PlacementKey}; graphics_render::Placement as RenderPlacement,
use crate::page::Cell; graphics_storage::{ImageStorage, Location, PlacementKey},
use crate::page_list::{CellSubset, Direction, PageList, Pin, RowIterator}; };
use crate::point::Tag; use crate::{
use crate::size::CellCountInt; page::Cell,
use crate::style::Color; page_list::{CellSubset, Direction, PageList, Pin, RowIterator},
point::Tag,
size::CellCountInt,
style::Color,
};
/// Codepoint for the unicode placeholder character. /// Codepoint for the unicode placeholder character.
pub const PLACEHOLDER: u32 = 0x10EEEE; pub const PLACEHOLDER: u32 = 0x10EEEE;
@@ -638,11 +642,13 @@ const DIACRITICS: &[u32] = &[
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use ghostty_vt::{modes::Mode, sgr::Attribute};
use super::*; use super::*;
use crate::kitty::graphics_storage::Placement as StoragePlacement; use crate::{
use crate::terminal::{Options, Terminal}; kitty::graphics_storage::Placement as StoragePlacement,
use ghostty_vt::modes::Mode; terminal::{Options, Terminal},
use ghostty_vt::sgr::Attribute; };
fn term(cols: u16, rows: u16) -> Terminal { fn term(cols: u16, rows: u16) -> Terminal {
let mut t = Terminal::new(Options::new(cols, rows)).unwrap(); let mut t = Terminal::new(Options::new(cols, rows)).unwrap();
-1
View File
@@ -17,7 +17,6 @@ pub mod graphics_storage;
pub mod graphics_unicode; pub mod graphics_unicode;
pub use ghostty_vt::kitty::{color, graphics_command, key}; pub use ghostty_vt::kitty::{color, graphics_command, key};
pub use graphics_command::{Command, Parser as CommandParser, Response}; pub use graphics_command::{Command, Parser as CommandParser, Response};
pub use graphics_exec::{ExecTerminal, execute}; pub use graphics_exec::{ExecTerminal, execute};
pub use graphics_image::Image; pub use graphics_image::Image;
+4 -2
View File
@@ -1,11 +1,13 @@
//! Compact cells and rows, with bounded owned page storage. //! Compact cells and rows, with bounded owned page storage.
use std::collections::{HashMap, HashSet};
use ghostty_vt::color::Rgb;
use crate::{ use crate::{
hyperlink::{self, Hyperlink, HyperlinkId}, hyperlink::{self, Hyperlink, HyperlinkId},
ref_counted_set::{AddError, Layout as SetLayout}, ref_counted_set::{AddError, Layout as SetLayout},
style::{self, Style}, style::{self, Style},
}; };
use ghostty_vt::color::Rgb;
use std::collections::{HashMap, HashSet};
/// Default grapheme allocation request, in bytes. /// Default grapheme allocation request, in bytes.
pub const GRAPHEME_BYTES_DEFAULT: u32 = 1024; pub const GRAPHEME_BYTES_DEFAULT: u32 = 1024;
/// Default string allocation request, in bytes. /// Default string allocation request, in bytes.
+19 -8
View File
@@ -1,15 +1,25 @@
//! Linked terminal pages, byte-bounded history, and stable tracked coordinates. //! Linked terminal pages, byte-bounded history, and stable tracked coordinates.
use crate::{
page::{
self, Adjustment, Capacity, Cell, ContentTag, Error, Page, Row, SemanticContent,
SemanticPrompt, Wide,
},
point::{Coordinate, Point, Tag},
};
use std::{ use std::{
collections::HashMap, collections::HashMap,
sync::atomic::{AtomicUsize, Ordering}, sync::atomic::{AtomicUsize, Ordering},
}; };
use crate::{
page::{
self,
Adjustment,
Capacity,
Cell,
ContentTag,
Error,
Page,
Row,
SemanticContent,
SemanticPrompt,
Wide,
},
point::{Coordinate, Point, Tag},
};
/// Slab index and generation; stale references never alias a reused node. /// Slab index and generation; stale references never alias a reused node.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct NodeId { pub struct NodeId {
@@ -7214,8 +7224,9 @@ mod tests {
} }
#[test] #[test]
fn page_list_resize_reflow_exceeds_style_memory_forcing_capacity_increase() { fn page_list_resize_reflow_exceeds_style_memory_forcing_capacity_increase() {
use crate::style::{Color, Style};
use ghostty_vt::color::Rgb; use ghostty_vt::color::Rgb;
use crate::style::{Color, Style};
let mut s = two_page_fixture(page::STD_CAPACITY.styles - 1, 1, Some(0)); let mut s = two_page_fixture(page::STD_CAPACITY.styles - 1, 1, Some(0));
assert_ne!(s.first, s.last); assert_ne!(s.first, s.last);
assert_eq!(s.node(s.first.unwrap()).unwrap().next, s.last); assert_eq!(s.node(s.first.unwrap()).unwrap().next, s.last);
+7 -5
View File
@@ -34,6 +34,13 @@
//! waste, it is recommended that the caller drop and start with an //! waste, it is recommended that the caller drop and start with an
//! empty render state every so often. //! empty render state every so often.
use std::collections::HashSet;
use ghostty_vt::{
color::{self, Palette, Rgb},
modes::Mode,
};
use crate::{ use crate::{
cursor, cursor,
highlight::Flattened, highlight::Flattened,
@@ -46,11 +53,6 @@ use crate::{
style::{Color, Style}, style::{Color, Style},
terminal::{Dirty as TerminalDirty, Terminal}, terminal::{Dirty as TerminalDirty, Terminal},
}; };
use ghostty_vt::{
color::{self, Palette, Rgb},
modes::Mode,
};
use std::collections::HashSet;
/// Contains the state required to render the screen. See the module docs. /// Contains the state required to render the screen. See the module docs.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
+24 -17
View File
@@ -18,21 +18,6 @@
clippy::doc_overindented_list_items, clippy::doc_overindented_list_items,
clippy::items_after_statements clippy::items_after_statements
)] )]
use crate::{
cursor::Style as CursorStyle,
formatter::{Content as FormatContent, Options as FormatOptions, ScreenFormatter},
hyperlink::{self, Hyperlink, HyperlinkId},
kitty::graphics_storage::ImageStorage,
page::{Cell, ContentTag, Page, Row, SemanticContent, SemanticPrompt as RowPrompt, Wide},
page_list::{
CellSubset, Chunk, Direction, IncreaseCapacity, NodeId, PageList, Pin,
Scroll as ListScroll, TrackedPin, Viewport,
},
point::{Coordinate, Point, Tag},
selection::{Bounds, Order, Selection},
size,
style::{self, Style},
};
use ghostty_vt::{ use ghostty_vt::{
ansi::ProtectedMode, ansi::ProtectedMode,
charsets::{Charset, Slots}, charsets::{Charset, Slots},
@@ -41,11 +26,33 @@ use ghostty_vt::{
sgr, sgr,
}; };
pub use crate::page::Error;
/// The Unicode codepoint used by the Kitty graphics protocol for virtual /// The Unicode codepoint used by the Kitty graphics protocol for virtual
/// placements (`kitty.graphics.unicode.placeholder`). /// placements (`kitty.graphics.unicode.placeholder`).
use crate::kitty::graphics_unicode::PLACEHOLDER as KITTY_PLACEHOLDER; use crate::kitty::graphics_unicode::PLACEHOLDER as KITTY_PLACEHOLDER;
pub use crate::page::Error;
use crate::{
cursor::Style as CursorStyle,
formatter::{Content as FormatContent, Options as FormatOptions, ScreenFormatter},
hyperlink::{self, Hyperlink, HyperlinkId},
kitty::graphics_storage::ImageStorage,
page::{Cell, ContentTag, Page, Row, SemanticContent, SemanticPrompt as RowPrompt, Wide},
page_list::{
CellSubset,
Chunk,
Direction,
IncreaseCapacity,
NodeId,
PageList,
Pin,
Scroll as ListScroll,
TrackedPin,
Viewport,
},
point::{Coordinate, Point, Tag},
selection::{Bounds, Order, Selection},
size,
style::{self, Style},
};
/// See Terminal.Dirty. This behaves the same way. /// See Terminal.Dirty. This behaves the same way.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
@@ -1,6 +1,7 @@
use super::*;
use ghostty_vt::sgr::Attribute as A; use ghostty_vt::sgr::Attribute as A;
use super::*;
#[test] #[test]
fn screen_read_and_write() { fn screen_read_and_write() {
let mut s = init(80, 24, 1000); let mut s = init(80, 24, 1000);
@@ -1,6 +1,7 @@
use super::*;
use ghostty_vt::{color::Rgb, sgr::Attribute as A}; use ghostty_vt::{color::Rgb, sgr::Attribute as A};
use super::*;
fn bg155() -> A<'static> { fn bg155() -> A<'static> {
A::DirectColorBg(Rgb { r: 155, g: 0, b: 0 }) A::DirectColorBg(Rgb { r: 155, g: 0, b: 0 })
} }
@@ -1,6 +1,8 @@
use super::*; use super::*;
use crate::page::Wide; use crate::{
use crate::screen::{PromptKind, SemanticContentSet}; page::Wide,
screen::{PromptKind, SemanticContentSet},
};
fn cell_at(s: &Screen, pt: Point) -> Cell { fn cell_at(s: &Screen, pt: Point) -> Cell {
s.pages.get_cell(pt).unwrap() s.pages.get_cell(pt).unwrap()
@@ -1,8 +1,7 @@
use ghostty_vt::{color::Rgb, sgr::Attribute as A};
use super::*; use super::*;
use crate::page::STD_CAPACITY; use crate::{page::STD_CAPACITY, style::Color};
use crate::style::Color;
use ghostty_vt::color::Rgb;
use ghostty_vt::sgr::Attribute as A;
fn sel_str(s: &Screen, sel: Selection, trim: bool) -> String { fn sel_str(s: &Screen, sel: Selection, trim: bool) -> String {
s.selection_string(SelectionString { sel, trim }) s.selection_string(SelectionString { sel, trim })
+5 -4
View File
@@ -9,8 +9,10 @@
//! and handling the active area moving as new lines are added to the bottom. //! and handling the active area moving as new lines are added to the bottom.
use super::sliding_window::{Direction, SlidingWindow}; use super::sliding_window::{Direction, SlidingWindow};
use crate::highlight::Flattened; use crate::{
use crate::page_list::{NodeId, PageList}; highlight::Flattened,
page_list::{NodeId, PageList},
};
#[derive(Debug)] #[derive(Debug)]
pub struct ActiveSearch { pub struct ActiveSearch {
@@ -103,8 +105,7 @@ impl ActiveSearch {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::super::test_util::*; use super::{super::test_util::*, *};
use super::*;
use crate::point::Tag; use crate::point::Tag;
fn check(list: &PageList, h: &Flattened, s: (u16, u32), e: (u16, u32)) { fn check(list: &PageList, h: &Flattened, s: (u16, u32), e: (u16, u32)) {
@@ -18,9 +18,11 @@
//! list takes it as a parameter. //! list takes it as a parameter.
use super::sliding_window::{Direction, SlidingWindow}; use super::sliding_window::{Direction, SlidingWindow};
use crate::highlight::Flattened; use crate::{
use crate::page::Error; highlight::Flattened,
use crate::page_list::{NodeId, PageList, Pin, TrackedPin}; page::Error,
page_list::{NodeId, PageList, Pin, TrackedPin},
};
#[derive(Debug)] #[derive(Debug)]
pub struct PageListSearch { pub struct PageListSearch {
@@ -144,11 +146,8 @@ impl PageListSearch {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::super::test_util::*; use super::{super::test_util::*, *};
use super::*; use crate::{point::Tag, screen::SelectionString, selection::Selection};
use crate::point::Tag;
use crate::screen::SelectionString;
use crate::selection::Selection;
fn check(list: &PageList, h: &Flattened, s: (u16, u32), e: (u16, u32)) { fn check(list: &PageList, h: &Flattened, s: (u16, u32), e: (u16, u32)) {
let sel = h.untracked(); let sel = h.untracked();
+17 -12
View File
@@ -17,14 +17,18 @@
//! that touches it (`new`, `deinit`, `feed`, `reload_active`, `select`, //! that touches it (`new`, `deinit`, `feed`, `reload_active`, `select`,
//! `search_all`); `tick`, `matches`, `selected_match` etc. do not need it. //! `search_all`); `tick`, `matches`, `selected_match` etc. do not need it.
use super::active::ActiveSearch; use super::{
use super::pagelist::PageListSearch; active::ActiveSearch,
use super::sliding_window::{Direction, SlidingWindow}; pagelist::PageListSearch,
use crate::highlight::{Flattened, Tracked}; sliding_window::{Direction, SlidingWindow},
use crate::page::Error; };
use crate::page_list::{NodeId, PageList, Pin, TrackedPin}; use crate::{
use crate::screen::Screen; highlight::{Flattened, Tracked},
use crate::size::CellCountInt; page::Error,
page_list::{NodeId, PageList, Pin, TrackedPin},
screen::Screen,
size::CellCountInt,
};
#[derive(Debug)] #[derive(Debug)]
pub struct ScreenSearch { pub struct ScreenSearch {
@@ -856,10 +860,11 @@ impl ScreenSearch {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::super::test_util::*; use super::{super::test_util::*, *};
use super::*; use crate::{
use crate::point::{Point, Tag}; point::{Point, Tag},
use crate::terminal::Terminal; terminal::Terminal,
};
fn pts(t: &Terminal, h: &Flattened, tag: Tag) -> (Option<Point>, Option<Point>) { fn pts(t: &Terminal, h: &Flattened, tag: Tag) -> (Option<Point>, Option<Point>) {
let sel = h.untracked(); let sel = h.untracked();
@@ -23,11 +23,13 @@
use std::collections::VecDeque; use std::collections::VecDeque;
use crate::formatter::{Options, PageFormatter}; use crate::{
use crate::highlight::{Chunk, Flattened}; formatter::{Options, PageFormatter},
use crate::page::Page; highlight::{Chunk, Flattened},
use crate::page_list::{Node, NodeId, PageList}; page::Page,
use crate::point::Coordinate; page_list::{Node, NodeId, PageList},
point::Coordinate,
};
/// The search direction. If the direction is forward then pages should /// The search direction. If the direction is forward then pages should
/// be appended in forward linked list order from the PageList. If the /// be appended in forward linked list order from the PageList. If the
@@ -464,11 +466,12 @@ impl SlidingWindow {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::super::test_util::*; use super::{super::test_util::*, *};
use super::*; use crate::{
use crate::highlight::Flattened; highlight::Flattened,
use crate::point::{Point, Tag}; point::{Point, Tag},
use crate::screen::Screen; screen::Screen,
};
fn check(list: &PageList, h: &Flattened, tag: Tag, s: (u16, u32), e: (u16, u32)) { fn check(list: &PageList, h: &Flattened, tag: Tag, s: (u16, u32), e: (u16, u32)) {
let sel = h.untracked(); let sel = h.untracked();
@@ -1,9 +1,11 @@
//! Shared helpers for search tests. //! Shared helpers for search tests.
use crate::page_list::{NodeId, PageList}; use crate::{
use crate::point::{Coordinate, Point, Tag}; page_list::{NodeId, PageList},
use crate::screen::{Options, Screen}; point::{Coordinate, Point, Tag},
use crate::terminal::{self, Terminal}; screen::{Options, Screen},
terminal::{self, Terminal},
};
pub fn screen(cols: u16, rows: u16, max_scrollback: usize) -> Screen { pub fn screen(cols: u16, rows: u16, max_scrollback: usize) -> Screen {
Screen::new(Options::new(cols, rows, max_scrollback)).unwrap() Screen::new(Options::new(cols, rows, max_scrollback)).unwrap()
+19 -13
View File
@@ -13,19 +13,25 @@
//! based refresh timer. The terminal and its mutex are combined into an //! based refresh timer. The terminal and its mutex are combined into an
//! `Arc<Mutex<Terminal>>`. //! `Arc<Mutex<Terminal>>`.
use std::ops::DerefMut; use std::{
use std::sync::{Arc, Mutex, PoisonError}; ops::DerefMut,
use std::time::{Duration, Instant}; sync::{Arc, Mutex, PoisonError},
time::{Duration, Instant},
};
use crossbeam_channel::{Receiver, Sender, TrySendError}; use crossbeam_channel::{Receiver, Sender, TrySendError};
use super::screen::{ScreenSearch, Select, TickError}; use super::{
use super::viewport::ViewportSearch; screen::{ScreenSearch, Select, TickError},
use crate::highlight::{Flattened, Untracked}; viewport::ViewportSearch,
use crate::page_list::{Chunk, Direction as ListDirection}; };
use crate::point::{Coordinate, Point}; use crate::{
use crate::screen_set::Key as ScreenKey; highlight::{Flattened, Untracked},
use crate::terminal::Terminal; page_list::{Chunk, Direction as ListDirection},
point::{Coordinate, Point},
screen_set::Key as ScreenKey,
terminal::Terminal,
};
// TODO: Some stuff that could be improved: // TODO: Some stuff that could be improved:
// - pause the refresh timer when the terminal isn't focused // - pause the refresh timer when the terminal isn't focused
@@ -770,11 +776,11 @@ impl Search {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::super::test_util::*;
use super::*;
use crate::point::Tag;
use std::sync::mpsc; use std::sync::mpsc;
use super::{super::test_util::*, *};
use crate::point::Tag;
#[derive(Default)] #[derive(Default)]
struct TestUserData { struct TestUserData {
total: usize, total: usize,
@@ -13,9 +13,11 @@
//! lives in the same page. //! lives in the same page.
use super::sliding_window::{Direction, SlidingWindow}; use super::sliding_window::{Direction, SlidingWindow};
use crate::highlight::Flattened; use crate::{
use crate::page_list::{Direction as ListDirection, NodeId, PageList}; highlight::Flattened,
use crate::point::{Coordinate, Point, Tag}; page_list::{Direction as ListDirection, NodeId, PageList},
point::{Coordinate, Point, Tag},
};
#[derive(Debug)] #[derive(Debug)]
pub struct ViewportSearch { pub struct ViewportSearch {
@@ -223,8 +225,7 @@ impl ViewportSearch {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::super::test_util::*; use super::{super::test_util::*, *};
use super::*;
use crate::terminal::ScrollViewport; use crate::terminal::ScrollViewport;
fn check(list: &PageList, h: &Flattened, tag: Tag, s: (u16, u32), e: (u16, u32)) { fn check(list: &PageList, h: &Flattened, tag: Tag, s: (u16, u32), e: (u16, u32)) {
+15 -7
View File
@@ -12,12 +12,6 @@
//! output and doesn't need to respond (since it maybe isn't running the //! output and doesn't need to respond (since it maybe isn't running the
//! actual program), this is the stream type to use. For example, this is //! actual program), this is the stream type to use. For example, this is
//! ideal for replay tooling, CI logs, PaaS builder output, etc. //! ideal for replay tooling, CI logs, PaaS builder output, etc.
use crate::{
cursor::Style as CursorStyle,
terminal::{
DeccolmMode, Error, MouseEvents, MouseFormat, MouseShiftCapture, SwitchScreenMode, Terminal,
},
};
use ghostty_vt::{ use ghostty_vt::{
ansi::{CursorStyle as AnsiCursorStyle, ModifyKeyFormat, ProtectedMode}, ansi::{CursorStyle as AnsiCursorStyle, ModifyKeyFormat, ProtectedMode},
color::Dynamic as DynamicColor, color::Dynamic as DynamicColor,
@@ -28,6 +22,19 @@ use ghostty_vt::{
stream::{self, Action}, stream::{self, Action},
}; };
use crate::{
cursor::Style as CursorStyle,
terminal::{
DeccolmMode,
Error,
MouseEvents,
MouseFormat,
MouseShiftCapture,
SwitchScreenMode,
Terminal,
},
};
/// The stream type wrapping [`Handler`]. /// The stream type wrapping [`Handler`].
pub type Stream<'a> = stream::Stream<Handler<'a>>; pub type Stream<'a> = stream::Stream<Handler<'a>>;
@@ -450,9 +457,10 @@ impl stream::Handler for Handler<'_> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use ghostty_vt::osc::semantic_prompt::Redraw;
use super::*; use super::*;
use crate::{page::SemanticContent, screen_set::Key as ScreenKey, terminal::Options}; use crate::{page::SemanticContent, screen_set::Key as ScreenKey, terminal::Options};
use ghostty_vt::osc::semantic_prompt::Redraw;
fn term(cols: u16, rows: u16) -> Terminal { fn term(cols: u16, rows: u16) -> Terminal {
Terminal::new(Options::new(cols, rows)).unwrap() Terminal::new(Options::new(cols, rows)).unwrap()
+2 -1
View File
@@ -3,9 +3,10 @@
//! //!
//! Port of `ZIG/src/terminal/StringMap.zig`. Regex matching uses Oniguruma //! Port of `ZIG/src/terminal/StringMap.zig`. Regex matching uses Oniguruma
//! (the `onig` crate), like Ghostty. //! (the `onig` crate), like Ghostty.
use crate::{page_list::Pin, selection::Selection};
use onig::{MatchParam, Regex, Region, SearchOptions}; use onig::{MatchParam, Regex, Region, SearchOptions};
use crate::{page_list::Pin, selection::Selection};
/// Retry budget for StringMap regex searches. /// Retry budget for StringMap regex searches.
/// ///
/// Units are Oniguruma retry steps (internal backtracking/retry counter), /// Units are Oniguruma retry steps (internal backtracking/retry counter),
+7 -5
View File
@@ -1,13 +1,15 @@
//! Cell styles, color resolution, and VT/HTML serialization. //! Cell styles, color resolution, and VT/HTML serialization.
use crate::page::{Cell, ContentTag};
use ghostty_vt::{
color::{Palette, Rgb},
sgr::Underline,
};
use std::{ use std::{
fmt, fmt,
hash::{Hash, Hasher}, hash::{Hash, Hasher},
}; };
use ghostty_vt::{
color::{Palette, Rgb},
sgr::Underline,
};
use crate::page::{Cell, ContentTag};
/// Nonzero page-local style identifier. /// Nonzero page-local style identifier.
pub type Id = u16; pub type Id = u16;
/// The default style needs no set lookup. /// The default style needs no set lookup.
+20 -13
View File
@@ -18,19 +18,6 @@
clippy::items_after_statements, clippy::items_after_statements,
clippy::too_many_lines clippy::too_many_lines
)] )]
use crate::{
page::{Cell, ContentTag, Page, SemanticContent, SemanticPrompt as RowPrompt, Wide},
page_list::{Direction, IncreaseCapacity, Pin},
point::{Coordinate, Point},
screen::{
CharsetState, InputClear, Options as ScreenOptions, Resize as ScreenResize, SavedCursor,
Screen, Scroll, SemanticClick, SemanticContentSet as SetSemantic,
},
screen_set::{Key as ScreenKey, ScreenSet},
size,
style::{self, Color as StyleColor, Style},
tabstops::Tabstops,
};
use ghostty_vt::{ use ghostty_vt::{
ansi::{ProtectedMode, StatusDisplay}, ansi::{ProtectedMode, StatusDisplay},
charsets::{self, Charset, Slots}, charsets::{self, Charset, Slots},
@@ -47,6 +34,26 @@ use ghostty_vt::{
}; };
pub use crate::page::Error; pub use crate::page::Error;
use crate::{
page::{Cell, ContentTag, Page, SemanticContent, SemanticPrompt as RowPrompt, Wide},
page_list::{Direction, IncreaseCapacity, Pin},
point::{Coordinate, Point},
screen::{
CharsetState,
InputClear,
Options as ScreenOptions,
Resize as ScreenResize,
SavedCursor,
Screen,
Scroll,
SemanticClick,
SemanticContentSet as SetSemantic,
},
screen_set::{Key as ScreenKey, ScreenSet},
size,
style::{self, Color as StyleColor, Style},
tabstops::Tabstops,
};
/// Default tabstop interval /// Default tabstop interval
const TABSTOP_INTERVAL: usize = 8; const TABSTOP_INTERVAL: usize = 8;
@@ -1,7 +1,7 @@
use ghostty_vt::{color::Rgb, sgr::Attribute};
use super::*; use super::*;
use crate::page::{Cell, Wide}; use crate::page::{Cell, Wide};
use ghostty_vt::color::Rgb;
use ghostty_vt::sgr::Attribute;
fn c(t: &Terminal, x: u16, y: u32) -> Cell { fn c(t: &Terminal, x: u16, y: u32) -> Cell {
cell_at(t, pt_screen(x, y)) cell_at(t, pt_screen(x, y))
@@ -1,9 +1,7 @@
use ghostty_vt::{color::Rgb, modes::Mode, sgr::Attribute as A};
use super::*; use super::*;
use crate::page::ContentTag; use crate::{page::ContentTag, point::Tag};
use crate::point::Tag;
use ghostty_vt::color::Rgb;
use ghostty_vt::modes::Mode;
use ghostty_vt::sgr::Attribute as A;
fn cr_lf(t: &mut Terminal) { fn cr_lf(t: &mut Terminal) {
t.carriage_return(); t.carriage_return();
@@ -1,6 +1,6 @@
use ghostty_vt::{color::Rgb, sgr::Attribute as A};
use super::*; use super::*;
use ghostty_vt::color::Rgb;
use ghostty_vt::sgr::Attribute as A;
const RED: Rgb = Rgb { const RED: Rgb = Rgb {
r: 0xFF, r: 0xFF,
@@ -1,7 +1,7 @@
use ghostty_vt::{color::Rgb, sgr::Attribute};
use super::*; use super::*;
use crate::page::ContentTag; use crate::page::ContentTag;
use ghostty_vt::color::Rgb;
use ghostty_vt::sgr::Attribute;
fn prints(t: &mut Terminal, s: &str) { fn prints(t: &mut Terminal, s: &str) {
for c in s.chars() { for c in s.chars() {
@@ -1,8 +1,7 @@
use ghostty_vt::{charsets::Slots, color::Rgb, sgr::Attribute};
use super::*; use super::*;
use crate::page::{ContentTag, Wide}; use crate::page::{ContentTag, Wide};
use ghostty_vt::charsets::Slots;
use ghostty_vt::color::Rgb;
use ghostty_vt::sgr::Attribute;
/// Zig `for ("...") |c| try t.print(c)`. /// Zig `for ("...") |c| try t.print(c)`.
fn pr(t: &mut Terminal, s: &str) { fn pr(t: &mut Terminal, s: &str) {
@@ -1,5 +1,3 @@
use super::*;
use crate::page::{ContentTag, SemanticContent, SemanticPrompt as RowPrompt};
use ghostty_vt::{ use ghostty_vt::{
ansi::ProtectedMode, ansi::ProtectedMode,
color::Rgb, color::Rgb,
@@ -8,6 +6,9 @@ use ghostty_vt::{
sgr::{Attribute as A, Underline}, sgr::{Attribute as A, Underline},
}; };
use super::*;
use crate::page::{ContentTag, SemanticContent, SemanticPrompt as RowPrompt};
fn pr(t: &mut Terminal, s: &str) { fn pr(t: &mut Terminal, s: &str) {
for c in s.chars() { for c in s.chars() {
t.print(u32::from(c)).unwrap(); t.print(u32::from(c)).unwrap();
@@ -1,12 +1,17 @@
use ghostty_vt::{
color::Rgb,
osc::{
SemanticPrompt as Cmd,
semantic_prompt::{Action as A, Click},
},
sgr::Attribute,
};
use super::*; use super::*;
use crate::page::{ContentTag, SemanticContent, SemanticPrompt as RowPrompt}; use crate::{
use crate::screen::SemanticClick; page::{ContentTag, SemanticContent, SemanticPrompt as RowPrompt},
use ghostty_vt::color::Rgb; screen::SemanticClick,
use ghostty_vt::osc::{
SemanticPrompt as Cmd,
semantic_prompt::{Action as A, Click},
}; };
use ghostty_vt::sgr::Attribute;
fn sp(a: A) -> Cmd { fn sp(a: A) -> Cmd {
Cmd::init(a) Cmd::init(a)
+4 -2
View File
@@ -4,7 +4,9 @@ pub mod layout;
pub mod output; pub mod output;
pub mod viewer; pub mod viewer;
pub use ghostty_vt::tmux::control; pub use ghostty_vt::tmux::{
pub use ghostty_vt::tmux::control::{Notification as ControlNotification, Parser as ControlParser}; control,
control::{Notification as ControlNotification, Parser as ControlParser},
};
pub use layout::Layout; pub use layout::Layout;
pub use viewer::Viewer; pub use viewer::Viewer;
+2 -1
View File
@@ -316,9 +316,10 @@ pub fn format(vars: &[Variable], delimiter: char) -> String {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use Variable::*; use Variable::*;
use super::*;
fn flag(v: Variable) { fn flag(v: Variable) {
assert_eq!(v.parse("1"), Ok(Value::Bool(true))); assert_eq!(v.parse("1"), Ok(Value::Bool(true)));
assert_eq!(v.parse("0"), Ok(Value::Bool(false))); assert_eq!(v.parse("0"), Ok(Value::Bool(false)));
+13 -10
View File
@@ -62,17 +62,20 @@
use std::collections::VecDeque; use std::collections::VecDeque;
use ghostty_vt::modes::Mode; use ghostty_vt::{modes::Mode, tmux::control::Notification};
use ghostty_vt::tmux::control::Notification;
use super::layout::{self, Content, Layout}; use super::{
use super::output::{self, Variable}; layout::{self, Content, Layout},
use crate::cursor::Style as CursorStyle; output::{self, Variable},
use crate::page; };
use crate::point::{Coordinate, Point}; use crate::{
use crate::screen_set::Key as ScreenKey; cursor::Style as CursorStyle,
use crate::size::CellCountInt; page,
use crate::terminal::{Options as TerminalOptions, Terminal}; point::{Coordinate, Point},
screen_set::Key as ScreenKey,
size::CellCountInt,
terminal::{Options as TerminalOptions, Terminal},
};
/// The initial capacity of the command queue. /// The initial capacity of the command queue.
const COMMAND_QUEUE_INITIAL: usize = 8; const COMMAND_QUEUE_INITIAL: usize = 8;
+6 -4
View File
@@ -6,10 +6,12 @@ use std::sync::Arc;
use ghostty_renderer::size::{GridSize, ScreenSize}; use ghostty_renderer::size::{GridSize, ScreenSize};
use ghostty_terminal::terminal::Terminal; use ghostty_terminal::terminal::Terminal;
use crate::exec::{self, Exec}; use crate::{
use crate::sinks::SurfaceMailbox; exec::{self, Exec},
use crate::state::SharedState; sinks::SurfaceMailbox,
use crate::termio::Output; state::SharedState,
termio::Output,
};
/// The kinds of backends. /// The kinds of backends.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
+2 -4
View File
@@ -14,7 +14,7 @@
use std::{ use std::{
ffi::{CString, NulError, c_char}, ffi::{CString, NulError, c_char},
os::fd::OwnedFd, os::{fd::OwnedFd, unix::ffi::OsStrExt},
panic::{AssertUnwindSafe, catch_unwind}, panic::{AssertUnwindSafe, catch_unwind},
}; };
@@ -24,7 +24,6 @@ use rustix::{
process::{self, WaitOptions}, process::{self, WaitOptions},
stdio, stdio,
}; };
use std::os::unix::ffi::OsStrExt;
/// Function executed /in the child process/ after the fork, but before /// Function executed /in the child process/ after the fork, but before
/// exec'ing the command. If the function returns `Some(code)`, the child /// exec'ing the command. If the function returns `Some(code)`, the child
@@ -609,11 +608,10 @@ mod tests {
use std::{ use std::{
fs::File, fs::File,
io::{Read, Seek, SeekFrom}, io::{Read, Seek, SeekFrom},
os::fd::AsRawFd,
sync::Arc, sync::Arc,
}; };
use std::os::fd::AsRawFd;
use ghostty_os::TempDir; use ghostty_os::TempDir;
use super::*; use super::*;
+35 -21
View File
@@ -15,35 +15,49 @@
//! `POLLOUT` is polled only while the queue is non-empty, //! `POLLOUT` is polled only while the queue is non-empty,
//! * termios timer: a plain deadline. //! * termios timer: a plain deadline.
use std::collections::VecDeque; use std::{
use std::io; collections::VecDeque,
use std::os::fd::{AsFd, BorrowedFd, OwnedFd}; io,
use std::sync::Arc; os::fd::{AsFd, BorrowedFd, OwnedFd},
use std::thread::JoinHandle; sync::Arc,
use std::time::{Duration, Instant}; thread::JoinHandle,
time::{Duration, Instant},
};
use crossbeam_channel::Receiver; use crossbeam_channel::Receiver;
use ghostty_config::command::Command as ConfigCommand; use ghostty_apprt::surface::{ChildExited, Message as SurfaceMessage};
use ghostty_config::repeatable_string_map::RepeatableStringMap; use ghostty_config::{
use ghostty_config::types_b::{ShellIntegration, ShellIntegrationFeatures}; command::Command as ConfigCommand,
repeatable_string_map::RepeatableStringMap,
types_b::{ShellIntegration, ShellIntegrationFeatures},
};
use ghostty_datastruct::blocking_queue::Timeout; use ghostty_datastruct::blocking_queue::Timeout;
use ghostty_os::file::Rlimit; use ghostty_os::file::Rlimit;
use ghostty_renderer::size::{GridSize, ScreenSize}; use ghostty_renderer::size::{GridSize, ScreenSize};
use ghostty_terminal::terminal::Terminal; use ghostty_terminal::terminal::Terminal;
use rustix::event::{PollFd, PollFlags}; use rustix::{
use rustix::process::{Pid, PidfdFlags, Signal, WaitOptions}; event::{PollFd, PollFlags},
process::{Pid, PidfdFlags, Signal, WaitOptions},
};
use crate::command::{ use crate::{
self, Command, Exit, PostForkError, RtPostForkInfo, RtPreExecInfo, linux_cgroup_post_fork, command::{
linux_cgroup_pre_exec, self,
Command,
Exit,
PostForkError,
RtPostForkInfo,
RtPreExecInfo,
linux_cgroup_post_fork,
linux_cgroup_pre_exec,
},
pty::{self, Mode, Pty, Winsize},
shell_integration::{self, EnvMap, Shell},
sinks::SurfaceMailbox,
state::{SharedState, SharedStateExt},
termio::Output,
wakeup::Wakeup,
}; };
use crate::pty::{self, Mode, Pty, Winsize};
use crate::shell_integration::{self, EnvMap, Shell};
use crate::sinks::SurfaceMailbox;
use crate::state::{SharedState, SharedStateExt};
use crate::termio::Output;
use crate::wakeup::Wakeup;
use ghostty_apprt::surface::{ChildExited, Message as SurfaceMessage};
/// The termios poll rate in milliseconds. /// The termios poll rate in milliseconds.
pub const TERMIOS_POLL_MS: u64 = 200; pub const TERMIOS_POLL_MS: u64 = 200;
+3 -3
View File
@@ -10,8 +10,7 @@ use std::sync::{Mutex, MutexGuard, PoisonError};
use crossbeam_channel::{Receiver, Sender, TrySendError, bounded}; use crossbeam_channel::{Receiver, Sender, TrySendError, bounded};
use crate::message::Message; use crate::{message::Message, wakeup::Wakeup};
use crate::wakeup::Wakeup;
/// Capacity of the queue. Hardcoded to a value that empirically has made /// Capacity of the queue. Hardcoded to a value that empirically has made
/// sense for Ghostty usage (`BlockingQueue(termio.Message, 64)`). /// sense for Ghostty usage (`BlockingQueue(termio.Message, 64)`).
@@ -128,9 +127,10 @@ impl Mailbox {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use std::sync::Arc; use std::sync::Arc;
use super::*;
#[test] #[test]
fn send_pop_order() { fn send_pop_order() {
let mb = Mailbox::new().unwrap(); let mb = Mailbox::new().unwrap();
+7 -5
View File
@@ -6,11 +6,13 @@ use std::sync::Arc;
use ghostty_config::config::Config; use ghostty_config::config::Config;
use ghostty_renderer::size::Size; use ghostty_renderer::size::Size;
use crate::backend::Backend; use crate::{
use crate::mailbox::Mailbox; backend::Backend,
use crate::sinks::{RendererMailbox, SurfaceMailbox}; mailbox::Mailbox,
use crate::termio::DerivedConfig; sinks::{RendererMailbox, SurfaceMailbox},
use crate::wakeup::Wakeup; termio::DerivedConfig,
wakeup::Wakeup,
};
/// See the module docs. /// See the module docs.
pub struct Options<'a> { pub struct Options<'a> {
@@ -42,8 +42,7 @@ impl Shell {
} }
} }
pub use ghostty_config::command::Command; pub use ghostty_config::{command::Command, types_b::ShellIntegrationFeatures};
pub use ghostty_config::types_b::ShellIntegrationFeatures;
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum Error { pub enum Error {
+4 -2
View File
@@ -5,8 +5,10 @@
//! [`SharedState`]). This module only provides a convenience for termio: //! [`SharedState`]). This module only provides a convenience for termio:
//! locking the state and borrowing just the [`Terminal`]. //! locking the state and borrowing just the [`Terminal`].
use std::ops::{Deref, DerefMut}; use std::{
use std::sync::{MutexGuard, PoisonError}; ops::{Deref, DerefMut},
sync::{MutexGuard, PoisonError},
};
pub use ghostty_renderer::state::{SharedState, State}; pub use ghostty_renderer::state::{SharedState, State};
use ghostty_terminal::terminal::Terminal; use ghostty_terminal::terminal::Terminal;
+61 -34
View File
@@ -23,44 +23,67 @@
//! [`HandlerState`], which the caller flushes after unlocking //! [`HandlerState`], which the caller flushes after unlocking
//! ([`TerminalStream::flush_outbox`]; `Termio::process_output` does this). //! ([`TerminalStream::flush_outbox`]; `Termio::process_output` does this).
use std::collections::VecDeque; use std::{
use std::fmt::Write as _; collections::VecDeque,
use std::sync::{Arc, OnceLock}; fmt::Write as _,
sync::{Arc, OnceLock},
};
use ghostty_apprt::structs::Clipboard; use ghostty_apprt::{
use ghostty_apprt::surface::{ structs::Clipboard,
DesktopNotification, Message as SurfaceMessage, ReportTitleStyle, SET_TITLE_LEN, WriteReq, surface::{
DesktopNotification,
Message as SurfaceMessage,
ReportTitleStyle,
SET_TITLE_LEN,
WriteReq,
},
}; };
use ghostty_config::types_b::{ClipboardAccess, OSCColorReportFormat}; use ghostty_config::types_b::{ClipboardAccess, OSCColorReportFormat};
use ghostty_datastruct::blocking_queue::Timeout; use ghostty_datastruct::blocking_queue::Timeout;
use ghostty_renderer::size::Size; use ghostty_renderer::size::Size;
use ghostty_terminal::cursor::Style as CursorStyle; use ghostty_terminal::{
use ghostty_terminal::terminal::{ cursor::Style as CursorStyle,
DeccolmMode, Error, MouseEvents, MouseFormat, MouseShiftCapture, ScrollViewport, terminal::{
SwitchScreenMode, Terminal, DeccolmMode,
Error,
MouseEvents,
MouseFormat,
MouseShiftCapture,
ScrollViewport,
SwitchScreenMode,
Terminal,
},
}; };
use ghostty_vt::ansi::{ use ghostty_vt::{
CursorStyle as AnsiCursorStyle, DeviceAttributeReq, ModifyKeyFormat, ProtectedMode, ansi::{CursorStyle as AnsiCursorStyle, DeviceAttributeReq, ModifyKeyFormat, ProtectedMode},
apc,
color::{Dynamic as DynamicColor, Rgb},
csi,
dcs,
device_status,
kitty::{self, key::SetMode as KittySetMode},
modes::Mode,
mouse_shape::MouseShape,
osc::{
ProgressReport,
ProgressState,
Terminator,
color::{self as osc_color, Request, Target},
semantic_prompt::Action as PromptAction,
},
parser::{Dcs, Parser},
stream::{self, Action},
utf8_decoder::Utf8Decoder,
}; };
use ghostty_vt::color::{Dynamic as DynamicColor, Rgb};
use ghostty_vt::csi;
use ghostty_vt::device_status;
use ghostty_vt::kitty::{self, key::SetMode as KittySetMode};
use ghostty_vt::modes::Mode;
use ghostty_vt::mouse_shape::MouseShape;
use ghostty_vt::osc::color::{self as osc_color, Request, Target};
use ghostty_vt::osc::semantic_prompt::Action as PromptAction;
use ghostty_vt::osc::{ProgressReport, ProgressState, Terminator};
use ghostty_vt::parser::{Dcs, Parser};
use ghostty_vt::stream::{self, Action};
use ghostty_vt::utf8_decoder::Utf8Decoder;
use ghostty_vt::{apc, dcs};
use crate::mailbox::Mailbox; use crate::{
use crate::message::{Message, SizeReport}; mailbox::Mailbox,
use crate::sinks::SurfaceMailbox; message::{Message, SizeReport},
use crate::terminfo; sinks::SurfaceMailbox,
use crate::wakeup::Wakeup; terminfo,
wakeup::Wakeup,
};
/// `build_config.version_string`. /// `build_config.version_string`.
pub const VERSION_STRING: &str = "1.3.1"; pub const VERSION_STRING: &str = "1.3.1";
@@ -648,8 +671,10 @@ impl StreamHandler<'_> {
fn dcs_command(&mut self, cmd: dcs::Command) { fn dcs_command(&mut self, cmd: dcs::Command) {
match cmd { match cmd {
dcs::Command::Tmux(tmux) => { dcs::Command::Tmux(tmux) => {
use ghostty_terminal::tmux::control::Notification; use ghostty_terminal::tmux::{
use ghostty_terminal::tmux::viewer::{Action as ViewerAction, Input}; control::Notification,
viewer::{Action as ViewerAction, Input},
};
log::info!("tmux control mode event cmd={tmux:?}"); log::info!("tmux control mode event cmd={tmux:?}");
@@ -1510,10 +1535,12 @@ impl stream::Handler for StreamHandler<'_> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use ghostty_terminal::terminal::Options;
use std::sync::Mutex; use std::sync::Mutex;
use ghostty_terminal::terminal::Options;
use super::*;
/// Records surface messages. /// Records surface messages.
#[derive(Default)] #[derive(Default)]
struct Rec(Mutex<Vec<SurfaceMessage>>); struct Rec(Mutex<Vec<SurfaceMessage>>);
+1 -2
View File
@@ -6,8 +6,7 @@
//! //!
//! Port of `terminfo/Source.zig`. //! Port of `terminfo/Source.zig`.
use std::collections::HashMap; use std::{collections::HashMap, io};
use std::io;
/// A terminfo source description. /// A terminfo source description.
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
+37 -30
View File
@@ -22,39 +22,46 @@
//! Lock order is always terminal mutex first, then the stream mutex inside //! Lock order is always terminal mutex first, then the stream mutex inside
//! [`Output`]. //! [`Output`].
use std::io::Read; use std::{
use std::sync::{Arc, Mutex, PoisonError}; io::Read,
use std::time::{Duration, Instant}; sync::{Arc, Mutex, MutexGuard, PoisonError},
time::{Duration, Instant},
};
use ghostty_config::conditional; use ghostty_config::{
use ghostty_config::config::Config; conditional,
use ghostty_config::io::ReadableIO; config::Config,
use ghostty_config::types_a::{Color, CursorStyle, TerminalColor}; io::ReadableIO,
use ghostty_config::types_b::{ClipboardAccess, GraphemeWidthMethod, OSCColorReportFormat}; types_a::{Color, CursorStyle, TerminalColor},
types_b::{ClipboardAccess, GraphemeWidthMethod, OSCColorReportFormat},
};
use ghostty_datastruct::blocking_queue::Timeout; use ghostty_datastruct::blocking_queue::Timeout;
use ghostty_renderer::message::Message as RendererMessage; use ghostty_renderer::{message::Message as RendererMessage, size::Size, state::InspectorHook};
use ghostty_renderer::size::Size; use ghostty_terminal::{
use ghostty_renderer::state::InspectorHook; kitty::graphics_storage::TerminalInfo,
use ghostty_terminal::kitty::graphics_storage::TerminalInfo; point::{Coordinate, Point},
use ghostty_terminal::point::{Coordinate, Point}; screen::Scroll,
use ghostty_terminal::screen::Scroll; screen_set::Key as ScreenKey,
use ghostty_terminal::screen_set::Key as ScreenKey; terminal::{Colors, Options as TerminalOptions, ScrollViewport, Terminal},
use ghostty_terminal::terminal::{Colors, Options as TerminalOptions, ScrollViewport, Terminal}; };
use ghostty_vt::color::{DynamicPalette, DynamicRgb, Palette}; use ghostty_vt::{
use ghostty_vt::csi; color::{DynamicPalette, DynamicRgb, Palette},
use ghostty_vt::kitty::graphics_command::Delete as KittyDelete; csi,
use ghostty_vt::modes::{Mode, ModePacked}; kitty::graphics_command::Delete as KittyDelete,
use std::sync::MutexGuard; modes::{Mode, ModePacked},
};
use crate::backend::{self, Backend}; use crate::{
use crate::exec; backend::{self, Backend},
use crate::mailbox::Mailbox; exec,
use crate::message::{Message, SizeReport}; mailbox::Mailbox,
use crate::options::Options; message::{Message, SizeReport},
use crate::sinks::{RendererMailbox, SurfaceMailbox}; options::Options,
use crate::state::{SharedState, SharedStateExt, State}; sinks::{RendererMailbox, SurfaceMailbox},
use crate::stream_handler::{HandlerOptions, HandlerState, TerminalStream}; state::{SharedState, SharedStateExt, State},
use crate::wakeup::Wakeup; stream_handler::{HandlerOptions, HandlerState, TerminalStream},
wakeup::Wakeup,
};
/// Errors from termio initialization and thread setup. /// Errors from termio initialization and thread setup.
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
+13 -10
View File
@@ -18,22 +18,25 @@
//! deadlines (selection scroll, resize coalescing, synchronized-output reset, //! deadlines (selection scroll, resize coalescing, synchronized-output reset,
//! termios polling). See [`Thread::thread_main`]. //! termios polling). See [`Thread::thread_main`].
use std::io; use std::{
use std::time::{Duration, Instant}; io,
time::{Duration, Instant},
};
use ghostty_apprt::surface::Message as SurfaceMessage; use ghostty_apprt::surface::Message as SurfaceMessage;
use ghostty_datastruct::blocking_queue::Timeout; use ghostty_datastruct::blocking_queue::Timeout;
use ghostty_renderer::size::Size; use ghostty_renderer::size::Size;
use ghostty_vt::csi; use ghostty_vt::{csi, modes::Mode};
use ghostty_vt::modes::Mode;
use rustix::event::{PollFd, PollFlags}; use rustix::event::{PollFd, PollFlags};
use crate::backend::ThreadData as BackendThreadData; use crate::{
use crate::exec; backend::ThreadData as BackendThreadData,
use crate::message::Message; exec,
use crate::state::SharedStateExt; message::Message,
use crate::termio::{Error, Termio, ThreadData}; state::SharedStateExt,
use crate::wakeup::Wakeup; termio::{Error, Termio, ThreadData},
wakeup::Wakeup,
};
/// The number of milliseconds to coalesce certain messages like resize for. /// The number of milliseconds to coalesce certain messages like resize for.
/// Not all message types are coalesced. /// Not all message types are coalesced.
+7 -4
View File
@@ -5,9 +5,11 @@
//! thread, any number of times; the waiter calls [`Wakeup::drain`] after //! thread, any number of times; the waiter calls [`Wakeup::drain`] after
//! `poll` reports the fd readable. //! `poll` reports the fd readable.
use std::io; use std::{
use std::os::fd::{AsFd, BorrowedFd, OwnedFd}; io,
use std::sync::Arc; os::fd::{AsFd, BorrowedFd, OwnedFd},
sync::Arc,
};
use rustix::event::{EventfdFlags, eventfd}; use rustix::event::{EventfdFlags, eventfd};
@@ -74,9 +76,10 @@ impl Wakeup {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use rustix::event::{PollFd, PollFlags, poll}; use rustix::event::{PollFd, PollFlags, poll};
use super::*;
fn readable(w: &Wakeup) -> bool { fn readable(w: &Wakeup) -> bool {
let mut fds = [PollFd::from_borrowed_fd(w.as_fd(), PollFlags::IN)]; let mut fds = [PollFd::from_borrowed_fd(w.as_fd(), PollFlags::IN)];
poll( poll(
+32 -17
View File
@@ -3,28 +3,43 @@
//! `Termio` + `Thread` (IO thread) + the pty read thread, against a real //! `Termio` + `Thread` (IO thread) + the pty read thread, against a real
//! `Terminal`. //! `Terminal`.
use std::sync::Arc; use std::{
use std::sync::Mutex; sync::{
use std::sync::atomic::{AtomicUsize, Ordering}; Arc,
use std::thread::JoinHandle; Mutex,
use std::time::{Duration, Instant}; atomic::{AtomicUsize, Ordering},
},
thread::JoinHandle,
time::{Duration, Instant},
};
use crossbeam_channel::{Receiver, Sender, unbounded}; use crossbeam_channel::{Receiver, Sender, unbounded};
use ghostty_apprt::surface::Message as SurfaceMessage; use ghostty_apprt::surface::Message as SurfaceMessage;
use ghostty_config::command::Command as ConfigCommand; use ghostty_config::{
use ghostty_config::config::Config; command::Command as ConfigCommand,
use ghostty_config::io::ReadableIO; config::Config,
use ghostty_config::types_b::{LinuxCgroup, ShellIntegration}; io::ReadableIO,
types_b::{LinuxCgroup, ShellIntegration},
};
use ghostty_datastruct::blocking_queue::Timeout; use ghostty_datastruct::blocking_queue::Timeout;
use ghostty_renderer::message::Message as RendererMessage; use ghostty_renderer::{
use ghostty_renderer::size::{CellSize, Padding, ScreenSize, Size}; message::Message as RendererMessage,
use ghostty_termio::SharedStateExt; size::{CellSize, Padding, ScreenSize, Size},
use ghostty_termio::backend::{self, Backend}; };
use ghostty_termio::exec;
use ghostty_termio::message::Message;
use ghostty_termio::termio::DerivedConfig;
use ghostty_termio::{ use ghostty_termio::{
Mailbox, Options, RendererMailbox, SharedState, SurfaceMailbox, Termio, Thread, Wakeup, Mailbox,
Options,
RendererMailbox,
SharedState,
SharedStateExt,
SurfaceMailbox,
Termio,
Thread,
Wakeup,
backend::{self, Backend},
exec,
message::Message,
termio::DerivedConfig,
}; };
struct SurfaceRec(Sender<SurfaceMessage>); struct SurfaceRec(Sender<SurfaceMessage>);
+1 -4
View File
@@ -17,10 +17,7 @@ mod props;
#[path = "build_support/ucd.rs"] #[path = "build_support/ucd.rs"]
mod ucd; mod ucd;
use std::env; use std::{env, fmt::Write as _, fs, path::PathBuf};
use std::fmt::Write as _;
use std::fs;
use std::path::PathBuf;
fn main() { fn main() {
let manifest = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap()); let manifest = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap());
+2 -2
View File
@@ -17,9 +17,9 @@
clippy::expect_used clippy::expect_used
)] )]
use std::{fs, path::Path};
use crate::props::{GraphemeBreakNoControl as Gb, Properties}; use crate::props::{GraphemeBreakNoControl as Gb, Properties};
use std::fs;
use std::path::Path;
/// Highest codepoint known to the UCD (`uucode.config.max_code_point`). /// Highest codepoint known to the UCD (`uucode.config.max_code_point`).
pub const MAX_CODE_POINT: u32 = 0x10FFFF; pub const MAX_CODE_POINT: u32 = 0x10FFFF;
+3 -3
View File
@@ -2,8 +2,7 @@
//! `x.grapheme.computeGraphemeBreakNoControl` precomputed for every //! `x.grapheme.computeGraphemeBreakNoControl` precomputed for every
//! combination of state and break properties. //! combination of state and break properties.
use crate::props::GraphemeBreakNoControl as Gb; use crate::{props::GraphemeBreakNoControl as Gb, props_table::table};
use crate::props_table::table;
/// State carried between sequential [`grapheme_break`] calls /// State carried between sequential [`grapheme_break`] calls
/// (`uucode.grapheme.BreakState`). /// (`uucode.grapheme.BreakState`).
@@ -312,9 +311,10 @@ pub fn grapheme_break_props(gb1: Gb, gb2: Gb, state: &mut BreakState) -> bool {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use std::path::Path; use std::path::Path;
use super::*;
#[test] #[test]
fn grapheme_break_emoji_modifier() { fn grapheme_break_emoji_modifier() {
// Emoji and modifier // Emoji and modifier
+1 -2
View File
@@ -14,8 +14,7 @@
clippy::expect_used clippy::expect_used
)] )]
use std::collections::HashMap; use std::{collections::HashMap, fmt::Write as _};
use std::fmt::Write as _;
const BLOCK_SIZE: usize = 256; const BLOCK_SIZE: usize = 256;
+4 -2
View File
@@ -1,8 +1,10 @@
//! The generated Unicode property lookup table for Ghostty //! The generated Unicode property lookup table for Ghostty
//! (`props_table.zig`). Generated by `build.rs`. //! (`props_table.zig`). Generated by `build.rs`.
use crate::lut::Tables; use crate::{
use crate::props::{GraphemeBreakNoControl, Properties}; lut::Tables,
props::{GraphemeBreakNoControl, Properties},
};
mod generated { mod generated {
use super::{GraphemeBreakNoControl, Properties}; use super::{GraphemeBreakNoControl, Properties};
+4 -2
View File
@@ -2,8 +2,10 @@
//! into a stream. The hook/put/unhook functions are meant to be called from //! into a stream. The hook/put/unhook functions are meant to be called from
//! the stream's dcsHook, dcsPut, and dcsUnhook functions, respectively. //! the stream's dcsHook, dcsPut, and dcsUnhook functions, respectively.
use crate::parser::Dcs; use crate::{
use crate::tmux::control::{Notification, Parser as TmuxParser}; parser::Dcs,
tmux::control::{Notification, Parser as TmuxParser},
};
/// DCS command handler. /// DCS command handler.
#[derive(Debug)] #[derive(Debug)]
+2 -2
View File
@@ -1,9 +1,9 @@
//! Kitty color protocol (ZIG/src/terminal/kitty/color.zig). //! Kitty color protocol (ZIG/src/terminal/kitty/color.zig).
use crate::color::Rgb;
use crate::osc::Terminator;
use std::fmt; use std::fmt;
use crate::{color::Rgb, osc::Terminator};
/// OSC 21 payload. /// OSC 21 payload.
#[derive(Debug, Clone, PartialEq, Default)] #[derive(Debug, Clone, PartialEq, Default)]
pub struct OSC { pub struct OSC {
@@ -69,8 +69,10 @@ fn parse_int(buf: &[u8], signed: bool) -> Result<u32, Error> {
/// Decode base64 payload data. The reference implementation uses simdutf, /// Decode base64 payload data. The reference implementation uses simdutf,
/// which ignores ASCII whitespace and tolerates missing padding. /// which ignores ASCII whitespace and tolerates missing padding.
pub fn decode_base64(input: &[u8]) -> Result<Vec<u8>, Error> { pub fn decode_base64(input: &[u8]) -> Result<Vec<u8>, Error> {
use base64::Engine; use base64::{
use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig}; Engine,
engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig},
};
const ENGINE: GeneralPurpose = GeneralPurpose::new( const ENGINE: GeneralPurpose = GeneralPurpose::new(
&base64::alphabet::STANDARD, &base64::alphabet::STANDARD,
GeneralPurposeConfig::new() GeneralPurposeConfig::new()
+1 -2
View File
@@ -18,8 +18,7 @@
pub mod encoding; pub mod encoding;
pub mod parsers; pub mod parsers;
pub use parsers::color; pub use parsers::{color, semantic_prompt};
pub use parsers::semantic_prompt;
use crate::kitty::color as kitty_color; use crate::kitty::color as kitty_color;
+4 -2
View File
@@ -1,8 +1,10 @@
//! OSC color operations: 4, 5, 10-19, 104, 105, 110-119 //! OSC color operations: 4, 5, 10-19, 104, 105, 110-119
//! (ZIG/src/terminal/osc/parsers/color.zig). //! (ZIG/src/terminal/osc/parsers/color.zig).
use crate::color::{Dynamic as DynamicColor, Rgb, Special as SpecialColor}; use crate::{
use crate::osc::{Command, Parser, State, Terminator}; color::{Dynamic as DynamicColor, Rgb, Special as SpecialColor},
osc::{Command, Parser, State, Terminator},
};
/// The possible operations we support for colors. /// The possible operations we support for colors.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
@@ -1,8 +1,10 @@
//! OSC 21, the Kitty Color Protocol (ZIG/src/terminal/osc/parsers/kitty_color.zig). //! OSC 21, the Kitty Color Protocol (ZIG/src/terminal/osc/parsers/kitty_color.zig).
use crate::color::Rgb; use crate::{
use crate::kitty::color::{Kind, OSC, Request}; color::Rgb,
use crate::osc::{Command, Parser, State, Terminator}; kitty::color::{Kind, OSC, Request},
osc::{Command, Parser, State, Terminator},
};
/// Parse OSC 21, the Kitty Color Protocol. /// Parse OSC 21, the Kitty Color Protocol.
pub fn parse(parser: &mut Parser, terminator_ch: Option<u8>) -> Option<Command> { pub fn parse(parser: &mut Parser, terminator_ch: Option<u8>) -> Option<Command> {
@@ -3,8 +3,10 @@
//! //!
//! <https://gitlab.freedesktop.org/Per_Bothner/specifications/blob/master/proposals/semantic-prompts.md> //! <https://gitlab.freedesktop.org/Per_Bothner/specifications/blob/master/proposals/semantic-prompts.md>
use crate::osc::{Command as OscCommand, Parser, State}; use crate::{
use crate::string_encoding::{printf_q_decode, url_percent_decode}; osc::{Command as OscCommand, Parser, State},
string_encoding::{printf_q_decode, url_percent_decode},
};
/// Error returned when decoding a command line fails (Zig /// Error returned when decoding a command line fails (Zig
/// `error.DecodeError`). /// `error.DecodeError`).
+1 -2
View File
@@ -13,8 +13,7 @@
//! through `params()` / `intermediates()` accessors, so an `Action` owns its //! through `params()` / `intermediates()` accessors, so an `Action` owns its
//! data and is independent of the parser's lifetime. //! data and is independent of the parser's lifetime.
use crate::osc; use crate::{osc, parse_table::TABLE};
use crate::parse_table::TABLE;
/// Maximum number of CSI parameters. This is a const in Ghostty so we /// Maximum number of CSI parameters. This is a const in Ghostty so we
/// match it. /// match it.
+6 -3
View File
@@ -4,8 +4,10 @@
//! C-ABI helpers of the Zig version (`Attribute.C`, `cval`, `lib.Enum` //! C-ABI helpers of the Zig version (`Attribute.C`, `cval`, `lib.Enum`
//! `Tag`) are intentionally not ported. //! `Tag`) are intentionally not ported.
use crate::color::{Name, Rgb}; use crate::{
use crate::parser::{MAX_PARAMS, SepList}; color::{Name, Rgb},
parser::{MAX_PARAMS, SepList},
};
/// Attribute type for SGR /// Attribute type for SGR
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -413,9 +415,10 @@ impl<'a> Iterator for Parser<'a> {
mod tests { mod tests {
#![allow(clippy::unwrap_used)] #![allow(clippy::unwrap_used)]
use super::*;
use Attribute as A; use Attribute as A;
use super::*;
fn rgb(r: u8, g: u8, b: u8) -> Rgb { fn rgb(r: u8, g: u8, b: u8) -> Rgb {
Rgb { r, g, b } Rgb { r, g, b }
} }
+16 -13
View File
@@ -18,18 +18,20 @@
#![allow(clippy::single_match_else, clippy::if_not_else)] #![allow(clippy::single_match_else, clippy::if_not_else)]
use crate::ansi; use crate::{
use crate::charsets; ansi,
use crate::csi; charsets,
use crate::device_status; csi,
use crate::kitty; device_status,
use crate::modes; kitty,
use crate::mouse_shape::MouseShape; modes,
use crate::osc; mouse_shape::MouseShape,
use crate::parser::{self, Csi, Esc, MAX_PARAMS, Parser, State}; osc,
use crate::sgr; parser::{self, Csi, Esc, MAX_PARAMS, Parser, State},
use crate::simd; sgr,
use crate::utf8_decoder::Utf8Decoder; simd,
utf8_decoder::Utf8Decoder,
};
macro_rules! define_actions { macro_rules! define_actions {
($( $(#[$meta:meta])* $name:ident $( ( $ty:ty ) )? ),* $(,)?) => { ($( $(#[$meta:meta])* $name:ident $( ( $ty:ty ) )? ),* $(,)?) => {
@@ -1658,9 +1660,10 @@ impl<H: Handler> Stream<H> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
#![allow(clippy::unwrap_used)] #![allow(clippy::unwrap_used)]
use super::*;
use std::convert::Infallible; use std::convert::Infallible;
use super::*;
/// Test handler that forwards every action to a closure. /// Test handler that forwards every action to a closure.
struct F<T, C: FnMut(&mut T, Action<'_>)> { struct F<T, C: FnMut(&mut T, Action<'_>)> {
state: T, state: T,
+2 -2
View File
@@ -1,8 +1,8 @@
//! X11 color names (ZIG/src/terminal/x11_color.zig). //! X11 color names (ZIG/src/terminal/x11_color.zig).
use std::{collections::HashMap, sync::OnceLock};
use crate::color::Rgb; use crate::color::Rgb;
use std::collections::HashMap;
use std::sync::OnceLock;
/// This is the rgb.txt file from the X11 project. This was last sourced /// This is the rgb.txt file from the X11 project. This was last sourced
/// from this location: https://gitlab.freedesktop.org/xorg/app/rgb /// from this location: https://gitlab.freedesktop.org/xorg/app/rgb
+1 -2
View File
@@ -5,8 +5,7 @@
//! `ghostty-cli`; otherwise the configuration is loaded by the GTK runtime //! `ghostty-cli`; otherwise the configuration is loaded by the GTK runtime
//! and the terminal application is run with the real core. //! and the terminal application is run with the real core.
use std::process::ExitCode; use std::{process::ExitCode, rc::Rc};
use std::rc::Rc;
use ghostty_apprt::ipc; use ghostty_apprt::ipc;
use ghostty_apprt_gtk::{adw_version, gtk_version}; use ghostty_apprt_gtk::{adw_version, gtk_version};