repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/input/layout.rs | zellij-utils/src/input/layout.rs | //! The layout system.
// Layouts have been moved from [`zellij-server`] to
// [`zellij-utils`] in order to provide more helpful
// error messages to the user until a more general
// logging system is in place.
// In case there is a logging system in place evaluate,
// if [`zellij-utils`], or [`zellij-server`] is a proper
// place.
// If plugins should be able to depend on the layout system
// then [`zellij-utils`] could be a proper place.
#[cfg(not(target_family = "wasm"))]
use crate::downloader::Downloader;
use crate::{
data::{Direction, LayoutInfo},
home::{default_layout_dir, find_default_config_dir},
input::{
command::RunCommand,
config::{Config, ConfigError},
},
pane_size::{Constraint, Dimension, PaneGeom},
setup::{self},
};
#[cfg(not(target_family = "wasm"))]
use async_std::task;
use std::cmp::Ordering;
use std::fmt::{Display, Formatter};
use std::str::FromStr;
use super::plugins::{PluginAliases, PluginTag, PluginsConfigError};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::vec::Vec;
use std::{
fmt,
ops::Not,
path::{Path, PathBuf},
};
use std::{fs::File, io::prelude::*};
use url::Url;
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone, Copy)]
pub enum SplitDirection {
Horizontal,
Vertical,
}
impl Not for SplitDirection {
type Output = Self;
fn not(self) -> Self::Output {
match self {
SplitDirection::Horizontal => SplitDirection::Vertical,
SplitDirection::Vertical => SplitDirection::Horizontal,
}
}
}
impl From<Direction> for SplitDirection {
fn from(direction: Direction) -> Self {
match direction {
Direction::Left | Direction::Right => SplitDirection::Horizontal,
Direction::Down | Direction::Up => SplitDirection::Vertical,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
pub enum SplitSize {
#[serde(alias = "percent")]
Percent(usize), // 1 to 100
#[serde(alias = "fixed")]
Fixed(usize), // An absolute number of columns or rows
}
impl SplitSize {
pub fn to_fixed(&self, full_size: usize) -> usize {
match self {
SplitSize::Percent(percent) => {
((*percent as f64 / 100.0) * full_size as f64).floor() as usize
},
SplitSize::Fixed(fixed) => *fixed,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Hash)]
pub enum RunPluginOrAlias {
RunPlugin(RunPlugin),
Alias(PluginAlias),
}
impl Default for RunPluginOrAlias {
fn default() -> Self {
RunPluginOrAlias::RunPlugin(Default::default())
}
}
impl RunPluginOrAlias {
pub fn location_string(&self) -> String {
match self {
RunPluginOrAlias::RunPlugin(run_plugin) => run_plugin.location.display(),
RunPluginOrAlias::Alias(plugin_alias) => plugin_alias.name.clone(),
}
}
pub fn populate_run_plugin_if_needed(&mut self, plugin_aliases: &PluginAliases) {
if let RunPluginOrAlias::Alias(run_plugin_alias) = self {
if run_plugin_alias.run_plugin.is_some() {
log::warn!("Overriding plugin alias");
}
let merged_run_plugin = plugin_aliases
.aliases
.get(run_plugin_alias.name.as_str())
.map(|r| {
let mut merged_run_plugin = r.clone().merge_configuration(
&run_plugin_alias
.configuration
.as_ref()
.map(|c| c.inner().clone()),
);
// if the alias has its own cwd, it should always override the alias
// value's cwd
if run_plugin_alias.initial_cwd.is_some() {
merged_run_plugin.initial_cwd = run_plugin_alias.initial_cwd.clone();
}
merged_run_plugin
});
run_plugin_alias.run_plugin = merged_run_plugin;
}
}
pub fn get_run_plugin(&self) -> Option<RunPlugin> {
match self {
RunPluginOrAlias::RunPlugin(run_plugin) => Some(run_plugin.clone()),
RunPluginOrAlias::Alias(plugin_alias) => plugin_alias.run_plugin.clone(),
}
}
pub fn get_configuration(&self) -> Option<PluginUserConfiguration> {
self.get_run_plugin().map(|r| r.configuration.clone())
}
pub fn get_initial_cwd(&self) -> Option<PathBuf> {
self.get_run_plugin().and_then(|r| r.initial_cwd.clone())
}
pub fn from_url(
url: &str,
configuration: &Option<BTreeMap<String, String>>,
alias_dict: Option<&PluginAliases>,
cwd: Option<PathBuf>,
) -> Result<Self, String> {
match RunPluginLocation::parse(&url, cwd) {
Ok(location) => Ok(RunPluginOrAlias::RunPlugin(RunPlugin {
_allow_exec_host_cmd: false,
location,
configuration: configuration
.as_ref()
.map(|c| PluginUserConfiguration::new(c.clone()))
.unwrap_or_default(),
..Default::default()
})),
Err(PluginsConfigError::InvalidUrlScheme(_))
| Err(PluginsConfigError::InvalidUrl(..)) => {
let mut plugin_alias = PluginAlias::new(&url, configuration, None);
if let Some(alias_dict) = alias_dict {
plugin_alias.run_plugin = alias_dict
.aliases
.get(url)
.map(|r| r.clone().merge_configuration(configuration));
}
Ok(RunPluginOrAlias::Alias(plugin_alias))
},
Err(e) => {
return Err(format!("Failed to parse plugin location {url}: {}", e));
},
}
}
pub fn is_equivalent_to_run(&self, run: &Option<Run>) -> bool {
match (self, run) {
(
RunPluginOrAlias::Alias(self_alias),
Some(Run::Plugin(RunPluginOrAlias::Alias(run_alias))),
) => {
self_alias.name == run_alias.name
&& self_alias
.configuration
.as_ref()
// we do the is_empty() checks because an empty configuration is the same as no
// configuration (i.e. None)
.and_then(|c| if c.inner().is_empty() { None } else { Some(c) })
== run_alias.configuration.as_ref().and_then(|c| {
let mut to_compare = c.inner().clone();
// caller_cwd is a special attribute given to alias and should not be
// considered when weighing configuration equivalency
to_compare.remove("caller_cwd");
if to_compare.is_empty() {
None
} else {
Some(c)
}
})
},
(
RunPluginOrAlias::Alias(self_alias),
Some(Run::Plugin(RunPluginOrAlias::RunPlugin(other_run_plugin))),
) => self_alias.run_plugin.as_ref() == Some(other_run_plugin),
(
RunPluginOrAlias::RunPlugin(self_run_plugin),
Some(Run::Plugin(RunPluginOrAlias::RunPlugin(other_run_plugin))),
) => self_run_plugin == other_run_plugin,
_ => false,
}
}
pub fn with_initial_cwd(mut self, initial_cwd: Option<PathBuf>) -> Self {
match self {
RunPluginOrAlias::RunPlugin(ref mut run_plugin) => {
run_plugin.initial_cwd = initial_cwd;
},
RunPluginOrAlias::Alias(ref mut alias) => {
alias.initial_cwd = initial_cwd;
},
}
self
}
pub fn add_initial_cwd(&mut self, initial_cwd: &PathBuf) {
match self {
RunPluginOrAlias::RunPlugin(ref mut run_plugin) => {
run_plugin.initial_cwd = Some(initial_cwd.clone());
},
RunPluginOrAlias::Alias(ref mut alias) => {
alias.initial_cwd = Some(initial_cwd.clone());
},
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub enum Run {
#[serde(rename = "plugin")]
Plugin(RunPluginOrAlias),
#[serde(rename = "command")]
Command(RunCommand),
EditFile(PathBuf, Option<usize>, Option<PathBuf>),
Cwd(PathBuf),
}
impl Run {
pub fn merge(base: &Option<Run>, other: &Option<Run>) -> Option<Run> {
// This method is necessary to merge between pane_templates and their consumers
// TODO: reconsider the way we parse command/edit/plugin pane_templates from layouts to prevent this
// madness
// TODO: handle Plugin variants once there's a need
match (base, other) {
(Some(Run::Command(base_run_command)), Some(Run::Command(other_run_command))) => {
let mut merged = other_run_command.clone();
if merged.cwd.is_none() && base_run_command.cwd.is_some() {
merged.cwd = base_run_command.cwd.clone();
}
if merged.args.is_empty() && !base_run_command.args.is_empty() {
merged.args = base_run_command.args.clone();
}
Some(Run::Command(merged))
},
(Some(Run::Command(base_run_command)), Some(Run::Cwd(other_cwd))) => {
let mut merged = base_run_command.clone();
merged.cwd = Some(other_cwd.clone());
Some(Run::Command(merged))
},
(Some(Run::Cwd(base_cwd)), Some(Run::Command(other_command))) => {
let mut merged = other_command.clone();
if merged.cwd.is_none() {
merged.cwd = Some(base_cwd.clone());
}
Some(Run::Command(merged))
},
(
Some(Run::Command(base_run_command)),
Some(Run::EditFile(file_to_edit, line_number, edit_cwd)),
) => match &base_run_command.cwd {
Some(cwd) => Some(Run::EditFile(
cwd.join(&file_to_edit),
*line_number,
Some(cwd.join(edit_cwd.clone().unwrap_or_default())),
)),
None => Some(Run::EditFile(
file_to_edit.clone(),
*line_number,
edit_cwd.clone(),
)),
},
(Some(Run::Cwd(cwd)), Some(Run::EditFile(file_to_edit, line_number, edit_cwd))) => {
let cwd = edit_cwd.clone().unwrap_or(cwd.clone());
Some(Run::EditFile(
cwd.join(&file_to_edit),
*line_number,
Some(cwd),
))
},
(Some(_base), Some(other)) => Some(other.clone()),
(Some(base), _) => Some(base.clone()),
(None, Some(other)) => Some(other.clone()),
(None, None) => None,
}
}
pub fn add_cwd(&mut self, cwd: &PathBuf) {
match self {
Run::Command(run_command) => match run_command.cwd.as_mut() {
Some(run_cwd) => {
*run_cwd = cwd.join(&run_cwd);
},
None => {
run_command.cwd = Some(cwd.clone());
},
},
Run::EditFile(path_to_file, _line_number, edit_cwd) => {
match edit_cwd.as_mut() {
Some(edit_cwd) => {
*edit_cwd = cwd.join(&edit_cwd);
},
None => {
let _ = edit_cwd.insert(cwd.clone());
},
};
*path_to_file = cwd.join(&path_to_file);
},
Run::Cwd(path) => {
*path = cwd.join(&path);
},
Run::Plugin(run_plugin_or_alias) => {
run_plugin_or_alias.add_initial_cwd(&cwd);
},
}
}
pub fn add_args(&mut self, args: Option<Vec<String>>) {
// overrides the args of a Run::Command if they are Some
// and not empty
if let Some(args) = args {
if let Run::Command(run_command) = self {
if !args.is_empty() {
run_command.args = args.clone();
}
}
}
}
pub fn add_close_on_exit(&mut self, close_on_exit: Option<bool>) {
// overrides the hold_on_close of a Run::Command if it is Some
// and not empty
if let Some(close_on_exit) = close_on_exit {
if let Run::Command(run_command) = self {
run_command.hold_on_close = !close_on_exit;
}
}
}
pub fn add_start_suspended(&mut self, start_suspended: Option<bool>) {
// overrides the hold_on_start of a Run::Command if they are Some
// and not empty
if let Some(start_suspended) = start_suspended {
if let Run::Command(run_command) = self {
run_command.hold_on_start = start_suspended;
}
}
}
pub fn is_same_category(first: &Option<Run>, second: &Option<Run>) -> bool {
match (first, second) {
(Some(Run::Plugin(..)), Some(Run::Plugin(..))) => true,
(Some(Run::Command(..)), Some(Run::Command(..))) => true,
(Some(Run::EditFile(..)), Some(Run::EditFile(..))) => true,
(Some(Run::Cwd(..)), Some(Run::Cwd(..))) => true,
_ => false,
}
}
pub fn is_terminal(run: &Option<Run>) -> bool {
match run {
Some(Run::Command(..)) | Some(Run::EditFile(..)) | Some(Run::Cwd(..)) | None => true,
_ => false,
}
}
pub fn get_cwd(&self) -> Option<PathBuf> {
match self {
Run::Plugin(_) => None, // TBD
Run::Command(run_command) => run_command.cwd.clone(),
Run::EditFile(_file, _line_num, cwd) => cwd.clone(),
Run::Cwd(cwd) => Some(cwd.clone()),
}
}
pub fn get_run_plugin(&self) -> Option<RunPlugin> {
match self {
Run::Plugin(RunPluginOrAlias::RunPlugin(run_plugin)) => Some(run_plugin.clone()),
Run::Plugin(RunPluginOrAlias::Alias(plugin_alias)) => {
plugin_alias.run_plugin.as_ref().map(|r| r.clone())
},
_ => None,
}
}
pub fn populate_run_plugin_if_needed(&mut self, alias_dict: &PluginAliases) {
match self {
Run::Plugin(run_plugin_alias) => {
run_plugin_alias.populate_run_plugin_if_needed(alias_dict)
},
_ => {},
}
}
}
#[allow(clippy::derive_hash_xor_eq)]
#[derive(Debug, Serialize, Deserialize, Clone, Hash, Default)]
pub struct RunPlugin {
#[serde(default)]
pub _allow_exec_host_cmd: bool,
pub location: RunPluginLocation,
pub configuration: PluginUserConfiguration,
pub initial_cwd: Option<PathBuf>,
}
impl RunPlugin {
pub fn from_url(url: &str) -> Result<Self, PluginsConfigError> {
let location = RunPluginLocation::parse(url, None)?;
Ok(RunPlugin {
location,
..Default::default()
})
}
pub fn with_configuration(mut self, configuration: BTreeMap<String, String>) -> Self {
self.configuration = PluginUserConfiguration::new(configuration);
self
}
pub fn with_initial_cwd(mut self, initial_cwd: Option<PathBuf>) -> Self {
self.initial_cwd = initial_cwd;
self
}
pub fn merge_configuration(mut self, configuration: &Option<BTreeMap<String, String>>) -> Self {
if let Some(configuration) = configuration {
self.configuration.merge(configuration);
}
self
}
}
#[derive(Debug, Serialize, Deserialize, Clone, Default, Eq)]
pub struct PluginAlias {
pub name: String,
pub configuration: Option<PluginUserConfiguration>,
pub initial_cwd: Option<PathBuf>,
pub run_plugin: Option<RunPlugin>,
}
impl PartialEq for PluginAlias {
fn eq(&self, other: &Self) -> bool {
// NOTE: Keep this in sync with what the `Hash` trait impl does.
self.name == other.name && self.configuration == other.configuration
}
}
impl std::hash::Hash for PluginAlias {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
// NOTE: Keep this in sync with what the `PartiqlEq` trait impl does.
self.name.hash(state);
self.configuration.hash(state);
}
}
impl PluginAlias {
pub fn new(
name: &str,
configuration: &Option<BTreeMap<String, String>>,
initial_cwd: Option<PathBuf>,
) -> Self {
PluginAlias {
name: name.to_owned(),
configuration: configuration
.as_ref()
.map(|c| PluginUserConfiguration::new(c.clone())),
initial_cwd,
..Default::default()
}
}
pub fn set_caller_cwd_if_not_set(&mut self, caller_cwd: Option<PathBuf>) {
// we do this only for an alias because in all other cases this will be handled by the
// "cwd" configuration key above
// for an alias we might have cases where the cwd is defined on the alias but we still
// want to pass the "caller" cwd for the plugin the alias resolves into (eg. a
// filepicker that has access to the whole filesystem but wants to start in a specific
// folder)
if let Some(caller_cwd) = caller_cwd {
if self
.configuration
.as_ref()
.map(|c| c.inner().get("caller_cwd").is_none())
.unwrap_or(true)
{
let configuration = self
.configuration
.get_or_insert_with(|| PluginUserConfiguration::new(BTreeMap::new()));
configuration.insert("caller_cwd", caller_cwd.display().to_string());
}
}
}
}
#[allow(clippy::derive_hash_xor_eq)]
impl PartialEq for RunPlugin {
fn eq(&self, other: &Self) -> bool {
// TODO: normalize paths here if the location is a file so that relative/absolute paths
// will work properly
(&self.location, &self.configuration) == (&other.location, &other.configuration)
}
}
impl Eq for RunPlugin {}
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct PluginUserConfiguration(BTreeMap<String, String>);
impl PluginUserConfiguration {
pub fn new(mut configuration: BTreeMap<String, String>) -> Self {
// reserved words
configuration.remove("hold_on_close");
configuration.remove("hold_on_start");
configuration.remove("cwd");
configuration.remove("name");
configuration.remove("direction");
configuration.remove("floating");
configuration.remove("move_to_focused_tab");
configuration.remove("launch_new");
configuration.remove("payload");
configuration.remove("skip_cache");
configuration.remove("title");
configuration.remove("in_place");
configuration.remove("skip_plugin_cache");
PluginUserConfiguration(configuration)
}
pub fn inner(&self) -> &BTreeMap<String, String> {
&self.0
}
pub fn insert(&mut self, config_key: impl Into<String>, config_value: impl Into<String>) {
self.0.insert(config_key.into(), config_value.into());
}
pub fn merge(&mut self, other_config: &BTreeMap<String, String>) {
for (key, value) in other_config {
self.0.insert(key.to_owned(), value.clone());
}
}
}
impl FromStr for PluginUserConfiguration {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut ret = BTreeMap::new();
let configs = s.split(',');
for config in configs {
let mut config = config.split('=');
let key = config.next().ok_or("invalid configuration key")?.to_owned();
let value = config.map(|c| c.to_owned()).collect::<Vec<_>>().join("=");
ret.insert(key, value);
}
Ok(PluginUserConfiguration(ret))
}
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Hash)]
pub enum RunPluginLocation {
File(PathBuf),
Zellij(PluginTag),
Remote(String),
}
impl Default for RunPluginLocation {
fn default() -> Self {
RunPluginLocation::File(Default::default())
}
}
impl RunPluginLocation {
pub fn parse(location: &str, cwd: Option<PathBuf>) -> Result<Self, PluginsConfigError> {
let url = Url::parse(location)?;
let decoded_path = percent_encoding::percent_decode_str(url.path()).decode_utf8_lossy();
match url.scheme() {
"zellij" => Ok(Self::Zellij(PluginTag::new(decoded_path))),
"file" => {
let path = if location.starts_with("file:/") {
// Path is absolute, its safe to use URL path.
//
// This is the case if the scheme and : delimiter are followed by a / slash
PathBuf::from(decoded_path.as_ref())
} else if location.starts_with("file:~") {
// Unwrap is safe here since location is a valid URL
PathBuf::from(location.strip_prefix("file:").unwrap())
} else {
// URL dep doesn't handle relative paths with `file` schema properly,
// it always makes them absolute. Use raw location string instead.
//
// Unwrap is safe here since location is a valid URL
let stripped = location.strip_prefix("file:").unwrap();
match cwd {
Some(cwd) => cwd.join(stripped),
None => PathBuf::from(stripped),
}
};
let path = match shellexpand::full(&path.to_string_lossy().to_string()) {
Ok(s) => PathBuf::from(s.as_ref()),
Err(e) => {
log::error!("Failed to shell expand plugin path: {}", e);
path
},
};
Ok(Self::File(path))
},
"https" | "http" => Ok(Self::Remote(url.as_str().to_owned())),
_ => Err(PluginsConfigError::InvalidUrlScheme(url)),
}
}
pub fn display(&self) -> String {
match self {
RunPluginLocation::File(pathbuf) => format!("file:{}", pathbuf.display()),
RunPluginLocation::Zellij(plugin_tag) => format!("zellij:{}", plugin_tag),
RunPluginLocation::Remote(url) => String::from(url),
}
}
}
impl From<&RunPluginLocation> for Url {
fn from(location: &RunPluginLocation) -> Self {
let url = match location {
RunPluginLocation::File(path) => format!(
"file:{}",
path.clone().into_os_string().into_string().unwrap()
),
RunPluginLocation::Zellij(tag) => format!("zellij:{}", tag),
RunPluginLocation::Remote(url) => String::from(url),
};
Self::parse(&url).unwrap()
}
}
impl fmt::Display for RunPluginLocation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
match self {
Self::File(path) => write!(
f,
"{}",
path.clone().into_os_string().into_string().unwrap()
),
Self::Zellij(tag) => write!(f, "{}", tag),
Self::Remote(url) => write!(f, "{}", url),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Ord, PartialOrd, Serialize, Deserialize)]
pub enum LayoutConstraint {
MaxPanes(usize),
MinPanes(usize),
ExactPanes(usize),
NoConstraint,
}
impl Display for LayoutConstraint {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
match self {
LayoutConstraint::MaxPanes(max_panes) => write!(f, "max_panes={}", max_panes),
LayoutConstraint::MinPanes(min_panes) => write!(f, "min_panes={}", min_panes),
LayoutConstraint::ExactPanes(exact_panes) => write!(f, "exact_panes={}", exact_panes),
LayoutConstraint::NoConstraint => write!(f, ""),
}
}
}
pub type SwapTiledLayout = (BTreeMap<LayoutConstraint, TiledPaneLayout>, Option<String>); // Option<String> is the swap layout name
pub type SwapFloatingLayout = (
BTreeMap<LayoutConstraint, Vec<FloatingPaneLayout>>,
Option<String>,
); // Option<String> is the swap layout name
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Default)]
pub struct Layout {
pub tabs: Vec<(Option<String>, TiledPaneLayout, Vec<FloatingPaneLayout>)>,
pub focused_tab_index: Option<usize>,
pub template: Option<(TiledPaneLayout, Vec<FloatingPaneLayout>)>,
pub swap_layouts: Vec<(TiledPaneLayout, Vec<FloatingPaneLayout>)>,
pub swap_tiled_layouts: Vec<SwapTiledLayout>,
pub swap_floating_layouts: Vec<SwapFloatingLayout>,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub enum PercentOrFixed {
Percent(usize), // 1 to 100
Fixed(usize), // An absolute number of columns or rows
}
impl From<Dimension> for PercentOrFixed {
fn from(dimension: Dimension) -> Self {
match dimension.constraint {
Constraint::Percent(percent) => PercentOrFixed::Percent(percent as usize),
Constraint::Fixed(fixed_size) => PercentOrFixed::Fixed(fixed_size),
}
}
}
impl PercentOrFixed {
pub fn to_position(&self, whole: usize) -> usize {
match self {
PercentOrFixed::Percent(percent) => {
(whole as f64 / 100.0 * *percent as f64).ceil() as usize
},
PercentOrFixed::Fixed(fixed) => {
if *fixed > whole {
whole
} else {
*fixed
}
},
}
}
}
impl PercentOrFixed {
pub fn is_zero(&self) -> bool {
match self {
PercentOrFixed::Percent(percent) => *percent == 0,
PercentOrFixed::Fixed(fixed) => *fixed == 0,
}
}
}
impl FromStr for PercentOrFixed {
type Err = Box<dyn std::error::Error>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.chars().last() == Some('%') {
let char_count = s.chars().count();
let percent_size = usize::from_str_radix(&s[..char_count.saturating_sub(1)], 10)?;
if percent_size <= 100 {
Ok(PercentOrFixed::Percent(percent_size))
} else {
Err("Percent must be between 0 and 100".into())
}
} else {
let fixed_size = usize::from_str_radix(s, 10)?;
Ok(PercentOrFixed::Fixed(fixed_size))
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Default)]
pub struct FloatingPaneLayout {
pub name: Option<String>,
pub height: Option<PercentOrFixed>,
pub width: Option<PercentOrFixed>,
pub x: Option<PercentOrFixed>,
pub y: Option<PercentOrFixed>,
pub pinned: Option<bool>,
pub run: Option<Run>,
pub focus: Option<bool>,
pub already_running: bool,
pub pane_initial_contents: Option<String>,
pub logical_position: Option<usize>,
}
impl FloatingPaneLayout {
pub fn new() -> Self {
FloatingPaneLayout {
name: None,
height: None,
width: None,
x: None,
y: None,
pinned: None,
run: None,
focus: None,
already_running: false,
pane_initial_contents: None,
logical_position: None,
}
}
pub fn add_cwd_to_layout(&mut self, cwd: &PathBuf) {
match self.run.as_mut() {
Some(run) => run.add_cwd(cwd),
None => {
self.run = Some(Run::Cwd(cwd.clone()));
},
}
}
pub fn add_start_suspended(&mut self, start_suspended: Option<bool>) {
if let Some(run) = self.run.as_mut() {
run.add_start_suspended(start_suspended);
}
}
}
impl From<&TiledPaneLayout> for FloatingPaneLayout {
fn from(pane_layout: &TiledPaneLayout) -> Self {
FloatingPaneLayout {
name: pane_layout.name.clone(),
run: pane_layout.run.clone(),
focus: pane_layout.focus,
..Default::default()
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Default)]
pub struct TiledPaneLayout {
pub children_split_direction: SplitDirection,
pub name: Option<String>,
pub children: Vec<TiledPaneLayout>,
pub split_size: Option<SplitSize>,
pub run: Option<Run>,
pub borderless: bool,
pub focus: Option<bool>,
pub external_children_index: Option<usize>,
pub children_are_stacked: bool,
pub is_expanded_in_stack: bool,
pub exclude_from_sync: Option<bool>,
pub run_instructions_to_ignore: Vec<Option<Run>>,
pub hide_floating_panes: bool, // only relevant if this is the base layout
pub pane_initial_contents: Option<String>,
}
impl TiledPaneLayout {
pub fn insert_children_layout(
&mut self,
children_layout: &mut TiledPaneLayout,
) -> Result<bool, ConfigError> {
// returns true if successfully inserted and false otherwise
match self.external_children_index {
Some(external_children_index) => {
self.children
.insert(external_children_index, children_layout.clone());
self.external_children_index = None;
Ok(true)
},
None => {
for pane in self.children.iter_mut() {
if pane.insert_children_layout(children_layout)? {
return Ok(true);
}
}
Ok(false)
},
}
}
pub fn insert_children_nodes(
&mut self,
children_nodes: &mut Vec<TiledPaneLayout>,
) -> Result<bool, ConfigError> {
// returns true if successfully inserted and false otherwise
match self.external_children_index {
Some(external_children_index) => {
children_nodes.reverse();
for child_node in children_nodes.drain(..) {
self.children.insert(external_children_index, child_node);
}
self.external_children_index = None;
Ok(true)
},
None => {
for pane in self.children.iter_mut() {
if pane.insert_children_nodes(children_nodes)? {
return Ok(true);
}
}
Ok(false)
},
}
}
pub fn children_block_count(&self) -> usize {
let mut count = 0;
if self.external_children_index.is_some() {
count += 1;
}
for pane in &self.children {
count += pane.children_block_count();
}
count
}
pub fn pane_count(&self) -> usize {
if self.children.is_empty() {
1 // self
} else {
let mut pane_count = 0;
for child in &self.children {
pane_count += child.pane_count();
}
pane_count
}
}
pub fn position_panes_in_space(
&self,
space: &PaneGeom,
max_panes: Option<usize>,
ignore_percent_split_sizes: bool,
focus_layout_if_not_focused: bool,
) -> Result<Vec<(TiledPaneLayout, PaneGeom)>, &'static str> {
let layouts = match max_panes {
Some(max_panes) => {
let mut layout_to_split = self.clone();
let pane_count_in_layout = layout_to_split.pane_count();
if max_panes > pane_count_in_layout {
// the + 1 here is because this was previously an "actual" pane and will now
// become just a container, so we need to account for it too
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/input/plugins.rs | zellij-utils/src/input/plugins.rs | //! Plugins configuration metadata
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use thiserror::Error;
use serde::{Deserialize, Serialize};
use url::Url;
use super::layout::{PluginUserConfiguration, RunPlugin, RunPluginLocation};
#[cfg(not(target_family = "wasm"))]
use crate::consts::ASSET_MAP;
pub use crate::data::PluginTag;
use crate::errors::prelude::*;
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct PluginAliases {
pub aliases: BTreeMap<String, RunPlugin>,
}
impl PluginAliases {
pub fn merge(&mut self, other: Self) {
self.aliases.extend(other.aliases);
}
pub fn from_data(aliases: BTreeMap<String, RunPlugin>) -> Self {
PluginAliases { aliases }
}
pub fn list(&self) -> Vec<String> {
self.aliases.keys().cloned().collect()
}
}
/// Plugin metadata
#[derive(Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub struct PluginConfig {
/// Path of the plugin, see resolve_wasm_bytes for resolution semantics
pub path: PathBuf,
/// Allow command execution from plugin
pub _allow_exec_host_cmd: bool,
/// Original location of the
pub location: RunPluginLocation,
/// Custom configuration for this plugin
pub userspace_configuration: PluginUserConfiguration,
/// plugin initial working directory
pub initial_cwd: Option<PathBuf>,
}
impl PluginConfig {
pub fn from_run_plugin(run_plugin: &RunPlugin) -> Option<PluginConfig> {
match &run_plugin.location {
RunPluginLocation::File(path) => Some(PluginConfig {
path: path.clone(),
_allow_exec_host_cmd: run_plugin._allow_exec_host_cmd,
location: run_plugin.location.clone(),
userspace_configuration: run_plugin.configuration.clone(),
initial_cwd: run_plugin.initial_cwd.clone(),
}),
RunPluginLocation::Zellij(tag) => {
let tag = tag.to_string();
if tag == "status-bar"
|| tag == "tab-bar"
|| tag == "compact-bar"
|| tag == "strider"
|| tag == "session-manager"
|| tag == "configuration"
|| tag == "plugin-manager"
|| tag == "about"
|| tag == "share"
|| tag == "multiple-select"
|| tag == "sequence"
{
Some(PluginConfig {
path: PathBuf::from(&tag),
_allow_exec_host_cmd: run_plugin._allow_exec_host_cmd,
location: RunPluginLocation::parse(&format!("zellij:{}", tag), None)
.ok()?,
userspace_configuration: run_plugin.configuration.clone(),
initial_cwd: run_plugin.initial_cwd.clone(),
})
} else {
None
}
},
RunPluginLocation::Remote(_) => Some(PluginConfig {
path: PathBuf::new(),
_allow_exec_host_cmd: run_plugin._allow_exec_host_cmd,
location: run_plugin.location.clone(),
userspace_configuration: run_plugin.configuration.clone(),
initial_cwd: run_plugin.initial_cwd.clone(),
}),
}
}
/// Resolve wasm plugin bytes for the plugin path and given plugin directory.
///
/// If zellij was built without the 'disable_automatic_asset_installation' feature, builtin
/// plugins (Starting with 'zellij:' in the layout file) are loaded directly from the
/// binary-internal asset map. Otherwise:
///
/// Attempts to first resolve the plugin path as an absolute path, then adds a ".wasm"
/// extension to the path and resolves that, finally we use the plugin directory joined with
/// the path with an appended ".wasm" extension. So if our path is "tab-bar" and the given
/// plugin dir is "/home/bob/.zellij/plugins" the lookup chain will be this:
///
/// ```bash
/// /tab-bar
/// /tab-bar.wasm
/// ```
///
pub fn resolve_wasm_bytes(&self, plugin_dir: &Path) -> Result<Vec<u8>> {
let err_context =
|err: std::io::Error, path: &PathBuf| format!("{}: '{}'", err, path.display());
// Locations we check for valid plugins
let paths_arr = [
&self.path,
&self.path.with_extension("wasm"),
&plugin_dir.join(&self.path).with_extension("wasm"),
];
// Throw out dupes, because it's confusing to read that zellij checked the same plugin
// location multiple times. Do NOT sort the vector here, because it will break the lookup!
let mut paths = paths_arr.to_vec();
paths.dedup();
// This looks weird and usually we would handle errors like this differently, but in this
// case it's helpful for users and developers alike. This way we preserve all the lookup
// errors and can report all of them back. We must initialize `last_err` with something,
// and since the user will only get to see it when loading a plugin failed, we may as well
// spell it out right here.
let mut last_err: Result<Vec<u8>> = Err(anyhow!("failed to load plugin from disk"));
for path in paths {
// Check if the plugin path matches an entry in the asset map. If so, load it directly
// from memory, don't bother with the disk.
#[cfg(not(target_family = "wasm"))]
if !cfg!(feature = "disable_automatic_asset_installation") && self.is_builtin() {
let asset_path = PathBuf::from("plugins").join(path);
if let Some(bytes) = ASSET_MAP.get(&asset_path) {
log::debug!("Loaded plugin '{}' from internal assets", path.display());
if plugin_dir.join(path).with_extension("wasm").exists() {
log::info!(
"Plugin '{}' exists in the 'PLUGIN DIR' at '{}' but is being ignored",
path.display(),
plugin_dir.display()
);
}
return Ok(bytes.to_vec());
}
}
// Try to read from disk
match fs::read(&path) {
Ok(val) => {
log::debug!("Loaded plugin '{}' from disk", path.display());
return Ok(val);
},
Err(err) => {
last_err = last_err.with_context(|| err_context(err, &path));
},
}
}
// Not reached if a plugin is found!
#[cfg(not(target_family = "wasm"))]
if self.is_builtin() {
// Layout requested a builtin plugin that wasn't found
let plugin_path = self.path.with_extension("wasm");
if cfg!(feature = "disable_automatic_asset_installation")
&& ASSET_MAP.contains_key(&PathBuf::from("plugins").join(&plugin_path))
{
return Err(ZellijError::BuiltinPluginMissing {
plugin_path,
plugin_dir: plugin_dir.to_owned(),
source: last_err.unwrap_err(),
})
.context("failed to load a plugin");
} else {
return Err(ZellijError::BuiltinPluginNonexistent {
plugin_path,
source: last_err.unwrap_err(),
})
.context("failed to load a plugin");
}
}
return last_err;
}
pub fn is_builtin(&self) -> bool {
matches!(self.location, RunPluginLocation::Zellij(_))
}
}
#[derive(Error, Debug, PartialEq)]
pub enum PluginsConfigError {
#[error("Duplication in plugin tag names is not allowed: '{}'", String::from(.0.clone()))]
DuplicatePlugins(PluginTag),
#[error("Failed to parse url: {0:?}")]
InvalidUrl(#[from] url::ParseError),
#[error("Only 'file:', 'http(s):' and 'zellij:' url schemes are supported for plugin lookup. '{0}' does not match either.")]
InvalidUrlScheme(Url),
#[error("Could not find plugin at the path: '{0:?}'")]
InvalidPluginLocation(PathBuf),
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/input/actions.rs | zellij-utils/src/input/actions.rs | //! Definition of the actions that can be bound to keys.
pub use super::command::{OpenFilePayload, RunCommandAction};
use super::layout::{
FloatingPaneLayout, Layout, PluginAlias, RunPlugin, RunPluginLocation, RunPluginOrAlias,
SwapFloatingLayout, SwapTiledLayout, TiledPaneLayout,
};
use crate::cli::CliAction;
use crate::data::{
CommandOrPlugin, Direction, KeyWithModifier, LayoutInfo, NewPanePlacement, OriginatingPlugin,
PaneId, Resize, UnblockCondition,
};
use crate::data::{FloatingPaneCoordinates, InputMode};
use crate::home::{find_default_config_dir, get_layout_dir};
use crate::input::config::{Config, ConfigError, KdlError};
use crate::input::mouse::MouseEvent;
use crate::input::options::OnForceClose;
use miette::{NamedSource, Report};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use uuid::Uuid;
use std::path::PathBuf;
use std::str::FromStr;
use crate::position::Position;
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub enum ResizeDirection {
Left,
Right,
Up,
Down,
Increase,
Decrease,
}
impl FromStr for ResizeDirection {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"Left" | "left" => Ok(ResizeDirection::Left),
"Right" | "right" => Ok(ResizeDirection::Right),
"Up" | "up" => Ok(ResizeDirection::Up),
"Down" | "down" => Ok(ResizeDirection::Down),
"Increase" | "increase" | "+" => Ok(ResizeDirection::Increase),
"Decrease" | "decrease" | "-" => Ok(ResizeDirection::Decrease),
_ => Err(format!(
"Failed to parse ResizeDirection. Unknown ResizeDirection: {}",
s
)),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub enum SearchDirection {
Down,
Up,
}
impl FromStr for SearchDirection {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"Down" | "down" => Ok(SearchDirection::Down),
"Up" | "up" => Ok(SearchDirection::Up),
_ => Err(format!(
"Failed to parse SearchDirection. Unknown SearchDirection: {}",
s
)),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub enum SearchOption {
CaseSensitivity,
WholeWord,
Wrap,
}
impl FromStr for SearchOption {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"CaseSensitivity" | "casesensitivity" | "Casesensitivity" => {
Ok(SearchOption::CaseSensitivity)
},
"WholeWord" | "wholeword" | "Wholeword" => Ok(SearchOption::WholeWord),
"Wrap" | "wrap" => Ok(SearchOption::Wrap),
_ => Err(format!(
"Failed to parse SearchOption. Unknown SearchOption: {}",
s
)),
}
}
}
// As these actions are bound to the default config, please
// do take care when refactoring - or renaming.
// They might need to be adjusted in the default config
// as well `../../assets/config/default.yaml`
/// Actions that can be bound to keys.
#[derive(
Clone,
Debug,
PartialEq,
Eq,
Deserialize,
Serialize,
strum_macros::Display,
strum_macros::EnumString,
strum_macros::EnumIter,
)]
#[strum(ascii_case_insensitive)]
pub enum Action {
/// Quit Zellij.
Quit,
/// Write to the terminal.
Write {
key_with_modifier: Option<KeyWithModifier>,
bytes: Vec<u8>,
is_kitty_keyboard_protocol: bool,
},
/// Write Characters to the terminal.
WriteChars {
chars: String,
},
/// Switch to the specified input mode.
SwitchToMode {
input_mode: InputMode,
},
/// Switch all connected clients to the specified input mode.
SwitchModeForAllClients {
input_mode: InputMode,
},
/// Shrink/enlarge focused pane at specified border
Resize {
resize: Resize,
direction: Option<Direction>,
},
/// Switch focus to next pane in specified direction.
FocusNextPane,
FocusPreviousPane,
/// Move the focus pane in specified direction.
SwitchFocus,
MoveFocus {
direction: Direction,
},
/// Tries to move the focus pane in specified direction.
/// If there is no pane in the direction, move to previous/next Tab.
MoveFocusOrTab {
direction: Direction,
},
MovePane {
direction: Option<Direction>,
},
MovePaneBackwards,
/// Clear all buffers of a current screen
ClearScreen,
/// Dumps the screen to a file
DumpScreen {
file_path: String,
include_scrollback: bool,
},
/// Dumps
DumpLayout,
/// Scroll up in focus pane.
EditScrollback,
ScrollUp,
/// Scroll up at point
ScrollUpAt {
position: Position,
},
/// Scroll down in focus pane.
ScrollDown,
/// Scroll down at point
ScrollDownAt {
position: Position,
},
/// Scroll down to bottom in focus pane.
ScrollToBottom,
/// Scroll up to top in focus pane.
ScrollToTop,
/// Scroll up one page in focus pane.
PageScrollUp,
/// Scroll down one page in focus pane.
PageScrollDown,
/// Scroll up half page in focus pane.
HalfPageScrollUp,
/// Scroll down half page in focus pane.
HalfPageScrollDown,
/// Toggle between fullscreen focus pane and normal layout.
ToggleFocusFullscreen,
/// Toggle frames around panes in the UI
TogglePaneFrames,
/// Toggle between sending text commands to all panes on the current tab and normal mode.
ToggleActiveSyncTab,
/// Open a new pane in the specified direction (relative to focus).
/// If no direction is specified, will try to use the biggest available space.
NewPane {
direction: Option<Direction>,
pane_name: Option<String>,
start_suppressed: bool,
},
NewBlockingPane {
placement: NewPanePlacement,
pane_name: Option<String>,
command: Option<RunCommandAction>,
unblock_condition: Option<UnblockCondition>,
near_current_pane: bool,
},
/// Open the file in a new pane using the default editor
EditFile {
payload: OpenFilePayload,
direction: Option<Direction>,
floating: bool,
in_place: bool,
start_suppressed: bool,
coordinates: Option<FloatingPaneCoordinates>,
near_current_pane: bool,
},
/// Open a new floating pane
NewFloatingPane {
command: Option<RunCommandAction>,
pane_name: Option<String>,
coordinates: Option<FloatingPaneCoordinates>,
near_current_pane: bool,
},
/// Open a new tiled (embedded, non-floating) pane
NewTiledPane {
direction: Option<Direction>,
command: Option<RunCommandAction>,
pane_name: Option<String>,
near_current_pane: bool,
},
/// Open a new pane in place of the focused one, suppressing it instead
NewInPlacePane {
command: Option<RunCommandAction>,
pane_name: Option<String>,
near_current_pane: bool,
pane_id_to_replace: Option<PaneId>,
close_replace_pane: bool,
},
NewStackedPane {
command: Option<RunCommandAction>,
pane_name: Option<String>,
near_current_pane: bool,
},
/// Embed focused pane in tab if floating or float focused pane if embedded
TogglePaneEmbedOrFloating,
/// Toggle the visibility of all floating panes (if any) in the current Tab
ToggleFloatingPanes,
/// Close the focus pane.
CloseFocus,
PaneNameInput {
input: Vec<u8>,
},
UndoRenamePane,
/// Create a new tab, optionally with a specified tab layout.
NewTab {
tiled_layout: Option<TiledPaneLayout>,
floating_layouts: Vec<FloatingPaneLayout>,
swap_tiled_layouts: Option<Vec<SwapTiledLayout>>,
swap_floating_layouts: Option<Vec<SwapFloatingLayout>>,
tab_name: Option<String>,
should_change_focus_to_new_tab: bool,
cwd: Option<PathBuf>,
initial_panes: Option<Vec<CommandOrPlugin>>,
first_pane_unblock_condition: Option<UnblockCondition>,
},
/// Do nothing.
NoOp,
/// Go to the next tab.
GoToNextTab,
/// Go to the previous tab.
GoToPreviousTab,
/// Close the current tab.
CloseTab,
GoToTab {
index: u32,
},
GoToTabName {
name: String,
create: bool,
},
ToggleTab,
TabNameInput {
input: Vec<u8>,
},
UndoRenameTab,
MoveTab {
direction: Direction,
},
/// Run specified command in new pane.
Run {
command: RunCommandAction,
near_current_pane: bool,
},
/// Detach session and exit
Detach,
/// Switch to a different session
SwitchSession {
name: String,
tab_position: Option<usize>,
pane_id: Option<(u32, bool)>, // (id, is_plugin)
layout: Option<LayoutInfo>,
cwd: Option<PathBuf>,
},
LaunchOrFocusPlugin {
plugin: RunPluginOrAlias,
should_float: bool,
move_to_focused_tab: bool,
should_open_in_place: bool,
skip_cache: bool,
},
LaunchPlugin {
plugin: RunPluginOrAlias,
should_float: bool,
should_open_in_place: bool,
skip_cache: bool,
cwd: Option<PathBuf>,
},
MouseEvent {
event: MouseEvent,
},
Copy,
/// Confirm a prompt
Confirm,
/// Deny a prompt
Deny,
/// Confirm an action that invokes a prompt automatically
SkipConfirm {
action: Box<Action>,
},
/// Search for String
SearchInput {
input: Vec<u8>,
},
/// Search for something
Search {
direction: SearchDirection,
},
/// Toggle case sensitivity of search
SearchToggleOption {
option: SearchOption,
},
ToggleMouseMode,
PreviousSwapLayout,
NextSwapLayout,
/// Override the layout of the active tab
OverrideLayout {
tiled_layout: Option<TiledPaneLayout>,
floating_layouts: Vec<FloatingPaneLayout>,
swap_tiled_layouts: Option<Vec<SwapTiledLayout>>,
swap_floating_layouts: Option<Vec<SwapFloatingLayout>>,
tab_name: Option<String>,
retain_existing_terminal_panes: bool,
retain_existing_plugin_panes: bool,
},
/// Query all tab names
QueryTabNames,
/// Open a new tiled (embedded, non-floating) plugin pane
NewTiledPluginPane {
plugin: RunPluginOrAlias,
pane_name: Option<String>,
skip_cache: bool,
cwd: Option<PathBuf>,
},
NewFloatingPluginPane {
plugin: RunPluginOrAlias,
pane_name: Option<String>,
skip_cache: bool,
cwd: Option<PathBuf>,
coordinates: Option<FloatingPaneCoordinates>,
},
NewInPlacePluginPane {
plugin: RunPluginOrAlias,
pane_name: Option<String>,
skip_cache: bool,
},
StartOrReloadPlugin {
plugin: RunPluginOrAlias,
},
CloseTerminalPane {
pane_id: u32,
},
ClosePluginPane {
pane_id: u32,
},
FocusTerminalPaneWithId {
pane_id: u32,
should_float_if_hidden: bool,
should_be_in_place_if_hidden: bool,
},
FocusPluginPaneWithId {
pane_id: u32,
should_float_if_hidden: bool,
should_be_in_place_if_hidden: bool,
},
RenameTerminalPane {
pane_id: u32,
name: Vec<u8>,
},
RenamePluginPane {
pane_id: u32,
name: Vec<u8>,
},
RenameTab {
tab_index: u32,
name: Vec<u8>,
},
BreakPane,
BreakPaneRight,
BreakPaneLeft,
RenameSession {
name: String,
},
CliPipe {
pipe_id: String,
name: Option<String>,
payload: Option<String>,
args: Option<BTreeMap<String, String>>,
plugin: Option<String>,
configuration: Option<BTreeMap<String, String>>,
launch_new: bool,
skip_cache: bool,
floating: Option<bool>,
in_place: Option<bool>,
cwd: Option<PathBuf>,
pane_title: Option<String>,
},
KeybindPipe {
name: Option<String>,
payload: Option<String>,
args: Option<BTreeMap<String, String>>,
plugin: Option<String>,
plugin_id: Option<u32>, // supercedes plugin if present
configuration: Option<BTreeMap<String, String>>,
launch_new: bool,
skip_cache: bool,
floating: Option<bool>,
in_place: Option<bool>,
cwd: Option<PathBuf>,
pane_title: Option<String>,
},
ListClients,
TogglePanePinned,
StackPanes {
pane_ids: Vec<PaneId>,
},
ChangeFloatingPaneCoordinates {
pane_id: PaneId,
coordinates: FloatingPaneCoordinates,
},
TogglePaneInGroup,
ToggleGroupMarking,
}
impl Default for Action {
fn default() -> Self {
Action::NoOp
}
}
impl Default for SearchDirection {
fn default() -> Self {
SearchDirection::Down
}
}
impl Default for SearchOption {
fn default() -> Self {
SearchOption::CaseSensitivity
}
}
impl Action {
/// Checks that two Action are match except their mutable attributes.
pub fn shallow_eq(&self, other_action: &Action) -> bool {
match (self, other_action) {
(Action::NewTab { .. }, Action::NewTab { .. }) => true,
(Action::LaunchOrFocusPlugin { .. }, Action::LaunchOrFocusPlugin { .. }) => true,
(Action::LaunchPlugin { .. }, Action::LaunchPlugin { .. }) => true,
(Action::OverrideLayout { .. }, Action::OverrideLayout { .. }) => true,
_ => self == other_action,
}
}
pub fn actions_from_cli(
cli_action: CliAction,
get_current_dir: Box<dyn Fn() -> PathBuf>,
config: Option<Config>,
) -> Result<Vec<Action>, String> {
match cli_action {
CliAction::Write { bytes } => Ok(vec![Action::Write {
key_with_modifier: None,
bytes,
is_kitty_keyboard_protocol: false,
}]),
CliAction::WriteChars { chars } => Ok(vec![Action::WriteChars { chars }]),
CliAction::Resize { resize, direction } => {
Ok(vec![Action::Resize { resize, direction }])
},
CliAction::FocusNextPane => Ok(vec![Action::FocusNextPane]),
CliAction::FocusPreviousPane => Ok(vec![Action::FocusPreviousPane]),
CliAction::MoveFocus { direction } => Ok(vec![Action::MoveFocus { direction }]),
CliAction::MoveFocusOrTab { direction } => {
Ok(vec![Action::MoveFocusOrTab { direction }])
},
CliAction::MovePane { direction } => Ok(vec![Action::MovePane { direction }]),
CliAction::MovePaneBackwards => Ok(vec![Action::MovePaneBackwards]),
CliAction::MoveTab { direction } => Ok(vec![Action::MoveTab { direction }]),
CliAction::Clear => Ok(vec![Action::ClearScreen]),
CliAction::DumpScreen { path, full } => Ok(vec![Action::DumpScreen {
file_path: path.as_os_str().to_string_lossy().into(),
include_scrollback: full,
}]),
CliAction::DumpLayout => Ok(vec![Action::DumpLayout]),
CliAction::EditScrollback => Ok(vec![Action::EditScrollback]),
CliAction::ScrollUp => Ok(vec![Action::ScrollUp]),
CliAction::ScrollDown => Ok(vec![Action::ScrollDown]),
CliAction::ScrollToBottom => Ok(vec![Action::ScrollToBottom]),
CliAction::ScrollToTop => Ok(vec![Action::ScrollToTop]),
CliAction::PageScrollUp => Ok(vec![Action::PageScrollUp]),
CliAction::PageScrollDown => Ok(vec![Action::PageScrollDown]),
CliAction::HalfPageScrollUp => Ok(vec![Action::HalfPageScrollUp]),
CliAction::HalfPageScrollDown => Ok(vec![Action::HalfPageScrollDown]),
CliAction::ToggleFullscreen => Ok(vec![Action::ToggleFocusFullscreen]),
CliAction::TogglePaneFrames => Ok(vec![Action::TogglePaneFrames]),
CliAction::ToggleActiveSyncTab => Ok(vec![Action::ToggleActiveSyncTab]),
CliAction::NewPane {
direction,
command,
plugin,
cwd,
floating,
in_place,
name,
close_on_exit,
start_suspended,
configuration,
skip_plugin_cache,
x,
y,
width,
height,
pinned,
stacked,
blocking,
unblock_condition,
near_current_pane,
} => {
let current_dir = get_current_dir();
// cwd should only be specified in a plugin alias if it was explicitly given to us,
// otherwise the current_dir might override a cwd defined in the alias itself
let alias_cwd = cwd.clone().map(|cwd| current_dir.join(cwd));
let cwd = cwd
.map(|cwd| current_dir.join(cwd))
.or_else(|| Some(current_dir.clone()));
if blocking || unblock_condition.is_some() {
// For blocking panes, we don't support plugins
if plugin.is_some() {
return Err("Blocking panes do not support plugin variants".to_string());
}
let command = if !command.is_empty() {
let mut command = command.clone();
let (command, args) = (PathBuf::from(command.remove(0)), command);
let hold_on_start = start_suspended;
let hold_on_close = !close_on_exit;
Some(RunCommandAction {
command,
args,
cwd,
direction,
hold_on_close,
hold_on_start,
..Default::default()
})
} else {
None
};
let placement = if floating {
NewPanePlacement::Floating(FloatingPaneCoordinates::new(
x, y, width, height, pinned,
))
} else if in_place {
NewPanePlacement::InPlace {
pane_id_to_replace: None,
close_replaced_pane: false,
}
} else if stacked {
NewPanePlacement::Stacked(None)
} else {
NewPanePlacement::Tiled(direction)
};
Ok(vec![Action::NewBlockingPane {
placement,
pane_name: name,
command,
unblock_condition,
near_current_pane,
}])
} else if let Some(plugin) = plugin {
let plugin = match RunPluginLocation::parse(&plugin, cwd.clone()) {
Ok(location) => {
let user_configuration = configuration.unwrap_or_default();
RunPluginOrAlias::RunPlugin(RunPlugin {
_allow_exec_host_cmd: false,
location,
configuration: user_configuration,
initial_cwd: cwd.clone(),
})
},
Err(_) => {
let mut plugin_alias = PluginAlias::new(
&plugin,
&configuration.map(|c| c.inner().clone()),
alias_cwd,
);
plugin_alias.set_caller_cwd_if_not_set(Some(current_dir));
RunPluginOrAlias::Alias(plugin_alias)
},
};
if floating {
Ok(vec![Action::NewFloatingPluginPane {
plugin,
pane_name: name,
skip_cache: skip_plugin_cache,
cwd,
coordinates: FloatingPaneCoordinates::new(x, y, width, height, pinned),
}])
} else if in_place {
Ok(vec![Action::NewInPlacePluginPane {
plugin,
pane_name: name,
skip_cache: skip_plugin_cache,
}])
} else {
// it is intentional that a new tiled plugin pane cannot include a
// direction
// this is because the cli client opening a tiled plugin pane is a
// different client than the one opening the pane, and this can potentially
// create very confusing races if the client changes focus while the plugin
// is being loaded
// this is not the case with terminal panes for historical reasons of
// backwards compatibility to a time before we had auto layouts
Ok(vec![Action::NewTiledPluginPane {
plugin,
pane_name: name,
skip_cache: skip_plugin_cache,
cwd,
}])
}
} else if !command.is_empty() {
let mut command = command.clone();
let (command, args) = (PathBuf::from(command.remove(0)), command);
let hold_on_start = start_suspended;
let hold_on_close = !close_on_exit;
let run_command_action = RunCommandAction {
command,
args,
cwd,
direction,
hold_on_close,
hold_on_start,
..Default::default()
};
if floating {
Ok(vec![Action::NewFloatingPane {
command: Some(run_command_action),
pane_name: name,
coordinates: FloatingPaneCoordinates::new(x, y, width, height, pinned),
near_current_pane,
}])
} else if in_place {
Ok(vec![Action::NewInPlacePane {
command: Some(run_command_action),
pane_name: name,
near_current_pane,
pane_id_to_replace: None, // TODO: support this
close_replace_pane: false,
}])
} else if stacked {
Ok(vec![Action::NewStackedPane {
command: Some(run_command_action),
pane_name: name,
near_current_pane,
}])
} else {
Ok(vec![Action::NewTiledPane {
direction,
command: Some(run_command_action),
pane_name: name,
near_current_pane,
}])
}
} else {
if floating {
Ok(vec![Action::NewFloatingPane {
command: None,
pane_name: name,
coordinates: FloatingPaneCoordinates::new(x, y, width, height, pinned),
near_current_pane,
}])
} else if in_place {
Ok(vec![Action::NewInPlacePane {
command: None,
pane_name: name,
near_current_pane,
pane_id_to_replace: None, // TODO: support this
close_replace_pane: false,
}])
} else if stacked {
Ok(vec![Action::NewStackedPane {
command: None,
pane_name: name,
near_current_pane,
}])
} else {
Ok(vec![Action::NewTiledPane {
direction,
command: None,
pane_name: name,
near_current_pane,
}])
}
}
},
CliAction::Edit {
direction,
file,
line_number,
floating,
in_place,
cwd,
x,
y,
width,
height,
pinned,
near_current_pane,
} => {
let mut file = file;
let current_dir = get_current_dir();
let cwd = cwd
.map(|cwd| current_dir.join(cwd))
.or_else(|| Some(current_dir));
if file.is_relative() {
if let Some(cwd) = cwd.as_ref() {
file = cwd.join(file);
}
}
let start_suppressed = false;
Ok(vec![Action::EditFile {
payload: OpenFilePayload::new(file, line_number, cwd),
direction,
floating,
in_place,
start_suppressed,
coordinates: FloatingPaneCoordinates::new(x, y, width, height, pinned),
near_current_pane,
}])
},
CliAction::SwitchMode { input_mode } => Ok(vec![Action::SwitchToMode { input_mode }]),
CliAction::TogglePaneEmbedOrFloating => Ok(vec![Action::TogglePaneEmbedOrFloating]),
CliAction::ToggleFloatingPanes => Ok(vec![Action::ToggleFloatingPanes]),
CliAction::ClosePane => Ok(vec![Action::CloseFocus]),
CliAction::RenamePane { name } => Ok(vec![
Action::UndoRenamePane,
Action::PaneNameInput {
input: name.as_bytes().to_vec(),
},
]),
CliAction::UndoRenamePane => Ok(vec![Action::UndoRenamePane]),
CliAction::GoToNextTab => Ok(vec![Action::GoToNextTab]),
CliAction::GoToPreviousTab => Ok(vec![Action::GoToPreviousTab]),
CliAction::CloseTab => Ok(vec![Action::CloseTab]),
CliAction::GoToTab { index } => Ok(vec![Action::GoToTab { index }]),
CliAction::GoToTabName { name, create } => {
Ok(vec![Action::GoToTabName { name, create }])
},
CliAction::RenameTab { name } => Ok(vec![
Action::TabNameInput { input: vec![0] },
Action::TabNameInput {
input: name.as_bytes().to_vec(),
},
]),
CliAction::UndoRenameTab => Ok(vec![Action::UndoRenameTab]),
CliAction::NewTab {
name,
layout,
layout_dir,
cwd,
initial_command,
initial_plugin,
close_on_exit,
start_suspended,
block_until_exit_success,
block_until_exit_failure,
block_until_exit,
} => {
let current_dir = get_current_dir();
let cwd = cwd
.map(|cwd| current_dir.join(cwd))
.or_else(|| Some(current_dir.clone()));
// Map CLI flags to UnblockCondition
let first_pane_unblock_condition = if block_until_exit_success {
Some(UnblockCondition::OnExitSuccess)
} else if block_until_exit_failure {
Some(UnblockCondition::OnExitFailure)
} else if block_until_exit {
Some(UnblockCondition::OnAnyExit)
} else {
None
};
// Parse initial_panes from initial_command or initial_plugin
let initial_panes = if let Some(plugin_url) = initial_plugin {
let plugin = match RunPluginLocation::parse(&plugin_url, cwd.clone()) {
Ok(location) => RunPluginOrAlias::RunPlugin(RunPlugin {
_allow_exec_host_cmd: false,
location,
configuration: Default::default(),
initial_cwd: cwd.clone(),
}),
Err(_) => {
let mut plugin_alias =
PluginAlias::new(&plugin_url, &None, cwd.clone());
plugin_alias.set_caller_cwd_if_not_set(Some(current_dir.clone()));
RunPluginOrAlias::Alias(plugin_alias)
},
};
Some(vec![CommandOrPlugin::Plugin(plugin)])
} else if !initial_command.is_empty() {
let mut command: Vec<String> = initial_command.clone();
let (command, args) = (
PathBuf::from(command.remove(0)),
command.into_iter().collect(),
);
let hold_on_close = !close_on_exit;
let hold_on_start = start_suspended;
let run_command_action = RunCommandAction {
command,
args,
cwd: cwd.clone(),
direction: None,
hold_on_close,
hold_on_start,
..Default::default()
};
Some(vec![CommandOrPlugin::Command(run_command_action)])
} else {
None
};
if let Some(layout_path) = layout {
let layout_dir = layout_dir
.or_else(|| config.and_then(|c| c.options.layout_dir))
.or_else(|| get_layout_dir(find_default_config_dir()));
let mut should_start_layout_commands_suspended = false;
let (path_to_raw_layout, raw_layout, swap_layouts) = if let Some(layout_url) =
layout_path.to_str().and_then(|l| {
if l.starts_with("http://") || l.starts_with("https://") {
Some(l)
} else {
None
}
}) {
should_start_layout_commands_suspended = true;
(
layout_url.to_owned(),
Layout::stringified_from_url(layout_url)
.map_err(|e| format!("Failed to load layout: {}", e))?,
None,
)
} else {
Layout::stringified_from_path_or_default(Some(&layout_path), layout_dir)
.map_err(|e| format!("Failed to load layout: {}", e))?
};
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/input/permission.rs | zellij-utils/src/input/permission.rs | use std::{
collections::HashMap,
fs::{self, File},
io::Write,
path::PathBuf,
};
use crate::{consts::ZELLIJ_PLUGIN_PERMISSIONS_CACHE, data::PermissionType};
pub type GrantedPermission = HashMap<String, Vec<PermissionType>>;
#[derive(Default, Debug)]
pub struct PermissionCache {
path: PathBuf,
granted: GrantedPermission,
}
impl PermissionCache {
pub fn cache(&mut self, plugin_name: String, permissions: Vec<PermissionType>) {
self.granted.insert(plugin_name, permissions);
}
pub fn get_permissions(&self, plugin_name: String) -> Option<&Vec<PermissionType>> {
self.granted.get(&plugin_name)
}
pub fn check_permissions(
&self,
plugin_name: String,
permissions_to_check: &Vec<PermissionType>,
) -> bool {
if let Some(target) = self.granted.get(&plugin_name) {
let mut all_granted = true;
for permission in permissions_to_check {
if !target.contains(permission) {
all_granted = false;
}
}
return all_granted;
}
false
}
pub fn from_path_or_default(cache_path: Option<PathBuf>) -> Self {
let cache_path = cache_path.unwrap_or(ZELLIJ_PLUGIN_PERMISSIONS_CACHE.to_path_buf());
let granted = match fs::read_to_string(cache_path.clone()) {
Ok(raw_string) => PermissionCache::from_string(raw_string).unwrap_or_default(),
Err(e) => {
log::error!("Failed to read permission cache file: {}", e);
GrantedPermission::default()
},
};
PermissionCache {
path: cache_path,
granted,
}
}
pub fn write_to_file(&self) -> std::io::Result<()> {
let mut f = File::create(&self.path)?;
write!(f, "{}", PermissionCache::to_string(&self.granted))?;
Ok(())
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/input/keybinds.rs | zellij-utils/src/input/keybinds.rs | use std::collections::{BTreeMap, HashMap};
use super::actions::Action;
use crate::data::{BareKey, InputMode, KeyWithModifier, KeybindsVec};
use serde::{Deserialize, Serialize};
use std::fmt;
/// Used in the config struct
#[derive(Clone, PartialEq, Deserialize, Serialize, Default)]
pub struct Keybinds(pub HashMap<InputMode, HashMap<KeyWithModifier, Vec<Action>>>);
impl fmt::Debug for Keybinds {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut stable_sorted = BTreeMap::new();
for (mode, keybinds) in self.0.iter() {
let mut stable_sorted_mode_keybinds = BTreeMap::new();
for (key, actions) in keybinds {
stable_sorted_mode_keybinds.insert(key, actions);
}
stable_sorted.insert(mode, stable_sorted_mode_keybinds);
}
write!(f, "{:#?}", stable_sorted)
}
}
impl Keybinds {
pub fn get_actions_for_key_in_mode(
&self,
mode: &InputMode,
key: &KeyWithModifier,
) -> Option<&Vec<Action>> {
self.0
.get(mode)
.and_then(|normal_mode_keybindings| normal_mode_keybindings.get(key))
}
pub fn get_actions_for_key_in_mode_or_default_action(
&self,
mode: &InputMode,
key_with_modifier: &KeyWithModifier,
raw_bytes: Vec<u8>,
default_input_mode: InputMode,
key_is_kitty_protocol: bool,
) -> Vec<Action> {
self.0
.get(mode)
.and_then(|mode_keybindings| {
if raw_bytes == &[10] {
handle_ctrl_j(&mode_keybindings, &raw_bytes, key_is_kitty_protocol)
} else {
mode_keybindings.get(key_with_modifier).cloned()
}
})
.unwrap_or_else(|| {
vec![self.default_action_for_mode(
mode,
Some(key_with_modifier),
raw_bytes,
default_input_mode,
key_is_kitty_protocol,
)]
})
}
pub fn get_input_mode_mut(
&mut self,
input_mode: &InputMode,
) -> &mut HashMap<KeyWithModifier, Vec<Action>> {
self.0.entry(*input_mode).or_insert_with(HashMap::new)
}
pub fn default_action_for_mode(
&self,
mode: &InputMode,
key_with_modifier: Option<&KeyWithModifier>,
raw_bytes: Vec<u8>,
default_input_mode: InputMode,
key_is_kitty_protocol: bool,
) -> Action {
match *mode {
InputMode::Locked => Action::Write {
key_with_modifier: key_with_modifier.cloned(),
bytes: raw_bytes,
is_kitty_keyboard_protocol: key_is_kitty_protocol,
},
mode if mode == default_input_mode => Action::Write {
key_with_modifier: key_with_modifier.cloned(),
bytes: raw_bytes,
is_kitty_keyboard_protocol: key_is_kitty_protocol,
},
InputMode::RenameTab => Action::TabNameInput { input: raw_bytes },
InputMode::RenamePane => Action::PaneNameInput { input: raw_bytes },
InputMode::EnterSearch => Action::SearchInput { input: raw_bytes },
_ => Action::NoOp,
}
}
pub fn to_keybinds_vec(&self) -> KeybindsVec {
let mut ret = vec![];
for (mode, mode_binds) in &self.0 {
let mut mode_binds_vec: Vec<(KeyWithModifier, Vec<Action>)> = vec![];
for (key, actions) in mode_binds {
mode_binds_vec.push((key.clone(), actions.clone()));
}
ret.push((*mode, mode_binds_vec))
}
ret
}
pub fn merge(&mut self, mut other: Keybinds) {
for (other_input_mode, mut other_input_mode_keybinds) in other.0.drain() {
let input_mode_keybinds = self
.0
.entry(other_input_mode)
.or_insert_with(|| Default::default());
for (other_action, other_action_keybinds) in other_input_mode_keybinds.drain() {
input_mode_keybinds.insert(other_action, other_action_keybinds);
}
}
}
}
// we need to do this because [10] in standard STDIN, [10] is both Enter (without a carriage
// return) and ctrl-j - so here, if ctrl-j is bound we return its bound action, and otherwise we
// just write the raw bytes to the terminal and let whichever program is there decide what they are
fn handle_ctrl_j(
mode_keybindings: &HashMap<KeyWithModifier, Vec<Action>>,
raw_bytes: &[u8],
key_is_kitty_protocol: bool,
) -> Option<Vec<Action>> {
let ctrl_j = KeyWithModifier::new(BareKey::Char('j')).with_ctrl_modifier();
if mode_keybindings.get(&ctrl_j).is_some() {
mode_keybindings.get(&ctrl_j).cloned()
} else {
Some(vec![Action::Write {
key_with_modifier: Some(ctrl_j),
bytes: raw_bytes.to_vec().clone(),
is_kitty_keyboard_protocol: key_is_kitty_protocol,
}])
}
}
// The unit test location.
#[cfg(test)]
#[path = "./unit/keybinds_test.rs"]
mod keybinds_test;
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/input/unit/layout_test.rs | zellij-utils/src/input/unit/layout_test.rs | use super::super::layout::*;
use insta::assert_snapshot;
#[test]
fn empty_layout() {
let kdl_layout = "layout";
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
let expected_layout = Layout {
template: Some((TiledPaneLayout::default(), vec![])),
..Default::default()
};
assert_eq!(layout, expected_layout);
}
#[test]
fn layout_with_one_pane() {
let kdl_layout = r#"
layout {
pane
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
let expected_layout = Layout {
template: Some((
TiledPaneLayout {
children: vec![TiledPaneLayout::default()],
..Default::default()
},
vec![],
)),
..Default::default()
};
assert_eq!(layout, expected_layout);
}
#[test]
fn layout_with_multiple_panes() {
let kdl_layout = r#"
layout {
pane
pane
pane
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
let expected_layout = Layout {
template: Some((
TiledPaneLayout {
children: vec![
TiledPaneLayout::default(),
TiledPaneLayout::default(),
TiledPaneLayout::default(),
],
..Default::default()
},
vec![],
)),
..Default::default()
};
assert_eq!(layout, expected_layout);
}
#[test]
fn layout_with_nested_panes() {
let kdl_layout = r#"
layout {
pane split_direction="Vertical" {
pane
pane
}
pane {
pane
pane
}
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
let expected_layout = Layout {
template: Some((
TiledPaneLayout {
children: vec![
TiledPaneLayout {
children_split_direction: SplitDirection::Vertical,
children: vec![TiledPaneLayout::default(), TiledPaneLayout::default()],
..Default::default()
},
TiledPaneLayout {
children: vec![TiledPaneLayout::default(), TiledPaneLayout::default()],
..Default::default()
},
],
..Default::default()
},
vec![],
)),
..Default::default()
};
assert_eq!(layout, expected_layout);
}
#[test]
fn layout_with_floating_panes() {
let kdl_layout = r#"
layout {
floating_panes {
pane
pane {
x 10
y "10%"
width 10
height "10%"
}
pane x=10 y="10%"
pane command="htop"
}
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
let expected_layout = Layout {
template: Some((
TiledPaneLayout::default(),
vec![
FloatingPaneLayout::default(),
FloatingPaneLayout {
x: Some(PercentOrFixed::Fixed(10)),
y: Some(PercentOrFixed::Percent(10)),
width: Some(PercentOrFixed::Fixed(10)),
height: Some(PercentOrFixed::Percent(10)),
..Default::default()
},
FloatingPaneLayout {
x: Some(PercentOrFixed::Fixed(10)),
y: Some(PercentOrFixed::Percent(10)),
..Default::default()
},
FloatingPaneLayout {
run: Some(Run::Command(RunCommand {
command: PathBuf::from("htop"),
hold_on_close: true,
..Default::default()
})),
..Default::default()
},
],
)),
..Default::default()
};
assert_eq!(layout, expected_layout);
}
#[test]
fn layout_with_mixed_panes_and_floating_panes() {
let kdl_layout = r#"
layout {
pane
pane
floating_panes {
pane
}
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
let expected_layout = Layout {
template: Some((
TiledPaneLayout {
children: vec![TiledPaneLayout::default(), TiledPaneLayout::default()],
..Default::default()
},
vec![FloatingPaneLayout::default()],
)),
..Default::default()
};
assert_eq!(layout, expected_layout);
}
#[test]
fn layout_with_hidden_floating_panes() {
let kdl_layout = r#"
layout {
tab hide_floating_panes=true {
pane
pane
floating_panes {
pane
}
}
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
let expected_layout = Layout {
tabs: vec![(
None,
TiledPaneLayout {
children: vec![TiledPaneLayout::default(), TiledPaneLayout::default()],
hide_floating_panes: true,
..Default::default()
},
vec![FloatingPaneLayout::default()],
)],
template: Some((TiledPaneLayout::default(), vec![])),
..Default::default()
};
assert_eq!(layout, expected_layout);
}
#[test]
fn layout_with_floating_panes_template() {
let kdl_layout = r#"
layout {
pane_template name="my_cool_template" {
x 10
y "10%"
}
pane
floating_panes {
pane
my_cool_template
}
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
let expected_layout = Layout {
template: Some((
TiledPaneLayout {
children: vec![TiledPaneLayout::default()],
..Default::default()
},
vec![
FloatingPaneLayout::default(),
FloatingPaneLayout {
x: Some(PercentOrFixed::Fixed(10)),
y: Some(PercentOrFixed::Percent(10)),
..Default::default()
},
],
)),
..Default::default()
};
assert_eq!(layout, expected_layout);
}
#[test]
fn layout_with_shared_tiled_and_floating_panes_template() {
let kdl_layout = r#"
layout {
pane_template name="htop" {
command "htop"
}
htop
floating_panes {
pane
htop
}
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
let expected_layout = Layout {
template: Some((
TiledPaneLayout {
children: vec![TiledPaneLayout {
run: Some(Run::Command(RunCommand {
command: PathBuf::from("htop"),
hold_on_close: true,
..Default::default()
})),
..Default::default()
}],
..Default::default()
},
vec![
FloatingPaneLayout::default(),
FloatingPaneLayout {
run: Some(Run::Command(RunCommand {
command: PathBuf::from("htop"),
hold_on_close: true,
..Default::default()
})),
..Default::default()
},
],
)),
..Default::default()
};
assert_eq!(layout, expected_layout);
}
#[test]
fn layout_with_tabs_and_floating_panes() {
let kdl_layout = r#"
layout {
tab {
floating_panes {
pane
}
}
tab {
floating_panes {
pane
pane
}
}
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
assert_snapshot!(format!("{:#?}", layout));
}
#[test]
fn layout_with_tabs() {
let kdl_layout = r#"
layout {
tab
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
let expected_layout = Layout {
tabs: vec![(None, TiledPaneLayout::default(), vec![])],
template: Some((TiledPaneLayout::default(), vec![])),
..Default::default()
};
assert_eq!(layout, expected_layout);
}
#[test]
fn layout_with_nested_differing_tabs() {
let kdl_layout = r#"
layout {
tab split_direction="Vertical" {
pane
pane
pane
}
tab {
pane
pane
}
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
let expected_layout = Layout {
tabs: vec![
(
None,
TiledPaneLayout {
children_split_direction: SplitDirection::Vertical,
children: vec![
TiledPaneLayout::default(),
TiledPaneLayout::default(),
TiledPaneLayout::default(),
],
..Default::default()
},
vec![], // floating panes
),
(
None,
TiledPaneLayout {
children_split_direction: SplitDirection::Horizontal,
children: vec![TiledPaneLayout::default(), TiledPaneLayout::default()],
..Default::default()
},
vec![], // floating panes
),
],
template: Some((TiledPaneLayout::default(), vec![])),
..Default::default()
};
assert_eq!(layout, expected_layout);
}
#[test]
fn layout_with_panes_in_different_mixed_split_sizes() {
let kdl_layout = r#"
layout {
pane size=1;
pane size="10%";
pane;
pane size=2;
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
let expected_layout = Layout {
template: Some((
TiledPaneLayout {
children: vec![
TiledPaneLayout {
split_size: Some(SplitSize::Fixed(1)),
..Default::default()
},
TiledPaneLayout {
split_size: Some(SplitSize::Percent(10)),
..Default::default()
},
TiledPaneLayout {
split_size: None,
..Default::default()
},
TiledPaneLayout {
split_size: Some(SplitSize::Fixed(2)),
..Default::default()
},
],
..Default::default()
},
vec![],
)),
..Default::default()
};
assert_eq!(layout, expected_layout);
}
#[test]
fn layout_with_command_panes() {
let kdl_layout = r#"
layout {
pane command="htop"
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
let expected_layout = Layout {
template: Some((
TiledPaneLayout {
children: vec![TiledPaneLayout {
run: Some(Run::Command(RunCommand {
command: PathBuf::from("htop"),
hold_on_close: true,
..Default::default()
})),
..Default::default()
}],
..Default::default()
},
vec![],
)),
..Default::default()
};
assert_eq!(layout, expected_layout);
}
#[test]
fn layout_with_command_panes_and_cwd() {
let kdl_layout = r#"
layout {
pane command="htop" cwd="/path/to/my/cwd"
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
let expected_layout = Layout {
template: Some((
TiledPaneLayout {
children: vec![TiledPaneLayout {
run: Some(Run::Command(RunCommand {
command: PathBuf::from("htop"),
cwd: Some(PathBuf::from("/path/to/my/cwd")),
hold_on_close: true,
..Default::default()
})),
..Default::default()
}],
..Default::default()
},
vec![],
)),
..Default::default()
};
assert_eq!(layout, expected_layout);
}
#[test]
fn layout_with_command_panes_and_cwd_and_args() {
let kdl_layout = r#"
layout {
pane command="htop" cwd="/path/to/my/cwd" {
args "-h" "-v"
}
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
let expected_layout = Layout {
template: Some((
TiledPaneLayout {
children: vec![TiledPaneLayout {
run: Some(Run::Command(RunCommand {
command: PathBuf::from("htop"),
cwd: Some(PathBuf::from("/path/to/my/cwd")),
args: vec![String::from("-h"), String::from("-v")],
hold_on_close: true,
..Default::default()
})),
..Default::default()
}],
..Default::default()
},
vec![],
)),
..Default::default()
};
assert_eq!(layout, expected_layout);
}
#[test]
fn layout_with_command_panes_and_close_on_exit() {
let kdl_layout = r#"
layout {
pane command="htop" {
close_on_exit true
}
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
assert_snapshot!(format!("{:#?}", layout));
}
#[test]
fn layout_with_command_panes_and_start_suspended() {
let kdl_layout = r#"
layout {
pane command="htop" {
start_suspended true
}
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
assert_snapshot!(format!("{:#?}", layout));
}
#[test]
fn layout_with_plugin_panes() {
let kdl_layout = r#"
layout {
pane {
plugin location="zellij:tab-bar"
}
pane {
plugin location="file:/path/to/my/plugin.wasm"
}
pane {
plugin location="zellij:status-bar" {
config_key_1 "config_value_1"
"2" true
}
}
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
let mut expected_plugin_configuration = BTreeMap::new();
expected_plugin_configuration.insert("config_key_1".to_owned(), "config_value_1".to_owned());
expected_plugin_configuration.insert("2".to_owned(), "true".to_owned());
let expected_layout = Layout {
template: Some((
TiledPaneLayout {
children: vec![
TiledPaneLayout {
run: Some(Run::Plugin(RunPluginOrAlias::RunPlugin(RunPlugin {
location: RunPluginLocation::Zellij(PluginTag::new("tab-bar")),
_allow_exec_host_cmd: false,
configuration: Default::default(),
..Default::default()
}))),
..Default::default()
},
TiledPaneLayout {
run: Some(Run::Plugin(RunPluginOrAlias::RunPlugin(RunPlugin {
location: RunPluginLocation::File(PathBuf::from(
"/path/to/my/plugin.wasm",
)),
_allow_exec_host_cmd: false,
configuration: Default::default(),
..Default::default()
}))),
..Default::default()
},
TiledPaneLayout {
run: Some(Run::Plugin(RunPluginOrAlias::RunPlugin(RunPlugin {
location: RunPluginLocation::Zellij(PluginTag::new("status-bar")),
_allow_exec_host_cmd: false,
configuration: PluginUserConfiguration(expected_plugin_configuration),
..Default::default()
}))),
..Default::default()
},
],
..Default::default()
},
vec![],
)),
..Default::default()
};
assert_eq!(layout, expected_layout);
}
#[test]
fn layout_with_borderless_panes() {
let kdl_layout = r#"
layout {
pane borderless=true
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
let expected_layout = Layout {
template: Some((
TiledPaneLayout {
children: vec![TiledPaneLayout {
borderless: true,
..Default::default()
}],
..Default::default()
},
vec![],
)),
..Default::default()
};
assert_eq!(layout, expected_layout);
}
#[test]
fn layout_with_focused_panes() {
let kdl_layout = r#"
layout {
pane focus=true
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
let expected_layout = Layout {
template: Some((
TiledPaneLayout {
children: vec![TiledPaneLayout {
focus: Some(true),
..Default::default()
}],
..Default::default()
},
vec![],
)),
..Default::default()
};
assert_eq!(layout, expected_layout);
}
#[test]
fn layout_with_pane_names() {
let kdl_layout = r#"
layout {
pane name="my awesome pane"
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
let expected_layout = Layout {
template: Some((
TiledPaneLayout {
children: vec![TiledPaneLayout {
name: Some("my awesome pane".into()),
..Default::default()
}],
..Default::default()
},
vec![],
)),
..Default::default()
};
assert_eq!(layout, expected_layout);
}
#[test]
fn layout_with_tab_names() {
let kdl_layout = r#"
layout {
tab name="my cool tab name 1"
tab name="my cool tab name 2"
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
let expected_layout = Layout {
tabs: vec![
(
Some("my cool tab name 1".into()),
TiledPaneLayout {
children: vec![],
..Default::default()
},
vec![], // floating panes
),
(
Some("my cool tab name 2".into()),
TiledPaneLayout {
children: vec![],
..Default::default()
},
vec![], // floating panes
),
],
template: Some((TiledPaneLayout::default(), vec![])),
..Default::default()
};
assert_eq!(layout, expected_layout);
}
#[test]
fn layout_with_focused_tab() {
let kdl_layout = r#"
layout {
tab
tab focus=true
tab
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
let expected_layout = Layout {
tabs: vec![
(None, TiledPaneLayout::default(), vec![]),
(None, TiledPaneLayout::default(), vec![]),
(None, TiledPaneLayout::default(), vec![]),
],
template: Some((TiledPaneLayout::default(), vec![])),
focused_tab_index: Some(1),
..Default::default()
};
assert_eq!(layout, expected_layout);
}
#[test]
fn layout_with_tab_templates() {
let kdl_layout = r#"
layout {
tab_template name="one-above-one-below" {
pane
children
pane
}
one-above-one-below name="my first tab" split_direction="Vertical" {
pane
pane
}
one-above-one-below name="my second tab" {
pane
pane
}
one-above-one-below
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
let expected_layout = Layout {
tabs: vec![
(
Some("my first tab".into()),
TiledPaneLayout {
children_split_direction: SplitDirection::Horizontal,
children: vec![
TiledPaneLayout::default(),
TiledPaneLayout {
children_split_direction: SplitDirection::Vertical,
children: vec![TiledPaneLayout::default(), TiledPaneLayout::default()],
..Default::default()
},
TiledPaneLayout::default(),
],
..Default::default()
},
vec![], // floating panes
),
(
Some("my second tab".into()),
TiledPaneLayout {
children_split_direction: SplitDirection::Horizontal,
children: vec![
TiledPaneLayout::default(),
TiledPaneLayout {
children_split_direction: SplitDirection::Horizontal,
children: vec![TiledPaneLayout::default(), TiledPaneLayout::default()],
..Default::default()
},
TiledPaneLayout::default(),
],
..Default::default()
},
vec![], // floating panes
),
(
None,
TiledPaneLayout {
children_split_direction: SplitDirection::Horizontal,
children: vec![
TiledPaneLayout::default(),
TiledPaneLayout::default(),
TiledPaneLayout::default(),
],
..Default::default()
},
vec![], // floating panes
),
],
template: Some((TiledPaneLayout::default(), vec![])),
..Default::default()
};
assert_eq!(layout, expected_layout);
}
#[test]
fn layout_with_default_tab_template() {
let kdl_layout = r#"
layout {
default_tab_template {
pane
children
pane
}
tab name="my first tab" split_direction="Vertical" {
pane
pane
}
tab name="my second tab" {
pane
pane
}
tab
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
assert_snapshot!(format!("{:#?}", layout));
}
#[test]
fn layout_with_new_tab_template() {
let kdl_layout = r#"
layout {
new_tab_template {
pane split_direction="vertical" {
pane
pane
}
}
tab name="my first tab" split_direction="Vertical" {
pane
pane
}
tab name="my second tab" {
pane
pane
}
tab
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
assert_snapshot!(format!("{:#?}", layout));
}
#[test]
fn layout_with_pane_templates() {
let kdl_layout = r#"
layout {
pane_template name="left-and-right" split_direction="Vertical" {
pane
children
pane
}
left-and-right {
pane
}
left-and-right {
pane
pane
}
left-and-right split_direction="Vertical" {
pane
pane
}
left-and-right
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
assert_snapshot!(format!("{:#?}", layout));
}
#[test]
fn layout_with_tab_and_pane_templates() {
let kdl_layout = r#"
layout {
tab_template name="left-right-and-htop" {
left-and-right {
pane command="htop"
}
}
pane_template name="left-and-right" split_direction="Vertical" {
pane
children
pane
}
left-right-and-htop
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
assert_snapshot!(format!("{:#?}", layout));
}
#[test]
fn layout_with_nested_pane_templates() {
let kdl_layout = r#"
layout {
pane_template name="left-and-right" split_direction="Vertical" {
pane
children
up-and-down
pane
}
pane_template name="up-and-down" split_direction="Horizontal" {
pane
pane
}
left-and-right
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
assert_snapshot!(format!("{:#?}", layout));
}
#[test]
fn layout_with_nested_branched_pane_templates() {
let kdl_layout = r#"
layout {
pane_template name="left-and-right" split_direction="Vertical" {
pane
children
up-and-down
three-horizontal-panes
}
pane_template name="three-horizontal-panes" split_direction="Horizontal" {
pane
pane
pane
}
pane_template name="up-and-down" split_direction="Horizontal" {
pane
pane
}
left-and-right
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
assert_snapshot!(format!("{:#?}", layout));
}
#[test]
fn circular_dependency_pane_templates_error() {
let kdl_layout = r#"
layout {
pane_template name="one" split_direction="Vertical" {
pane
children
two
}
pane_template name="two" split_direction="Horizontal" {
pane
three
pane
}
pane_template name="three" split_direction="Horizontal" {
one
}
one
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None);
assert!(layout.is_err(), "circular dependency detected");
}
#[test]
fn children_not_as_first_child_of_tab_template() {
let kdl_layout = r#"
layout {
tab_template name="horizontal-with-vertical-top" {
pane split_direction="Vertical" {
pane
children
}
pane
}
horizontal-with-vertical-top name="my tab" {
pane
pane
}
horizontal-with-vertical-top
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
assert_snapshot!(format!("{:#?}", layout));
}
#[test]
fn error_on_more_than_one_children_block_in_tab_template() {
let kdl_layout = r#"
layout {
tab_template name="horizontal-with-vertical-top" {
pane split_direction="Vertical" {
pane
children
}
children
pane
}
horizontal-with-vertical-top name="my tab" {
pane
pane
}
horizontal-with-vertical-top
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None);
assert!(
layout.is_err(),
"error provided for more than one children block"
);
}
#[test]
fn children_not_as_first_child_of_pane_template() {
let kdl_layout = r#"
layout {
pane_template name="horizontal-with-vertical-top" {
pane split_direction="Vertical" {
pane
children
}
pane
}
horizontal-with-vertical-top name="my pane" {
pane
pane
}
horizontal-with-vertical-top
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None).unwrap();
assert_snapshot!(format!("{:#?}", layout));
}
#[test]
fn error_on_more_than_one_children_block_in_pane_template() {
let kdl_layout = r#"
layout {
pane_template name="horizontal-with-vertical-top" {
pane split_direction="Vertical" {
pane
children
}
children
pane
}
horizontal-with-vertical-top name="my tab" {
pane
pane
}
horizontal-with-vertical-top
}
"#;
let layout = Layout::from_kdl(kdl_layout, Some("layout_file_name".into()), None, None);
assert!(
layout.is_err(),
"error provided for more than one children block"
);
}
#[test]
fn combined_tab_and_pane_template_both_with_children() {
let kdl_layout = r#"
layout {
tab_template name="horizontal-with-vertical-top" {
vertical-sandwich {
pane name="middle"
}
children
}
pane_template name="vertical-sandwich" split_direction="Vertical" {
pane
children
pane
}
horizontal-with-vertical-top name="my tab" {
pane
pane
}
horizontal-with-vertical-top
}
"#;
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/input/unit/theme_test.rs | zellij-utils/src/input/unit/theme_test.rs | use super::super::theme::*;
use insta::assert_snapshot;
use std::path::{Path, PathBuf};
fn theme_test_dir(theme: String) -> PathBuf {
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
let theme_dir = root.join("src/input/unit/fixtures/themes");
theme_dir.join(theme)
}
#[test]
fn dracula_theme_from_file() {
let path = theme_test_dir("dracula.kdl".into());
let theme = Themes::from_path(path).unwrap();
assert_snapshot!(format!("{:#?}", theme));
}
#[test]
fn no_theme_is_err() {
let path = theme_test_dir("nonexistent.kdl".into());
let theme = Themes::from_path(path);
assert!(theme.is_err());
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/input/unit/keybinds_test.rs | zellij-utils/src/input/unit/keybinds_test.rs | use super::super::actions::*;
use super::super::keybinds::*;
use crate::data::{BareKey, Direction, KeyWithModifier};
use crate::input::config::Config;
use insta::assert_snapshot;
use strum::IntoEnumIterator;
#[test]
fn can_define_keybindings_in_configfile() {
let config_contents = r#"
keybinds {
normal {
bind "Ctrl g" { SwitchToMode "Locked"; }
}
}
"#;
let config = Config::from_kdl(config_contents, None).unwrap();
let ctrl_g_normal_mode_action = config.keybinds.get_actions_for_key_in_mode(
&InputMode::Normal,
&KeyWithModifier::new(BareKey::Char('g')).with_ctrl_modifier(),
);
assert_eq!(
ctrl_g_normal_mode_action,
Some(&vec![Action::SwitchToMode {
input_mode: InputMode::Locked
}]),
"Keybinding successfully defined in config"
);
}
#[test]
fn can_define_multiple_keybinds_for_same_action() {
let config_contents = r#"
keybinds {
normal {
bind "Alt h" "Alt Left" { MoveFocusOrTab "Left"; }
}
}
"#;
let config = Config::from_kdl(config_contents, None).unwrap();
let alt_h_normal_mode_action = config.keybinds.get_actions_for_key_in_mode(
&InputMode::Normal,
&KeyWithModifier::new(BareKey::Left).with_alt_modifier(),
);
let alt_left_normal_mode_action = config.keybinds.get_actions_for_key_in_mode(
&InputMode::Normal,
&KeyWithModifier::new(BareKey::Char('h')).with_alt_modifier(),
);
assert_eq!(
alt_h_normal_mode_action,
Some(&vec![Action::MoveFocusOrTab {
direction: Direction::Left
}]),
"First keybinding successfully defined in config"
);
assert_eq!(
alt_left_normal_mode_action,
Some(&vec![Action::MoveFocusOrTab {
direction: Direction::Left
}]),
"Second keybinding successfully defined in config"
);
}
#[test]
fn can_define_series_of_actions_for_same_keybinding() {
let config_contents = r#"
keybinds {
pane {
bind "z" { TogglePaneFrames; SwitchToMode "Normal"; }
}
}
"#;
let config = Config::from_kdl(config_contents, None).unwrap();
let z_in_pane_mode = config
.keybinds
.get_actions_for_key_in_mode(&InputMode::Pane, &KeyWithModifier::new(BareKey::Char('z')));
assert_eq!(
z_in_pane_mode,
Some(&vec![
Action::TogglePaneFrames,
Action::SwitchToMode {
input_mode: InputMode::Normal
}
]),
"Action series successfully defined"
);
}
#[test]
fn keybindings_bind_order_is_preserved() {
let config_contents = r#"
keybinds {
pane {
bind "z" { TogglePaneFrames; SwitchToMode "Normal"; }
bind "z" { SwitchToMode "Resize"; }
}
}
"#;
let config = Config::from_kdl(config_contents, None).unwrap();
let z_in_pane_mode = config
.keybinds
.get_actions_for_key_in_mode(&InputMode::Pane, &KeyWithModifier::new(BareKey::Char('z')));
assert_eq!(
z_in_pane_mode,
Some(&vec![Action::SwitchToMode {
input_mode: InputMode::Resize
}]),
"Second keybinding was applied"
);
}
#[test]
fn uppercase_and_lowercase_keybindings_are_distinct() {
let config_contents = r#"
keybinds {
pane {
bind "z" { TogglePaneFrames; SwitchToMode "Normal"; }
bind "Z" { SwitchToMode "Resize"; }
}
}
"#;
let config = Config::from_kdl(config_contents, None).unwrap();
let z_in_pane_mode = config
.keybinds
.get_actions_for_key_in_mode(&InputMode::Pane, &KeyWithModifier::new(BareKey::Char('z')));
let uppercase_z_in_pane_mode = config
.keybinds
.get_actions_for_key_in_mode(&InputMode::Pane, &KeyWithModifier::new(BareKey::Char('Z')));
assert_eq!(
z_in_pane_mode,
Some(&vec![
Action::TogglePaneFrames,
Action::SwitchToMode {
input_mode: InputMode::Normal
}
]),
"Lowercase z successfully bound"
);
assert_eq!(
uppercase_z_in_pane_mode,
Some(&vec![Action::SwitchToMode {
input_mode: InputMode::Resize
}]),
"Uppercase z successfully bound"
);
}
#[test]
fn can_override_keybindings() {
let default_config_contents = r#"
keybinds {
pane {
bind "z" { TogglePaneFrames; SwitchToMode "Normal"; }
}
}
"#;
let config_contents = r#"
keybinds {
pane {
bind "z" { SwitchToMode "Resize"; }
}
}
"#;
let default_config = Config::from_kdl(default_config_contents, None).unwrap();
let config = Config::from_kdl(config_contents, Some(default_config)).unwrap();
let z_in_pane_mode = config
.keybinds
.get_actions_for_key_in_mode(&InputMode::Pane, &KeyWithModifier::new(BareKey::Char('z')));
assert_eq!(
z_in_pane_mode,
Some(&vec![Action::SwitchToMode {
input_mode: InputMode::Resize
}]),
"Keybinding from config overrode keybinding from default config"
);
}
#[test]
fn can_add_to_default_keybindings() {
// this test just makes sure keybindings defined in a custom config are added to different
// keybindings defined in the default config
let default_config_contents = r#"
keybinds {
pane {
bind "z" { TogglePaneFrames; SwitchToMode "Normal"; }
}
}
"#;
let config_contents = r#"
keybinds {
pane {
bind "r" { SwitchToMode "Resize"; }
}
}
"#;
let default_config = Config::from_kdl(default_config_contents, None).unwrap();
let config = Config::from_kdl(config_contents, Some(default_config)).unwrap();
let z_in_pane_mode = config
.keybinds
.get_actions_for_key_in_mode(&InputMode::Pane, &KeyWithModifier::new(BareKey::Char('z')));
let r_in_pane_mode = config
.keybinds
.get_actions_for_key_in_mode(&InputMode::Pane, &KeyWithModifier::new(BareKey::Char('r')));
assert_eq!(
z_in_pane_mode,
Some(&vec![
Action::TogglePaneFrames,
Action::SwitchToMode {
input_mode: InputMode::Normal
}
]),
"Keybinding from default config bound"
);
assert_eq!(
r_in_pane_mode,
Some(&vec![Action::SwitchToMode {
input_mode: InputMode::Resize
}]),
"Keybinding from custom config bound as well"
);
}
#[test]
fn can_clear_default_keybindings() {
let default_config_contents = r#"
keybinds {
normal {
bind "Ctrl g" { SwitchToMode "Locked"; }
}
pane {
bind "z" { TogglePaneFrames; SwitchToMode "Normal"; }
}
}
"#;
let config_contents = r#"
keybinds clear-defaults=true {
normal {
bind "Ctrl r" { SwitchToMode "Locked"; }
}
pane {
bind "r" { SwitchToMode "Resize"; }
}
}
"#;
let default_config = Config::from_kdl(default_config_contents, None).unwrap();
let config = Config::from_kdl(config_contents, Some(default_config)).unwrap();
let ctrl_g_normal_mode_action = config.keybinds.get_actions_for_key_in_mode(
&InputMode::Normal,
&KeyWithModifier::new(BareKey::Char('g')).with_ctrl_modifier(),
);
let z_in_pane_mode = config
.keybinds
.get_actions_for_key_in_mode(&InputMode::Pane, &KeyWithModifier::new(BareKey::Char('z')));
let ctrl_r_in_normal_mode = config.keybinds.get_actions_for_key_in_mode(
&InputMode::Normal,
&KeyWithModifier::new(BareKey::Char('r')).with_ctrl_modifier(),
);
let r_in_pane_mode = config
.keybinds
.get_actions_for_key_in_mode(&InputMode::Pane, &KeyWithModifier::new(BareKey::Char('r')));
assert_eq!(
ctrl_g_normal_mode_action, None,
"Keybinding from normal mode in default config cleared"
);
assert_eq!(
z_in_pane_mode, None,
"Keybinding from pane mode in default config cleared"
);
assert_eq!(
r_in_pane_mode,
Some(&vec![Action::SwitchToMode {
input_mode: InputMode::Resize
}]),
"Keybinding from pane mode in custom config still bound"
);
assert_eq!(
ctrl_r_in_normal_mode,
Some(&vec![Action::SwitchToMode {
input_mode: InputMode::Locked
}]),
"Keybinding from normal mode in custom config still bound"
);
}
#[test]
fn can_clear_default_keybindings_per_single_mode() {
let default_config_contents = r#"
keybinds {
normal {
bind "Ctrl g" { SwitchToMode "Locked"; }
}
pane {
bind "z" { TogglePaneFrames; SwitchToMode "Normal"; }
}
}
"#;
let config_contents = r#"
keybinds {
pane clear-defaults=true {
bind "r" { SwitchToMode "Resize"; }
}
}
"#;
let default_config = Config::from_kdl(default_config_contents, None).unwrap();
let config = Config::from_kdl(config_contents, Some(default_config)).unwrap();
let ctrl_g_normal_mode_action = config.keybinds.get_actions_for_key_in_mode(
&InputMode::Normal,
&KeyWithModifier::new(BareKey::Char('g')).with_ctrl_modifier(),
);
let z_in_pane_mode = config
.keybinds
.get_actions_for_key_in_mode(&InputMode::Pane, &KeyWithModifier::new(BareKey::Char('z')));
let r_in_pane_mode = config
.keybinds
.get_actions_for_key_in_mode(&InputMode::Pane, &KeyWithModifier::new(BareKey::Char('r')));
assert_eq!(
ctrl_g_normal_mode_action,
Some(&vec![Action::SwitchToMode {
input_mode: InputMode::Locked
}]),
"Keybind in different mode from default config not cleared"
);
assert_eq!(
z_in_pane_mode, None,
"Keybinding from pane mode in default config cleared"
);
assert_eq!(
r_in_pane_mode,
Some(&vec![Action::SwitchToMode {
input_mode: InputMode::Resize
}]),
"Keybinding from pane mode in custom config still bound"
);
}
#[test]
fn can_unbind_multiple_keys_globally() {
let default_config_contents = r#"
keybinds {
normal {
bind "Ctrl g" { SwitchToMode "Locked"; }
}
pane {
bind "Ctrl g" { SwitchToMode "Locked"; }
bind "z" { TogglePaneFrames; SwitchToMode "Normal"; }
bind "r" { TogglePaneFrames; }
}
}
"#;
let config_contents = r#"
keybinds {
unbind "Ctrl g" "z"
pane {
bind "t" { SwitchToMode "Tab"; }
}
}
"#;
let default_config = Config::from_kdl(default_config_contents, None).unwrap();
let config = Config::from_kdl(config_contents, Some(default_config)).unwrap();
let ctrl_g_normal_mode_action = config.keybinds.get_actions_for_key_in_mode(
&InputMode::Normal,
&KeyWithModifier::new(BareKey::Char('g')).with_ctrl_modifier(),
);
let ctrl_g_pane_mode_action = config.keybinds.get_actions_for_key_in_mode(
&InputMode::Pane,
&KeyWithModifier::new(BareKey::Char('g')).with_ctrl_modifier(),
);
let r_in_pane_mode = config
.keybinds
.get_actions_for_key_in_mode(&InputMode::Pane, &KeyWithModifier::new(BareKey::Char('r')));
let z_in_pane_mode = config
.keybinds
.get_actions_for_key_in_mode(&InputMode::Pane, &KeyWithModifier::new(BareKey::Char('z')));
let t_in_pane_mode = config
.keybinds
.get_actions_for_key_in_mode(&InputMode::Pane, &KeyWithModifier::new(BareKey::Char('t')));
assert_eq!(
ctrl_g_normal_mode_action, None,
"First keybind uncleared in one mode"
);
assert_eq!(
ctrl_g_pane_mode_action, None,
"First keybind uncleared in another mode"
);
assert_eq!(z_in_pane_mode, None, "Second keybind cleared as well");
assert_eq!(
r_in_pane_mode,
Some(&vec![Action::TogglePaneFrames]),
"Unrelated keybinding in default config still bound"
);
assert_eq!(
t_in_pane_mode,
Some(&vec![Action::SwitchToMode {
input_mode: InputMode::Tab
}]),
"Keybinding from custom config still bound"
);
}
#[test]
fn can_unbind_multiple_keys_per_single_mode() {
let default_config_contents = r#"
keybinds {
normal {
bind "Ctrl g" { SwitchToMode "Locked"; }
}
pane {
bind "Ctrl g" { SwitchToMode "Locked"; }
bind "z" { TogglePaneFrames; SwitchToMode "Normal"; }
bind "r" { TogglePaneFrames; }
}
}
"#;
let config_contents = r#"
keybinds {
pane {
unbind "Ctrl g" "z"
bind "t" { SwitchToMode "Tab"; }
}
}
"#;
let default_config = Config::from_kdl(default_config_contents, None).unwrap();
let config = Config::from_kdl(config_contents, Some(default_config)).unwrap();
let ctrl_g_normal_mode_action = config.keybinds.get_actions_for_key_in_mode(
&InputMode::Normal,
&KeyWithModifier::new(BareKey::Char('g')).with_ctrl_modifier(),
);
let ctrl_g_pane_mode_action = config.keybinds.get_actions_for_key_in_mode(
&InputMode::Pane,
&KeyWithModifier::new(BareKey::Char('g')).with_ctrl_modifier(),
);
let r_in_pane_mode = config
.keybinds
.get_actions_for_key_in_mode(&InputMode::Pane, &KeyWithModifier::new(BareKey::Char('r')));
let z_in_pane_mode = config
.keybinds
.get_actions_for_key_in_mode(&InputMode::Pane, &KeyWithModifier::new(BareKey::Char('z')));
let t_in_pane_mode = config
.keybinds
.get_actions_for_key_in_mode(&InputMode::Pane, &KeyWithModifier::new(BareKey::Char('t')));
assert_eq!(
ctrl_g_normal_mode_action,
Some(&vec![Action::SwitchToMode {
input_mode: InputMode::Locked
}]),
"Keybind in different mode not cleared"
);
assert_eq!(
ctrl_g_pane_mode_action, None,
"First Keybind cleared in its mode"
);
assert_eq!(
z_in_pane_mode, None,
"Second keybind cleared in its mode as well"
);
assert_eq!(
r_in_pane_mode,
Some(&vec![Action::TogglePaneFrames]),
"Unrelated keybinding in default config still bound"
);
assert_eq!(
t_in_pane_mode,
Some(&vec![Action::SwitchToMode {
input_mode: InputMode::Tab
}]),
"Keybinding from custom config still bound"
);
}
#[test]
fn can_define_shared_keybinds_for_all_modes() {
let config_contents = r#"
keybinds {
shared {
bind "Ctrl g" { SwitchToMode "Locked"; }
}
}
"#;
let config = Config::from_kdl(config_contents, None).unwrap();
for mode in InputMode::iter() {
let action_in_mode = config.keybinds.get_actions_for_key_in_mode(
&mode,
&KeyWithModifier::new(BareKey::Char('g')).with_ctrl_modifier(),
);
assert_eq!(
action_in_mode,
Some(&vec![Action::SwitchToMode {
input_mode: InputMode::Locked
}]),
"Keybind bound in mode"
);
}
}
#[test]
fn can_define_shared_keybinds_with_exclusion() {
let config_contents = r#"
keybinds {
shared_except "locked" {
bind "Ctrl g" { SwitchToMode "Locked"; }
}
}
"#;
let config = Config::from_kdl(config_contents, None).unwrap();
for mode in InputMode::iter() {
let action_in_mode = config.keybinds.get_actions_for_key_in_mode(
&mode,
&KeyWithModifier::new(BareKey::Char('g')).with_ctrl_modifier(),
);
if mode == InputMode::Locked {
assert_eq!(action_in_mode, None, "Keybind unbound in excluded mode");
} else {
assert_eq!(
action_in_mode,
Some(&vec![Action::SwitchToMode {
input_mode: InputMode::Locked
}]),
"Keybind bound in mode"
);
}
}
}
#[test]
fn can_define_shared_keybinds_with_inclusion() {
let config_contents = r#"
keybinds {
shared_among "normal" "resize" "pane" {
bind "Ctrl g" { SwitchToMode "Locked"; }
}
}
"#;
let config = Config::from_kdl(config_contents, None).unwrap();
for mode in InputMode::iter() {
let action_in_mode = config.keybinds.get_actions_for_key_in_mode(
&mode,
&KeyWithModifier::new(BareKey::Char('g')).with_ctrl_modifier(),
);
if mode == InputMode::Normal || mode == InputMode::Resize || mode == InputMode::Pane {
assert_eq!(
action_in_mode,
Some(&vec![Action::SwitchToMode {
input_mode: InputMode::Locked
}]),
"Keybind bound in included mode"
);
} else {
assert_eq!(action_in_mode, None, "Keybind unbound in other modes");
}
}
}
#[test]
fn keybindings_unbinds_happen_after_binds() {
let config_contents = r#"
keybinds {
pane {
unbind "z"
bind "z" { SwitchToMode "Resize"; }
}
}
"#;
let config = Config::from_kdl(config_contents, None).unwrap();
let z_in_pane_mode = config
.keybinds
.get_actions_for_key_in_mode(&InputMode::Pane, &KeyWithModifier::new(BareKey::Char('z')));
assert_eq!(z_in_pane_mode, None, "Key was ultimately unbound");
}
#[test]
fn error_received_on_unknown_input_mode() {
let config_contents = r#"
keybinds {
i_do_not_exist {
bind "z" { SwitchToMode "Resize"; }
}
}
"#;
let config_error = Config::from_kdl(config_contents, None).unwrap_err();
assert_snapshot!(format!("{:?}", config_error));
}
#[test]
fn error_received_on_unknown_key_instruction() {
let config_contents = r#"
keybinds {
pane {
i_am_not_bind_or_unbind
bind "z" { SwitchToMode "Resize"; }
}
}
"#;
let config_error = Config::from_kdl(config_contents, None).unwrap_err();
assert_snapshot!(format!("{:?}", config_error));
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/kdl/kdl_layout_parser.rs | zellij-utils/src/kdl/kdl_layout_parser.rs | use crate::input::{
command::RunCommand,
config::ConfigError,
layout::{
FloatingPaneLayout, Layout, LayoutConstraint, PercentOrFixed, PluginUserConfiguration, Run,
RunPluginOrAlias, SplitDirection, SplitSize, SwapFloatingLayout, SwapTiledLayout,
TiledPaneLayout,
},
};
use kdl::*;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::str::FromStr;
use crate::{
kdl_child_with_name, kdl_children_nodes, kdl_first_entry_as_bool, kdl_first_entry_as_i64,
kdl_first_entry_as_string, kdl_get_bool_property_or_child_value,
kdl_get_bool_property_or_child_value_with_error, kdl_get_child,
kdl_get_int_property_or_child_value, kdl_get_property_or_child,
kdl_get_string_property_or_child_value, kdl_get_string_property_or_child_value_with_error,
kdl_name, kdl_parsing_error, kdl_property_names, kdl_property_or_child_value_node,
kdl_string_arguments,
};
use std::path::PathBuf;
use std::vec::Vec;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PaneOrFloatingPane {
Pane(TiledPaneLayout),
FloatingPane(FloatingPaneLayout),
Either(TiledPaneLayout),
}
pub struct KdlLayoutParser<'a> {
global_cwd: Option<PathBuf>,
raw_layout: &'a str,
tab_templates: HashMap<String, (TiledPaneLayout, Vec<FloatingPaneLayout>, KdlNode)>,
pane_templates: HashMap<String, (PaneOrFloatingPane, KdlNode)>,
default_tab_template: Option<(TiledPaneLayout, Vec<FloatingPaneLayout>, KdlNode)>,
new_tab_template: Option<(TiledPaneLayout, Vec<FloatingPaneLayout>)>,
file_name: Option<PathBuf>,
}
impl<'a> KdlLayoutParser<'a> {
pub fn new(
raw_layout: &'a str,
global_cwd: Option<PathBuf>,
file_name: Option<String>,
) -> Self {
KdlLayoutParser {
raw_layout,
tab_templates: HashMap::new(),
pane_templates: HashMap::new(),
default_tab_template: None,
new_tab_template: None,
global_cwd,
file_name: file_name.map(|f| PathBuf::from(f)),
}
}
fn is_a_reserved_word(&self, word: &str) -> bool {
// note that it's important that none of these words happens to also be a config property,
// otherwise they might collide
word == "pane"
|| word == "layout"
|| word == "pane_template"
|| word == "tab_template"
|| word == "default_tab_template"
|| word == "new_tab_template"
|| word == "command"
|| word == "edit"
|| word == "plugin"
|| word == "children"
|| word == "tab"
|| word == "args"
|| word == "close_on_exit"
|| word == "start_suspended"
|| word == "borderless"
|| word == "focus"
|| word == "name"
|| word == "size"
|| word == "cwd"
|| word == "split_direction"
|| word == "swap_tiled_layout"
|| word == "swap_floating_layout"
|| word == "hide_floating_panes"
|| word == "contents_file"
}
fn is_a_valid_pane_property(&self, property_name: &str) -> bool {
property_name == "borderless"
|| property_name == "focus"
|| property_name == "name"
|| property_name == "size"
|| property_name == "plugin"
|| property_name == "command"
|| property_name == "edit"
|| property_name == "cwd"
|| property_name == "args"
|| property_name == "close_on_exit"
|| property_name == "start_suspended"
|| property_name == "split_direction"
|| property_name == "pane"
|| property_name == "children"
|| property_name == "stacked"
|| property_name == "expanded"
|| property_name == "exclude_from_sync"
|| property_name == "contents_file"
}
fn is_a_valid_floating_pane_property(&self, property_name: &str) -> bool {
property_name == "borderless"
|| property_name == "focus"
|| property_name == "name"
|| property_name == "plugin"
|| property_name == "command"
|| property_name == "edit"
|| property_name == "cwd"
|| property_name == "args"
|| property_name == "close_on_exit"
|| property_name == "start_suspended"
|| property_name == "x"
|| property_name == "y"
|| property_name == "width"
|| property_name == "height"
|| property_name == "pinned"
|| property_name == "contents_file"
}
fn is_a_valid_tab_property(&self, property_name: &str) -> bool {
property_name == "focus"
|| property_name == "name"
|| property_name == "split_direction"
|| property_name == "cwd"
|| property_name == "floating_panes"
|| property_name == "children"
|| property_name == "max_panes"
|| property_name == "min_panes"
|| property_name == "exact_panes"
|| property_name == "hide_floating_panes"
}
pub fn is_a_reserved_plugin_property(property_name: &str) -> bool {
property_name == "location"
|| property_name == "_allow_exec_host_cmd"
|| property_name == "path"
}
fn assert_legal_node_name(&self, name: &str, kdl_node: &KdlNode) -> Result<(), ConfigError> {
if name.contains(char::is_whitespace) {
Err(ConfigError::new_layout_kdl_error(
format!("Node names ({}) cannot contain whitespace.", name),
kdl_node.span().offset(),
kdl_node.span().len(),
))
} else if self.is_a_reserved_word(&name) {
Err(ConfigError::new_layout_kdl_error(
format!("Node name '{}' is a reserved word.", name),
kdl_node.span().offset(),
kdl_node.span().len(),
))
} else {
Ok(())
}
}
fn assert_legal_template_name(
&self,
name: &str,
kdl_node: &KdlNode,
) -> Result<(), ConfigError> {
if name.is_empty() {
Err(ConfigError::new_layout_kdl_error(
format!("Template names cannot be empty"),
kdl_node.span().offset(),
kdl_node.span().len(),
))
} else if name.contains(')') || name.contains('(') {
Err(ConfigError::new_layout_kdl_error(
format!("Template names cannot contain parantheses"),
kdl_node.span().offset(),
kdl_node.span().len(),
))
} else if name
.chars()
.next()
.map(|first_char| first_char.is_numeric())
.unwrap_or(false)
{
Err(ConfigError::new_layout_kdl_error(
format!("Template names cannot start with numbers"),
kdl_node.span().offset(),
kdl_node.span().len(),
))
} else {
Ok(())
}
}
fn assert_no_grandchildren_in_stack(
&self,
children: &[KdlNode],
is_part_of_stack: bool,
) -> Result<(), ConfigError> {
if is_part_of_stack {
for child in children {
if kdl_name!(child) == "pane" || self.pane_templates.get(kdl_name!(child)).is_some()
{
return Err(ConfigError::new_layout_kdl_error(
format!("Stacked panes cannot have children"),
child.span().offset(),
child.span().len(),
));
}
}
}
Ok(())
}
fn parse_split_size(&self, kdl_node: &KdlNode) -> Result<Option<SplitSize>, ConfigError> {
if let Some(size) = kdl_get_string_property_or_child_value!(kdl_node, "size") {
match SplitSize::from_str(size) {
Ok(size) => Ok(Some(size)),
Err(_e) => Err(kdl_parsing_error!(
format!(
"size should be a fixed number (eg. 1) or a quoted percent (eg. \"50%\")"
),
kdl_node
)),
}
} else if let Some(size) = kdl_get_int_property_or_child_value!(kdl_node, "size") {
if size == 0 {
return Err(kdl_parsing_error!(
format!("size should be greater than 0"),
kdl_node
));
}
Ok(Some(SplitSize::Fixed(size as usize)))
} else if let Some(node) = kdl_property_or_child_value_node!(kdl_node, "size") {
Err(kdl_parsing_error!(
format!("size should be a fixed number (eg. 1) or a quoted percent (eg. \"50%\")"),
node
))
} else if let Some(node) = kdl_child_with_name!(kdl_node, "size") {
Err(kdl_parsing_error!(
format!(
"size cannot be bare, it should have a value (eg. 'size 1', or 'size \"50%\"')"
),
node
))
} else {
Ok(None)
}
}
fn parse_percent_or_fixed(
&self,
kdl_node: &KdlNode,
value_name: &str,
can_be_zero: bool,
) -> Result<Option<PercentOrFixed>, ConfigError> {
if let Some(size) = kdl_get_string_property_or_child_value!(kdl_node, value_name) {
match PercentOrFixed::from_str(size) {
Ok(size) => {
if !can_be_zero && size.is_zero() {
Err(kdl_parsing_error!(
format!("{} should be greater than 0", value_name),
kdl_node
))
} else {
Ok(Some(size))
}
},
Err(_e) => Err(kdl_parsing_error!(
format!(
"{} should be a fixed number (eg. 1) or a quoted percent (eg. \"50%\")",
value_name
),
kdl_node
)),
}
} else if let Some(size) = kdl_get_int_property_or_child_value!(kdl_node, value_name) {
if size == 0 && !can_be_zero {
return Err(kdl_parsing_error!(
format!("{} should be greater than 0", value_name),
kdl_node
));
}
Ok(Some(PercentOrFixed::Fixed(size as usize)))
} else if let Some(node) = kdl_property_or_child_value_node!(kdl_node, "size") {
Err(kdl_parsing_error!(
format!(
"{} should be a fixed number (eg. 1) or a quoted percent (eg. \"50%\")",
value_name
),
node
))
} else if let Some(node) = kdl_child_with_name!(kdl_node, "size") {
Err(kdl_parsing_error!(
format!(
"{} cannot be bare, it should have a value (eg. 'size 1', or 'size \"50%\"')",
value_name
),
node
))
} else {
Ok(None)
}
}
fn parse_plugin_block(&self, plugin_block: &KdlNode) -> Result<Option<Run>, ConfigError> {
let _allow_exec_host_cmd =
kdl_get_bool_property_or_child_value_with_error!(plugin_block, "_allow_exec_host_cmd")
.unwrap_or(false);
let string_url =
kdl_get_string_property_or_child_value_with_error!(plugin_block, "location").ok_or(
ConfigError::new_layout_kdl_error(
"Plugins must have a location".into(),
plugin_block.span().offset(),
plugin_block.span().len(),
),
)?;
let url_node = kdl_get_property_or_child!(plugin_block, "location").ok_or(
ConfigError::new_layout_kdl_error(
"Plugins must have a location".into(),
plugin_block.span().offset(),
plugin_block.span().len(),
),
)?;
let configuration = KdlLayoutParser::parse_plugin_user_configuration(&plugin_block)?;
let initial_cwd =
kdl_get_string_property_or_child_value!(&plugin_block, "cwd").map(|s| PathBuf::from(s));
let cwd = self.cwd_prefix(initial_cwd.as_ref())?;
let run_plugin_or_alias = RunPluginOrAlias::from_url(
&string_url,
&Some(configuration.inner().clone()),
None,
cwd.clone(),
)
.map_err(|e| {
ConfigError::new_kdl_error(
format!("Failed to parse plugin: {}", e),
url_node.span().offset(),
url_node.span().len(),
)
})?
.with_initial_cwd(cwd);
Ok(Some(Run::Plugin(run_plugin_or_alias)))
}
pub fn parse_plugin_user_configuration(
plugin_block: &KdlNode,
) -> Result<PluginUserConfiguration, ConfigError> {
let mut configuration = BTreeMap::new();
for user_configuration_entry in plugin_block.entries() {
let name = user_configuration_entry.name();
let value = user_configuration_entry.value();
if let Some(name) = name {
let name = name.to_string();
if KdlLayoutParser::is_a_reserved_plugin_property(&name) {
continue;
}
configuration.insert(name, value.to_string());
}
// we ignore "bare" (eg. `plugin i_am_a_bare_true_argument { arg_one 1; }`) entries
// to prevent diverging behaviour with the keybindings config
}
if let Some(user_config) = kdl_children_nodes!(plugin_block) {
for user_configuration_entry in user_config {
let config_entry_name = kdl_name!(user_configuration_entry);
if KdlLayoutParser::is_a_reserved_plugin_property(&config_entry_name) {
continue;
}
let config_entry_str_value = kdl_first_entry_as_string!(user_configuration_entry)
.map(|s| format!("{}", s.to_string()));
let config_entry_int_value = kdl_first_entry_as_i64!(user_configuration_entry)
.map(|s| format!("{}", s.to_string()));
let config_entry_bool_value = kdl_first_entry_as_bool!(user_configuration_entry)
.map(|s| format!("{}", s.to_string()));
let config_entry_children = user_configuration_entry
.children()
.map(|s| format!("{}", s.to_string().trim()));
let config_entry_value = config_entry_str_value
.or(config_entry_int_value)
.or(config_entry_bool_value)
.or(config_entry_children)
.ok_or(ConfigError::new_kdl_error(
format!(
"Failed to parse plugin block configuration: {:?}",
user_configuration_entry
),
plugin_block.span().offset(),
plugin_block.span().len(),
))?;
configuration.insert(config_entry_name.into(), config_entry_value);
}
}
Ok(PluginUserConfiguration::new(configuration))
}
fn parse_args(&self, pane_node: &KdlNode) -> Result<Option<Vec<String>>, ConfigError> {
match kdl_get_child!(pane_node, "args") {
Some(kdl_args) => {
if kdl_args.entries().is_empty() {
return Err(kdl_parsing_error!(format!("args cannot be empty and should contain one or more command arguments (eg. args \"-h\" \"-v\")"), kdl_args));
}
Ok(Some(
kdl_string_arguments!(kdl_args)
.iter()
.map(|s| String::from(*s))
.collect(),
))
},
None => Ok(None),
}
}
fn cwd_prefix(&self, tab_cwd: Option<&PathBuf>) -> Result<Option<PathBuf>, ConfigError> {
Ok(match (&self.global_cwd, tab_cwd) {
(Some(global_cwd), Some(tab_cwd)) => Some(global_cwd.join(tab_cwd)),
(None, Some(tab_cwd)) => Some(tab_cwd.clone()),
(Some(global_cwd), None) => Some(global_cwd.clone()),
(None, None) => None,
})
}
fn parse_path(
&self,
kdl_node: &KdlNode,
name: &'static str,
) -> Result<Option<PathBuf>, ConfigError> {
match kdl_get_string_property_or_child_value_with_error!(kdl_node, name) {
Some(s) => match shellexpand::full(s) {
Ok(s) => Ok(Some(PathBuf::from(s.as_ref()))),
Err(e) => Err(kdl_parsing_error!(e.to_string(), kdl_node)),
},
None => Ok(None),
}
}
fn parse_pane_command(
&self,
pane_node: &KdlNode,
is_template: bool,
) -> Result<Option<Run>, ConfigError> {
let command = self.parse_path(pane_node, "command")?;
let edit = self.parse_path(pane_node, "edit")?;
let cwd = self.parse_path(pane_node, "cwd")?;
let args = self.parse_args(pane_node)?;
let close_on_exit =
kdl_get_bool_property_or_child_value_with_error!(pane_node, "close_on_exit");
let start_suspended =
kdl_get_bool_property_or_child_value_with_error!(pane_node, "start_suspended");
if !is_template {
self.assert_no_bare_attributes_in_pane_node(
&command,
&args,
&close_on_exit,
&start_suspended,
pane_node,
)?;
}
let hold_on_close = close_on_exit.map(|c| !c).unwrap_or(true);
let hold_on_start = start_suspended.map(|c| c).unwrap_or(false);
match (command, edit, cwd) {
(None, None, Some(cwd)) => Ok(Some(Run::Cwd(cwd))),
(Some(command), None, cwd) => Ok(Some(Run::Command(RunCommand {
command,
args: args.unwrap_or_else(|| vec![]),
cwd,
hold_on_close,
hold_on_start,
..Default::default()
}))),
(None, Some(edit), Some(cwd)) => {
Ok(Some(Run::EditFile(cwd.join(edit), None, Some(cwd))))
},
(None, Some(edit), None) => Ok(Some(Run::EditFile(edit, None, None))),
(Some(_command), Some(_edit), _) => Err(ConfigError::new_layout_kdl_error(
"cannot have both a command and an edit instruction for the same pane".into(),
pane_node.span().offset(),
pane_node.span().len(),
)),
_ => Ok(None),
}
}
fn parse_command_plugin_or_edit_block(
&self,
kdl_node: &KdlNode,
) -> Result<Option<Run>, ConfigError> {
let mut run = self.parse_pane_command(kdl_node, false)?;
if let Some(plugin_block) = kdl_get_child!(kdl_node, "plugin") {
let has_non_cwd_run_prop = run
.map(|r| match r {
Run::Cwd(_) => false,
_ => true,
})
.unwrap_or(false);
if has_non_cwd_run_prop {
return Err(ConfigError::new_layout_kdl_error(
"Cannot have both a command/edit and a plugin block for a single pane".into(),
plugin_block.span().offset(),
plugin_block.span().len(),
));
}
run = self.parse_plugin_block(plugin_block)?;
}
Ok(run)
}
fn parse_command_plugin_or_edit_block_for_template(
&self,
kdl_node: &KdlNode,
) -> Result<Option<Run>, ConfigError> {
let mut run = self.parse_pane_command(kdl_node, true)?;
if let Some(plugin_block) = kdl_get_child!(kdl_node, "plugin") {
let has_non_cwd_run_prop = run
.map(|r| match r {
Run::Cwd(_) => false,
_ => true,
})
.unwrap_or(false);
if has_non_cwd_run_prop {
return Err(ConfigError::new_layout_kdl_error(
"Cannot have both a command/edit and a plugin block for a single pane".into(),
plugin_block.span().offset(),
plugin_block.span().len(),
));
}
run = self.parse_plugin_block(plugin_block)?;
}
Ok(run)
}
fn parse_pane_node(
&self,
kdl_node: &KdlNode,
is_part_of_stack: bool,
) -> Result<TiledPaneLayout, ConfigError> {
self.assert_valid_pane_properties(kdl_node)?;
let children_are_stacked =
kdl_get_bool_property_or_child_value_with_error!(kdl_node, "stacked").unwrap_or(false);
let is_expanded_in_stack =
kdl_get_bool_property_or_child_value_with_error!(kdl_node, "expanded").unwrap_or(false);
let borderless = kdl_get_bool_property_or_child_value_with_error!(kdl_node, "borderless");
let focus = kdl_get_bool_property_or_child_value_with_error!(kdl_node, "focus");
let name = kdl_get_string_property_or_child_value_with_error!(kdl_node, "name")
.map(|name| name.to_string());
let exclude_from_sync =
kdl_get_bool_property_or_child_value_with_error!(kdl_node, "exclude_from_sync");
let contents_file =
kdl_get_string_property_or_child_value_with_error!(kdl_node, "contents_file");
let split_size = self.parse_split_size(kdl_node)?;
let run = self.parse_command_plugin_or_edit_block(kdl_node)?;
let children_split_direction = self.parse_split_direction(kdl_node)?;
let (external_children_index, children) = match kdl_children_nodes!(kdl_node) {
Some(children) => {
self.assert_no_grandchildren_in_stack(&children, is_part_of_stack)?;
self.parse_child_pane_nodes_for_pane(&children, children_are_stacked)?
},
None => (None, vec![]),
};
if children_are_stacked && external_children_index.is_none() && children.is_empty() {
return Err(ConfigError::new_layout_kdl_error(
format!("A stacked pane must have children nodes or possibly a \"children\" node if in a swap_layout"),
kdl_node.span().offset(),
kdl_node.span().len(),
));
} else if children_are_stacked && children_split_direction == SplitDirection::Vertical {
return Err(ConfigError::new_layout_kdl_error(
format!("Stacked panes cannot be vertical"),
kdl_node.span().offset(),
kdl_node.span().len(),
));
} else if is_expanded_in_stack && !is_part_of_stack {
return Err(ConfigError::new_layout_kdl_error(
format!("An expanded pane must be part of a stack"),
kdl_node.span().offset(),
kdl_node.span().len(),
));
}
self.assert_no_mixed_children_and_properties(kdl_node)?;
let pane_initial_contents = contents_file.and_then(|contents_file| {
self.file_name
.as_ref()
.and_then(|f| f.parent())
.and_then(|parent_folder| {
std::fs::read_to_string(parent_folder.join(contents_file)).ok()
})
});
Ok(TiledPaneLayout {
borderless: borderless.unwrap_or_default(),
focus,
name,
split_size,
run,
children_split_direction,
external_children_index,
exclude_from_sync,
children,
children_are_stacked,
is_expanded_in_stack,
pane_initial_contents,
..Default::default()
})
}
fn parse_floating_pane_node(
&self,
kdl_node: &KdlNode,
) -> Result<FloatingPaneLayout, ConfigError> {
self.assert_valid_floating_pane_properties(kdl_node)?;
let height = self.parse_percent_or_fixed(kdl_node, "height", false)?;
let width = self.parse_percent_or_fixed(kdl_node, "width", false)?;
let x = self.parse_percent_or_fixed(kdl_node, "x", true)?;
let y = self.parse_percent_or_fixed(kdl_node, "y", true)?;
let pinned = kdl_get_bool_property_or_child_value_with_error!(kdl_node, "pinned");
let run = self.parse_command_plugin_or_edit_block(kdl_node)?;
let focus = kdl_get_bool_property_or_child_value_with_error!(kdl_node, "focus");
let name = kdl_get_string_property_or_child_value_with_error!(kdl_node, "name")
.map(|name| name.to_string());
let contents_file =
kdl_get_string_property_or_child_value_with_error!(kdl_node, "contents_file");
self.assert_no_mixed_children_and_properties(kdl_node)?;
let pane_initial_contents = contents_file.and_then(|contents_file| {
self.file_name
.as_ref()
.and_then(|f| f.parent())
.and_then(|parent_folder| {
std::fs::read_to_string(parent_folder.join(contents_file)).ok()
})
});
Ok(FloatingPaneLayout {
name,
height,
width,
x,
y,
run,
focus,
pinned,
pane_initial_contents,
..Default::default()
})
}
fn insert_children_to_pane_template(
&self,
kdl_node: &KdlNode,
pane_template: &mut TiledPaneLayout,
pane_template_kdl_node: &KdlNode,
) -> Result<(), ConfigError> {
let children_are_stacked =
kdl_get_bool_property_or_child_value_with_error!(kdl_node, "stacked")
.unwrap_or(pane_template.children_are_stacked);
let is_expanded_in_stack =
kdl_get_bool_property_or_child_value_with_error!(kdl_node, "expanded")
.unwrap_or(pane_template.children_are_stacked);
let children_split_direction = self.parse_split_direction(kdl_node)?;
let (external_children_index, pane_parts) = match kdl_children_nodes!(kdl_node) {
Some(children) => {
self.parse_child_pane_nodes_for_pane(&children, children_are_stacked)?
},
None => (None, vec![]),
};
if pane_parts.len() > 0 {
let child_panes_layout = TiledPaneLayout {
children_split_direction,
children: pane_parts,
external_children_index,
children_are_stacked,
is_expanded_in_stack,
..Default::default()
};
self.assert_one_children_block(&pane_template, pane_template_kdl_node)?;
self.insert_layout_children_or_error(
pane_template,
child_panes_layout,
pane_template_kdl_node,
)?;
}
Ok(())
}
fn populate_external_children_index(
&self,
kdl_node: &KdlNode,
) -> Result<Option<usize>, ConfigError> {
// Option<external_children_index>
if let Some(pane_child_nodes) = kdl_children_nodes!(kdl_node) {
for (i, child) in pane_child_nodes.iter().enumerate() {
if kdl_name!(child) == "children" {
if let Some(grand_children) = kdl_children_nodes!(child) {
let grand_children: Vec<&str> =
grand_children.iter().map(|g| kdl_name!(g)).collect();
if !grand_children.is_empty() {
return Err(ConfigError::new_layout_kdl_error(
format!(
"Invalid `children` properties: {}",
grand_children.join(", ")
),
child.span().offset(),
child.span().len(),
));
}
}
return Ok(Some(i));
}
}
}
return Ok(None);
}
fn parse_pane_node_with_template(
&self,
kdl_node: &KdlNode,
pane_template: PaneOrFloatingPane,
should_mark_external_children_index: bool,
pane_template_kdl_node: &KdlNode,
) -> Result<TiledPaneLayout, ConfigError> {
match pane_template {
PaneOrFloatingPane::Pane(mut pane_template)
| PaneOrFloatingPane::Either(mut pane_template) => {
let borderless =
kdl_get_bool_property_or_child_value_with_error!(kdl_node, "borderless");
let focus = kdl_get_bool_property_or_child_value_with_error!(kdl_node, "focus");
let name = kdl_get_string_property_or_child_value_with_error!(kdl_node, "name")
.map(|name| name.to_string());
let children_are_stacked =
kdl_get_bool_property_or_child_value_with_error!(kdl_node, "stacked");
let is_expanded_in_stack =
kdl_get_bool_property_or_child_value_with_error!(kdl_node, "expanded");
let args = self.parse_args(kdl_node)?;
let close_on_exit =
kdl_get_bool_property_or_child_value_with_error!(kdl_node, "close_on_exit");
let start_suspended =
kdl_get_bool_property_or_child_value_with_error!(kdl_node, "start_suspended");
let split_size = self.parse_split_size(kdl_node)?;
let run = self.parse_command_plugin_or_edit_block_for_template(kdl_node)?;
let exclude_from_sync =
kdl_get_bool_property_or_child_value_with_error!(kdl_node, "exclude_from_sync");
let external_children_index = if should_mark_external_children_index {
self.populate_external_children_index(kdl_node)?
} else {
None
};
self.assert_no_bare_attributes_in_pane_node_with_template(
&run,
&pane_template.run,
&args,
&close_on_exit,
&start_suspended,
kdl_node,
)?;
self.insert_children_to_pane_template(
kdl_node,
&mut pane_template,
pane_template_kdl_node,
)?;
pane_template.run = Run::merge(&pane_template.run, &run);
if let Some(pane_template_run_command) = pane_template.run.as_mut() {
// we need to do this because panes consuming a pane_template
// can have bare args without a command
pane_template_run_command.add_args(args);
pane_template_run_command.add_close_on_exit(close_on_exit);
pane_template_run_command.add_start_suspended(start_suspended);
};
if let Some(borderless) = borderless {
pane_template.borderless = borderless;
}
if let Some(focus) = focus {
pane_template.focus = Some(focus);
}
if let Some(name) = name {
pane_template.name = Some(name);
}
if let Some(exclude_from_sync) = exclude_from_sync {
pane_template.exclude_from_sync = Some(exclude_from_sync);
}
if let Some(split_size) = split_size {
pane_template.split_size = Some(split_size);
}
if let Some(index_of_children) = pane_template.external_children_index {
pane_template.children.insert(
index_of_children,
TiledPaneLayout {
children_are_stacked: children_are_stacked.unwrap_or_default(),
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/kdl/mod.rs | zellij-utils/src/kdl/mod.rs | mod kdl_layout_parser;
use crate::data::{
BareKey, Direction, FloatingPaneCoordinates, InputMode, KeyWithModifier, LayoutInfo,
MultiplayerColors, Palette, PaletteColor, PaneId, PaneInfo, PaneManifest, PermissionType,
Resize, SessionInfo, StyleDeclaration, Styling, TabInfo, WebSharing, DEFAULT_STYLES,
};
use crate::envs::EnvironmentVariables;
use crate::home::{find_default_config_dir, get_layout_dir};
use crate::input::config::{Config, ConfigError, KdlError};
use crate::input::keybinds::Keybinds;
use crate::input::layout::{
Layout, PluginUserConfiguration, RunPlugin, RunPluginOrAlias, SplitSize,
};
use crate::input::options::{Clipboard, OnForceClose, Options};
use crate::input::permission::{GrantedPermission, PermissionCache};
use crate::input::plugins::PluginAliases;
use crate::input::theme::{FrameConfig, Theme, Themes, UiConfig};
use crate::input::web_client::WebClientConfig;
use kdl_layout_parser::KdlLayoutParser;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::net::{IpAddr, Ipv4Addr};
use strum::IntoEnumIterator;
use uuid::Uuid;
use miette::NamedSource;
use kdl::{KdlDocument, KdlEntry, KdlNode, KdlValue};
use std::path::PathBuf;
use std::str::FromStr;
use crate::input::actions::{Action, SearchDirection, SearchOption};
use crate::input::command::RunCommandAction;
#[macro_export]
macro_rules! parse_kdl_action_arguments {
( $action_name:expr, $action_arguments:expr, $action_node:expr ) => {{
if !$action_arguments.is_empty() {
Err(ConfigError::new_kdl_error(
format!("Action '{}' must have arguments", $action_name),
$action_node.span().offset(),
$action_node.span().len(),
))
} else {
match $action_name {
"Quit" => Ok(Action::Quit),
"FocusNextPane" => Ok(Action::FocusNextPane),
"FocusPreviousPane" => Ok(Action::FocusPreviousPane),
"SwitchFocus" => Ok(Action::SwitchFocus),
"EditScrollback" => Ok(Action::EditScrollback),
"ScrollUp" => Ok(Action::ScrollUp),
"ScrollDown" => Ok(Action::ScrollDown),
"ScrollToBottom" => Ok(Action::ScrollToBottom),
"ScrollToTop" => Ok(Action::ScrollToTop),
"PageScrollUp" => Ok(Action::PageScrollUp),
"PageScrollDown" => Ok(Action::PageScrollDown),
"HalfPageScrollUp" => Ok(Action::HalfPageScrollUp),
"HalfPageScrollDown" => Ok(Action::HalfPageScrollDown),
"ToggleFocusFullscreen" => Ok(Action::ToggleFocusFullscreen),
"TogglePaneFrames" => Ok(Action::TogglePaneFrames),
"ToggleActiveSyncTab" => Ok(Action::ToggleActiveSyncTab),
"TogglePaneEmbedOrFloating" => Ok(Action::TogglePaneEmbedOrFloating),
"ToggleFloatingPanes" => Ok(Action::ToggleFloatingPanes),
"CloseFocus" => Ok(Action::CloseFocus),
"UndoRenamePane" => Ok(Action::UndoRenamePane),
"NoOp" => Ok(Action::NoOp),
"GoToNextTab" => Ok(Action::GoToNextTab),
"GoToPreviousTab" => Ok(Action::GoToPreviousTab),
"CloseTab" => Ok(Action::CloseTab),
"ToggleTab" => Ok(Action::ToggleTab),
"UndoRenameTab" => Ok(Action::UndoRenameTab),
"Detach" => Ok(Action::Detach),
"Copy" => Ok(Action::Copy),
"Confirm" => Ok(Action::Confirm),
"Deny" => Ok(Action::Deny),
"ToggleMouseMode" => Ok(Action::ToggleMouseMode),
"PreviousSwapLayout" => Ok(Action::PreviousSwapLayout),
"NextSwapLayout" => Ok(Action::NextSwapLayout),
"Clear" => Ok(Action::ClearScreen),
_ => Err(ConfigError::new_kdl_error(
format!("Unsupported action: {:?}", $action_name),
$action_node.span().offset(),
$action_node.span().len(),
)),
}
}
}};
}
#[macro_export]
macro_rules! parse_kdl_action_u8_arguments {
( $action_name:expr, $action_arguments:expr, $action_node:expr ) => {{
let mut bytes = vec![];
for kdl_entry in $action_arguments.iter() {
match kdl_entry.value().as_i64() {
Some(int_value) => bytes.push(int_value as u8),
None => {
return Err(ConfigError::new_kdl_error(
format!("Arguments for '{}' must be integers", $action_name),
kdl_entry.span().offset(),
kdl_entry.span().len(),
));
},
}
}
Action::new_from_bytes($action_name, bytes, $action_node)
}};
}
#[macro_export]
macro_rules! kdl_parsing_error {
( $message:expr, $entry:expr ) => {
ConfigError::new_kdl_error($message, $entry.span().offset(), $entry.span().len())
};
}
#[macro_export]
macro_rules! kdl_entries_as_i64 {
( $node:expr ) => {
$node
.entries()
.iter()
.map(|kdl_node| kdl_node.value().as_i64())
};
}
#[macro_export]
macro_rules! kdl_first_entry_as_string {
( $node:expr ) => {
$node
.entries()
.iter()
.next()
.and_then(|s| s.value().as_string())
};
}
#[macro_export]
macro_rules! kdl_first_entry_as_i64 {
( $node:expr ) => {
$node
.entries()
.iter()
.next()
.and_then(|i| i.value().as_i64())
};
}
#[macro_export]
macro_rules! kdl_first_entry_as_bool {
( $node:expr ) => {
$node
.entries()
.iter()
.next()
.and_then(|i| i.value().as_bool())
};
}
#[macro_export]
macro_rules! entry_count {
( $node:expr ) => {{
$node.entries().iter().len()
}};
}
#[macro_export]
macro_rules! parse_kdl_action_char_or_string_arguments {
( $action_name:expr, $action_arguments:expr, $action_node:expr ) => {{
let mut chars_to_write = String::new();
for kdl_entry in $action_arguments.iter() {
match kdl_entry.value().as_string() {
Some(string_value) => chars_to_write.push_str(string_value),
None => {
return Err(ConfigError::new_kdl_error(
format!("All entries for action '{}' must be strings", $action_name),
kdl_entry.span().offset(),
kdl_entry.span().len(),
))
},
}
}
Action::new_from_string($action_name, chars_to_write, $action_node)
}};
}
#[macro_export]
macro_rules! kdl_arg_is_truthy {
( $kdl_node:expr, $arg_name:expr ) => {
match $kdl_node.get($arg_name) {
Some(arg) => match arg.value().as_bool() {
Some(value) => value,
None => {
return Err(ConfigError::new_kdl_error(
format!("Argument must be true or false, found: {}", arg.value()),
arg.span().offset(),
arg.span().len(),
))
},
},
None => false,
}
};
}
#[macro_export]
macro_rules! kdl_children_nodes_or_error {
( $kdl_node:expr, $error:expr ) => {
$kdl_node
.children()
.ok_or(ConfigError::new_kdl_error(
$error.into(),
$kdl_node.span().offset(),
$kdl_node.span().len(),
))?
.nodes()
};
}
#[macro_export]
macro_rules! kdl_children_nodes {
( $kdl_node:expr ) => {
$kdl_node.children().map(|c| c.nodes())
};
}
#[macro_export]
macro_rules! kdl_property_nodes {
( $kdl_node:expr ) => {{
$kdl_node
.entries()
.iter()
.filter_map(|e| e.name())
.map(|e| e.value())
}};
}
#[macro_export]
macro_rules! kdl_children_or_error {
( $kdl_node:expr, $error:expr ) => {
$kdl_node.children().ok_or(ConfigError::new_kdl_error(
$error.into(),
$kdl_node.span().offset(),
$kdl_node.span().len(),
))?
};
}
#[macro_export]
macro_rules! kdl_children {
( $kdl_node:expr ) => {
$kdl_node.children().iter().copied().collect()
};
}
#[macro_export]
macro_rules! kdl_get_string_property_or_child_value {
( $kdl_node:expr, $name:expr ) => {
$kdl_node
.get($name)
.and_then(|e| e.value().as_string())
.or_else(|| {
$kdl_node
.children()
.and_then(|c| c.get($name))
.and_then(|c| c.get(0))
.and_then(|c| c.value().as_string())
})
};
}
#[macro_export]
macro_rules! kdl_string_arguments {
( $kdl_node:expr ) => {{
let res: Result<Vec<_>, _> = $kdl_node
.entries()
.iter()
.map(|e| {
e.value().as_string().ok_or(ConfigError::new_kdl_error(
"Not a string".into(),
e.span().offset(),
e.span().len(),
))
})
.collect();
res?
}};
}
#[macro_export]
macro_rules! kdl_property_names {
( $kdl_node:expr ) => {{
$kdl_node
.entries()
.iter()
.filter_map(|e| e.name())
.map(|e| e.value())
}};
}
#[macro_export]
macro_rules! kdl_argument_values {
( $kdl_node:expr ) => {
$kdl_node.entries().iter().collect()
};
}
#[macro_export]
macro_rules! kdl_name {
( $kdl_node:expr ) => {
$kdl_node.name().value()
};
}
#[macro_export]
macro_rules! kdl_document_name {
( $kdl_node:expr ) => {
$kdl_node.node().name().value()
};
}
#[macro_export]
macro_rules! keys_from_kdl {
( $kdl_node:expr ) => {
kdl_string_arguments!($kdl_node)
.iter()
.map(|k| {
KeyWithModifier::from_str(k).map_err(|_| {
ConfigError::new_kdl_error(
format!("Invalid key: '{}'", k),
$kdl_node.span().offset(),
$kdl_node.span().len(),
)
})
})
.collect::<Result<_, _>>()?
};
}
#[macro_export]
macro_rules! actions_from_kdl {
( $kdl_node:expr, $config_options:expr ) => {
kdl_children_nodes_or_error!($kdl_node, "no actions found for key_block")
.iter()
.map(|kdl_action| Action::try_from((kdl_action, $config_options)))
.collect::<Result<_, _>>()?
};
}
pub fn kdl_arguments_that_are_strings<'a>(
arguments: impl Iterator<Item = &'a KdlEntry>,
) -> Result<Vec<String>, ConfigError> {
let mut args: Vec<String> = vec![];
for kdl_entry in arguments {
match kdl_entry.value().as_string() {
Some(string_value) => args.push(string_value.to_string()),
None => {
return Err(ConfigError::new_kdl_error(
format!("Argument must be a string"),
kdl_entry.span().offset(),
kdl_entry.span().len(),
));
},
}
}
Ok(args)
}
pub fn kdl_arguments_that_are_digits<'a>(
arguments: impl Iterator<Item = &'a KdlEntry>,
) -> Result<Vec<i64>, ConfigError> {
let mut args: Vec<i64> = vec![];
for kdl_entry in arguments {
match kdl_entry.value().as_i64() {
Some(digit_value) => {
args.push(digit_value);
},
None => {
return Err(ConfigError::new_kdl_error(
format!("Argument must be a digit"),
kdl_entry.span().offset(),
kdl_entry.span().len(),
));
},
}
}
Ok(args)
}
pub fn kdl_child_string_value_for_entry<'a>(
command_metadata: &'a KdlDocument,
entry_name: &'a str,
) -> Option<&'a str> {
command_metadata
.get(entry_name)
.and_then(|cwd| cwd.entries().iter().next())
.and_then(|cwd_value| cwd_value.value().as_string())
}
pub fn kdl_child_bool_value_for_entry<'a>(
command_metadata: &'a KdlDocument,
entry_name: &'a str,
) -> Option<bool> {
command_metadata
.get(entry_name)
.and_then(|cwd| cwd.entries().iter().next())
.and_then(|cwd_value| cwd_value.value().as_bool())
}
impl Action {
pub fn new_from_bytes(
action_name: &str,
bytes: Vec<u8>,
action_node: &KdlNode,
) -> Result<Self, ConfigError> {
match action_name {
"Write" => Ok(Action::Write {
key_with_modifier: None,
bytes,
is_kitty_keyboard_protocol: false,
}),
"PaneNameInput" => Ok(Action::PaneNameInput { input: bytes }),
"TabNameInput" => Ok(Action::TabNameInput { input: bytes }),
"SearchInput" => Ok(Action::SearchInput { input: bytes }),
"GoToTab" => {
let tab_index = *bytes.get(0).ok_or_else(|| {
ConfigError::new_kdl_error(
format!("Missing tab index"),
action_node.span().offset(),
action_node.span().len(),
)
})? as u32;
Ok(Action::GoToTab { index: tab_index })
},
_ => Err(ConfigError::new_kdl_error(
"Failed to parse action".into(),
action_node.span().offset(),
action_node.span().len(),
)),
}
}
pub fn new_from_string(
action_name: &str,
string: String,
action_node: &KdlNode,
) -> Result<Self, ConfigError> {
match action_name {
"WriteChars" => Ok(Action::WriteChars { chars: string }),
"SwitchToMode" => match InputMode::from_str(string.as_str()) {
Ok(input_mode) => Ok(Action::SwitchToMode { input_mode }),
Err(_e) => {
return Err(ConfigError::new_kdl_error(
format!("Unknown InputMode '{}'", string),
action_node.span().offset(),
action_node.span().len(),
))
},
},
"Resize" => {
let mut resize: Option<Resize> = None;
let mut direction: Option<Direction> = None;
for word in string.to_ascii_lowercase().split_whitespace() {
match Resize::from_str(word) {
Ok(value) => resize = Some(value),
Err(_) => match Direction::from_str(word) {
Ok(value) => direction = Some(value),
Err(_) => {
return Err(ConfigError::new_kdl_error(
format!(
"failed to read either of resize type or direction from '{}'",
word
),
action_node.span().offset(),
action_node.span().len(),
))
},
},
}
}
let resize = resize.unwrap_or(Resize::Increase);
Ok(Action::Resize { resize, direction })
},
"MoveFocus" => {
let direction = Direction::from_str(string.as_str()).map_err(|_| {
ConfigError::new_kdl_error(
format!("Invalid direction: '{}'", string),
action_node.span().offset(),
action_node.span().len(),
)
})?;
Ok(Action::MoveFocus { direction })
},
"MoveFocusOrTab" => {
let direction = Direction::from_str(string.as_str()).map_err(|_| {
ConfigError::new_kdl_error(
format!("Invalid direction: '{}'", string),
action_node.span().offset(),
action_node.span().len(),
)
})?;
Ok(Action::MoveFocusOrTab { direction })
},
"MoveTab" => {
let direction = Direction::from_str(string.as_str()).map_err(|_| {
ConfigError::new_kdl_error(
format!("Invalid direction: '{}'", string),
action_node.span().offset(),
action_node.span().len(),
)
})?;
if direction.is_vertical() {
Err(ConfigError::new_kdl_error(
format!("Invalid horizontal direction: '{}'", string),
action_node.span().offset(),
action_node.span().len(),
))
} else {
Ok(Action::MoveTab { direction })
}
},
"MovePane" => {
if string.is_empty() {
return Ok(Action::MovePane { direction: None });
} else {
let direction = Direction::from_str(string.as_str()).map_err(|_| {
ConfigError::new_kdl_error(
format!("Invalid direction: '{}'", string),
action_node.span().offset(),
action_node.span().len(),
)
})?;
Ok(Action::MovePane {
direction: Some(direction),
})
}
},
"MovePaneBackwards" => Ok(Action::MovePaneBackwards),
"DumpScreen" => Ok(Action::DumpScreen {
file_path: string,
include_scrollback: false,
}),
"DumpLayout" => Ok(Action::DumpLayout),
"NewPane" => {
if string.is_empty() {
return Ok(Action::NewPane {
direction: None,
pane_name: None,
start_suppressed: false,
});
} else if string == "stacked" {
return Ok(Action::NewStackedPane {
command: None,
pane_name: None,
near_current_pane: false,
});
} else {
let direction = Direction::from_str(string.as_str()).map_err(|_| {
ConfigError::new_kdl_error(
format!("Invalid direction: '{}'", string),
action_node.span().offset(),
action_node.span().len(),
)
})?;
Ok(Action::NewPane {
direction: Some(direction),
pane_name: None,
start_suppressed: false,
})
}
},
"SearchToggleOption" => {
let toggle_option = SearchOption::from_str(string.as_str()).map_err(|_| {
ConfigError::new_kdl_error(
format!("Invalid direction: '{}'", string),
action_node.span().offset(),
action_node.span().len(),
)
})?;
Ok(Action::SearchToggleOption {
option: toggle_option,
})
},
"Search" => {
let search_direction =
SearchDirection::from_str(string.as_str()).map_err(|_| {
ConfigError::new_kdl_error(
format!("Invalid direction: '{}'", string),
action_node.span().offset(),
action_node.span().len(),
)
})?;
Ok(Action::Search {
direction: search_direction,
})
},
"RenameSession" => Ok(Action::RenameSession { name: string }),
_ => Err(ConfigError::new_kdl_error(
format!("Unsupported action: {}", action_name),
action_node.span().offset(),
action_node.span().len(),
)),
}
}
pub fn to_kdl(&self) -> Option<KdlNode> {
match self {
Action::Quit => Some(KdlNode::new("Quit")),
Action::Write {
key_with_modifier: _key,
bytes,
is_kitty_keyboard_protocol: _is_kitty,
} => {
let mut node = KdlNode::new("Write");
for byte in bytes {
node.push(KdlValue::Base10(*byte as i64));
}
Some(node)
},
Action::WriteChars { chars: string } => {
let mut node = KdlNode::new("WriteChars");
node.push(string.clone());
Some(node)
},
Action::SwitchToMode { input_mode } => {
let mut node = KdlNode::new("SwitchToMode");
node.push(format!("{:?}", input_mode).to_lowercase());
Some(node)
},
Action::Resize {
resize,
direction: resize_direction,
} => {
let mut node = KdlNode::new("Resize");
let resize = match resize {
Resize::Increase => "Increase",
Resize::Decrease => "Decrease",
};
if let Some(resize_direction) = resize_direction {
let resize_direction = match resize_direction {
Direction::Left => "left",
Direction::Right => "right",
Direction::Up => "up",
Direction::Down => "down",
};
node.push(format!("{} {}", resize, resize_direction));
} else {
node.push(format!("{}", resize));
}
Some(node)
},
Action::FocusNextPane => Some(KdlNode::new("FocusNextPane")),
Action::FocusPreviousPane => Some(KdlNode::new("FocusPreviousPane")),
Action::SwitchFocus => Some(KdlNode::new("SwitchFocus")),
Action::MoveFocus { direction } => {
let mut node = KdlNode::new("MoveFocus");
let direction = match direction {
Direction::Left => "left",
Direction::Right => "right",
Direction::Up => "up",
Direction::Down => "down",
};
node.push(direction);
Some(node)
},
Action::MoveFocusOrTab { direction } => {
let mut node = KdlNode::new("MoveFocusOrTab");
let direction = match direction {
Direction::Left => "left",
Direction::Right => "right",
Direction::Up => "up",
Direction::Down => "down",
};
node.push(direction);
Some(node)
},
Action::MovePane { direction } => {
let mut node = KdlNode::new("MovePane");
if let Some(direction) = direction {
let direction = match direction {
Direction::Left => "left",
Direction::Right => "right",
Direction::Up => "up",
Direction::Down => "down",
};
node.push(direction);
}
Some(node)
},
Action::MovePaneBackwards => Some(KdlNode::new("MovePaneBackwards")),
Action::DumpScreen {
file_path: file,
include_scrollback: _,
} => {
let mut node = KdlNode::new("DumpScreen");
node.push(file.clone());
Some(node)
},
Action::DumpLayout => Some(KdlNode::new("DumpLayout")),
Action::EditScrollback => Some(KdlNode::new("EditScrollback")),
Action::ScrollUp => Some(KdlNode::new("ScrollUp")),
Action::ScrollDown => Some(KdlNode::new("ScrollDown")),
Action::ScrollToBottom => Some(KdlNode::new("ScrollToBottom")),
Action::ScrollToTop => Some(KdlNode::new("ScrollToTop")),
Action::PageScrollUp => Some(KdlNode::new("PageScrollUp")),
Action::PageScrollDown => Some(KdlNode::new("PageScrollDown")),
Action::HalfPageScrollUp => Some(KdlNode::new("HalfPageScrollUp")),
Action::HalfPageScrollDown => Some(KdlNode::new("HalfPageScrollDown")),
Action::ToggleFocusFullscreen => Some(KdlNode::new("ToggleFocusFullscreen")),
Action::TogglePaneFrames => Some(KdlNode::new("TogglePaneFrames")),
Action::ToggleActiveSyncTab => Some(KdlNode::new("ToggleActiveSyncTab")),
Action::NewPane {
direction,
pane_name: _,
start_suppressed: _,
} => {
let mut node = KdlNode::new("NewPane");
if let Some(direction) = direction {
let direction = match direction {
Direction::Left => "left",
Direction::Right => "right",
Direction::Up => "up",
Direction::Down => "down",
};
node.push(direction);
}
Some(node)
},
Action::TogglePaneEmbedOrFloating => Some(KdlNode::new("TogglePaneEmbedOrFloating")),
Action::ToggleFloatingPanes => Some(KdlNode::new("ToggleFloatingPanes")),
Action::CloseFocus => Some(KdlNode::new("CloseFocus")),
Action::PaneNameInput { input: bytes } => {
let mut node = KdlNode::new("PaneNameInput");
for byte in bytes {
node.push(KdlValue::Base10(*byte as i64));
}
Some(node)
},
Action::UndoRenamePane => Some(KdlNode::new("UndoRenamePane")),
Action::NewTab {
tiled_layout: _,
floating_layouts: _,
swap_tiled_layouts: _,
swap_floating_layouts: _,
tab_name: name,
should_change_focus_to_new_tab,
cwd,
initial_panes: _,
first_pane_unblock_condition: _,
} => {
let mut node = KdlNode::new("NewTab");
let mut children = KdlDocument::new();
if let Some(name) = name {
let mut name_node = KdlNode::new("name");
if !should_change_focus_to_new_tab {
let mut should_change_focus_to_new_tab_node =
KdlNode::new("should_change_focus_to_new_tab");
should_change_focus_to_new_tab_node.push(KdlValue::Bool(false));
children
.nodes_mut()
.push(should_change_focus_to_new_tab_node);
}
name_node.push(name.clone());
children.nodes_mut().push(name_node);
}
if let Some(cwd) = cwd {
let mut cwd_node = KdlNode::new("cwd");
cwd_node.push(cwd.display().to_string());
children.nodes_mut().push(cwd_node);
}
if name.is_some() || cwd.is_some() {
node.set_children(children);
}
Some(node)
},
Action::GoToNextTab => Some(KdlNode::new("GoToNextTab")),
Action::GoToPreviousTab => Some(KdlNode::new("GoToPreviousTab")),
Action::CloseTab => Some(KdlNode::new("CloseTab")),
Action::GoToTab { index } => {
let mut node = KdlNode::new("GoToTab");
node.push(KdlValue::Base10(*index as i64));
Some(node)
},
Action::ToggleTab => Some(KdlNode::new("ToggleTab")),
Action::TabNameInput { input: bytes } => {
let mut node = KdlNode::new("TabNameInput");
for byte in bytes {
node.push(KdlValue::Base10(*byte as i64));
}
Some(node)
},
Action::UndoRenameTab => Some(KdlNode::new("UndoRenameTab")),
Action::MoveTab { direction } => {
let mut node = KdlNode::new("MoveTab");
let direction = match direction {
Direction::Left => "left",
Direction::Right => "right",
Direction::Up => "up",
Direction::Down => "down",
};
node.push(direction);
Some(node)
},
Action::NewTiledPane {
direction,
command: run_command_action,
pane_name: name,
near_current_pane: false,
} => {
let mut node = KdlNode::new("Run");
let mut node_children = KdlDocument::new();
if let Some(run_command_action) = run_command_action {
node.push(run_command_action.command.display().to_string());
for arg in &run_command_action.args {
node.push(arg.clone());
}
if let Some(cwd) = &run_command_action.cwd {
let mut cwd_node = KdlNode::new("cwd");
cwd_node.push(cwd.display().to_string());
node_children.nodes_mut().push(cwd_node);
}
if run_command_action.hold_on_start {
let mut hos_node = KdlNode::new("hold_on_start");
hos_node.push(KdlValue::Bool(true));
node_children.nodes_mut().push(hos_node);
}
if !run_command_action.hold_on_close {
let mut hoc_node = KdlNode::new("hold_on_close");
hoc_node.push(KdlValue::Bool(false));
node_children.nodes_mut().push(hoc_node);
}
}
if let Some(name) = name {
let mut name_node = KdlNode::new("name");
name_node.push(name.clone());
node_children.nodes_mut().push(name_node);
}
if let Some(direction) = direction {
let mut direction_node = KdlNode::new("direction");
let direction = match direction {
Direction::Left => "left",
Direction::Right => "right",
Direction::Up => "up",
Direction::Down => "down",
};
direction_node.push(direction);
node_children.nodes_mut().push(direction_node);
}
if !node_children.nodes().is_empty() {
node.set_children(node_children);
}
Some(node)
},
Action::NewFloatingPane {
command: run_command_action,
pane_name: name,
coordinates: floating_pane_coordinates,
near_current_pane: false,
} => {
let mut node = KdlNode::new("Run");
let mut node_children = KdlDocument::new();
let mut floating_pane = KdlNode::new("floating");
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/assets/prost_web_server/web_server_contract.rs | zellij-utils/assets/prost_web_server/web_server_contract.rs | #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct InstructionForWebServer {
#[prost(oneof="instruction_for_web_server::Instruction", tags="1")]
pub instruction: ::core::option::Option<instruction_for_web_server::Instruction>,
}
/// Nested message and enum types in `InstructionForWebServer`.
pub mod instruction_for_web_server {
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Instruction {
/// Future commands can be added here
/// RestartWebServerMsg restart_web_server = 2;
/// ReloadConfigMsg reload_config = 3;
#[prost(message, tag="1")]
ShutdownWebServer(super::ShutdownWebServerMsg),
}
}
/// Empty for now, but allows for future parameters like graceful timeout
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ShutdownWebServerMsg {
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/assets/prost_web_server/generated_web_server_api.rs | zellij-utils/assets/prost_web_server/generated_web_server_api.rs | pub mod web_server_contract {
include!("web_server_contract.rs");
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/assets/prost/api.pipe_message.rs | zellij-utils/assets/prost/api.pipe_message.rs | #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PipeMessage {
#[prost(enumeration="PipeSource", tag="1")]
pub source: i32,
#[prost(string, optional, tag="2")]
pub cli_source_id: ::core::option::Option<::prost::alloc::string::String>,
#[prost(uint32, optional, tag="3")]
pub plugin_source_id: ::core::option::Option<u32>,
#[prost(string, tag="4")]
pub name: ::prost::alloc::string::String,
#[prost(string, optional, tag="5")]
pub payload: ::core::option::Option<::prost::alloc::string::String>,
#[prost(message, repeated, tag="6")]
pub args: ::prost::alloc::vec::Vec<Arg>,
#[prost(bool, tag="7")]
pub is_private: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Arg {
#[prost(string, tag="1")]
pub key: ::prost::alloc::string::String,
#[prost(string, tag="2")]
pub value: ::prost::alloc::string::String,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
#[repr(i32)]
pub enum PipeSource {
Cli = 0,
Plugin = 1,
Keybind = 2,
}
impl PipeSource {
/// String value of the enum field names used in the ProtoBuf definition.
///
/// The values are not transformed in any way and thus are considered stable
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
PipeSource::Cli => "Cli",
PipeSource::Plugin => "Plugin",
PipeSource::Keybind => "Keybind",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
pub fn from_str_name(value: &str) -> ::core::option::Option<Self> {
match value {
"Cli" => Some(Self::Cli),
"Plugin" => Some(Self::Plugin),
"Keybind" => Some(Self::Keybind),
_ => None,
}
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/assets/prost/generated_plugin_api.rs | zellij-utils/assets/prost/generated_plugin_api.rs | pub mod api {
pub mod action {
include!("api.action.rs");
}
pub mod command {
include!("api.command.rs");
}
pub mod event {
include!("api.event.rs");
}
pub mod file {
include!("api.file.rs");
}
pub mod input_mode {
include!("api.input_mode.rs");
}
pub mod key {
include!("api.key.rs");
}
pub mod message {
include!("api.message.rs");
}
pub mod pipe_message {
include!("api.pipe_message.rs");
}
pub mod plugin_command {
include!("api.plugin_command.rs");
}
pub mod plugin_ids {
include!("api.plugin_ids.rs");
}
pub mod plugin_permission {
include!("api.plugin_permission.rs");
}
pub mod resize {
include!("api.resize.rs");
}
pub mod style {
include!("api.style.rs");
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/assets/prost/api.plugin_ids.rs | zellij-utils/assets/prost/api.plugin_ids.rs | #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PluginIds {
#[prost(int32, tag="1")]
pub plugin_id: i32,
#[prost(int32, tag="2")]
pub zellij_pid: i32,
#[prost(string, tag="3")]
pub initial_cwd: ::prost::alloc::string::String,
#[prost(uint32, tag="4")]
pub client_id: u32,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ZellijVersion {
#[prost(string, tag="1")]
pub version: ::prost::alloc::string::String,
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/assets/prost/api.resize.rs | zellij-utils/assets/prost/api.resize.rs | #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Resize {
#[prost(enumeration="ResizeAction", tag="1")]
pub resize_action: i32,
#[prost(enumeration="ResizeDirection", optional, tag="2")]
pub direction: ::core::option::Option<i32>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct MoveDirection {
#[prost(enumeration="ResizeDirection", tag="1")]
pub direction: i32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
#[repr(i32)]
pub enum ResizeAction {
Increase = 0,
Decrease = 1,
}
impl ResizeAction {
/// String value of the enum field names used in the ProtoBuf definition.
///
/// The values are not transformed in any way and thus are considered stable
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
ResizeAction::Increase => "Increase",
ResizeAction::Decrease => "Decrease",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
pub fn from_str_name(value: &str) -> ::core::option::Option<Self> {
match value {
"Increase" => Some(Self::Increase),
"Decrease" => Some(Self::Decrease),
_ => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
#[repr(i32)]
pub enum ResizeDirection {
Left = 0,
Right = 1,
Up = 2,
Down = 3,
}
impl ResizeDirection {
/// String value of the enum field names used in the ProtoBuf definition.
///
/// The values are not transformed in any way and thus are considered stable
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
ResizeDirection::Left => "Left",
ResizeDirection::Right => "Right",
ResizeDirection::Up => "Up",
ResizeDirection::Down => "Down",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
pub fn from_str_name(value: &str) -> ::core::option::Option<Self> {
match value {
"Left" => Some(Self::Left),
"Right" => Some(Self::Right),
"Up" => Some(Self::Up),
"Down" => Some(Self::Down),
_ => None,
}
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/assets/prost/api.style.rs | zellij-utils/assets/prost/api.style.rs | #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Style {
#[deprecated]
#[prost(message, optional, tag="1")]
pub palette: ::core::option::Option<Palette>,
#[prost(bool, tag="2")]
pub rounded_corners: bool,
#[prost(bool, tag="3")]
pub hide_session_name: bool,
#[prost(message, optional, tag="4")]
pub styling: ::core::option::Option<Styling>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Palette {
#[prost(enumeration="ThemeHue", tag="1")]
pub theme_hue: i32,
#[prost(message, optional, tag="2")]
pub fg: ::core::option::Option<Color>,
#[prost(message, optional, tag="3")]
pub bg: ::core::option::Option<Color>,
#[prost(message, optional, tag="4")]
pub black: ::core::option::Option<Color>,
#[prost(message, optional, tag="5")]
pub red: ::core::option::Option<Color>,
#[prost(message, optional, tag="6")]
pub green: ::core::option::Option<Color>,
#[prost(message, optional, tag="7")]
pub yellow: ::core::option::Option<Color>,
#[prost(message, optional, tag="8")]
pub blue: ::core::option::Option<Color>,
#[prost(message, optional, tag="9")]
pub magenta: ::core::option::Option<Color>,
#[prost(message, optional, tag="10")]
pub cyan: ::core::option::Option<Color>,
#[prost(message, optional, tag="11")]
pub white: ::core::option::Option<Color>,
#[prost(message, optional, tag="12")]
pub orange: ::core::option::Option<Color>,
#[prost(message, optional, tag="13")]
pub gray: ::core::option::Option<Color>,
#[prost(message, optional, tag="14")]
pub purple: ::core::option::Option<Color>,
#[prost(message, optional, tag="15")]
pub gold: ::core::option::Option<Color>,
#[prost(message, optional, tag="16")]
pub silver: ::core::option::Option<Color>,
#[prost(message, optional, tag="17")]
pub pink: ::core::option::Option<Color>,
#[prost(message, optional, tag="18")]
pub brown: ::core::option::Option<Color>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Color {
#[prost(enumeration="ColorType", tag="1")]
pub color_type: i32,
#[prost(oneof="color::Payload", tags="2, 3")]
pub payload: ::core::option::Option<color::Payload>,
}
/// Nested message and enum types in `Color`.
pub mod color {
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Payload {
#[prost(message, tag="2")]
RgbColorPayload(super::RgbColorPayload),
#[prost(uint32, tag="3")]
EightBitColorPayload(u32),
}
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct RgbColorPayload {
#[prost(uint32, tag="1")]
pub red: u32,
#[prost(uint32, tag="2")]
pub green: u32,
#[prost(uint32, tag="3")]
pub blue: u32,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Styling {
#[prost(message, repeated, tag="1")]
pub text_unselected: ::prost::alloc::vec::Vec<Color>,
#[prost(message, repeated, tag="2")]
pub text_selected: ::prost::alloc::vec::Vec<Color>,
#[prost(message, repeated, tag="3")]
pub ribbon_unselected: ::prost::alloc::vec::Vec<Color>,
#[prost(message, repeated, tag="4")]
pub ribbon_selected: ::prost::alloc::vec::Vec<Color>,
#[prost(message, repeated, tag="5")]
pub table_title: ::prost::alloc::vec::Vec<Color>,
#[prost(message, repeated, tag="6")]
pub table_cell_unselected: ::prost::alloc::vec::Vec<Color>,
#[prost(message, repeated, tag="7")]
pub table_cell_selected: ::prost::alloc::vec::Vec<Color>,
#[prost(message, repeated, tag="8")]
pub list_unselected: ::prost::alloc::vec::Vec<Color>,
#[prost(message, repeated, tag="9")]
pub list_selected: ::prost::alloc::vec::Vec<Color>,
#[prost(message, repeated, tag="10")]
pub frame_unselected: ::prost::alloc::vec::Vec<Color>,
#[prost(message, repeated, tag="11")]
pub frame_selected: ::prost::alloc::vec::Vec<Color>,
#[prost(message, repeated, tag="12")]
pub frame_highlight: ::prost::alloc::vec::Vec<Color>,
#[prost(message, repeated, tag="13")]
pub exit_code_success: ::prost::alloc::vec::Vec<Color>,
#[prost(message, repeated, tag="14")]
pub exit_code_error: ::prost::alloc::vec::Vec<Color>,
#[prost(message, repeated, tag="15")]
pub multiplayer_user_colors: ::prost::alloc::vec::Vec<Color>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
#[repr(i32)]
pub enum ColorType {
Rgb = 0,
EightBit = 1,
}
impl ColorType {
/// String value of the enum field names used in the ProtoBuf definition.
///
/// The values are not transformed in any way and thus are considered stable
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
ColorType::Rgb => "Rgb",
ColorType::EightBit => "EightBit",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
pub fn from_str_name(value: &str) -> ::core::option::Option<Self> {
match value {
"Rgb" => Some(Self::Rgb),
"EightBit" => Some(Self::EightBit),
_ => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
#[repr(i32)]
pub enum ThemeHue {
Dark = 0,
Light = 1,
}
impl ThemeHue {
/// String value of the enum field names used in the ProtoBuf definition.
///
/// The values are not transformed in any way and thus are considered stable
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
ThemeHue::Dark => "Dark",
ThemeHue::Light => "Light",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
pub fn from_str_name(value: &str) -> ::core::option::Option<Self> {
match value {
"Dark" => Some(Self::Dark),
"Light" => Some(Self::Light),
_ => None,
}
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/assets/prost/api.message.rs | zellij-utils/assets/prost/api.message.rs | #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Message {
#[prost(string, tag="1")]
pub name: ::prost::alloc::string::String,
#[prost(string, tag="2")]
pub payload: ::prost::alloc::string::String,
#[prost(string, optional, tag="3")]
pub worker_name: ::core::option::Option<::prost::alloc::string::String>,
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/assets/prost/api.command.rs | zellij-utils/assets/prost/api.command.rs | #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Command {
#[prost(string, tag="1")]
pub path: ::prost::alloc::string::String,
#[prost(string, repeated, tag="2")]
pub args: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
#[prost(string, optional, tag="3")]
pub cwd: ::core::option::Option<::prost::alloc::string::String>,
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/assets/prost/api.key.rs | zellij-utils/assets/prost/api.key.rs | #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Key {
#[prost(enumeration="key::KeyModifier", optional, tag="1")]
pub modifier: ::core::option::Option<i32>,
#[prost(enumeration="key::KeyModifier", repeated, tag="4")]
pub additional_modifiers: ::prost::alloc::vec::Vec<i32>,
#[prost(oneof="key::MainKey", tags="2, 3")]
pub main_key: ::core::option::Option<key::MainKey>,
}
/// Nested message and enum types in `Key`.
pub mod key {
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
#[repr(i32)]
pub enum KeyModifier {
Ctrl = 0,
Alt = 1,
Shift = 2,
Super = 3,
}
impl KeyModifier {
/// String value of the enum field names used in the ProtoBuf definition.
///
/// The values are not transformed in any way and thus are considered stable
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
KeyModifier::Ctrl => "CTRL",
KeyModifier::Alt => "ALT",
KeyModifier::Shift => "SHIFT",
KeyModifier::Super => "SUPER",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
pub fn from_str_name(value: &str) -> ::core::option::Option<Self> {
match value {
"CTRL" => Some(Self::Ctrl),
"ALT" => Some(Self::Alt),
"SHIFT" => Some(Self::Shift),
"SUPER" => Some(Self::Super),
_ => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
#[repr(i32)]
pub enum NamedKey {
PageDown = 0,
PageUp = 1,
LeftArrow = 2,
DownArrow = 3,
UpArrow = 4,
RightArrow = 5,
Home = 6,
End = 7,
Backspace = 8,
Delete = 9,
Insert = 10,
F1 = 11,
F2 = 12,
F3 = 13,
F4 = 14,
F5 = 15,
F6 = 16,
F7 = 17,
F8 = 18,
F9 = 19,
F10 = 20,
F11 = 21,
F12 = 22,
Tab = 23,
Esc = 24,
CapsLock = 25,
ScrollLock = 26,
NumLock = 27,
PrintScreen = 28,
Pause = 29,
Menu = 30,
Enter = 31,
}
impl NamedKey {
/// String value of the enum field names used in the ProtoBuf definition.
///
/// The values are not transformed in any way and thus are considered stable
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
NamedKey::PageDown => "PageDown",
NamedKey::PageUp => "PageUp",
NamedKey::LeftArrow => "LeftArrow",
NamedKey::DownArrow => "DownArrow",
NamedKey::UpArrow => "UpArrow",
NamedKey::RightArrow => "RightArrow",
NamedKey::Home => "Home",
NamedKey::End => "End",
NamedKey::Backspace => "Backspace",
NamedKey::Delete => "Delete",
NamedKey::Insert => "Insert",
NamedKey::F1 => "F1",
NamedKey::F2 => "F2",
NamedKey::F3 => "F3",
NamedKey::F4 => "F4",
NamedKey::F5 => "F5",
NamedKey::F6 => "F6",
NamedKey::F7 => "F7",
NamedKey::F8 => "F8",
NamedKey::F9 => "F9",
NamedKey::F10 => "F10",
NamedKey::F11 => "F11",
NamedKey::F12 => "F12",
NamedKey::Tab => "Tab",
NamedKey::Esc => "Esc",
NamedKey::CapsLock => "CapsLock",
NamedKey::ScrollLock => "ScrollLock",
NamedKey::NumLock => "NumLock",
NamedKey::PrintScreen => "PrintScreen",
NamedKey::Pause => "Pause",
NamedKey::Menu => "Menu",
NamedKey::Enter => "Enter",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
pub fn from_str_name(value: &str) -> ::core::option::Option<Self> {
match value {
"PageDown" => Some(Self::PageDown),
"PageUp" => Some(Self::PageUp),
"LeftArrow" => Some(Self::LeftArrow),
"DownArrow" => Some(Self::DownArrow),
"UpArrow" => Some(Self::UpArrow),
"RightArrow" => Some(Self::RightArrow),
"Home" => Some(Self::Home),
"End" => Some(Self::End),
"Backspace" => Some(Self::Backspace),
"Delete" => Some(Self::Delete),
"Insert" => Some(Self::Insert),
"F1" => Some(Self::F1),
"F2" => Some(Self::F2),
"F3" => Some(Self::F3),
"F4" => Some(Self::F4),
"F5" => Some(Self::F5),
"F6" => Some(Self::F6),
"F7" => Some(Self::F7),
"F8" => Some(Self::F8),
"F9" => Some(Self::F9),
"F10" => Some(Self::F10),
"F11" => Some(Self::F11),
"F12" => Some(Self::F12),
"Tab" => Some(Self::Tab),
"Esc" => Some(Self::Esc),
"CapsLock" => Some(Self::CapsLock),
"ScrollLock" => Some(Self::ScrollLock),
"NumLock" => Some(Self::NumLock),
"PrintScreen" => Some(Self::PrintScreen),
"Pause" => Some(Self::Pause),
"Menu" => Some(Self::Menu),
"Enter" => Some(Self::Enter),
_ => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
#[repr(i32)]
pub enum Char {
A = 0,
B = 1,
C = 2,
D = 3,
E = 4,
F = 5,
G = 6,
H = 7,
I = 8,
J = 9,
K = 10,
L = 11,
M = 12,
N = 13,
O = 14,
P = 15,
Q = 16,
R = 17,
S = 18,
T = 19,
U = 20,
V = 21,
W = 22,
X = 23,
Y = 24,
Z = 25,
Zero = 26,
One = 27,
Two = 28,
Three = 29,
Four = 30,
Five = 31,
Six = 32,
Seven = 33,
Eight = 34,
Nine = 35,
}
impl Char {
/// String value of the enum field names used in the ProtoBuf definition.
///
/// The values are not transformed in any way and thus are considered stable
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
Char::A => "a",
Char::B => "b",
Char::C => "c",
Char::D => "d",
Char::E => "e",
Char::F => "f",
Char::G => "g",
Char::H => "h",
Char::I => "i",
Char::J => "j",
Char::K => "k",
Char::L => "l",
Char::M => "m",
Char::N => "n",
Char::O => "o",
Char::P => "p",
Char::Q => "q",
Char::R => "r",
Char::S => "s",
Char::T => "t",
Char::U => "u",
Char::V => "v",
Char::W => "w",
Char::X => "x",
Char::Y => "y",
Char::Z => "z",
Char::Zero => "zero",
Char::One => "one",
Char::Two => "two",
Char::Three => "three",
Char::Four => "four",
Char::Five => "five",
Char::Six => "six",
Char::Seven => "seven",
Char::Eight => "eight",
Char::Nine => "nine",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
pub fn from_str_name(value: &str) -> ::core::option::Option<Self> {
match value {
"a" => Some(Self::A),
"b" => Some(Self::B),
"c" => Some(Self::C),
"d" => Some(Self::D),
"e" => Some(Self::E),
"f" => Some(Self::F),
"g" => Some(Self::G),
"h" => Some(Self::H),
"i" => Some(Self::I),
"j" => Some(Self::J),
"k" => Some(Self::K),
"l" => Some(Self::L),
"m" => Some(Self::M),
"n" => Some(Self::N),
"o" => Some(Self::O),
"p" => Some(Self::P),
"q" => Some(Self::Q),
"r" => Some(Self::R),
"s" => Some(Self::S),
"t" => Some(Self::T),
"u" => Some(Self::U),
"v" => Some(Self::V),
"w" => Some(Self::W),
"x" => Some(Self::X),
"y" => Some(Self::Y),
"z" => Some(Self::Z),
"zero" => Some(Self::Zero),
"one" => Some(Self::One),
"two" => Some(Self::Two),
"three" => Some(Self::Three),
"four" => Some(Self::Four),
"five" => Some(Self::Five),
"six" => Some(Self::Six),
"seven" => Some(Self::Seven),
"eight" => Some(Self::Eight),
"nine" => Some(Self::Nine),
_ => None,
}
}
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum MainKey {
#[prost(enumeration="NamedKey", tag="2")]
Key(i32),
#[prost(enumeration="Char", tag="3")]
Char(i32),
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/assets/prost/api.input_mode.rs | zellij-utils/assets/prost/api.input_mode.rs | #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct InputModeMessage {
#[prost(enumeration="InputMode", tag="1")]
pub input_mode: i32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
#[repr(i32)]
pub enum InputMode {
/// / In `Normal` mode, input is always written to the terminal, except for the shortcuts leading
/// / to other modes
Normal = 0,
/// / In `Locked` mode, input is always written to the terminal and all shortcuts are disabled
/// / except the one leading back to normal mode
Locked = 1,
/// / `Resize` mode allows resizing the different existing panes.
Resize = 2,
/// / `Pane` mode allows creating and closing panes, as well as moving between them.
Pane = 3,
/// / `Tab` mode allows creating and closing tabs, as well as moving between them.
Tab = 4,
/// / `Scroll` mode allows scrolling up and down within a pane.
Scroll = 5,
/// / `EnterSearch` mode allows for typing in the needle for a search in the scroll buffer of a pane.
EnterSearch = 6,
/// / `Search` mode allows for searching a term in a pane (superset of `Scroll`).
Search = 7,
/// / `RenameTab` mode allows assigning a new name to a tab.
RenameTab = 8,
/// / `RenamePane` mode allows assigning a new name to a pane.
RenamePane = 9,
/// / `Session` mode allows detaching sessions
Session = 10,
/// / `Move` mode allows moving the different existing panes within a tab
Move = 11,
/// / `Prompt` mode allows interacting with active prompts.
Prompt = 12,
/// / `Tmux` mode allows for basic tmux keybindings functionality
Tmux = 13,
}
impl InputMode {
/// String value of the enum field names used in the ProtoBuf definition.
///
/// The values are not transformed in any way and thus are considered stable
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
InputMode::Normal => "Normal",
InputMode::Locked => "Locked",
InputMode::Resize => "Resize",
InputMode::Pane => "Pane",
InputMode::Tab => "Tab",
InputMode::Scroll => "Scroll",
InputMode::EnterSearch => "EnterSearch",
InputMode::Search => "Search",
InputMode::RenameTab => "RenameTab",
InputMode::RenamePane => "RenamePane",
InputMode::Session => "Session",
InputMode::Move => "Move",
InputMode::Prompt => "Prompt",
InputMode::Tmux => "Tmux",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
pub fn from_str_name(value: &str) -> ::core::option::Option<Self> {
match value {
"Normal" => Some(Self::Normal),
"Locked" => Some(Self::Locked),
"Resize" => Some(Self::Resize),
"Pane" => Some(Self::Pane),
"Tab" => Some(Self::Tab),
"Scroll" => Some(Self::Scroll),
"EnterSearch" => Some(Self::EnterSearch),
"Search" => Some(Self::Search),
"RenameTab" => Some(Self::RenameTab),
"RenamePane" => Some(Self::RenamePane),
"Session" => Some(Self::Session),
"Move" => Some(Self::Move),
"Prompt" => Some(Self::Prompt),
"Tmux" => Some(Self::Tmux),
_ => None,
}
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/assets/prost/api.action.rs | zellij-utils/assets/prost/api.action.rs | #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PercentOrFixed {
#[prost(oneof="percent_or_fixed::SizeType", tags="1, 2")]
pub size_type: ::core::option::Option<percent_or_fixed::SizeType>,
}
/// Nested message and enum types in `PercentOrFixed`.
pub mod percent_or_fixed {
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum SizeType {
#[prost(uint32, tag="1")]
Percent(u32),
#[prost(uint32, tag="2")]
Fixed(u32),
}
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct LayoutConstraintWithValue {
#[prost(enumeration="LayoutConstraint", tag="1")]
pub constraint_type: i32,
#[prost(uint32, optional, tag="2")]
pub value: ::core::option::Option<u32>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PluginUserConfiguration {
#[prost(map="string, string", tag="1")]
pub configuration: ::std::collections::HashMap<::prost::alloc::string::String, ::prost::alloc::string::String>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct RunPluginLocationData {
#[prost(enumeration="RunPluginLocation", tag="1")]
pub location_type: i32,
#[prost(oneof="run_plugin_location_data::LocationData", tags="2, 3, 4")]
pub location_data: ::core::option::Option<run_plugin_location_data::LocationData>,
}
/// Nested message and enum types in `RunPluginLocationData`.
pub mod run_plugin_location_data {
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum LocationData {
#[prost(string, tag="2")]
FilePath(::prost::alloc::string::String),
#[prost(message, tag="3")]
ZellijTag(super::PluginTag),
#[prost(string, tag="4")]
RemoteUrl(::prost::alloc::string::String),
}
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PluginTag {
#[prost(string, tag="1")]
pub tag: ::prost::alloc::string::String,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct RunPlugin {
#[prost(bool, tag="1")]
pub allow_exec_host_cmd: bool,
#[prost(message, optional, tag="2")]
pub location: ::core::option::Option<RunPluginLocationData>,
#[prost(message, optional, tag="3")]
pub configuration: ::core::option::Option<PluginUserConfiguration>,
#[prost(string, optional, tag="4")]
pub initial_cwd: ::core::option::Option<::prost::alloc::string::String>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PluginAlias {
#[prost(string, tag="1")]
pub name: ::prost::alloc::string::String,
#[prost(message, optional, tag="2")]
pub configuration: ::core::option::Option<PluginUserConfiguration>,
#[prost(string, optional, tag="3")]
pub initial_cwd: ::core::option::Option<::prost::alloc::string::String>,
#[prost(message, optional, tag="4")]
pub run_plugin: ::core::option::Option<RunPlugin>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct RunPluginOrAlias {
#[prost(oneof="run_plugin_or_alias::PluginType", tags="1, 2")]
pub plugin_type: ::core::option::Option<run_plugin_or_alias::PluginType>,
}
/// Nested message and enum types in `RunPluginOrAlias`.
pub mod run_plugin_or_alias {
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum PluginType {
#[prost(message, tag="1")]
Plugin(super::RunPlugin),
#[prost(message, tag="2")]
Alias(super::PluginAlias),
}
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct RunEditFileAction {
#[prost(string, tag="1")]
pub file_path: ::prost::alloc::string::String,
#[prost(uint32, optional, tag="2")]
pub line_number: ::core::option::Option<u32>,
#[prost(string, optional, tag="3")]
pub cwd: ::core::option::Option<::prost::alloc::string::String>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PaneRun {
#[prost(oneof="pane_run::RunType", tags="1, 2, 3, 4")]
pub run_type: ::core::option::Option<pane_run::RunType>,
}
/// Nested message and enum types in `PaneRun`.
pub mod pane_run {
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum RunType {
#[prost(message, tag="1")]
Command(super::RunCommandAction),
#[prost(message, tag="2")]
Plugin(super::RunPluginOrAlias),
#[prost(message, tag="3")]
EditFile(super::RunEditFileAction),
#[prost(string, tag="4")]
Cwd(::prost::alloc::string::String),
}
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct TiledPaneLayout {
#[prost(enumeration="SplitDirection", tag="1")]
pub children_split_direction: i32,
#[prost(string, optional, tag="2")]
pub name: ::core::option::Option<::prost::alloc::string::String>,
#[prost(message, repeated, tag="3")]
pub children: ::prost::alloc::vec::Vec<TiledPaneLayout>,
#[prost(message, optional, tag="4")]
pub split_size: ::core::option::Option<SplitSize>,
#[prost(message, optional, tag="5")]
pub run: ::core::option::Option<PaneRun>,
#[prost(bool, tag="6")]
pub borderless: bool,
#[prost(string, optional, tag="7")]
pub focus: ::core::option::Option<::prost::alloc::string::String>,
#[prost(bool, optional, tag="8")]
pub exclude_from_sync: ::core::option::Option<bool>,
#[prost(bool, tag="9")]
pub children_are_stacked: bool,
#[prost(uint32, optional, tag="10")]
pub external_children_index: ::core::option::Option<u32>,
#[prost(bool, tag="11")]
pub is_expanded_in_stack: bool,
#[prost(bool, tag="12")]
pub hide_floating_panes: bool,
#[prost(string, optional, tag="13")]
pub pane_initial_contents: ::core::option::Option<::prost::alloc::string::String>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct FloatingPaneLayout {
#[prost(string, optional, tag="1")]
pub name: ::core::option::Option<::prost::alloc::string::String>,
#[prost(message, optional, tag="2")]
pub height: ::core::option::Option<PercentOrFixed>,
#[prost(message, optional, tag="3")]
pub width: ::core::option::Option<PercentOrFixed>,
#[prost(message, optional, tag="4")]
pub x: ::core::option::Option<PercentOrFixed>,
#[prost(message, optional, tag="5")]
pub y: ::core::option::Option<PercentOrFixed>,
#[prost(bool, optional, tag="6")]
pub pinned: ::core::option::Option<bool>,
#[prost(message, optional, tag="7")]
pub run: ::core::option::Option<PaneRun>,
#[prost(bool, optional, tag="8")]
pub focus: ::core::option::Option<bool>,
#[prost(bool, tag="9")]
pub already_running: bool,
#[prost(string, optional, tag="10")]
pub pane_initial_contents: ::core::option::Option<::prost::alloc::string::String>,
#[prost(uint32, optional, tag="11")]
pub logical_position: ::core::option::Option<u32>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct SwapTiledLayout {
#[prost(message, repeated, tag="1")]
pub constraint_map: ::prost::alloc::vec::Vec<LayoutConstraintTiledPair>,
#[prost(string, optional, tag="2")]
pub name: ::core::option::Option<::prost::alloc::string::String>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct SwapFloatingLayout {
#[prost(message, repeated, tag="1")]
pub constraint_map: ::prost::alloc::vec::Vec<LayoutConstraintFloatingPair>,
#[prost(string, optional, tag="2")]
pub name: ::core::option::Option<::prost::alloc::string::String>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct LayoutConstraintTiledPair {
#[prost(message, optional, tag="1")]
pub constraint: ::core::option::Option<LayoutConstraintWithValue>,
#[prost(message, optional, tag="2")]
pub layout: ::core::option::Option<TiledPaneLayout>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct LayoutConstraintFloatingPair {
#[prost(message, optional, tag="1")]
pub constraint: ::core::option::Option<LayoutConstraintWithValue>,
#[prost(message, repeated, tag="2")]
pub layouts: ::prost::alloc::vec::Vec<FloatingPaneLayout>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CommandOrPlugin {
#[prost(oneof="command_or_plugin::CommandOrPluginType", tags="1, 2")]
pub command_or_plugin_type: ::core::option::Option<command_or_plugin::CommandOrPluginType>,
}
/// Nested message and enum types in `CommandOrPlugin`.
pub mod command_or_plugin {
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum CommandOrPluginType {
#[prost(message, tag="1")]
Command(super::RunCommandAction),
#[prost(message, tag="2")]
Plugin(super::RunPluginOrAlias),
}
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct NewTabPayload {
#[prost(message, optional, tag="1")]
pub tiled_layout: ::core::option::Option<TiledPaneLayout>,
#[prost(message, repeated, tag="2")]
pub floating_layouts: ::prost::alloc::vec::Vec<FloatingPaneLayout>,
#[prost(message, repeated, tag="3")]
pub swap_tiled_layouts: ::prost::alloc::vec::Vec<SwapTiledLayout>,
#[prost(message, repeated, tag="4")]
pub swap_floating_layouts: ::prost::alloc::vec::Vec<SwapFloatingLayout>,
#[prost(string, optional, tag="5")]
pub tab_name: ::core::option::Option<::prost::alloc::string::String>,
#[prost(bool, tag="6")]
pub should_change_focus_to_new_tab: bool,
#[prost(string, optional, tag="7")]
pub cwd: ::core::option::Option<::prost::alloc::string::String>,
#[prost(message, repeated, tag="8")]
pub initial_panes: ::prost::alloc::vec::Vec<CommandOrPlugin>,
#[prost(enumeration="UnblockCondition", optional, tag="9")]
pub first_pane_unblock_condition: ::core::option::Option<i32>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct OverrideLayoutPayload {
#[prost(message, optional, tag="1")]
pub tiled_layout: ::core::option::Option<TiledPaneLayout>,
#[prost(message, repeated, tag="2")]
pub floating_layouts: ::prost::alloc::vec::Vec<FloatingPaneLayout>,
#[prost(message, repeated, tag="3")]
pub swap_tiled_layouts: ::prost::alloc::vec::Vec<SwapTiledLayout>,
#[prost(message, repeated, tag="4")]
pub swap_floating_layouts: ::prost::alloc::vec::Vec<SwapFloatingLayout>,
#[prost(string, optional, tag="5")]
pub tab_name: ::core::option::Option<::prost::alloc::string::String>,
#[prost(bool, tag="10")]
pub retain_existing_terminal_panes: bool,
#[prost(bool, tag="11")]
pub retain_existing_plugin_panes: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Action {
#[prost(enumeration="ActionName", tag="1")]
pub name: i32,
#[prost(oneof="action::OptionalPayload", tags="2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53")]
pub optional_payload: ::core::option::Option<action::OptionalPayload>,
}
/// Nested message and enum types in `Action`.
pub mod action {
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum OptionalPayload {
#[prost(message, tag="2")]
SwitchToModePayload(super::SwitchToModePayload),
#[prost(message, tag="3")]
WritePayload(super::WritePayload),
#[prost(message, tag="4")]
WriteCharsPayload(super::WriteCharsPayload),
#[prost(message, tag="5")]
SwitchModeForAllClientsPayload(super::SwitchToModePayload),
#[prost(message, tag="6")]
ResizePayload(super::super::resize::Resize),
#[prost(enumeration="super::super::resize::ResizeDirection", tag="7")]
MoveFocusPayload(i32),
#[prost(enumeration="super::super::resize::ResizeDirection", tag="8")]
MoveFocusOrTabPayload(i32),
#[prost(message, tag="9")]
MovePanePayload(super::MovePanePayload),
#[prost(message, tag="10")]
DumpScreenPayload(super::DumpScreenPayload),
#[prost(message, tag="11")]
ScrollUpAtPayload(super::ScrollAtPayload),
#[prost(message, tag="12")]
ScrollDownAtPayload(super::ScrollAtPayload),
#[prost(message, tag="13")]
NewPanePayload(super::NewPanePayload),
#[prost(message, tag="14")]
EditFilePayload(super::EditFilePayload),
#[prost(message, tag="15")]
NewFloatingPanePayload(super::NewFloatingPanePayload),
#[prost(message, tag="16")]
NewTiledPanePayload(super::NewTiledPanePayload),
#[prost(bytes, tag="17")]
PaneNameInputPayload(::prost::alloc::vec::Vec<u8>),
#[prost(uint32, tag="18")]
GoToTabPayload(u32),
#[prost(message, tag="19")]
GoToTabNamePayload(super::GoToTabNamePayload),
#[prost(bytes, tag="20")]
TabNameInputPayload(::prost::alloc::vec::Vec<u8>),
#[prost(message, tag="21")]
RunPayload(super::RunCommandAction),
#[prost(message, tag="22")]
LeftClickPayload(super::Position),
#[prost(message, tag="23")]
RightClickPayload(super::Position),
#[prost(message, tag="24")]
MiddleClickPayload(super::Position),
#[prost(message, tag="25")]
LaunchOrFocusPluginPayload(super::LaunchOrFocusPluginPayload),
#[prost(message, tag="26")]
LeftMouseReleasePayload(super::Position),
#[prost(message, tag="27")]
RightMouseReleasePayload(super::Position),
#[prost(message, tag="28")]
MiddleMouseReleasePayload(super::Position),
#[prost(bytes, tag="32")]
SearchInputPayload(::prost::alloc::vec::Vec<u8>),
#[prost(enumeration="super::SearchDirection", tag="33")]
SearchPayload(i32),
#[prost(enumeration="super::SearchOption", tag="34")]
SearchToggleOptionPayload(i32),
#[prost(message, tag="35")]
NewTiledPluginPanePayload(super::NewPluginPanePayload),
#[prost(message, tag="36")]
NewFloatingPluginPanePayload(super::NewPluginPanePayload),
#[prost(string, tag="37")]
StartOrReloadPluginPayload(::prost::alloc::string::String),
#[prost(uint32, tag="38")]
CloseTerminalPanePayload(u32),
#[prost(uint32, tag="39")]
ClosePluginPanePayload(u32),
#[prost(message, tag="40")]
FocusTerminalPaneWithIdPayload(super::PaneIdAndShouldFloat),
#[prost(message, tag="41")]
FocusPluginPaneWithIdPayload(super::PaneIdAndShouldFloat),
#[prost(message, tag="42")]
RenameTerminalPanePayload(super::IdAndName),
#[prost(message, tag="43")]
RenamePluginPanePayload(super::IdAndName),
#[prost(message, tag="44")]
RenameTabPayload(super::IdAndName),
#[prost(string, tag="45")]
RenameSessionPayload(::prost::alloc::string::String),
#[prost(message, tag="46")]
LaunchPluginPayload(super::LaunchOrFocusPluginPayload),
#[prost(message, tag="47")]
MessagePayload(super::CliPipePayload),
#[prost(enumeration="super::MoveTabDirection", tag="48")]
MoveTabPayload(i32),
#[prost(message, tag="49")]
MouseEventPayload(super::MouseEventPayload),
#[prost(message, tag="50")]
NewBlockingPanePayload(super::NewBlockingPanePayload),
#[prost(message, tag="51")]
NewTabPayload(super::NewTabPayload),
#[prost(message, tag="52")]
NewInPlacePanePayload(super::NewInPlacePanePayload),
#[prost(message, tag="53")]
OverrideLayoutPayload(super::OverrideLayoutPayload),
}
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CliPipePayload {
#[prost(string, optional, tag="1")]
pub name: ::core::option::Option<::prost::alloc::string::String>,
#[prost(string, tag="2")]
pub payload: ::prost::alloc::string::String,
#[prost(message, repeated, tag="3")]
pub args: ::prost::alloc::vec::Vec<NameAndValue>,
#[prost(string, optional, tag="4")]
pub plugin: ::core::option::Option<::prost::alloc::string::String>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct IdAndName {
#[prost(bytes="vec", tag="1")]
pub name: ::prost::alloc::vec::Vec<u8>,
#[prost(uint32, tag="2")]
pub id: u32,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PaneIdAndShouldFloat {
#[prost(uint32, tag="1")]
pub pane_id: u32,
#[prost(bool, tag="2")]
pub should_float: bool,
#[prost(bool, tag="3")]
pub should_be_in_place: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct NewPluginPanePayload {
#[prost(string, tag="1")]
pub plugin_url: ::prost::alloc::string::String,
#[prost(string, optional, tag="2")]
pub pane_name: ::core::option::Option<::prost::alloc::string::String>,
#[prost(bool, tag="3")]
pub skip_plugin_cache: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct LaunchOrFocusPluginPayload {
#[prost(string, tag="1")]
pub plugin_url: ::prost::alloc::string::String,
#[prost(bool, tag="2")]
pub should_float: bool,
#[prost(message, optional, tag="3")]
pub plugin_configuration: ::core::option::Option<PluginConfiguration>,
#[prost(bool, tag="4")]
pub move_to_focused_tab: bool,
#[prost(bool, tag="5")]
pub should_open_in_place: bool,
#[prost(bool, tag="6")]
pub skip_plugin_cache: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct GoToTabNamePayload {
#[prost(string, tag="1")]
pub tab_name: ::prost::alloc::string::String,
#[prost(bool, tag="2")]
pub create: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct NewFloatingPanePayload {
#[prost(message, optional, tag="1")]
pub command: ::core::option::Option<RunCommandAction>,
#[prost(bool, tag="2")]
pub near_current_pane: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct NewTiledPanePayload {
#[prost(message, optional, tag="1")]
pub command: ::core::option::Option<RunCommandAction>,
#[prost(enumeration="super::resize::ResizeDirection", optional, tag="2")]
pub direction: ::core::option::Option<i32>,
#[prost(bool, tag="3")]
pub near_current_pane: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct MovePanePayload {
#[prost(enumeration="super::resize::ResizeDirection", optional, tag="1")]
pub direction: ::core::option::Option<i32>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct EditFilePayload {
#[prost(string, tag="1")]
pub file_to_edit: ::prost::alloc::string::String,
#[prost(uint32, optional, tag="2")]
pub line_number: ::core::option::Option<u32>,
#[prost(string, optional, tag="3")]
pub cwd: ::core::option::Option<::prost::alloc::string::String>,
#[prost(enumeration="super::resize::ResizeDirection", optional, tag="4")]
pub direction: ::core::option::Option<i32>,
#[prost(bool, tag="5")]
pub should_float: bool,
#[prost(bool, tag="6")]
pub near_current_pane: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ScrollAtPayload {
#[prost(message, optional, tag="1")]
pub position: ::core::option::Option<Position>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct NewPanePayload {
#[prost(enumeration="super::resize::ResizeDirection", optional, tag="1")]
pub direction: ::core::option::Option<i32>,
#[prost(string, optional, tag="2")]
pub pane_name: ::core::option::Option<::prost::alloc::string::String>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct NewBlockingPanePayload {
#[prost(message, optional, tag="1")]
pub placement: ::core::option::Option<NewPanePlacement>,
#[prost(string, optional, tag="2")]
pub pane_name: ::core::option::Option<::prost::alloc::string::String>,
#[prost(message, optional, tag="3")]
pub command: ::core::option::Option<RunCommandAction>,
#[prost(enumeration="UnblockCondition", optional, tag="4")]
pub unblock_condition: ::core::option::Option<i32>,
#[prost(bool, tag="5")]
pub near_current_pane: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct NewInPlacePanePayload {
#[prost(message, optional, tag="1")]
pub command: ::core::option::Option<RunCommandAction>,
#[prost(string, optional, tag="2")]
pub pane_name: ::core::option::Option<::prost::alloc::string::String>,
#[prost(bool, tag="3")]
pub near_current_pane: bool,
#[prost(message, optional, tag="4")]
pub pane_id_to_replace: ::core::option::Option<PaneId>,
#[prost(bool, tag="5")]
pub close_replace_pane: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct SwitchToModePayload {
#[prost(enumeration="super::input_mode::InputMode", tag="1")]
pub input_mode: i32,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct WritePayload {
#[prost(bytes="vec", tag="1")]
pub bytes_to_write: ::prost::alloc::vec::Vec<u8>,
#[prost(message, optional, tag="2")]
pub key_with_modifier: ::core::option::Option<KeyWithModifier>,
#[prost(bool, tag="3")]
pub is_kitty_keyboard_protocol: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct WriteCharsPayload {
#[prost(string, tag="1")]
pub chars: ::prost::alloc::string::String,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct DumpScreenPayload {
#[prost(string, tag="1")]
pub file_path: ::prost::alloc::string::String,
#[prost(bool, tag="2")]
pub include_scrollback: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Position {
#[prost(int64, tag="1")]
pub line: i64,
#[prost(int64, tag="2")]
pub column: i64,
}
/// SplitSize represents a dimension that can be either a percentage or fixed size
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct SplitSize {
#[prost(oneof="split_size::SplitSizeVariant", tags="1, 2")]
pub split_size_variant: ::core::option::Option<split_size::SplitSizeVariant>,
}
/// Nested message and enum types in `SplitSize`.
pub mod split_size {
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum SplitSizeVariant {
/// 1 to 100
#[prost(uint32, tag="1")]
Percent(u32),
/// absolute number of columns or rows
#[prost(uint32, tag="2")]
Fixed(u32),
}
}
/// PaneId identifies either a terminal or plugin pane
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PaneId {
#[prost(oneof="pane_id::PaneIdVariant", tags="1, 2")]
pub pane_id_variant: ::core::option::Option<pane_id::PaneIdVariant>,
}
/// Nested message and enum types in `PaneId`.
pub mod pane_id {
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum PaneIdVariant {
#[prost(uint32, tag="1")]
Terminal(u32),
#[prost(uint32, tag="2")]
Plugin(u32),
}
}
/// FloatingPaneCoordinates specifies the position and size of a floating pane
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct FloatingPaneCoordinates {
#[prost(message, optional, tag="1")]
pub x: ::core::option::Option<SplitSize>,
#[prost(message, optional, tag="2")]
pub y: ::core::option::Option<SplitSize>,
#[prost(message, optional, tag="3")]
pub width: ::core::option::Option<SplitSize>,
#[prost(message, optional, tag="4")]
pub height: ::core::option::Option<SplitSize>,
#[prost(bool, optional, tag="5")]
pub pinned: ::core::option::Option<bool>,
}
/// NewPanePlacement specifies where a new pane should be placed
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct NewPanePlacement {
#[prost(oneof="new_pane_placement::PlacementVariant", tags="1, 2, 3, 4, 5")]
pub placement_variant: ::core::option::Option<new_pane_placement::PlacementVariant>,
}
/// Nested message and enum types in `NewPanePlacement`.
pub mod new_pane_placement {
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum PlacementVariant {
#[prost(bool, tag="1")]
NoPreference(bool),
#[prost(message, tag="2")]
Tiled(super::TiledPlacement),
#[prost(message, tag="3")]
Floating(super::FloatingPlacement),
#[prost(message, tag="4")]
InPlace(super::InPlaceConfig),
#[prost(message, tag="5")]
Stacked(super::StackedPlacement),
}
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct TiledPlacement {
#[prost(enumeration="super::resize::ResizeDirection", optional, tag="1")]
pub direction: ::core::option::Option<i32>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct FloatingPlacement {
#[prost(message, optional, tag="1")]
pub coordinates: ::core::option::Option<FloatingPaneCoordinates>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct InPlaceConfig {
#[prost(message, optional, tag="1")]
pub pane_id_to_replace: ::core::option::Option<PaneId>,
#[prost(bool, tag="2")]
pub close_replaced_pane: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct StackedPlacement {
#[prost(message, optional, tag="1")]
pub pane_id: ::core::option::Option<PaneId>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct MouseEventPayload {
#[prost(uint32, tag="1")]
pub event_type: u32,
#[prost(bool, tag="2")]
pub left: bool,
#[prost(bool, tag="3")]
pub right: bool,
#[prost(bool, tag="4")]
pub middle: bool,
#[prost(bool, tag="5")]
pub wheel_up: bool,
#[prost(bool, tag="6")]
pub wheel_down: bool,
#[prost(bool, tag="7")]
pub shift: bool,
#[prost(bool, tag="8")]
pub alt: bool,
#[prost(bool, tag="9")]
pub ctrl: bool,
#[prost(int64, tag="10")]
pub line: i64,
#[prost(int64, tag="11")]
pub column: i64,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct RunCommandAction {
#[prost(string, tag="1")]
pub command: ::prost::alloc::string::String,
#[prost(string, repeated, tag="2")]
pub args: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
#[prost(string, optional, tag="3")]
pub cwd: ::core::option::Option<::prost::alloc::string::String>,
#[prost(enumeration="super::resize::ResizeDirection", optional, tag="4")]
pub direction: ::core::option::Option<i32>,
#[prost(string, optional, tag="5")]
pub pane_name: ::core::option::Option<::prost::alloc::string::String>,
#[prost(bool, tag="6")]
pub hold_on_close: bool,
#[prost(bool, tag="7")]
pub hold_on_start: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PluginConfiguration {
#[prost(message, repeated, tag="1")]
pub name_and_value: ::prost::alloc::vec::Vec<NameAndValue>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct NameAndValue {
#[prost(string, tag="1")]
pub name: ::prost::alloc::string::String,
#[prost(string, tag="2")]
pub value: ::prost::alloc::string::String,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct KeyWithModifier {
#[prost(enumeration="BareKey", tag="1")]
pub bare_key: i32,
#[prost(enumeration="KeyModifier", repeated, tag="2")]
pub key_modifiers: ::prost::alloc::vec::Vec<i32>,
/// Only set when bare_key is CHAR
#[prost(string, optional, tag="3")]
pub character: ::core::option::Option<::prost::alloc::string::String>,
}
// Layout and related types
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
#[repr(i32)]
pub enum SplitDirection {
Unspecified = 0,
Horizontal = 1,
Vertical = 2,
}
impl SplitDirection {
/// String value of the enum field names used in the ProtoBuf definition.
///
/// The values are not transformed in any way and thus are considered stable
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
SplitDirection::Unspecified => "SPLIT_DIRECTION_UNSPECIFIED",
SplitDirection::Horizontal => "SPLIT_DIRECTION_HORIZONTAL",
SplitDirection::Vertical => "SPLIT_DIRECTION_VERTICAL",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
pub fn from_str_name(value: &str) -> ::core::option::Option<Self> {
match value {
"SPLIT_DIRECTION_UNSPECIFIED" => Some(Self::Unspecified),
"SPLIT_DIRECTION_HORIZONTAL" => Some(Self::Horizontal),
"SPLIT_DIRECTION_VERTICAL" => Some(Self::Vertical),
_ => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
#[repr(i32)]
pub enum LayoutConstraint {
Unspecified = 0,
MaxPanes = 1,
MinPanes = 2,
ExactPanes = 3,
NoConstraint = 4,
}
impl LayoutConstraint {
/// String value of the enum field names used in the ProtoBuf definition.
///
/// The values are not transformed in any way and thus are considered stable
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
LayoutConstraint::Unspecified => "LAYOUT_CONSTRAINT_UNSPECIFIED",
LayoutConstraint::MaxPanes => "LAYOUT_CONSTRAINT_MAX_PANES",
LayoutConstraint::MinPanes => "LAYOUT_CONSTRAINT_MIN_PANES",
LayoutConstraint::ExactPanes => "LAYOUT_CONSTRAINT_EXACT_PANES",
LayoutConstraint::NoConstraint => "LAYOUT_CONSTRAINT_NO_CONSTRAINT",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
pub fn from_str_name(value: &str) -> ::core::option::Option<Self> {
match value {
"LAYOUT_CONSTRAINT_UNSPECIFIED" => Some(Self::Unspecified),
"LAYOUT_CONSTRAINT_MAX_PANES" => Some(Self::MaxPanes),
"LAYOUT_CONSTRAINT_MIN_PANES" => Some(Self::MinPanes),
"LAYOUT_CONSTRAINT_EXACT_PANES" => Some(Self::ExactPanes),
"LAYOUT_CONSTRAINT_NO_CONSTRAINT" => Some(Self::NoConstraint),
_ => None,
}
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/assets/prost/api.event.rs | zellij-utils/assets/prost/api.event.rs | #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct EventNameList {
#[prost(enumeration="EventType", repeated, tag="1")]
pub event_types: ::prost::alloc::vec::Vec<i32>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Event {
#[prost(enumeration="EventType", tag="1")]
pub name: i32,
#[prost(oneof="event::Payload", tags="2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33")]
pub payload: ::core::option::Option<event::Payload>,
}
/// Nested message and enum types in `Event`.
pub mod event {
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Payload {
#[prost(message, tag="2")]
ModeUpdatePayload(super::ModeUpdatePayload),
#[prost(message, tag="3")]
TabUpdatePayload(super::TabUpdatePayload),
#[prost(message, tag="4")]
PaneUpdatePayload(super::PaneUpdatePayload),
#[prost(message, tag="5")]
KeyPayload(super::super::key::Key),
#[prost(message, tag="6")]
MouseEventPayload(super::MouseEventPayload),
#[prost(float, tag="7")]
TimerPayload(f32),
#[prost(enumeration="super::CopyDestination", tag="8")]
CopyToClipboardPayload(i32),
#[prost(bool, tag="9")]
VisiblePayload(bool),
#[prost(message, tag="10")]
CustomMessagePayload(super::CustomMessagePayload),
#[prost(message, tag="11")]
FileListPayload(super::FileListPayload),
#[prost(message, tag="12")]
PermissionRequestResultPayload(super::PermissionRequestResultPayload),
#[prost(message, tag="13")]
SessionUpdatePayload(super::SessionUpdatePayload),
#[prost(message, tag="14")]
RunCommandResultPayload(super::RunCommandResultPayload),
#[prost(message, tag="15")]
WebRequestResultPayload(super::WebRequestResultPayload),
#[prost(message, tag="16")]
CommandPaneOpenedPayload(super::CommandPaneOpenedPayload),
#[prost(message, tag="17")]
CommandPaneExitedPayload(super::CommandPaneExitedPayload),
#[prost(message, tag="18")]
PaneClosedPayload(super::PaneClosedPayload),
#[prost(message, tag="19")]
EditPaneOpenedPayload(super::EditPaneOpenedPayload),
#[prost(message, tag="20")]
EditPaneExitedPayload(super::EditPaneExitedPayload),
#[prost(message, tag="21")]
CommandPaneRerunPayload(super::CommandPaneReRunPayload),
#[prost(message, tag="22")]
FailedToWriteConfigToDiskPayload(super::FailedToWriteConfigToDiskPayload),
#[prost(message, tag="23")]
ListClientsPayload(super::ListClientsPayload),
#[prost(message, tag="24")]
HostFolderChangedPayload(super::HostFolderChangedPayload),
#[prost(message, tag="25")]
FailedToChangeHostFolderPayload(super::FailedToChangeHostFolderPayload),
#[prost(message, tag="26")]
PastedTextPayload(super::PastedTextPayload),
#[prost(message, tag="27")]
WebServerStatusPayload(super::WebServerStatusPayload),
#[prost(message, tag="28")]
FailedToStartWebServerPayload(super::FailedToStartWebServerPayload),
#[prost(message, tag="29")]
InterceptedKeyPayload(super::super::key::Key),
#[prost(message, tag="30")]
PaneRenderReportPayload(super::PaneRenderReportPayload),
#[prost(message, tag="31")]
UserActionPayload(super::UserActionPayload),
#[prost(message, tag="32")]
ActionCompletePayload(super::ActionCompletePayload),
#[prost(message, tag="33")]
CwdChangedPayload(super::CwdChangedPayload),
}
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CwdChangedPayload {
#[prost(message, optional, tag="1")]
pub pane_id: ::core::option::Option<PaneId>,
#[prost(string, tag="2")]
pub new_cwd: ::prost::alloc::string::String,
#[prost(uint32, repeated, tag="3")]
pub focused_client_ids: ::prost::alloc::vec::Vec<u32>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct FailedToStartWebServerPayload {
#[prost(string, tag="1")]
pub error: ::prost::alloc::string::String,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PastedTextPayload {
#[prost(string, tag="1")]
pub pasted_text: ::prost::alloc::string::String,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct WebServerStatusPayload {
#[prost(enumeration="WebServerStatusIndication", tag="1")]
pub web_server_status_indication: i32,
#[prost(string, optional, tag="2")]
pub payload: ::core::option::Option<::prost::alloc::string::String>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct FailedToChangeHostFolderPayload {
#[prost(string, optional, tag="1")]
pub error_message: ::core::option::Option<::prost::alloc::string::String>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct HostFolderChangedPayload {
#[prost(string, tag="1")]
pub new_host_folder_path: ::prost::alloc::string::String,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ListClientsPayload {
#[prost(message, repeated, tag="1")]
pub client_info: ::prost::alloc::vec::Vec<ClientInfo>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ClientInfo {
#[prost(uint32, tag="1")]
pub client_id: u32,
#[prost(message, optional, tag="2")]
pub pane_id: ::core::option::Option<PaneId>,
#[prost(string, tag="3")]
pub running_command: ::prost::alloc::string::String,
#[prost(bool, tag="4")]
pub is_current_client: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct FailedToWriteConfigToDiskPayload {
#[prost(string, optional, tag="1")]
pub file_path: ::core::option::Option<::prost::alloc::string::String>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CommandPaneReRunPayload {
#[prost(uint32, tag="1")]
pub terminal_pane_id: u32,
#[prost(message, repeated, tag="3")]
pub context: ::prost::alloc::vec::Vec<ContextItem>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PaneClosedPayload {
#[prost(message, optional, tag="1")]
pub pane_id: ::core::option::Option<PaneId>,
}
/// duplicate of plugin_command.PaneId because protobuffs don't like recursive imports
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PaneId {
#[prost(enumeration="PaneType", tag="1")]
pub pane_type: i32,
#[prost(uint32, tag="2")]
pub id: u32,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CommandPaneOpenedPayload {
#[prost(uint32, tag="1")]
pub terminal_pane_id: u32,
#[prost(message, repeated, tag="2")]
pub context: ::prost::alloc::vec::Vec<ContextItem>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct EditPaneOpenedPayload {
#[prost(uint32, tag="1")]
pub terminal_pane_id: u32,
#[prost(message, repeated, tag="2")]
pub context: ::prost::alloc::vec::Vec<ContextItem>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CommandPaneExitedPayload {
#[prost(uint32, tag="1")]
pub terminal_pane_id: u32,
#[prost(int32, optional, tag="2")]
pub exit_code: ::core::option::Option<i32>,
#[prost(message, repeated, tag="3")]
pub context: ::prost::alloc::vec::Vec<ContextItem>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct EditPaneExitedPayload {
#[prost(uint32, tag="1")]
pub terminal_pane_id: u32,
#[prost(int32, optional, tag="2")]
pub exit_code: ::core::option::Option<i32>,
#[prost(message, repeated, tag="3")]
pub context: ::prost::alloc::vec::Vec<ContextItem>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct SessionUpdatePayload {
#[prost(message, repeated, tag="1")]
pub session_manifests: ::prost::alloc::vec::Vec<SessionManifest>,
#[prost(message, repeated, tag="2")]
pub resurrectable_sessions: ::prost::alloc::vec::Vec<ResurrectableSession>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct RunCommandResultPayload {
#[prost(int32, optional, tag="1")]
pub exit_code: ::core::option::Option<i32>,
#[prost(bytes="vec", tag="2")]
pub stdout: ::prost::alloc::vec::Vec<u8>,
#[prost(bytes="vec", tag="3")]
pub stderr: ::prost::alloc::vec::Vec<u8>,
#[prost(message, repeated, tag="4")]
pub context: ::prost::alloc::vec::Vec<ContextItem>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct WebRequestResultPayload {
#[prost(int32, tag="1")]
pub status: i32,
#[prost(message, repeated, tag="2")]
pub headers: ::prost::alloc::vec::Vec<Header>,
#[prost(bytes="vec", tag="3")]
pub body: ::prost::alloc::vec::Vec<u8>,
#[prost(message, repeated, tag="4")]
pub context: ::prost::alloc::vec::Vec<ContextItem>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ContextItem {
#[prost(string, tag="1")]
pub name: ::prost::alloc::string::String,
#[prost(string, tag="2")]
pub value: ::prost::alloc::string::String,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Header {
#[prost(string, tag="1")]
pub name: ::prost::alloc::string::String,
#[prost(string, tag="2")]
pub value: ::prost::alloc::string::String,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PermissionRequestResultPayload {
#[prost(bool, tag="1")]
pub granted: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct FileListPayload {
#[prost(string, repeated, tag="1")]
pub paths: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
#[prost(message, repeated, tag="2")]
pub paths_metadata: ::prost::alloc::vec::Vec<FileMetadata>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct FileMetadata {
/// if this is false, the metadata for this file has not been read
#[prost(bool, tag="1")]
pub metadata_is_set: bool,
#[prost(bool, tag="2")]
pub is_dir: bool,
#[prost(bool, tag="3")]
pub is_file: bool,
#[prost(bool, tag="4")]
pub is_symlink: bool,
#[prost(uint64, tag="5")]
pub len: u64,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CustomMessagePayload {
#[prost(string, tag="1")]
pub message_name: ::prost::alloc::string::String,
#[prost(string, tag="2")]
pub payload: ::prost::alloc::string::String,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct MouseEventPayload {
#[prost(enumeration="MouseEventName", tag="1")]
pub mouse_event_name: i32,
#[prost(oneof="mouse_event_payload::MouseEventPayload", tags="2, 3")]
pub mouse_event_payload: ::core::option::Option<mouse_event_payload::MouseEventPayload>,
}
/// Nested message and enum types in `MouseEventPayload`.
pub mod mouse_event_payload {
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum MouseEventPayload {
#[prost(uint32, tag="2")]
LineCount(u32),
#[prost(message, tag="3")]
Position(super::super::action::Position),
}
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct TabUpdatePayload {
#[prost(message, repeated, tag="1")]
pub tab_info: ::prost::alloc::vec::Vec<TabInfo>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PaneUpdatePayload {
#[prost(message, repeated, tag="1")]
pub pane_manifest: ::prost::alloc::vec::Vec<PaneManifest>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PaneManifest {
#[prost(uint32, tag="1")]
pub tab_index: u32,
#[prost(message, repeated, tag="2")]
pub panes: ::prost::alloc::vec::Vec<PaneInfo>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct SessionManifest {
#[prost(string, tag="1")]
pub name: ::prost::alloc::string::String,
#[prost(message, repeated, tag="2")]
pub tabs: ::prost::alloc::vec::Vec<TabInfo>,
#[prost(message, repeated, tag="3")]
pub panes: ::prost::alloc::vec::Vec<PaneManifest>,
#[prost(uint32, tag="4")]
pub connected_clients: u32,
#[prost(bool, tag="5")]
pub is_current_session: bool,
#[prost(message, repeated, tag="6")]
pub available_layouts: ::prost::alloc::vec::Vec<LayoutInfo>,
#[prost(message, repeated, tag="7")]
pub plugins: ::prost::alloc::vec::Vec<PluginInfo>,
#[prost(bool, tag="8")]
pub web_clients_allowed: bool,
#[prost(uint32, tag="9")]
pub web_client_count: u32,
#[prost(message, repeated, tag="10")]
pub tab_history: ::prost::alloc::vec::Vec<ClientTabHistory>,
#[prost(message, repeated, tag="11")]
pub pane_history: ::prost::alloc::vec::Vec<ClientPaneHistory>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ClientTabHistory {
#[prost(uint32, tag="1")]
pub client_id: u32,
#[prost(uint32, repeated, tag="2")]
pub tab_history: ::prost::alloc::vec::Vec<u32>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ClientPaneHistory {
#[prost(uint32, tag="1")]
pub client_id: u32,
#[prost(message, repeated, tag="2")]
pub pane_history: ::prost::alloc::vec::Vec<PaneId>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PluginInfo {
#[prost(uint32, tag="1")]
pub plugin_id: u32,
#[prost(string, tag="2")]
pub plugin_url: ::prost::alloc::string::String,
#[prost(message, repeated, tag="3")]
pub plugin_config: ::prost::alloc::vec::Vec<ContextItem>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct LayoutInfo {
#[prost(string, tag="1")]
pub name: ::prost::alloc::string::String,
#[prost(string, tag="2")]
pub source: ::prost::alloc::string::String,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ResurrectableSession {
#[prost(string, tag="1")]
pub name: ::prost::alloc::string::String,
#[prost(uint64, tag="2")]
pub creation_time: u64,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PaneInfo {
#[prost(uint32, tag="1")]
pub id: u32,
#[prost(bool, tag="2")]
pub is_plugin: bool,
#[prost(bool, tag="3")]
pub is_focused: bool,
#[prost(bool, tag="4")]
pub is_fullscreen: bool,
#[prost(bool, tag="5")]
pub is_floating: bool,
#[prost(bool, tag="6")]
pub is_suppressed: bool,
#[prost(string, tag="7")]
pub title: ::prost::alloc::string::String,
#[prost(bool, tag="8")]
pub exited: bool,
#[prost(int32, optional, tag="9")]
pub exit_status: ::core::option::Option<i32>,
#[prost(bool, tag="10")]
pub is_held: bool,
#[prost(uint32, tag="11")]
pub pane_x: u32,
#[prost(uint32, tag="12")]
pub pane_content_x: u32,
#[prost(uint32, tag="13")]
pub pane_y: u32,
#[prost(uint32, tag="14")]
pub pane_content_y: u32,
#[prost(uint32, tag="15")]
pub pane_rows: u32,
#[prost(uint32, tag="16")]
pub pane_content_rows: u32,
#[prost(uint32, tag="17")]
pub pane_columns: u32,
#[prost(uint32, tag="18")]
pub pane_content_columns: u32,
#[prost(message, optional, tag="19")]
pub cursor_coordinates_in_pane: ::core::option::Option<super::action::Position>,
#[prost(string, optional, tag="20")]
pub terminal_command: ::core::option::Option<::prost::alloc::string::String>,
#[prost(string, optional, tag="21")]
pub plugin_url: ::core::option::Option<::prost::alloc::string::String>,
#[prost(bool, tag="22")]
pub is_selectable: bool,
#[prost(message, repeated, tag="23")]
pub index_in_pane_group: ::prost::alloc::vec::Vec<IndexInPaneGroup>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct IndexInPaneGroup {
#[prost(uint32, tag="1")]
pub client_id: u32,
#[prost(uint32, tag="2")]
pub index: u32,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct TabInfo {
#[prost(uint32, tag="1")]
pub position: u32,
#[prost(string, tag="2")]
pub name: ::prost::alloc::string::String,
#[prost(bool, tag="3")]
pub active: bool,
#[prost(uint32, tag="4")]
pub panes_to_hide: u32,
#[prost(bool, tag="5")]
pub is_fullscreen_active: bool,
#[prost(bool, tag="6")]
pub is_sync_panes_active: bool,
#[prost(bool, tag="7")]
pub are_floating_panes_visible: bool,
#[prost(uint32, repeated, tag="8")]
pub other_focused_clients: ::prost::alloc::vec::Vec<u32>,
#[prost(string, optional, tag="9")]
pub active_swap_layout_name: ::core::option::Option<::prost::alloc::string::String>,
#[prost(bool, tag="10")]
pub is_swap_layout_dirty: bool,
#[prost(uint32, tag="11")]
pub viewport_rows: u32,
#[prost(uint32, tag="12")]
pub viewport_columns: u32,
#[prost(uint32, tag="13")]
pub display_area_rows: u32,
#[prost(uint32, tag="14")]
pub display_area_columns: u32,
#[prost(uint32, tag="15")]
pub selectable_tiled_panes_count: u32,
#[prost(uint32, tag="16")]
pub selectable_floating_panes_count: u32,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ModeUpdatePayload {
#[prost(enumeration="super::input_mode::InputMode", tag="1")]
pub current_mode: i32,
#[prost(message, repeated, tag="2")]
pub keybinds: ::prost::alloc::vec::Vec<InputModeKeybinds>,
#[prost(message, optional, tag="3")]
pub style: ::core::option::Option<super::style::Style>,
#[prost(bool, tag="4")]
pub arrow_fonts_support: bool,
#[prost(string, optional, tag="5")]
pub session_name: ::core::option::Option<::prost::alloc::string::String>,
#[prost(enumeration="super::input_mode::InputMode", optional, tag="6")]
pub base_mode: ::core::option::Option<i32>,
#[prost(string, optional, tag="7")]
pub editor: ::core::option::Option<::prost::alloc::string::String>,
#[prost(string, optional, tag="8")]
pub shell: ::core::option::Option<::prost::alloc::string::String>,
#[prost(bool, optional, tag="9")]
pub web_clients_allowed: ::core::option::Option<bool>,
#[prost(enumeration="WebSharing", optional, tag="10")]
pub web_sharing: ::core::option::Option<i32>,
#[prost(bool, optional, tag="11")]
pub currently_marking_pane_group: ::core::option::Option<bool>,
#[prost(bool, optional, tag="12")]
pub is_web_client: ::core::option::Option<bool>,
#[prost(string, optional, tag="13")]
pub web_server_ip: ::core::option::Option<::prost::alloc::string::String>,
#[prost(uint32, optional, tag="14")]
pub web_server_port: ::core::option::Option<u32>,
#[prost(bool, optional, tag="15")]
pub web_server_capability: ::core::option::Option<bool>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct InputModeKeybinds {
#[prost(enumeration="super::input_mode::InputMode", tag="1")]
pub mode: i32,
#[prost(message, repeated, tag="2")]
pub key_bind: ::prost::alloc::vec::Vec<KeyBind>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct KeyBind {
#[prost(message, optional, tag="1")]
pub key: ::core::option::Option<super::key::Key>,
#[prost(message, repeated, tag="2")]
pub action: ::prost::alloc::vec::Vec<super::action::Action>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PaneRenderReportPayload {
#[prost(message, repeated, tag="1")]
pub pane_contents: ::prost::alloc::vec::Vec<PaneContentsEntry>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PaneContentsEntry {
#[prost(message, optional, tag="1")]
pub pane_id: ::core::option::Option<PaneId>,
#[prost(message, optional, tag="2")]
pub pane_contents: ::core::option::Option<PaneContents>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PaneContents {
#[prost(string, repeated, tag="1")]
pub viewport: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
#[prost(message, optional, tag="2")]
pub selected_text: ::core::option::Option<SelectedText>,
#[prost(string, repeated, tag="3")]
pub lines_above_viewport: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
#[prost(string, repeated, tag="4")]
pub lines_below_viewport: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PaneScrollbackResponse {
#[prost(oneof="pane_scrollback_response::Response", tags="1, 2")]
pub response: ::core::option::Option<pane_scrollback_response::Response>,
}
/// Nested message and enum types in `PaneScrollbackResponse`.
pub mod pane_scrollback_response {
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Response {
#[prost(message, tag="1")]
Ok(super::PaneContents),
#[prost(string, tag="2")]
Err(::prost::alloc::string::String),
}
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct SelectedText {
#[prost(message, optional, tag="1")]
pub start: ::core::option::Option<super::action::Position>,
#[prost(message, optional, tag="2")]
pub end: ::core::option::Option<super::action::Position>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct UserActionPayload {
#[prost(message, optional, tag="1")]
pub action: ::core::option::Option<super::action::Action>,
#[prost(uint32, tag="2")]
pub client_id: u32,
#[prost(uint32, optional, tag="3")]
pub terminal_id: ::core::option::Option<u32>,
#[prost(uint32, optional, tag="4")]
pub cli_client_id: ::core::option::Option<u32>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ActionCompletePayload {
#[prost(message, optional, tag="1")]
pub action: ::core::option::Option<super::action::Action>,
#[prost(message, optional, tag="2")]
pub pane_id: ::core::option::Option<PaneId>,
#[prost(message, repeated, tag="3")]
pub context: ::prost::alloc::vec::Vec<ContextItem>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
#[repr(i32)]
pub enum EventType {
/// / The input mode or relevant metadata changed
ModeUpdate = 0,
/// / The tab state in the app was changed
TabUpdate = 1,
/// / The pane state in the app was changed
PaneUpdate = 2,
/// / A key was pressed while the user is focused on this plugin's pane
Key = 3,
/// / A mouse event happened while the user is focused on this plugin's pane
Mouse = 4,
/// / A timer expired set by the `set_timeout` method exported by `zellij-tile`.
Timer = 5,
/// / Text was copied to the clipboard anywhere in the app
CopyToClipboard = 6,
/// / Failed to copy text to clipboard anywhere in the app
SystemClipboardFailure = 7,
/// / Input was received anywhere in the app
InputReceived = 8,
/// / This plugin became visible or invisible
Visible = 9,
/// / A message from one of the plugin's workers
CustomMessage = 10,
/// / A file was created somewhere in the Zellij CWD folder
FileSystemCreate = 11,
/// / A file was accessed somewhere in the Zellij CWD folder
FileSystemRead = 12,
/// / A file was modified somewhere in the Zellij CWD folder
FileSystemUpdate = 13,
/// / A file was deleted somewhere in the Zellij CWD folder
FileSystemDelete = 14,
PermissionRequestResult = 15,
SessionUpdate = 16,
RunCommandResult = 17,
WebRequestResult = 18,
CommandPaneOpened = 19,
CommandPaneExited = 20,
PaneClosed = 21,
EditPaneOpened = 22,
EditPaneExited = 23,
CommandPaneReRun = 24,
FailedToWriteConfigToDisk = 25,
ListClients = 26,
HostFolderChanged = 27,
FailedToChangeHostFolder = 28,
PastedText = 29,
ConfigWasWrittenToDisk = 30,
WebServerStatus = 31,
BeforeClose = 32,
FailedToStartWebServer = 34,
InterceptedKeyPress = 35,
PaneRenderReport = 36,
UserAction = 37,
ActionComplete = 38,
CwdChanged = 39,
}
impl EventType {
/// String value of the enum field names used in the ProtoBuf definition.
///
/// The values are not transformed in any way and thus are considered stable
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
EventType::ModeUpdate => "ModeUpdate",
EventType::TabUpdate => "TabUpdate",
EventType::PaneUpdate => "PaneUpdate",
EventType::Key => "Key",
EventType::Mouse => "Mouse",
EventType::Timer => "Timer",
EventType::CopyToClipboard => "CopyToClipboard",
EventType::SystemClipboardFailure => "SystemClipboardFailure",
EventType::InputReceived => "InputReceived",
EventType::Visible => "Visible",
EventType::CustomMessage => "CustomMessage",
EventType::FileSystemCreate => "FileSystemCreate",
EventType::FileSystemRead => "FileSystemRead",
EventType::FileSystemUpdate => "FileSystemUpdate",
EventType::FileSystemDelete => "FileSystemDelete",
EventType::PermissionRequestResult => "PermissionRequestResult",
EventType::SessionUpdate => "SessionUpdate",
EventType::RunCommandResult => "RunCommandResult",
EventType::WebRequestResult => "WebRequestResult",
EventType::CommandPaneOpened => "CommandPaneOpened",
EventType::CommandPaneExited => "CommandPaneExited",
EventType::PaneClosed => "PaneClosed",
EventType::EditPaneOpened => "EditPaneOpened",
EventType::EditPaneExited => "EditPaneExited",
EventType::CommandPaneReRun => "CommandPaneReRun",
EventType::FailedToWriteConfigToDisk => "FailedToWriteConfigToDisk",
EventType::ListClients => "ListClients",
EventType::HostFolderChanged => "HostFolderChanged",
EventType::FailedToChangeHostFolder => "FailedToChangeHostFolder",
EventType::PastedText => "PastedText",
EventType::ConfigWasWrittenToDisk => "ConfigWasWrittenToDisk",
EventType::WebServerStatus => "WebServerStatus",
EventType::BeforeClose => "BeforeClose",
EventType::FailedToStartWebServer => "FailedToStartWebServer",
EventType::InterceptedKeyPress => "InterceptedKeyPress",
EventType::PaneRenderReport => "PaneRenderReport",
EventType::UserAction => "UserAction",
EventType::ActionComplete => "ActionComplete",
EventType::CwdChanged => "CwdChanged",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
pub fn from_str_name(value: &str) -> ::core::option::Option<Self> {
match value {
"ModeUpdate" => Some(Self::ModeUpdate),
"TabUpdate" => Some(Self::TabUpdate),
"PaneUpdate" => Some(Self::PaneUpdate),
"Key" => Some(Self::Key),
"Mouse" => Some(Self::Mouse),
"Timer" => Some(Self::Timer),
"CopyToClipboard" => Some(Self::CopyToClipboard),
"SystemClipboardFailure" => Some(Self::SystemClipboardFailure),
"InputReceived" => Some(Self::InputReceived),
"Visible" => Some(Self::Visible),
"CustomMessage" => Some(Self::CustomMessage),
"FileSystemCreate" => Some(Self::FileSystemCreate),
"FileSystemRead" => Some(Self::FileSystemRead),
"FileSystemUpdate" => Some(Self::FileSystemUpdate),
"FileSystemDelete" => Some(Self::FileSystemDelete),
"PermissionRequestResult" => Some(Self::PermissionRequestResult),
"SessionUpdate" => Some(Self::SessionUpdate),
"RunCommandResult" => Some(Self::RunCommandResult),
"WebRequestResult" => Some(Self::WebRequestResult),
"CommandPaneOpened" => Some(Self::CommandPaneOpened),
"CommandPaneExited" => Some(Self::CommandPaneExited),
"PaneClosed" => Some(Self::PaneClosed),
"EditPaneOpened" => Some(Self::EditPaneOpened),
"EditPaneExited" => Some(Self::EditPaneExited),
"CommandPaneReRun" => Some(Self::CommandPaneReRun),
"FailedToWriteConfigToDisk" => Some(Self::FailedToWriteConfigToDisk),
"ListClients" => Some(Self::ListClients),
"HostFolderChanged" => Some(Self::HostFolderChanged),
"FailedToChangeHostFolder" => Some(Self::FailedToChangeHostFolder),
"PastedText" => Some(Self::PastedText),
"ConfigWasWrittenToDisk" => Some(Self::ConfigWasWrittenToDisk),
"WebServerStatus" => Some(Self::WebServerStatus),
"BeforeClose" => Some(Self::BeforeClose),
"FailedToStartWebServer" => Some(Self::FailedToStartWebServer),
"InterceptedKeyPress" => Some(Self::InterceptedKeyPress),
"PaneRenderReport" => Some(Self::PaneRenderReport),
"UserAction" => Some(Self::UserAction),
"ActionComplete" => Some(Self::ActionComplete),
"CwdChanged" => Some(Self::CwdChanged),
_ => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
#[repr(i32)]
pub enum WebServerStatusIndication {
Online = 0,
Offline = 1,
DifferentVersion = 2,
}
impl WebServerStatusIndication {
/// String value of the enum field names used in the ProtoBuf definition.
///
/// The values are not transformed in any way and thus are considered stable
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
WebServerStatusIndication::Online => "Online",
WebServerStatusIndication::Offline => "Offline",
WebServerStatusIndication::DifferentVersion => "DifferentVersion",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
pub fn from_str_name(value: &str) -> ::core::option::Option<Self> {
match value {
"Online" => Some(Self::Online),
"Offline" => Some(Self::Offline),
"DifferentVersion" => Some(Self::DifferentVersion),
_ => None,
}
}
}
/// duplicate of plugin_command.PaneType because protobuffs don't like recursive imports
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
#[repr(i32)]
pub enum PaneType {
Terminal = 0,
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/assets/prost/api.plugin_command.rs | zellij-utils/assets/prost/api.plugin_command.rs | #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PluginCommand {
#[prost(enumeration="CommandName", tag="1")]
pub name: i32,
#[prost(oneof="plugin_command::Payload", tags="2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 119, 120, 121, 122, 123")]
pub payload: ::core::option::Option<plugin_command::Payload>,
}
/// Nested message and enum types in `PluginCommand`.
pub mod plugin_command {
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Payload {
#[prost(message, tag="2")]
SubscribePayload(super::SubscribePayload),
#[prost(message, tag="3")]
UnsubscribePayload(super::UnsubscribePayload),
#[prost(bool, tag="4")]
SetSelectablePayload(bool),
#[prost(message, tag="5")]
OpenFilePayload(super::OpenFilePayload),
#[prost(message, tag="6")]
OpenFileFloatingPayload(super::OpenFilePayload),
#[prost(message, tag="7")]
OpenTerminalPayload(super::OpenFilePayload),
#[prost(message, tag="8")]
OpenTerminalFloatingPayload(super::OpenFilePayload),
#[prost(message, tag="9")]
OpenCommandPanePayload(super::OpenCommandPanePayload),
#[prost(message, tag="10")]
OpenCommandPaneFloatingPayload(super::OpenCommandPanePayload),
#[prost(message, tag="11")]
SwitchTabToPayload(super::SwitchTabToPayload),
#[prost(message, tag="12")]
SetTimeoutPayload(super::SetTimeoutPayload),
#[prost(message, tag="13")]
ExecCmdPayload(super::ExecCmdPayload),
#[prost(message, tag="14")]
PostMessageToPayload(super::PluginMessagePayload),
#[prost(message, tag="15")]
PostMessageToPluginPayload(super::PluginMessagePayload),
#[prost(bool, tag="16")]
ShowSelfPayload(bool),
#[prost(message, tag="17")]
SwitchToModePayload(super::super::action::SwitchToModePayload),
#[prost(string, tag="18")]
NewTabsWithLayoutPayload(::prost::alloc::string::String),
#[prost(message, tag="19")]
ResizePayload(super::ResizePayload),
#[prost(message, tag="20")]
ResizeWithDirectionPayload(super::ResizePayload),
#[prost(message, tag="21")]
MoveFocusPayload(super::MovePayload),
#[prost(message, tag="22")]
MoveFocusOrTabPayload(super::MovePayload),
#[prost(bytes, tag="23")]
WritePayload(::prost::alloc::vec::Vec<u8>),
#[prost(string, tag="24")]
WriteCharsPayload(::prost::alloc::string::String),
#[prost(message, tag="25")]
MovePaneWithDirectionPayload(super::MovePayload),
#[prost(string, tag="26")]
GoToTabNamePayload(::prost::alloc::string::String),
#[prost(string, tag="27")]
FocusOrCreateTabPayload(::prost::alloc::string::String),
#[prost(uint32, tag="28")]
GoToTabPayload(u32),
#[prost(string, tag="29")]
StartOrReloadPluginPayload(::prost::alloc::string::String),
#[prost(uint32, tag="30")]
CloseTerminalPanePayload(u32),
#[prost(uint32, tag="31")]
ClosePluginPanePayload(u32),
#[prost(message, tag="32")]
FocusTerminalPanePayload(super::super::action::PaneIdAndShouldFloat),
#[prost(message, tag="33")]
FocusPluginPanePayload(super::super::action::PaneIdAndShouldFloat),
#[prost(message, tag="34")]
RenameTerminalPanePayload(super::IdAndNewName),
#[prost(message, tag="35")]
RenamePluginPanePayload(super::IdAndNewName),
#[prost(message, tag="36")]
RenameTabPayload(super::IdAndNewName),
#[prost(string, tag="37")]
ReportCrashPayload(::prost::alloc::string::String),
#[prost(message, tag="38")]
RequestPluginPermissionPayload(super::RequestPluginPermissionPayload),
#[prost(message, tag="39")]
SwitchSessionPayload(super::SwitchSessionPayload),
#[prost(message, tag="40")]
OpenFileInPlacePayload(super::OpenFilePayload),
#[prost(message, tag="41")]
OpenTerminalInPlacePayload(super::OpenFilePayload),
#[prost(message, tag="42")]
OpenCommandPaneInPlacePayload(super::OpenCommandPanePayload),
#[prost(message, tag="43")]
RunCommandPayload(super::RunCommandPayload),
#[prost(message, tag="44")]
WebRequestPayload(super::WebRequestPayload),
#[prost(string, tag="45")]
DeleteDeadSessionPayload(::prost::alloc::string::String),
#[prost(string, tag="46")]
RenameSessionPayload(::prost::alloc::string::String),
#[prost(string, tag="47")]
UnblockCliPipeInputPayload(::prost::alloc::string::String),
#[prost(string, tag="48")]
BlockCliPipeInputPayload(::prost::alloc::string::String),
#[prost(message, tag="49")]
CliPipeOutputPayload(super::CliPipeOutputPayload),
#[prost(message, tag="50")]
MessageToPluginPayload(super::MessageToPluginPayload),
#[prost(message, tag="60")]
KillSessionsPayload(super::KillSessionsPayload),
#[prost(string, tag="61")]
ScanHostFolderPayload(::prost::alloc::string::String),
#[prost(message, tag="62")]
NewTabsWithLayoutInfoPayload(super::NewTabsWithLayoutInfoPayload),
#[prost(message, tag="63")]
ReconfigurePayload(super::ReconfigurePayload),
#[prost(message, tag="64")]
HidePaneWithIdPayload(super::HidePaneWithIdPayload),
#[prost(message, tag="65")]
ShowPaneWithIdPayload(super::ShowPaneWithIdPayload),
#[prost(message, tag="66")]
OpenCommandPaneBackgroundPayload(super::OpenCommandPanePayload),
#[prost(message, tag="67")]
RerunCommandPanePayload(super::RerunCommandPanePayload),
#[prost(message, tag="68")]
ResizePaneIdWithDirectionPayload(super::ResizePaneIdWithDirectionPayload),
#[prost(message, tag="69")]
EditScrollbackForPaneWithIdPayload(super::EditScrollbackForPaneWithIdPayload),
#[prost(message, tag="70")]
WriteToPaneIdPayload(super::WriteToPaneIdPayload),
#[prost(message, tag="71")]
WriteCharsToPaneIdPayload(super::WriteCharsToPaneIdPayload),
#[prost(message, tag="72")]
MovePaneWithPaneIdPayload(super::MovePaneWithPaneIdPayload),
#[prost(message, tag="73")]
MovePaneWithPaneIdInDirectionPayload(super::MovePaneWithPaneIdInDirectionPayload),
#[prost(message, tag="74")]
ClearScreenForPaneIdPayload(super::ClearScreenForPaneIdPayload),
#[prost(message, tag="75")]
ScrollUpInPaneIdPayload(super::ScrollUpInPaneIdPayload),
#[prost(message, tag="76")]
ScrollDownInPaneIdPayload(super::ScrollDownInPaneIdPayload),
#[prost(message, tag="77")]
ScrollToTopInPaneIdPayload(super::ScrollToTopInPaneIdPayload),
#[prost(message, tag="78")]
ScrollToBottomInPaneIdPayload(super::ScrollToBottomInPaneIdPayload),
#[prost(message, tag="79")]
PageScrollUpInPaneIdPayload(super::PageScrollUpInPaneIdPayload),
#[prost(message, tag="80")]
PageScrollDownInPaneIdPayload(super::PageScrollDownInPaneIdPayload),
#[prost(message, tag="81")]
TogglePaneIdFullscreenPayload(super::TogglePaneIdFullscreenPayload),
#[prost(message, tag="82")]
TogglePaneEmbedOrEjectForPaneIdPayload(super::TogglePaneEmbedOrEjectForPaneIdPayload),
#[prost(message, tag="83")]
CloseTabWithIndexPayload(super::CloseTabWithIndexPayload),
#[prost(message, tag="84")]
BreakPanesToNewTabPayload(super::BreakPanesToNewTabPayload),
#[prost(message, tag="85")]
BreakPanesToTabWithIndexPayload(super::BreakPanesToTabWithIndexPayload),
#[prost(message, tag="86")]
ReloadPluginPayload(super::ReloadPluginPayload),
#[prost(message, tag="87")]
LoadNewPluginPayload(super::LoadNewPluginPayload),
#[prost(message, tag="88")]
RebindKeysPayload(super::RebindKeysPayload),
#[prost(message, tag="89")]
ChangeHostFolderPayload(super::ChangeHostFolderPayload),
#[prost(message, tag="90")]
SetFloatingPanePinnedPayload(super::SetFloatingPanePinnedPayload),
#[prost(message, tag="91")]
StackPanesPayload(super::StackPanesPayload),
#[prost(message, tag="92")]
ChangeFloatingPanesCoordinatesPayload(super::ChangeFloatingPanesCoordinatesPayload),
#[prost(message, tag="93")]
OpenCommandPaneNearPluginPayload(super::OpenCommandPaneNearPluginPayload),
#[prost(message, tag="94")]
OpenTerminalNearPluginPayload(super::OpenTerminalNearPluginPayload),
#[prost(message, tag="95")]
OpenTerminalFloatingNearPluginPayload(super::OpenTerminalFloatingNearPluginPayload),
#[prost(message, tag="96")]
OpenTerminalInPlaceOfPluginPayload(super::OpenTerminalInPlaceOfPluginPayload),
#[prost(message, tag="97")]
OpenCommandPaneFloatingNearPluginPayload(super::OpenCommandPaneFloatingNearPluginPayload),
#[prost(message, tag="98")]
OpenCommandPaneInPlaceOfPluginPayload(super::OpenCommandPaneInPlaceOfPluginPayload),
#[prost(message, tag="99")]
OpenFileNearPluginPayload(super::OpenFileNearPluginPayload),
#[prost(message, tag="100")]
OpenFileFloatingNearPluginPayload(super::OpenFileFloatingNearPluginPayload),
#[prost(message, tag="101")]
OpenFileInPlaceOfPluginPayload(super::OpenFileInPlaceOfPluginPayload),
#[prost(message, tag="102")]
GroupAndUngroupPanesPayload(super::GroupAndUngroupPanesPayload),
#[prost(message, tag="103")]
HighlightAndUnhighlightPanesPayload(super::HighlightAndUnhighlightPanesPayload),
#[prost(message, tag="104")]
CloseMultiplePanesPayload(super::CloseMultiplePanesPayload),
#[prost(message, tag="105")]
FloatMultiplePanesPayload(super::FloatMultiplePanesPayload),
#[prost(message, tag="106")]
EmbedMultiplePanesPayload(super::EmbedMultiplePanesPayload),
#[prost(message, tag="107")]
SetSelfMouseSelectionSupportPayload(super::SetSelfMouseSelectionSupportPayload),
#[prost(message, tag="108")]
GenerateWebLoginTokenPayload(super::GenerateWebLoginTokenPayload),
#[prost(message, tag="109")]
RevokeWebLoginTokenPayload(super::RevokeWebLoginTokenPayload),
#[prost(message, tag="110")]
RenameWebLoginTokenPayload(super::RenameWebLoginTokenPayload),
#[prost(message, tag="111")]
ReplacePaneWithExistingPanePayload(super::ReplacePaneWithExistingPanePayload),
#[prost(message, tag="112")]
NewTabPayload(super::NewTabPayload),
#[prost(message, tag="113")]
GetPaneScrollbackPayload(super::GetPaneScrollbackPayload),
#[prost(message, tag="114")]
RunActionPayload(super::RunActionPayload),
#[prost(message, tag="119")]
ShowCursorPayload(super::ShowCursorPayload),
#[prost(message, tag="120")]
CopyToClipboardPayload(super::CopyToClipboardPayload),
#[prost(message, tag="121")]
SendSigintToPaneIdPayload(super::PaneId),
#[prost(message, tag="122")]
SendSigkillToPaneIdPayload(super::PaneId),
#[prost(message, tag="123")]
GetPanePidPayload(super::GetPanePidPayload),
}
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct NewTabPayload {
#[prost(string, optional, tag="1")]
pub name: ::core::option::Option<::prost::alloc::string::String>,
#[prost(string, optional, tag="2")]
pub cwd: ::core::option::Option<::prost::alloc::string::String>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct RunActionPayload {
#[prost(message, optional, tag="1")]
pub action: ::core::option::Option<super::action::Action>,
#[prost(message, repeated, tag="2")]
pub context: ::prost::alloc::vec::Vec<ContextItem>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ReplacePaneWithExistingPanePayload {
#[prost(message, optional, tag="1")]
pub pane_id_to_replace: ::core::option::Option<PaneId>,
#[prost(message, optional, tag="2")]
pub existing_pane_id: ::core::option::Option<PaneId>,
#[prost(bool, tag="3")]
pub suppress_replaced_pane: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct RenameWebLoginTokenPayload {
#[prost(string, tag="1")]
pub old_name: ::prost::alloc::string::String,
#[prost(string, tag="2")]
pub new_name: ::prost::alloc::string::String,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct RevokeWebLoginTokenPayload {
#[prost(string, tag="1")]
pub token_label: ::prost::alloc::string::String,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct GenerateWebLoginTokenPayload {
#[prost(string, optional, tag="1")]
pub token_label: ::core::option::Option<::prost::alloc::string::String>,
#[prost(bool, optional, tag="2")]
pub read_only: ::core::option::Option<bool>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct SetSelfMouseSelectionSupportPayload {
#[prost(bool, tag="1")]
pub support_mouse_selection: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct EmbedMultiplePanesPayload {
#[prost(message, repeated, tag="1")]
pub pane_ids: ::prost::alloc::vec::Vec<PaneId>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct FloatMultiplePanesPayload {
#[prost(message, repeated, tag="1")]
pub pane_ids: ::prost::alloc::vec::Vec<PaneId>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CloseMultiplePanesPayload {
#[prost(message, repeated, tag="1")]
pub pane_ids: ::prost::alloc::vec::Vec<PaneId>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct HighlightAndUnhighlightPanesPayload {
#[prost(message, repeated, tag="1")]
pub pane_ids_to_highlight: ::prost::alloc::vec::Vec<PaneId>,
#[prost(message, repeated, tag="2")]
pub pane_ids_to_unhighlight: ::prost::alloc::vec::Vec<PaneId>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct GroupAndUngroupPanesPayload {
#[prost(message, repeated, tag="1")]
pub pane_ids_to_group: ::prost::alloc::vec::Vec<PaneId>,
#[prost(message, repeated, tag="2")]
pub pane_ids_to_ungroup: ::prost::alloc::vec::Vec<PaneId>,
#[prost(bool, tag="3")]
pub for_all_clients: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct OpenFileInPlaceOfPluginPayload {
#[prost(message, optional, tag="1")]
pub file_to_open: ::core::option::Option<super::file::File>,
#[prost(message, optional, tag="2")]
pub floating_pane_coordinates: ::core::option::Option<FloatingPaneCoordinates>,
#[prost(message, repeated, tag="3")]
pub context: ::prost::alloc::vec::Vec<ContextItem>,
#[prost(bool, tag="4")]
pub close_plugin_after_replace: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct OpenFileFloatingNearPluginPayload {
#[prost(message, optional, tag="1")]
pub file_to_open: ::core::option::Option<super::file::File>,
#[prost(message, optional, tag="2")]
pub floating_pane_coordinates: ::core::option::Option<FloatingPaneCoordinates>,
#[prost(message, repeated, tag="3")]
pub context: ::prost::alloc::vec::Vec<ContextItem>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct OpenFileNearPluginPayload {
#[prost(message, optional, tag="1")]
pub file_to_open: ::core::option::Option<super::file::File>,
#[prost(message, optional, tag="2")]
pub floating_pane_coordinates: ::core::option::Option<FloatingPaneCoordinates>,
#[prost(message, repeated, tag="3")]
pub context: ::prost::alloc::vec::Vec<ContextItem>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct OpenCommandPaneInPlaceOfPluginPayload {
#[prost(message, optional, tag="1")]
pub command_to_run: ::core::option::Option<super::command::Command>,
#[prost(message, repeated, tag="3")]
pub context: ::prost::alloc::vec::Vec<ContextItem>,
#[prost(bool, tag="4")]
pub close_plugin_after_replace: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct OpenCommandPaneFloatingNearPluginPayload {
#[prost(message, optional, tag="1")]
pub command_to_run: ::core::option::Option<super::command::Command>,
#[prost(message, optional, tag="2")]
pub floating_pane_coordinates: ::core::option::Option<FloatingPaneCoordinates>,
#[prost(message, repeated, tag="3")]
pub context: ::prost::alloc::vec::Vec<ContextItem>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct OpenTerminalInPlaceOfPluginPayload {
#[prost(message, optional, tag="1")]
pub file_to_open: ::core::option::Option<super::file::File>,
#[prost(message, repeated, tag="3")]
pub context: ::prost::alloc::vec::Vec<ContextItem>,
#[prost(bool, tag="4")]
pub close_plugin_after_replace: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct OpenTerminalFloatingNearPluginPayload {
#[prost(message, optional, tag="1")]
pub file_to_open: ::core::option::Option<super::file::File>,
#[prost(message, optional, tag="2")]
pub floating_pane_coordinates: ::core::option::Option<FloatingPaneCoordinates>,
#[prost(message, repeated, tag="3")]
pub context: ::prost::alloc::vec::Vec<ContextItem>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct OpenTerminalNearPluginPayload {
#[prost(message, optional, tag="1")]
pub file_to_open: ::core::option::Option<super::file::File>,
#[prost(message, repeated, tag="3")]
pub context: ::prost::alloc::vec::Vec<ContextItem>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct OpenCommandPaneNearPluginPayload {
#[prost(message, optional, tag="1")]
pub command_to_run: ::core::option::Option<super::command::Command>,
#[prost(message, optional, tag="2")]
pub floating_pane_coordinates: ::core::option::Option<FloatingPaneCoordinates>,
#[prost(message, repeated, tag="3")]
pub context: ::prost::alloc::vec::Vec<ContextItem>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ChangeFloatingPanesCoordinatesPayload {
#[prost(message, repeated, tag="1")]
pub pane_ids_and_floating_panes_coordinates: ::prost::alloc::vec::Vec<PaneIdAndFloatingPaneCoordinates>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct StackPanesPayload {
#[prost(message, repeated, tag="1")]
pub pane_ids: ::prost::alloc::vec::Vec<PaneId>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct SetFloatingPanePinnedPayload {
#[prost(message, optional, tag="1")]
pub pane_id: ::core::option::Option<PaneId>,
#[prost(bool, tag="2")]
pub should_be_pinned: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ChangeHostFolderPayload {
#[prost(string, tag="1")]
pub new_host_folder: ::prost::alloc::string::String,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct RebindKeysPayload {
#[prost(message, repeated, tag="1")]
pub keys_to_rebind: ::prost::alloc::vec::Vec<KeyToRebind>,
#[prost(message, repeated, tag="2")]
pub keys_to_unbind: ::prost::alloc::vec::Vec<KeyToUnbind>,
#[prost(bool, tag="3")]
pub write_config_to_disk: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct KeyToRebind {
#[prost(enumeration="super::input_mode::InputMode", tag="1")]
pub input_mode: i32,
#[prost(message, optional, tag="2")]
pub key: ::core::option::Option<super::key::Key>,
#[prost(message, repeated, tag="3")]
pub actions: ::prost::alloc::vec::Vec<super::action::Action>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct KeyToUnbind {
#[prost(enumeration="super::input_mode::InputMode", tag="1")]
pub input_mode: i32,
#[prost(message, optional, tag="2")]
pub key: ::core::option::Option<super::key::Key>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct LoadNewPluginPayload {
#[prost(string, tag="1")]
pub plugin_url: ::prost::alloc::string::String,
#[prost(message, repeated, tag="2")]
pub plugin_config: ::prost::alloc::vec::Vec<ContextItem>,
#[prost(bool, tag="3")]
pub should_load_plugin_in_background: bool,
#[prost(bool, tag="4")]
pub should_skip_plugin_cache: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ReloadPluginPayload {
#[prost(uint32, tag="1")]
pub plugin_id: u32,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct BreakPanesToTabWithIndexPayload {
#[prost(message, repeated, tag="1")]
pub pane_ids: ::prost::alloc::vec::Vec<PaneId>,
#[prost(uint32, tag="2")]
pub tab_index: u32,
#[prost(bool, tag="3")]
pub should_change_focus_to_target_tab: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct BreakPanesToNewTabPayload {
#[prost(message, repeated, tag="1")]
pub pane_ids: ::prost::alloc::vec::Vec<PaneId>,
#[prost(bool, tag="2")]
pub should_change_focus_to_new_tab: bool,
#[prost(string, optional, tag="3")]
pub new_tab_name: ::core::option::Option<::prost::alloc::string::String>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct MovePaneWithPaneIdPayload {
#[prost(message, optional, tag="1")]
pub pane_id: ::core::option::Option<PaneId>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct MovePaneWithPaneIdInDirectionPayload {
#[prost(message, optional, tag="1")]
pub pane_id: ::core::option::Option<PaneId>,
#[prost(message, optional, tag="2")]
pub direction: ::core::option::Option<super::resize::MoveDirection>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ClearScreenForPaneIdPayload {
#[prost(message, optional, tag="1")]
pub pane_id: ::core::option::Option<PaneId>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ScrollUpInPaneIdPayload {
#[prost(message, optional, tag="1")]
pub pane_id: ::core::option::Option<PaneId>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ScrollDownInPaneIdPayload {
#[prost(message, optional, tag="1")]
pub pane_id: ::core::option::Option<PaneId>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ScrollToTopInPaneIdPayload {
#[prost(message, optional, tag="1")]
pub pane_id: ::core::option::Option<PaneId>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ScrollToBottomInPaneIdPayload {
#[prost(message, optional, tag="1")]
pub pane_id: ::core::option::Option<PaneId>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PageScrollUpInPaneIdPayload {
#[prost(message, optional, tag="1")]
pub pane_id: ::core::option::Option<PaneId>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PageScrollDownInPaneIdPayload {
#[prost(message, optional, tag="1")]
pub pane_id: ::core::option::Option<PaneId>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct TogglePaneIdFullscreenPayload {
#[prost(message, optional, tag="1")]
pub pane_id: ::core::option::Option<PaneId>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct TogglePaneEmbedOrEjectForPaneIdPayload {
#[prost(message, optional, tag="1")]
pub pane_id: ::core::option::Option<PaneId>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CloseTabWithIndexPayload {
#[prost(uint32, tag="1")]
pub tab_index: u32,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct WriteCharsToPaneIdPayload {
#[prost(string, tag="1")]
pub chars_to_write: ::prost::alloc::string::String,
#[prost(message, optional, tag="2")]
pub pane_id: ::core::option::Option<PaneId>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct WriteToPaneIdPayload {
#[prost(bytes="vec", tag="1")]
pub bytes_to_write: ::prost::alloc::vec::Vec<u8>,
#[prost(message, optional, tag="2")]
pub pane_id: ::core::option::Option<PaneId>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct EditScrollbackForPaneWithIdPayload {
#[prost(message, optional, tag="1")]
pub pane_id: ::core::option::Option<PaneId>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ResizePaneIdWithDirectionPayload {
#[prost(message, optional, tag="1")]
pub resize: ::core::option::Option<super::resize::Resize>,
#[prost(message, optional, tag="2")]
pub pane_id: ::core::option::Option<PaneId>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ReconfigurePayload {
#[prost(string, tag="1")]
pub config: ::prost::alloc::string::String,
#[prost(bool, tag="2")]
pub write_to_disk: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct RerunCommandPanePayload {
#[prost(uint32, tag="1")]
pub terminal_pane_id: u32,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct HidePaneWithIdPayload {
#[prost(message, optional, tag="1")]
pub pane_id: ::core::option::Option<PaneId>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ShowPaneWithIdPayload {
#[prost(message, optional, tag="1")]
pub pane_id: ::core::option::Option<PaneId>,
#[prost(bool, tag="2")]
pub should_float_if_hidden: bool,
#[prost(bool, tag="3")]
pub should_focus_pane: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct NewTabsWithLayoutInfoPayload {
#[prost(message, optional, tag="1")]
pub layout_info: ::core::option::Option<super::event::LayoutInfo>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct KillSessionsPayload {
#[prost(string, repeated, tag="1")]
pub session_names: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CliPipeOutputPayload {
#[prost(string, tag="1")]
pub pipe_name: ::prost::alloc::string::String,
#[prost(string, tag="2")]
pub output: ::prost::alloc::string::String,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct MessageToPluginPayload {
#[prost(string, optional, tag="1")]
pub plugin_url: ::core::option::Option<::prost::alloc::string::String>,
#[prost(message, repeated, tag="2")]
pub plugin_config: ::prost::alloc::vec::Vec<ContextItem>,
#[prost(string, tag="3")]
pub message_name: ::prost::alloc::string::String,
#[prost(string, optional, tag="4")]
pub message_payload: ::core::option::Option<::prost::alloc::string::String>,
#[prost(message, repeated, tag="5")]
pub message_args: ::prost::alloc::vec::Vec<ContextItem>,
#[prost(message, optional, tag="6")]
pub new_plugin_args: ::core::option::Option<NewPluginArgs>,
#[prost(uint32, optional, tag="7")]
pub destination_plugin_id: ::core::option::Option<u32>,
#[prost(message, optional, tag="8")]
pub floating_pane_coordinates: ::core::option::Option<FloatingPaneCoordinates>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct NewPluginArgs {
#[prost(bool, optional, tag="1")]
pub should_float: ::core::option::Option<bool>,
#[prost(message, optional, tag="2")]
pub pane_id_to_replace: ::core::option::Option<PaneId>,
#[prost(string, optional, tag="3")]
pub pane_title: ::core::option::Option<::prost::alloc::string::String>,
#[prost(string, optional, tag="4")]
pub cwd: ::core::option::Option<::prost::alloc::string::String>,
#[prost(bool, tag="5")]
pub skip_cache: bool,
#[prost(bool, optional, tag="6")]
pub should_focus: ::core::option::Option<bool>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PaneId {
#[prost(enumeration="PaneType", tag="1")]
pub pane_type: i32,
#[prost(uint32, tag="2")]
pub id: u32,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct SwitchSessionPayload {
#[prost(string, optional, tag="1")]
pub name: ::core::option::Option<::prost::alloc::string::String>,
#[prost(uint32, optional, tag="2")]
pub tab_position: ::core::option::Option<u32>,
#[prost(uint32, optional, tag="3")]
pub pane_id: ::core::option::Option<u32>,
#[prost(bool, optional, tag="4")]
pub pane_id_is_plugin: ::core::option::Option<bool>,
#[prost(message, optional, tag="5")]
pub layout: ::core::option::Option<super::event::LayoutInfo>,
#[prost(string, optional, tag="6")]
pub cwd: ::core::option::Option<::prost::alloc::string::String>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct RequestPluginPermissionPayload {
#[prost(enumeration="super::plugin_permission::PermissionType", repeated, tag="1")]
pub permissions: ::prost::alloc::vec::Vec<i32>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct SubscribePayload {
#[prost(message, optional, tag="1")]
pub subscriptions: ::core::option::Option<super::event::EventNameList>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct UnsubscribePayload {
#[prost(message, optional, tag="1")]
pub subscriptions: ::core::option::Option<super::event::EventNameList>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct OpenFilePayload {
#[prost(message, optional, tag="1")]
pub file_to_open: ::core::option::Option<super::file::File>,
#[prost(message, optional, tag="2")]
pub floating_pane_coordinates: ::core::option::Option<FloatingPaneCoordinates>,
#[prost(message, repeated, tag="3")]
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/assets/prost/api.plugin_permission.rs | zellij-utils/assets/prost/api.plugin_permission.rs | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
#[repr(i32)]
pub enum PermissionType {
ReadApplicationState = 0,
ChangeApplicationState = 1,
OpenFiles = 2,
RunCommands = 3,
OpenTerminalsOrPlugins = 4,
WriteToStdin = 5,
WebAccess = 6,
ReadCliPipes = 7,
MessageAndLaunchOtherPlugins = 8,
Reconfigure = 9,
FullHdAccess = 10,
StartWebServer = 11,
InterceptInput = 12,
ReadPaneContents = 13,
RunActionsAsUser = 14,
WriteToClipboard = 15,
}
impl PermissionType {
/// String value of the enum field names used in the ProtoBuf definition.
///
/// The values are not transformed in any way and thus are considered stable
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
pub fn as_str_name(&self) -> &'static str {
match self {
PermissionType::ReadApplicationState => "ReadApplicationState",
PermissionType::ChangeApplicationState => "ChangeApplicationState",
PermissionType::OpenFiles => "OpenFiles",
PermissionType::RunCommands => "RunCommands",
PermissionType::OpenTerminalsOrPlugins => "OpenTerminalsOrPlugins",
PermissionType::WriteToStdin => "WriteToStdin",
PermissionType::WebAccess => "WebAccess",
PermissionType::ReadCliPipes => "ReadCliPipes",
PermissionType::MessageAndLaunchOtherPlugins => "MessageAndLaunchOtherPlugins",
PermissionType::Reconfigure => "Reconfigure",
PermissionType::FullHdAccess => "FullHdAccess",
PermissionType::StartWebServer => "StartWebServer",
PermissionType::InterceptInput => "InterceptInput",
PermissionType::ReadPaneContents => "ReadPaneContents",
PermissionType::RunActionsAsUser => "RunActionsAsUser",
PermissionType::WriteToClipboard => "WriteToClipboard",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
pub fn from_str_name(value: &str) -> ::core::option::Option<Self> {
match value {
"ReadApplicationState" => Some(Self::ReadApplicationState),
"ChangeApplicationState" => Some(Self::ChangeApplicationState),
"OpenFiles" => Some(Self::OpenFiles),
"RunCommands" => Some(Self::RunCommands),
"OpenTerminalsOrPlugins" => Some(Self::OpenTerminalsOrPlugins),
"WriteToStdin" => Some(Self::WriteToStdin),
"WebAccess" => Some(Self::WebAccess),
"ReadCliPipes" => Some(Self::ReadCliPipes),
"MessageAndLaunchOtherPlugins" => Some(Self::MessageAndLaunchOtherPlugins),
"Reconfigure" => Some(Self::Reconfigure),
"FullHdAccess" => Some(Self::FullHdAccess),
"StartWebServer" => Some(Self::StartWebServer),
"InterceptInput" => Some(Self::InterceptInput),
"ReadPaneContents" => Some(Self::ReadPaneContents),
"RunActionsAsUser" => Some(Self::RunActionsAsUser),
"WriteToClipboard" => Some(Self::WriteToClipboard),
_ => None,
}
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/assets/prost/api.file.rs | zellij-utils/assets/prost/api.file.rs | #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct File {
#[prost(string, tag="1")]
pub path: ::prost::alloc::string::String,
#[prost(int32, optional, tag="2")]
pub line_number: ::core::option::Option<i32>,
#[prost(string, optional, tag="3")]
pub cwd: ::core::option::Option<::prost::alloc::string::String>,
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/assets/prost_ipc/client_server_contract.rs | zellij-utils/assets/prost_ipc/client_server_contract.rs | #[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Size {
#[prost(uint32, tag="1")]
pub cols: u32,
#[prost(uint32, tag="2")]
pub rows: u32,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PixelDimensions {
#[prost(message, optional, tag="1")]
pub text_area_size: ::core::option::Option<SizeInPixels>,
#[prost(message, optional, tag="2")]
pub character_cell_size: ::core::option::Option<SizeInPixels>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct SizeInPixels {
#[prost(uint32, tag="1")]
pub width: u32,
#[prost(uint32, tag="2")]
pub height: u32,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PaneReference {
#[prost(uint32, tag="1")]
pub pane_id: u32,
#[prost(bool, tag="2")]
pub is_plugin: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ColorRegister {
#[prost(uint32, tag="1")]
pub index: u32,
#[prost(string, tag="2")]
pub color: ::prost::alloc::string::String,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct KeyWithModifier {
#[prost(enumeration="BareKey", tag="1")]
pub bare_key: i32,
#[prost(enumeration="KeyModifier", repeated, tag="2")]
pub key_modifiers: ::prost::alloc::vec::Vec<i32>,
/// Only set when bare_key is CHAR
#[prost(string, optional, tag="3")]
pub character: ::core::option::Option<::prost::alloc::string::String>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CharKey {
#[prost(string, tag="1")]
pub character: ::prost::alloc::string::String,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct FunctionKey {
#[prost(uint32, tag="1")]
pub function_number: u32,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Style {
#[prost(message, optional, tag="1")]
pub colors: ::core::option::Option<Styling>,
#[prost(bool, tag="2")]
pub rounded_corners: bool,
#[prost(bool, tag="3")]
pub hide_session_name: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Styling {
#[prost(message, optional, tag="1")]
pub base: ::core::option::Option<PaletteColor>,
#[prost(message, optional, tag="2")]
pub background: ::core::option::Option<PaletteColor>,
#[prost(message, optional, tag="3")]
pub emphasis_0: ::core::option::Option<PaletteColor>,
#[prost(message, optional, tag="4")]
pub emphasis_1: ::core::option::Option<PaletteColor>,
#[prost(message, optional, tag="5")]
pub emphasis_2: ::core::option::Option<PaletteColor>,
#[prost(message, optional, tag="6")]
pub emphasis_3: ::core::option::Option<PaletteColor>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PaletteColor {
#[prost(oneof="palette_color::ColorType", tags="1, 2, 3")]
pub color_type: ::core::option::Option<palette_color::ColorType>,
}
/// Nested message and enum types in `PaletteColor`.
pub mod palette_color {
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum ColorType {
#[prost(message, tag="1")]
Rgb(super::RgbColor),
#[prost(uint32, tag="2")]
EightBit(u32),
#[prost(enumeration="super::AnsiCode", tag="3")]
Ansi(i32),
}
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct RgbColor {
#[prost(uint32, tag="1")]
pub r: u32,
#[prost(uint32, tag="2")]
pub g: u32,
#[prost(uint32, tag="3")]
pub b: u32,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Action {
#[prost(oneof="action::ActionType", tags="1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94")]
pub action_type: ::core::option::Option<action::ActionType>,
}
/// Nested message and enum types in `Action`.
pub mod action {
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum ActionType {
#[prost(message, tag="1")]
Quit(super::QuitAction),
#[prost(message, tag="2")]
Write(super::WriteAction),
#[prost(message, tag="3")]
WriteChars(super::WriteCharsAction),
#[prost(message, tag="4")]
SwitchToMode(super::SwitchToModeAction),
#[prost(message, tag="5")]
SwitchModeForAllClients(super::SwitchModeForAllClientsAction),
#[prost(message, tag="6")]
Resize(super::ResizeAction),
#[prost(message, tag="7")]
FocusNextPane(super::FocusNextPaneAction),
#[prost(message, tag="8")]
FocusPreviousPane(super::FocusPreviousPaneAction),
#[prost(message, tag="9")]
SwitchFocus(super::SwitchFocusAction),
#[prost(message, tag="10")]
MoveFocus(super::MoveFocusAction),
#[prost(message, tag="11")]
MoveFocusOrTab(super::MoveFocusOrTabAction),
#[prost(message, tag="12")]
MovePane(super::MovePaneAction),
#[prost(message, tag="13")]
MovePaneBackwards(super::MovePaneBackwardsAction),
#[prost(message, tag="14")]
ClearScreen(super::ClearScreenAction),
#[prost(message, tag="15")]
DumpScreen(super::DumpScreenAction),
#[prost(message, tag="16")]
DumpLayout(super::DumpLayoutAction),
#[prost(message, tag="17")]
EditScrollback(super::EditScrollbackAction),
#[prost(message, tag="18")]
ScrollUp(super::ScrollUpAction),
#[prost(message, tag="19")]
ScrollUpAt(super::ScrollUpAtAction),
#[prost(message, tag="20")]
ScrollDown(super::ScrollDownAction),
#[prost(message, tag="21")]
ScrollDownAt(super::ScrollDownAtAction),
#[prost(message, tag="22")]
ScrollToBottom(super::ScrollToBottomAction),
#[prost(message, tag="23")]
ScrollToTop(super::ScrollToTopAction),
#[prost(message, tag="24")]
PageScrollUp(super::PageScrollUpAction),
#[prost(message, tag="25")]
PageScrollDown(super::PageScrollDownAction),
#[prost(message, tag="26")]
HalfPageScrollUp(super::HalfPageScrollUpAction),
#[prost(message, tag="27")]
HalfPageScrollDown(super::HalfPageScrollDownAction),
#[prost(message, tag="28")]
ToggleFocusFullscreen(super::ToggleFocusFullscreenAction),
#[prost(message, tag="29")]
TogglePaneFrames(super::TogglePaneFramesAction),
#[prost(message, tag="30")]
ToggleActiveSyncTab(super::ToggleActiveSyncTabAction),
#[prost(message, tag="31")]
NewPane(super::NewPaneAction),
#[prost(message, tag="32")]
EditFile(super::EditFileAction),
#[prost(message, tag="33")]
NewFloatingPane(super::NewFloatingPaneAction),
#[prost(message, tag="34")]
NewTiledPane(super::NewTiledPaneAction),
#[prost(message, tag="35")]
NewInPlacePane(super::NewInPlacePaneAction),
#[prost(message, tag="36")]
NewStackedPane(super::NewStackedPaneAction),
#[prost(message, tag="37")]
TogglePaneEmbedOrFloating(super::TogglePaneEmbedOrFloatingAction),
#[prost(message, tag="38")]
ToggleFloatingPanes(super::ToggleFloatingPanesAction),
#[prost(message, tag="39")]
CloseFocus(super::CloseFocusAction),
#[prost(message, tag="40")]
PaneNameInput(super::PaneNameInputAction),
#[prost(message, tag="41")]
UndoRenamePane(super::UndoRenamePaneAction),
#[prost(message, tag="42")]
NewTab(super::NewTabAction),
#[prost(message, tag="43")]
NoOp(super::NoOpAction),
#[prost(message, tag="44")]
GoToNextTab(super::GoToNextTabAction),
#[prost(message, tag="45")]
GoToPreviousTab(super::GoToPreviousTabAction),
#[prost(message, tag="46")]
CloseTab(super::CloseTabAction),
#[prost(message, tag="47")]
GoToTab(super::GoToTabAction),
#[prost(message, tag="48")]
GoToTabName(super::GoToTabNameAction),
#[prost(message, tag="49")]
ToggleTab(super::ToggleTabAction),
#[prost(message, tag="50")]
TabNameInput(super::TabNameInputAction),
#[prost(message, tag="51")]
UndoRenameTab(super::UndoRenameTabAction),
#[prost(message, tag="52")]
MoveTab(super::MoveTabAction),
#[prost(message, tag="53")]
Run(super::RunAction),
#[prost(message, tag="54")]
Detach(super::DetachAction),
#[prost(message, tag="55")]
LaunchOrFocusPlugin(super::LaunchOrFocusPluginAction),
#[prost(message, tag="56")]
LaunchPlugin(super::LaunchPluginAction),
#[prost(message, tag="57")]
MouseEvent(super::MouseEventAction),
#[prost(message, tag="58")]
Copy(super::CopyAction),
#[prost(message, tag="59")]
Confirm(super::ConfirmAction),
#[prost(message, tag="60")]
Deny(super::DenyAction),
#[prost(message, tag="61")]
SkipConfirm(::prost::alloc::boxed::Box<super::SkipConfirmAction>),
#[prost(message, tag="62")]
SearchInput(super::SearchInputAction),
#[prost(message, tag="63")]
Search(super::SearchAction),
#[prost(message, tag="64")]
SearchToggleOption(super::SearchToggleOptionAction),
#[prost(message, tag="65")]
ToggleMouseMode(super::ToggleMouseModeAction),
#[prost(message, tag="66")]
PreviousSwapLayout(super::PreviousSwapLayoutAction),
#[prost(message, tag="67")]
NextSwapLayout(super::NextSwapLayoutAction),
#[prost(message, tag="68")]
QueryTabNames(super::QueryTabNamesAction),
#[prost(message, tag="69")]
NewTiledPluginPane(super::NewTiledPluginPaneAction),
#[prost(message, tag="70")]
NewFloatingPluginPane(super::NewFloatingPluginPaneAction),
#[prost(message, tag="71")]
NewInPlacePluginPane(super::NewInPlacePluginPaneAction),
#[prost(message, tag="72")]
StartOrReloadPlugin(super::StartOrReloadPluginAction),
#[prost(message, tag="73")]
CloseTerminalPane(super::CloseTerminalPaneAction),
#[prost(message, tag="74")]
ClosePluginPane(super::ClosePluginPaneAction),
#[prost(message, tag="75")]
FocusTerminalPaneWithId(super::FocusTerminalPaneWithIdAction),
#[prost(message, tag="76")]
FocusPluginPaneWithId(super::FocusPluginPaneWithIdAction),
#[prost(message, tag="77")]
RenameTerminalPane(super::RenameTerminalPaneAction),
#[prost(message, tag="78")]
RenamePluginPane(super::RenamePluginPaneAction),
#[prost(message, tag="79")]
RenameTab(super::RenameTabAction),
#[prost(message, tag="80")]
BreakPane(super::BreakPaneAction),
#[prost(message, tag="81")]
BreakPaneRight(super::BreakPaneRightAction),
#[prost(message, tag="82")]
BreakPaneLeft(super::BreakPaneLeftAction),
#[prost(message, tag="83")]
RenameSession(super::RenameSessionAction),
#[prost(message, tag="84")]
CliPipe(super::CliPipeAction),
#[prost(message, tag="85")]
KeybindPipe(super::KeybindPipeAction),
#[prost(message, tag="86")]
ListClients(super::ListClientsAction),
#[prost(message, tag="87")]
TogglePanePinned(super::TogglePanePinnedAction),
#[prost(message, tag="88")]
StackPanes(super::StackPanesAction),
#[prost(message, tag="89")]
ChangeFloatingPaneCoordinates(super::ChangeFloatingPaneCoordinatesAction),
#[prost(message, tag="90")]
TogglePaneInGroup(super::TogglePaneInGroupAction),
#[prost(message, tag="91")]
ToggleGroupMarking(super::ToggleGroupMarkingAction),
#[prost(message, tag="92")]
SwitchSession(super::SwitchSessionAction),
#[prost(message, tag="93")]
NewBlockingPane(super::NewBlockingPaneAction),
#[prost(message, tag="94")]
OverrideLayout(super::OverrideLayoutAction),
}
}
// Action message definitions (all 92 variants)
/// Simple action types (no data)
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QuitAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct FocusNextPaneAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct FocusPreviousPaneAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct SwitchFocusAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct MovePaneBackwardsAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ClearScreenAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct DumpLayoutAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct EditScrollbackAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ScrollUpAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ScrollDownAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ScrollToBottomAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ScrollToTopAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PageScrollUpAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PageScrollDownAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct HalfPageScrollUpAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct HalfPageScrollDownAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ToggleFocusFullscreenAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct TogglePaneFramesAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ToggleActiveSyncTabAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct TogglePaneEmbedOrFloatingAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ToggleFloatingPanesAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CloseFocusAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct UndoRenamePaneAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct NoOpAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct GoToNextTabAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct GoToPreviousTabAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CloseTabAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ToggleTabAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct UndoRenameTabAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct DetachAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CopyAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ConfirmAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct DenyAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ToggleMouseModeAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PreviousSwapLayoutAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct NextSwapLayoutAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct OverrideLayoutAction {
#[prost(message, optional, tag="1")]
pub tiled_layout: ::core::option::Option<TiledPaneLayout>,
#[prost(message, repeated, tag="2")]
pub floating_layouts: ::prost::alloc::vec::Vec<FloatingPaneLayout>,
#[prost(message, repeated, tag="3")]
pub swap_tiled_layouts: ::prost::alloc::vec::Vec<SwapTiledLayout>,
#[prost(message, repeated, tag="4")]
pub swap_floating_layouts: ::prost::alloc::vec::Vec<SwapFloatingLayout>,
#[prost(string, optional, tag="5")]
pub tab_name: ::core::option::Option<::prost::alloc::string::String>,
#[prost(bool, tag="6")]
pub retain_existing_terminal_panes: bool,
#[prost(bool, tag="7")]
pub retain_existing_plugin_panes: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct QueryTabNamesAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct BreakPaneAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct BreakPaneRightAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct BreakPaneLeftAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ListClientsAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct TogglePanePinnedAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct TogglePaneInGroupAction {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ToggleGroupMarkingAction {
}
/// Complex action types (with data)
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct WriteAction {
#[prost(message, optional, tag="1")]
pub key_with_modifier: ::core::option::Option<KeyWithModifier>,
#[prost(uint32, repeated, tag="2")]
pub bytes: ::prost::alloc::vec::Vec<u32>,
#[prost(bool, tag="3")]
pub is_kitty_keyboard_protocol: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct WriteCharsAction {
#[prost(string, tag="1")]
pub chars: ::prost::alloc::string::String,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct SwitchToModeAction {
#[prost(enumeration="InputMode", tag="1")]
pub input_mode: i32,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct SwitchModeForAllClientsAction {
#[prost(enumeration="InputMode", tag="1")]
pub input_mode: i32,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ResizeAction {
#[prost(enumeration="ResizeType", tag="1")]
pub resize: i32,
#[prost(enumeration="Direction", optional, tag="2")]
pub direction: ::core::option::Option<i32>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct MoveFocusAction {
#[prost(enumeration="Direction", tag="1")]
pub direction: i32,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct MoveFocusOrTabAction {
#[prost(enumeration="Direction", tag="1")]
pub direction: i32,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct MovePaneAction {
#[prost(enumeration="Direction", optional, tag="1")]
pub direction: ::core::option::Option<i32>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct DumpScreenAction {
#[prost(string, tag="1")]
pub file_path: ::prost::alloc::string::String,
#[prost(bool, tag="2")]
pub include_scrollback: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ScrollUpAtAction {
#[prost(message, optional, tag="1")]
pub position: ::core::option::Option<Position>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ScrollDownAtAction {
#[prost(message, optional, tag="1")]
pub position: ::core::option::Option<Position>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct NewPaneAction {
#[prost(enumeration="Direction", optional, tag="1")]
pub direction: ::core::option::Option<i32>,
#[prost(string, optional, tag="2")]
pub pane_name: ::core::option::Option<::prost::alloc::string::String>,
#[prost(bool, tag="3")]
pub start_suppressed: bool,
#[prost(bool, tag="4")]
pub near_current_pane: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct EditFileAction {
#[prost(message, optional, tag="1")]
pub payload: ::core::option::Option<OpenFilePayload>,
#[prost(enumeration="Direction", optional, tag="2")]
pub direction: ::core::option::Option<i32>,
#[prost(bool, tag="3")]
pub floating: bool,
#[prost(bool, tag="4")]
pub in_place: bool,
#[prost(bool, tag="5")]
pub start_suppressed: bool,
#[prost(message, optional, tag="6")]
pub coordinates: ::core::option::Option<FloatingPaneCoordinates>,
#[prost(bool, tag="7")]
pub near_current_pane: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct NewFloatingPaneAction {
#[prost(message, optional, tag="1")]
pub command: ::core::option::Option<RunCommandAction>,
#[prost(string, optional, tag="2")]
pub pane_name: ::core::option::Option<::prost::alloc::string::String>,
#[prost(message, optional, tag="3")]
pub coordinates: ::core::option::Option<FloatingPaneCoordinates>,
#[prost(bool, tag="7")]
pub near_current_pane: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct NewTiledPaneAction {
#[prost(enumeration="Direction", optional, tag="1")]
pub direction: ::core::option::Option<i32>,
#[prost(message, optional, tag="2")]
pub command: ::core::option::Option<RunCommandAction>,
#[prost(string, optional, tag="3")]
pub pane_name: ::core::option::Option<::prost::alloc::string::String>,
#[prost(bool, tag="7")]
pub near_current_pane: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct NewInPlacePaneAction {
#[prost(message, optional, tag="1")]
pub command: ::core::option::Option<RunCommandAction>,
#[prost(string, optional, tag="2")]
pub pane_name: ::core::option::Option<::prost::alloc::string::String>,
#[prost(bool, tag="3")]
pub near_current_pane: bool,
#[prost(message, optional, tag="4")]
pub pane_id_to_replace: ::core::option::Option<PaneId>,
#[prost(bool, tag="5")]
pub close_replace_pane: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct NewStackedPaneAction {
#[prost(message, optional, tag="1")]
pub command: ::core::option::Option<RunCommandAction>,
#[prost(string, optional, tag="2")]
pub pane_name: ::core::option::Option<::prost::alloc::string::String>,
#[prost(bool, tag="3")]
pub near_current_pane: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct NewBlockingPaneAction {
#[prost(message, optional, tag="1")]
pub placement: ::core::option::Option<NewPanePlacement>,
#[prost(string, optional, tag="2")]
pub pane_name: ::core::option::Option<::prost::alloc::string::String>,
#[prost(message, optional, tag="3")]
pub command: ::core::option::Option<RunCommandAction>,
#[prost(enumeration="UnblockCondition", optional, tag="4")]
pub unblock_condition: ::core::option::Option<i32>,
#[prost(bool, tag="5")]
pub near_current_pane: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PaneNameInputAction {
#[prost(uint32, repeated, tag="1")]
pub input: ::prost::alloc::vec::Vec<u32>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct NewTabAction {
#[prost(message, optional, tag="1")]
pub tiled_layout: ::core::option::Option<TiledPaneLayout>,
#[prost(message, repeated, tag="2")]
pub floating_layouts: ::prost::alloc::vec::Vec<FloatingPaneLayout>,
#[prost(message, repeated, tag="3")]
pub swap_tiled_layouts: ::prost::alloc::vec::Vec<SwapTiledLayout>,
#[prost(message, repeated, tag="4")]
pub swap_floating_layouts: ::prost::alloc::vec::Vec<SwapFloatingLayout>,
#[prost(string, optional, tag="5")]
pub tab_name: ::core::option::Option<::prost::alloc::string::String>,
#[prost(bool, tag="6")]
pub should_change_focus_to_new_tab: bool,
#[prost(string, optional, tag="7")]
pub cwd: ::core::option::Option<::prost::alloc::string::String>,
#[prost(message, repeated, tag="8")]
pub initial_panes: ::prost::alloc::vec::Vec<CommandOrPlugin>,
#[prost(enumeration="UnblockCondition", optional, tag="9")]
pub first_pane_unblock_condition: ::core::option::Option<i32>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct GoToTabAction {
#[prost(uint32, tag="1")]
pub index: u32,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct GoToTabNameAction {
#[prost(string, tag="1")]
pub name: ::prost::alloc::string::String,
#[prost(bool, tag="2")]
pub create: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct TabNameInputAction {
#[prost(uint32, repeated, tag="1")]
pub input: ::prost::alloc::vec::Vec<u32>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct MoveTabAction {
#[prost(enumeration="Direction", tag="1")]
pub direction: i32,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct RunAction {
#[prost(message, optional, tag="1")]
pub command: ::core::option::Option<RunCommandAction>,
#[prost(bool, tag="2")]
pub near_current_pane: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct LaunchOrFocusPluginAction {
#[prost(message, optional, tag="1")]
pub plugin: ::core::option::Option<RunPluginOrAlias>,
#[prost(bool, tag="2")]
pub should_float: bool,
#[prost(bool, tag="3")]
pub move_to_focused_tab: bool,
#[prost(bool, tag="4")]
pub should_open_in_place: bool,
#[prost(bool, tag="5")]
pub skip_cache: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct LaunchPluginAction {
#[prost(message, optional, tag="1")]
pub plugin: ::core::option::Option<RunPluginOrAlias>,
#[prost(bool, tag="2")]
pub should_float: bool,
#[prost(bool, tag="3")]
pub should_open_in_place: bool,
#[prost(bool, tag="4")]
pub skip_cache: bool,
#[prost(string, optional, tag="5")]
pub cwd: ::core::option::Option<::prost::alloc::string::String>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct MouseEventAction {
#[prost(message, optional, tag="1")]
pub event: ::core::option::Option<MouseEvent>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct SkipConfirmAction {
#[prost(message, optional, boxed, tag="1")]
pub action: ::core::option::Option<::prost::alloc::boxed::Box<Action>>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct SearchInputAction {
#[prost(uint32, repeated, tag="1")]
pub input: ::prost::alloc::vec::Vec<u32>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct SearchAction {
#[prost(enumeration="SearchDirection", tag="1")]
pub direction: i32,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct SearchToggleOptionAction {
#[prost(enumeration="SearchOption", tag="1")]
pub option: i32,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct NewTiledPluginPaneAction {
#[prost(message, optional, tag="1")]
pub plugin: ::core::option::Option<RunPluginOrAlias>,
#[prost(string, optional, tag="2")]
pub pane_name: ::core::option::Option<::prost::alloc::string::String>,
#[prost(bool, tag="3")]
pub skip_cache: bool,
#[prost(string, optional, tag="4")]
pub cwd: ::core::option::Option<::prost::alloc::string::String>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct NewFloatingPluginPaneAction {
#[prost(message, optional, tag="1")]
pub plugin: ::core::option::Option<RunPluginOrAlias>,
#[prost(string, optional, tag="2")]
pub pane_name: ::core::option::Option<::prost::alloc::string::String>,
#[prost(bool, tag="3")]
pub skip_cache: bool,
#[prost(string, optional, tag="4")]
pub cwd: ::core::option::Option<::prost::alloc::string::String>,
#[prost(message, optional, tag="5")]
pub coordinates: ::core::option::Option<FloatingPaneCoordinates>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct NewInPlacePluginPaneAction {
#[prost(message, optional, tag="1")]
pub plugin: ::core::option::Option<RunPluginOrAlias>,
#[prost(string, optional, tag="2")]
pub pane_name: ::core::option::Option<::prost::alloc::string::String>,
#[prost(bool, tag="3")]
pub skip_cache: bool,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct StartOrReloadPluginAction {
#[prost(message, optional, tag="1")]
pub plugin: ::core::option::Option<RunPluginOrAlias>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CloseTerminalPaneAction {
#[prost(uint32, tag="1")]
pub pane_id: u32,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ClosePluginPaneAction {
#[prost(uint32, tag="1")]
pub pane_id: u32,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct FocusTerminalPaneWithIdAction {
#[prost(uint32, tag="1")]
pub pane_id: u32,
#[prost(bool, tag="2")]
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/assets/prost_ipc/generated_client_server_api.rs | zellij-utils/assets/prost_ipc/generated_client_server_api.rs | pub mod client_server_contract {
include!("client_server_contract.rs");
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/os_input_output.rs | zellij-client/src/os_input_output.rs | use anyhow::{Context, Result};
use async_trait::async_trait;
use interprocess;
use libc;
use nix;
use signal_hook;
use zellij_utils::pane_size::Size;
use interprocess::local_socket::LocalSocketStream;
use mio::{unix::SourceFd, Events, Interest, Poll, Token};
use nix::pty::Winsize;
use nix::sys::termios;
use signal_hook::{consts::signal::*, iterator::Signals};
use std::io::prelude::*;
use std::io::IsTerminal;
use std::os::unix::io::RawFd;
use std::path::Path;
use std::sync::{Arc, Mutex};
use std::{io, thread, time};
use zellij_utils::{
data::Palette,
errors::ErrorContext,
ipc::{ClientToServerMsg, IpcReceiverWithContext, IpcSenderWithContext, ServerToClientMsg},
shared::default_palette,
};
const SIGWINCH_CB_THROTTLE_DURATION: time::Duration = time::Duration::from_millis(50);
const ENABLE_MOUSE_SUPPORT: &str =
"\u{1b}[?1000h\u{1b}[?1002h\u{1b}[?1003h\u{1b}[?1015h\u{1b}[?1006h";
const DISABLE_MOUSE_SUPPORT: &str =
"\u{1b}[?1006l\u{1b}[?1015l\u{1b}[?1003l\u{1b}[?1002l\u{1b}[?1000l";
/// Trait for async stdin reading, allowing for testable implementations
#[async_trait]
pub trait AsyncStdin: Send {
async fn read(&mut self) -> io::Result<Vec<u8>>;
}
pub struct AsyncStdinReader {
stdin: tokio::io::Stdin,
buffer: Vec<u8>,
}
impl AsyncStdinReader {
pub fn new() -> Self {
Self {
stdin: tokio::io::stdin(),
buffer: vec![0u8; 10 * 1024],
}
}
}
#[async_trait]
impl AsyncStdin for AsyncStdinReader {
async fn read(&mut self) -> io::Result<Vec<u8>> {
use tokio::io::AsyncReadExt;
let n = self.stdin.read(&mut self.buffer).await?;
Ok(self.buffer[..n].to_vec())
}
}
pub enum SignalEvent {
Resize,
Quit,
}
/// Trait for async signal listening, allowing for testable implementations
#[async_trait]
pub trait AsyncSignals: Send {
async fn recv(&mut self) -> Option<SignalEvent>;
}
pub struct AsyncSignalListener {
sigwinch: tokio::signal::unix::Signal,
sigterm: tokio::signal::unix::Signal,
sigint: tokio::signal::unix::Signal,
sigquit: tokio::signal::unix::Signal,
sighup: tokio::signal::unix::Signal,
}
impl AsyncSignalListener {
pub fn new() -> io::Result<Self> {
use tokio::signal::unix::{signal, SignalKind};
Ok(Self {
sigwinch: signal(SignalKind::window_change())?,
sigterm: signal(SignalKind::terminate())?,
sigint: signal(SignalKind::interrupt())?,
sigquit: signal(SignalKind::quit())?,
sighup: signal(SignalKind::hangup())?,
})
}
pub async fn recv_resize(&mut self) -> Option<()> {
self.sigwinch.recv().await
}
pub async fn recv_quit(&mut self) -> Option<()> {
tokio::select! {
result = self.sigterm.recv() => result,
result = self.sigint.recv() => result,
result = self.sigquit.recv() => result,
result = self.sighup.recv() => result,
}
}
}
#[async_trait]
impl AsyncSignals for AsyncSignalListener {
async fn recv(&mut self) -> Option<SignalEvent> {
tokio::select! {
result = self.sigwinch.recv() => result.map(|_| SignalEvent::Resize),
result = self.sigterm.recv() => result.map(|_| SignalEvent::Quit),
result = self.sigint.recv() => result.map(|_| SignalEvent::Quit),
result = self.sigquit.recv() => result.map(|_| SignalEvent::Quit),
result = self.sighup.recv() => result.map(|_| SignalEvent::Quit),
}
}
}
fn into_raw_mode(pid: RawFd) {
let mut tio = termios::tcgetattr(pid).expect("could not get terminal attribute");
termios::cfmakeraw(&mut tio);
match termios::tcsetattr(pid, termios::SetArg::TCSANOW, &tio) {
Ok(_) => {},
Err(e) => panic!("error {:?}", e),
};
}
fn unset_raw_mode(pid: RawFd, orig_termios: termios::Termios) -> Result<(), nix::Error> {
termios::tcsetattr(pid, termios::SetArg::TCSANOW, &orig_termios)
}
pub(crate) fn get_terminal_size_using_fd(fd: RawFd) -> Size {
// TODO: do this with the nix ioctl
use libc::ioctl;
use libc::TIOCGWINSZ;
let mut winsize = Winsize {
ws_row: 0,
ws_col: 0,
ws_xpixel: 0,
ws_ypixel: 0,
};
// TIOCGWINSZ is an u32, but the second argument to ioctl is u64 on
// some platforms. When checked on Linux, clippy will complain about
// useless conversion.
#[allow(clippy::useless_conversion)]
unsafe {
ioctl(fd, TIOCGWINSZ.into(), &mut winsize)
};
// fallback to default values when rows/cols == 0: https://github.com/zellij-org/zellij/issues/1551
let rows = if winsize.ws_row != 0 {
winsize.ws_row as usize
} else {
24
};
let cols = if winsize.ws_col != 0 {
winsize.ws_col as usize
} else {
80
};
Size { rows, cols }
}
#[derive(Clone)]
pub struct ClientOsInputOutput {
orig_termios: Option<Arc<Mutex<termios::Termios>>>,
send_instructions_to_server: Arc<Mutex<Option<IpcSenderWithContext<ClientToServerMsg>>>>,
receive_instructions_from_server: Arc<Mutex<Option<IpcReceiverWithContext<ServerToClientMsg>>>>,
reading_from_stdin: Arc<Mutex<Option<Vec<u8>>>>,
session_name: Arc<Mutex<Option<String>>>,
}
impl std::fmt::Debug for ClientOsInputOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ClientOsInputOutput").finish()
}
}
/// The `ClientOsApi` trait represents an abstract interface to the features of an operating system that
/// Zellij client requires.
pub trait ClientOsApi: Send + Sync + std::fmt::Debug {
/// Returns the size of the terminal associated to file descriptor `fd`.
fn get_terminal_size_using_fd(&self, fd: RawFd) -> Size;
/// Set the terminal associated to file descriptor `fd` to
/// [raw mode](https://en.wikipedia.org/wiki/Terminal_mode).
fn set_raw_mode(&mut self, fd: RawFd);
/// Set the terminal associated to file descriptor `fd` to
/// [cooked mode](https://en.wikipedia.org/wiki/Terminal_mode).
fn unset_raw_mode(&self, fd: RawFd) -> Result<(), nix::Error>;
/// Returns the writer that allows writing to standard output.
fn get_stdout_writer(&self) -> Box<dyn io::Write>;
/// Returns a BufReader that allows to read from STDIN line by line, also locks STDIN
fn get_stdin_reader(&self) -> Box<dyn io::BufRead>;
fn stdin_is_terminal(&self) -> bool {
true
}
fn stdout_is_terminal(&self) -> bool {
true
}
fn update_session_name(&mut self, new_session_name: String);
/// Returns the raw contents of standard input.
fn read_from_stdin(&mut self) -> Result<Vec<u8>, &'static str>;
/// Returns a [`Box`] pointer to this [`ClientOsApi`] struct.
fn box_clone(&self) -> Box<dyn ClientOsApi>;
/// Sends a message to the server.
fn send_to_server(&self, msg: ClientToServerMsg);
/// Receives a message on client-side IPC channel
// This should be called from the client-side router thread only.
fn recv_from_server(&self) -> Option<(ServerToClientMsg, ErrorContext)>;
fn handle_signals(&self, sigwinch_cb: Box<dyn Fn()>, quit_cb: Box<dyn Fn()>);
/// Establish a connection with the server socket.
fn connect_to_server(&self, path: &Path);
fn load_palette(&self) -> Palette;
fn enable_mouse(&self) -> Result<()>;
fn disable_mouse(&self) -> Result<()>;
// Repeatedly send action, until stdin is readable again
fn stdin_poller(&self) -> StdinPoller;
fn env_variable(&self, _name: &str) -> Option<String> {
None
}
/// Returns an async stdin reader that can be polled in tokio::select
fn get_async_stdin_reader(&self) -> Box<dyn AsyncStdin> {
Box::new(AsyncStdinReader::new())
}
/// Returns an async signal listener that can be polled in tokio::select
fn get_async_signal_listener(&self) -> io::Result<Box<dyn AsyncSignals>> {
Ok(Box::new(AsyncSignalListener::new()?))
}
}
impl ClientOsApi for ClientOsInputOutput {
fn get_terminal_size_using_fd(&self, fd: RawFd) -> Size {
get_terminal_size_using_fd(fd)
}
fn set_raw_mode(&mut self, fd: RawFd) {
into_raw_mode(fd);
}
fn unset_raw_mode(&self, fd: RawFd) -> Result<(), nix::Error> {
match &self.orig_termios {
Some(orig_termios) => {
let orig_termios = orig_termios.lock().unwrap();
unset_raw_mode(fd, orig_termios.clone())
},
None => {
log::warn!("trying to unset raw mode for a non-terminal session");
Ok(())
},
}
}
fn box_clone(&self) -> Box<dyn ClientOsApi> {
Box::new((*self).clone())
}
fn update_session_name(&mut self, new_session_name: String) {
*self.session_name.lock().unwrap() = Some(new_session_name);
}
fn read_from_stdin(&mut self) -> Result<Vec<u8>, &'static str> {
let session_name_at_calltime = { self.session_name.lock().unwrap().clone() };
// here we wait for a lock in case another thread is holding stdin
// this can happen for example when switching sessions, the old thread will only be
// released once it sees input over STDIN
//
// when this happens, we detect in the other thread that our session is ended (by comparing
// the session name at the beginning of the call and the one after we read from STDIN), and
// so place what we read from STDIN inside a buffer (the "reading_from_stdin" on our state)
// and release the lock
//
// then, another thread will see there's something in the buffer immediately as it acquires
// the lock (without having to wait for STDIN itself) forward this buffer and proceed to
// wait for the "real" STDIN net time it is called
let mut buffered_bytes = self.reading_from_stdin.lock().unwrap();
match buffered_bytes.take() {
Some(buffered_bytes) => Ok(buffered_bytes),
None => {
let stdin = std::io::stdin();
let mut stdin = stdin.lock();
let buffer = stdin.fill_buf().unwrap();
let length = buffer.len();
let read_bytes = Vec::from(buffer);
stdin.consume(length);
let session_name_after_reading_from_stdin =
{ self.session_name.lock().unwrap().clone() };
if session_name_at_calltime.is_some()
&& session_name_at_calltime != session_name_after_reading_from_stdin
{
*buffered_bytes = Some(read_bytes);
Err("Session ended")
} else {
Ok(read_bytes)
}
},
}
}
fn get_stdout_writer(&self) -> Box<dyn io::Write> {
let stdout = ::std::io::stdout();
Box::new(stdout)
}
fn get_stdin_reader(&self) -> Box<dyn io::BufRead> {
let stdin = ::std::io::stdin();
Box::new(stdin.lock())
}
fn stdin_is_terminal(&self) -> bool {
let stdin = ::std::io::stdin();
stdin.is_terminal()
}
fn stdout_is_terminal(&self) -> bool {
let stdout = ::std::io::stdout();
stdout.is_terminal()
}
fn send_to_server(&self, msg: ClientToServerMsg) {
match self.send_instructions_to_server.lock().unwrap().as_mut() {
Some(sender) => {
let _ = sender.send_client_msg(msg);
},
None => {
log::warn!("Server not ready, dropping message.");
},
}
}
fn recv_from_server(&self) -> Option<(ServerToClientMsg, ErrorContext)> {
self.receive_instructions_from_server
.lock()
.unwrap()
.as_mut()
.unwrap()
.recv_server_msg()
}
fn handle_signals(&self, sigwinch_cb: Box<dyn Fn()>, quit_cb: Box<dyn Fn()>) {
let mut sigwinch_cb_timestamp = time::Instant::now();
let mut signals = Signals::new(&[SIGWINCH, SIGTERM, SIGINT, SIGQUIT, SIGHUP]).unwrap();
for signal in signals.forever() {
match signal {
SIGWINCH => {
// throttle sigwinch_cb calls, reduce excessive renders while resizing
if sigwinch_cb_timestamp.elapsed() < SIGWINCH_CB_THROTTLE_DURATION {
thread::sleep(SIGWINCH_CB_THROTTLE_DURATION);
}
sigwinch_cb_timestamp = time::Instant::now();
sigwinch_cb();
},
SIGTERM | SIGINT | SIGQUIT | SIGHUP => {
quit_cb();
break;
},
_ => unreachable!(),
}
}
}
fn connect_to_server(&self, path: &Path) {
let socket;
loop {
match LocalSocketStream::connect(path) {
Ok(sock) => {
socket = sock;
break;
},
Err(_) => {
std::thread::sleep(std::time::Duration::from_millis(50));
},
}
}
let sender = IpcSenderWithContext::new(socket);
let receiver = sender.get_receiver();
*self.send_instructions_to_server.lock().unwrap() = Some(sender);
*self.receive_instructions_from_server.lock().unwrap() = Some(receiver);
}
fn load_palette(&self) -> Palette {
// this was removed because termbg doesn't release stdin in certain scenarios (we know of
// windows terminal and FreeBSD): https://github.com/zellij-org/zellij/issues/538
//
// let palette = default_palette();
// let timeout = std::time::Duration::from_millis(100);
// if let Ok(rgb) = termbg::rgb(timeout) {
// palette.bg = PaletteColor::Rgb((rgb.r as u8, rgb.g as u8, rgb.b as u8));
// // TODO: also dynamically get all other colors from the user's terminal
// // this should be done in the same method (OSC ]11), but there might be other
// // considerations here, hence using the library
// };
default_palette()
}
fn enable_mouse(&self) -> Result<()> {
let err_context = "failed to enable mouse mode";
let mut stdout = self.get_stdout_writer();
stdout
.write_all(ENABLE_MOUSE_SUPPORT.as_bytes())
.context(err_context)?;
stdout.flush().context(err_context)?;
Ok(())
}
fn disable_mouse(&self) -> Result<()> {
let err_context = "failed to enable mouse mode";
let mut stdout = self.get_stdout_writer();
stdout
.write_all(DISABLE_MOUSE_SUPPORT.as_bytes())
.context(err_context)?;
stdout.flush().context(err_context)?;
Ok(())
}
fn stdin_poller(&self) -> StdinPoller {
StdinPoller::default()
}
fn env_variable(&self, name: &str) -> Option<String> {
std::env::var(name).ok()
}
}
impl Clone for Box<dyn ClientOsApi> {
fn clone(&self) -> Box<dyn ClientOsApi> {
self.box_clone()
}
}
pub fn get_client_os_input() -> Result<ClientOsInputOutput, nix::Error> {
let current_termios = termios::tcgetattr(0).ok();
let orig_termios = current_termios.map(|termios| Arc::new(Mutex::new(termios)));
let reading_from_stdin = Arc::new(Mutex::new(None));
Ok(ClientOsInputOutput {
orig_termios,
send_instructions_to_server: Arc::new(Mutex::new(None)),
receive_instructions_from_server: Arc::new(Mutex::new(None)),
reading_from_stdin,
session_name: Arc::new(Mutex::new(None)),
})
}
pub fn get_cli_client_os_input() -> Result<ClientOsInputOutput, nix::Error> {
let orig_termios = None; // not a terminal
let reading_from_stdin = Arc::new(Mutex::new(None));
Ok(ClientOsInputOutput {
orig_termios,
send_instructions_to_server: Arc::new(Mutex::new(None)),
receive_instructions_from_server: Arc::new(Mutex::new(None)),
reading_from_stdin,
session_name: Arc::new(Mutex::new(None)),
})
}
pub const DEFAULT_STDIN_POLL_TIMEOUT_MS: u64 = 10;
pub struct StdinPoller {
poll: Poll,
events: Events,
timeout: time::Duration,
}
impl StdinPoller {
// use mio poll to check if stdin is readable without blocking
pub fn ready(&mut self) -> bool {
self.poll
.poll(&mut self.events, Some(self.timeout))
.expect("could not poll stdin for readiness");
for event in &self.events {
if event.token() == Token(0) && event.is_readable() {
return true;
}
}
false
}
}
impl Default for StdinPoller {
fn default() -> Self {
let stdin = 0;
let mut stdin_fd = SourceFd(&stdin);
let events = Events::with_capacity(128);
let poll = Poll::new().unwrap();
poll.registry()
.register(&mut stdin_fd, Token(0), Interest::READABLE)
.expect("could not create stdin poll");
let timeout = time::Duration::from_millis(DEFAULT_STDIN_POLL_TIMEOUT_MS);
Self {
poll,
events,
timeout,
}
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/lib.rs | zellij-client/src/lib.rs | pub mod os_input_output;
pub mod cli_client;
mod command_is_executing;
mod input_handler;
mod keyboard_parser;
pub mod old_config_converter;
#[cfg(feature = "web_server_capability")]
pub mod remote_attach;
mod stdin_ansi_parser;
mod stdin_handler;
#[cfg(feature = "web_server_capability")]
pub mod web_client;
use log::info;
use std::env::current_exe;
use std::io::{self, Write};
use std::net::{IpAddr, Ipv4Addr};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::{Arc, Mutex};
use std::thread;
use zellij_utils::errors::FatalError;
use zellij_utils::shared::web_server_base_url;
#[cfg(feature = "web_server_capability")]
use futures_util::{SinkExt, StreamExt};
#[cfg(feature = "web_server_capability")]
use tokio::runtime::Runtime;
#[cfg(feature = "web_server_capability")]
use tokio_tungstenite::tungstenite::Message;
#[cfg(feature = "web_server_capability")]
use crate::web_client::control_message::{
WebClientToWebServerControlMessage, WebClientToWebServerControlMessagePayload,
WebServerToWebClientControlMessage,
};
#[derive(Debug)]
pub enum RemoteClientError {
InvalidAuthToken,
SessionTokenExpired,
Unauthorized,
ConnectionFailed(String),
UrlParseError(url::ParseError),
IoError(std::io::Error),
Other(Box<dyn std::error::Error + Send + Sync>),
}
impl std::fmt::Display for RemoteClientError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
RemoteClientError::InvalidAuthToken => write!(f, "Invalid authentication token"),
RemoteClientError::SessionTokenExpired => write!(f, "Session token expired"),
RemoteClientError::Unauthorized => write!(f, "Unauthorized"),
RemoteClientError::ConnectionFailed(msg) => write!(f, "Connection failed: {}", msg),
RemoteClientError::UrlParseError(e) => write!(f, "Invalid URL: {}", e),
RemoteClientError::IoError(e) => write!(f, "IO error: {}", e),
RemoteClientError::Other(e) => write!(f, "{}", e),
}
}
}
impl std::error::Error for RemoteClientError {}
impl From<url::ParseError> for RemoteClientError {
fn from(error: url::ParseError) -> Self {
RemoteClientError::UrlParseError(error)
}
}
impl From<std::io::Error> for RemoteClientError {
fn from(error: std::io::Error) -> Self {
RemoteClientError::IoError(error)
}
}
use crate::stdin_ansi_parser::{AnsiStdinInstruction, StdinAnsiParser, SyncOutput};
use crate::{
command_is_executing::CommandIsExecuting, input_handler::input_loop,
os_input_output::ClientOsApi, stdin_handler::stdin_loop,
};
use termwiz::input::InputEvent;
use zellij_utils::cli::CliArgs;
use zellij_utils::{
channels::{self, ChannelWithContext, SenderWithContext},
consts::{set_permissions, ZELLIJ_SOCK_DIR},
data::{ClientId, ConnectToSession, KeyWithModifier, LayoutInfo},
envs,
errors::{ClientContext, ContextType, ErrorInstruction},
input::{cli_assets::CliAssets, config::Config, options::Options},
ipc::{ClientToServerMsg, ExitReason, ServerToClientMsg},
pane_size::Size,
};
/// Instructions related to the client-side application
#[derive(Debug, Clone)]
pub(crate) enum ClientInstruction {
Error(String),
Render(String),
UnblockInputThread,
Exit(ExitReason),
Connected,
StartedParsingStdinQuery,
DoneParsingStdinQuery,
Log(Vec<String>),
LogError(Vec<String>),
SwitchSession(ConnectToSession),
SetSynchronizedOutput(Option<SyncOutput>),
UnblockCliPipeInput(()), // String -> pipe name
CliPipeOutput((), ()), // String -> pipe name, String -> output
QueryTerminalSize,
StartWebServer,
#[allow(dead_code)] // we need the session name here even though we're not currently using it
RenamedSession(String), // String -> new session name
ConfigFileUpdated,
}
impl From<ServerToClientMsg> for ClientInstruction {
fn from(instruction: ServerToClientMsg) -> Self {
match instruction {
ServerToClientMsg::Exit { exit_reason } => ClientInstruction::Exit(exit_reason),
ServerToClientMsg::Render { content } => ClientInstruction::Render(content),
ServerToClientMsg::UnblockInputThread => ClientInstruction::UnblockInputThread,
ServerToClientMsg::Connected => ClientInstruction::Connected,
ServerToClientMsg::Log { lines } => ClientInstruction::Log(lines),
ServerToClientMsg::LogError { lines } => ClientInstruction::LogError(lines),
ServerToClientMsg::SwitchSession { connect_to_session } => {
ClientInstruction::SwitchSession(connect_to_session)
},
ServerToClientMsg::UnblockCliPipeInput { .. } => {
ClientInstruction::UnblockCliPipeInput(())
},
ServerToClientMsg::CliPipeOutput { .. } => ClientInstruction::CliPipeOutput((), ()),
ServerToClientMsg::QueryTerminalSize => ClientInstruction::QueryTerminalSize,
ServerToClientMsg::StartWebServer => ClientInstruction::StartWebServer,
ServerToClientMsg::RenamedSession { name } => ClientInstruction::RenamedSession(name),
ServerToClientMsg::ConfigFileUpdated => ClientInstruction::ConfigFileUpdated,
}
}
}
impl From<&ClientInstruction> for ClientContext {
fn from(client_instruction: &ClientInstruction) -> Self {
match *client_instruction {
ClientInstruction::Exit(_) => ClientContext::Exit,
ClientInstruction::Error(_) => ClientContext::Error,
ClientInstruction::Render(_) => ClientContext::Render,
ClientInstruction::UnblockInputThread => ClientContext::UnblockInputThread,
ClientInstruction::Connected => ClientContext::Connected,
ClientInstruction::Log(_) => ClientContext::Log,
ClientInstruction::LogError(_) => ClientContext::LogError,
ClientInstruction::StartedParsingStdinQuery => ClientContext::StartedParsingStdinQuery,
ClientInstruction::DoneParsingStdinQuery => ClientContext::DoneParsingStdinQuery,
ClientInstruction::SwitchSession(..) => ClientContext::SwitchSession,
ClientInstruction::SetSynchronizedOutput(..) => ClientContext::SetSynchronisedOutput,
ClientInstruction::UnblockCliPipeInput(..) => ClientContext::UnblockCliPipeInput,
ClientInstruction::CliPipeOutput(..) => ClientContext::CliPipeOutput,
ClientInstruction::QueryTerminalSize => ClientContext::QueryTerminalSize,
ClientInstruction::StartWebServer => ClientContext::StartWebServer,
ClientInstruction::RenamedSession(..) => ClientContext::RenamedSession,
ClientInstruction::ConfigFileUpdated => ClientContext::ConfigFileUpdated,
}
}
}
impl ErrorInstruction for ClientInstruction {
fn error(err: String) -> Self {
ClientInstruction::Error(err)
}
}
#[cfg(feature = "web_server_capability")]
fn spawn_web_server(cli_args: &CliArgs) -> Result<String, String> {
let mut cmd = Command::new(current_exe().map_err(|e| e.to_string())?);
if let Some(config_file_path) = Config::config_file_path(cli_args) {
let config_file_path_exists = Path::new(&config_file_path).exists();
if !config_file_path_exists {
return Err(format!(
"Config file: {} does not exist",
config_file_path.display()
));
}
// this is so that if Zellij itself was started with a different config file, we'll use it
// to start the webserver
cmd.arg("--config");
cmd.arg(format!("{}", config_file_path.display()));
}
cmd.arg("web");
cmd.arg("-d");
let output = cmd.output();
match output {
Ok(output) => {
if output.status.success() {
Ok(String::from_utf8_lossy(&output.stdout).to_string())
} else {
Err(String::from_utf8_lossy(&output.stderr).to_string())
}
},
Err(e) => Err(e.to_string()),
}
}
#[cfg(not(feature = "web_server_capability"))]
fn spawn_web_server(_cli_args: &CliArgs) -> Result<String, String> {
log::error!(
"This version of Zellij was compiled without web server support, cannot run web server!"
);
Ok("".to_owned())
}
pub fn spawn_server(socket_path: &Path, debug: bool) -> io::Result<()> {
let mut cmd = Command::new(current_exe()?);
cmd.arg("--server");
cmd.arg(socket_path);
if debug {
cmd.arg("--debug");
}
let status = cmd.status()?;
if status.success() {
Ok(())
} else {
let msg = "Process returned non-zero exit code";
let err_msg = match status.code() {
Some(c) => format!("{}: {}", msg, c),
None => msg.to_string(),
};
Err(io::Error::new(io::ErrorKind::Other, err_msg))
}
}
#[derive(Debug, Clone)]
pub enum ClientInfo {
Attach(String, Options),
New(String, Option<LayoutInfo>, Option<PathBuf>), // PathBuf -> explicit cwd
Resurrect(String, PathBuf, bool, Option<PathBuf>), // (name, path_to_layout, force_run_commands, cwd)
Watch(String, Options), // Watch mode (read-only)
}
impl ClientInfo {
pub fn get_session_name(&self) -> &str {
match self {
Self::Attach(ref name, _) => name,
Self::New(ref name, _layout_info, _layout_cwd) => name,
Self::Resurrect(ref name, _, _, _) => name,
Self::Watch(ref name, _) => name,
}
}
pub fn set_layout_info(&mut self, new_layout_info: LayoutInfo) {
match self {
ClientInfo::New(_, layout_info, _) => *layout_info = Some(new_layout_info),
_ => {},
}
}
pub fn set_cwd(&mut self, new_cwd: PathBuf) {
match self {
ClientInfo::New(_, _, cwd) => *cwd = Some(new_cwd),
ClientInfo::Resurrect(_, _, _, cwd) => *cwd = Some(new_cwd),
_ => {},
}
}
}
#[derive(Debug, Clone)]
pub(crate) enum InputInstruction {
KeyEvent(InputEvent, Vec<u8>),
KeyWithModifierEvent(KeyWithModifier, Vec<u8>),
AnsiStdinInstructions(Vec<AnsiStdinInstruction>),
StartedParsing,
DoneParsing,
Exit,
}
#[cfg(feature = "web_server_capability")]
pub async fn run_remote_client_terminal_loop(
os_input: Box<dyn ClientOsApi>,
mut connections: remote_attach::WebSocketConnections,
) -> Result<Option<ConnectToSession>, RemoteClientError> {
use crate::os_input_output::{AsyncSignals, AsyncStdin};
let synchronised_output = match os_input.env_variable("TERM").as_deref() {
Some("alacritty") => Some(SyncOutput::DCS),
_ => None,
};
let mut async_stdin: Box<dyn AsyncStdin> = os_input.get_async_stdin_reader();
let mut async_signals: Box<dyn AsyncSignals> = os_input
.get_async_signal_listener()
.map_err(|e| RemoteClientError::IoError(e))?;
let create_resize_message = |size: Size| {
Message::Text(
serde_json::to_string(&WebClientToWebServerControlMessage {
web_client_id: connections.web_client_id.clone(),
payload: WebClientToWebServerControlMessagePayload::TerminalResize(size),
})
.unwrap(),
)
};
// send size on startup
let new_size = os_input.get_terminal_size_using_fd(0);
if let Err(e) = connections
.control_ws
.send(create_resize_message(new_size))
.await
{
log::error!("Failed to send resize message: {}", e);
}
loop {
tokio::select! {
// Handle stdin input
result = async_stdin.read() => {
match result {
Ok(buf) if !buf.is_empty() => {
if let Err(e) = connections.terminal_ws.send(Message::Binary(buf)).await {
log::error!("Failed to send stdin to terminal WebSocket: {}", e);
break;
}
}
Ok(_) => {
// Empty buffer means EOF
break;
}
Err(e) => {
log::error!("Error reading from stdin: {}", e);
break;
}
}
}
// Handle signals
Some(signal) = async_signals.recv() => {
match signal {
crate::os_input_output::SignalEvent::Resize => {
let new_size = os_input.get_terminal_size_using_fd(0);
if let Err(e) = connections.control_ws.send(create_resize_message(new_size)).await {
log::error!("Failed to send resize message: {}", e);
break;
}
}
crate::os_input_output::SignalEvent::Quit => {
break;
}
}
}
// Handle terminal messages
terminal_msg = connections.terminal_ws.next() => {
match terminal_msg {
Some(Ok(Message::Text(text))) => {
let mut stdout = os_input.get_stdout_writer();
if let Some(sync) = synchronised_output {
stdout
.write_all(sync.start_seq())
.expect("cannot write to stdout");
}
stdout
.write_all(text.as_bytes())
.expect("cannot write to stdout");
if let Some(sync) = synchronised_output {
stdout
.write_all(sync.end_seq())
.expect("cannot write to stdout");
}
stdout.flush().expect("could not flush");
}
Some(Ok(Message::Binary(data))) => {
let mut stdout = os_input.get_stdout_writer();
if let Some(sync) = synchronised_output {
stdout
.write_all(sync.start_seq())
.expect("cannot write to stdout");
}
stdout
.write_all(&data)
.expect("cannot write to stdout");
if let Some(sync) = synchronised_output {
stdout
.write_all(sync.end_seq())
.expect("cannot write to stdout");
}
stdout.flush().expect("could not flush");
}
Some(Ok(Message::Close(_))) => {
break;
}
Some(Err(e)) => {
log::error!("Error: {}", e);
break;
}
None => {
log::error!("Received empty message from web server");
break;
}
_ => {}
}
}
control_msg = connections.control_ws.next() => {
match control_msg {
Some(Ok(Message::Text(msg))) => {
let deserialized_msg: Result<WebServerToWebClientControlMessage, _> =
serde_json::from_str(&msg);
match deserialized_msg {
Ok(WebServerToWebClientControlMessage::SetConfig(..)) => {
// no-op
}
Ok(WebServerToWebClientControlMessage::QueryTerminalSize) => {
let new_size = os_input.get_terminal_size_using_fd(0);
if let Err(e) = connections.control_ws.send(create_resize_message(new_size)).await {
log::error!("Failed to send resize message: {}", e);
}
}
Ok(WebServerToWebClientControlMessage::Log { lines }) => {
for line in lines {
log::info!("{}", line);
}
}
Ok(WebServerToWebClientControlMessage::LogError { lines }) => {
for line in lines {
log::error!("{}", line);
}
}
Ok(WebServerToWebClientControlMessage::SwitchedSession{ .. }) => {
// no-op
}
Err(e) => {
log::error!("Failed to deserialize control message: {}", e);
}
}
}
Some(Ok(Message::Close(_))) => {
break;
}
Some(Err(e)) => {
log::error!("{}", e);
break;
}
None => break,
_ => {}
}
}
}
}
Ok(None)
}
#[cfg(feature = "web_server_capability")]
pub fn start_remote_client(
mut os_input: Box<dyn ClientOsApi>,
remote_session_url: &str,
token: Option<String>,
remember: bool,
forget: bool,
) -> Result<Option<ConnectToSession>, RemoteClientError> {
info!("Starting Zellij client!");
let runtime = Runtime::new().map_err(|e| RemoteClientError::IoError(e))?;
let connections = remote_attach::attach_to_remote_session(
&runtime,
os_input.clone(),
remote_session_url,
token,
remember,
forget,
)?;
let reconnect_to_session = None;
let clear_client_terminal_attributes = "\u{1b}[?1l\u{1b}=\u{1b}[r\u{1b}[?1000l\u{1b}[?1002l\u{1b}[?1003l\u{1b}[?1005l\u{1b}[?1006l\u{1b}[?12l";
let take_snapshot = "\u{1b}[?1049h";
let bracketed_paste = "\u{1b}[?2004h";
let enter_kitty_keyboard_mode = "\u{1b}[>1u";
os_input.unset_raw_mode(0).unwrap();
let _ = os_input
.get_stdout_writer()
.write(take_snapshot.as_bytes())
.unwrap();
let _ = os_input
.get_stdout_writer()
.write(clear_client_terminal_attributes.as_bytes())
.unwrap();
let _ = os_input
.get_stdout_writer()
.write(enter_kitty_keyboard_mode.as_bytes())
.unwrap();
envs::set_zellij("0".to_string());
let full_screen_ws = os_input.get_terminal_size_using_fd(0);
os_input.set_raw_mode(0);
let _ = os_input
.get_stdout_writer()
.write(bracketed_paste.as_bytes())
.unwrap();
std::panic::set_hook({
use zellij_utils::errors::handle_panic;
let os_input = os_input.clone();
Box::new(move |info| {
if let Ok(()) = os_input.unset_raw_mode(0) {
handle_panic::<ClientInstruction>(info, None);
}
})
});
let reset_controlling_terminal_state = |e: String, exit_status: i32| {
os_input.unset_raw_mode(0).unwrap();
let goto_start_of_last_line = format!("\u{1b}[{};{}H", full_screen_ws.rows, 1);
let restore_alternate_screen = "\u{1b}[?1049l";
let exit_kitty_keyboard_mode = "\u{1b}[<1u";
let reset_style = "\u{1b}[m";
let show_cursor = "\u{1b}[?25h";
os_input.disable_mouse().non_fatal();
let error = format!(
"{}{}{}{}\n{}{}\n",
reset_style,
show_cursor,
restore_alternate_screen,
exit_kitty_keyboard_mode,
goto_start_of_last_line,
e
);
let _ = os_input
.get_stdout_writer()
.write(error.as_bytes())
.unwrap();
let _ = os_input.get_stdout_writer().flush().unwrap();
if exit_status == 0 {
log::info!("{}", e);
} else {
log::error!("{}", e);
};
std::process::exit(exit_status);
};
runtime.block_on(run_remote_client_terminal_loop(
os_input.clone(),
connections,
))?;
let exit_msg = String::from("Bye from Zellij!");
if reconnect_to_session.is_none() {
reset_controlling_terminal_state(exit_msg, 0);
std::process::exit(0);
} else {
let clear_screen = "\u{1b}[2J";
let mut stdout = os_input.get_stdout_writer();
let _ = stdout.write(clear_screen.as_bytes()).unwrap();
stdout.flush().unwrap();
}
Ok(reconnect_to_session)
}
pub fn start_client(
mut os_input: Box<dyn ClientOsApi>,
cli_args: CliArgs,
config: Config, // saved to disk (or default?)
config_options: Options, // CLI options merged into (getting priority over) saved config options
info: ClientInfo,
tab_position_to_focus: Option<usize>,
pane_id_to_focus: Option<(u32, bool)>, // (pane_id, is_plugin)
is_a_reconnect: bool,
start_detached_and_exit: bool,
) -> Option<ConnectToSession> {
if start_detached_and_exit {
start_server_detached(os_input, cli_args, config, config_options, info);
return None;
}
info!("Starting Zellij client!");
let explicitly_disable_kitty_keyboard_protocol = config_options
.support_kitty_keyboard_protocol
.map(|e| !e)
.unwrap_or(false);
let should_start_web_server = config_options.web_server.map(|w| w).unwrap_or(false);
let mut reconnect_to_session = None;
let clear_client_terminal_attributes = "\u{1b}[?1l\u{1b}=\u{1b}[r\u{1b}[?1000l\u{1b}[?1002l\u{1b}[?1003l\u{1b}[?1005l\u{1b}[?1006l\u{1b}[?12l";
let take_snapshot = "\u{1b}[?1049h";
let bracketed_paste = "\u{1b}[?2004h";
let enter_kitty_keyboard_mode = "\u{1b}[>1u";
os_input.unset_raw_mode(0).unwrap();
if !is_a_reconnect {
// we don't do this for a reconnect because our controlling terminal already has the
// attributes we want from it, and some terminals don't treat these atomically (looking at
// you Windows Terminal...)
let _ = os_input
.get_stdout_writer()
.write(take_snapshot.as_bytes())
.unwrap();
let _ = os_input
.get_stdout_writer()
.write(clear_client_terminal_attributes.as_bytes())
.unwrap();
if !explicitly_disable_kitty_keyboard_protocol {
let _ = os_input
.get_stdout_writer()
.write(enter_kitty_keyboard_mode.as_bytes())
.unwrap();
}
}
envs::set_zellij("0".to_string());
config.env.set_vars();
let full_screen_ws = os_input.get_terminal_size_using_fd(0);
let web_server_ip = config_options
.web_server_ip
.unwrap_or_else(|| IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
let web_server_port = config_options.web_server_port.unwrap_or_else(|| 8082);
let has_certificate =
config_options.web_server_cert.is_some() && config_options.web_server_key.is_some();
let enforce_https_for_localhost = config_options.enforce_https_for_localhost.unwrap_or(false);
let create_ipc_pipe = || -> std::path::PathBuf {
let mut sock_dir = ZELLIJ_SOCK_DIR.clone();
std::fs::create_dir_all(&sock_dir).unwrap();
set_permissions(&sock_dir, 0o700).unwrap();
sock_dir.push(envs::get_session_name().unwrap());
sock_dir
};
let (first_msg, ipc_pipe) = match info {
ClientInfo::Attach(name, config_options) => {
envs::set_session_name(name.clone());
os_input.update_session_name(name);
let ipc_pipe = create_ipc_pipe();
let is_web_client = false;
let cli_assets = CliAssets {
config_file_path: Config::config_file_path(&cli_args),
config_dir: cli_args.config_dir.clone(),
should_ignore_config: cli_args.is_setup_clean(),
configuration_options: Some(config_options.clone()),
layout: cli_args
.layout
.as_ref()
.and_then(|l| {
LayoutInfo::from_config(&config_options.layout_dir, &Some(l.clone()))
})
.or_else(|| {
LayoutInfo::from_config(
&config_options.layout_dir,
&config_options.default_layout,
)
}),
terminal_window_size: full_screen_ws,
data_dir: cli_args.data_dir.clone(),
is_debug: cli_args.debug,
max_panes: cli_args.max_panes,
force_run_layout_commands: false,
cwd: None,
};
(
ClientToServerMsg::AttachClient {
cli_assets,
tab_position_to_focus,
pane_to_focus: pane_id_to_focus.map(|(pane_id, is_plugin)| {
zellij_utils::ipc::PaneReference { pane_id, is_plugin }
}),
is_web_client,
},
ipc_pipe,
)
},
ClientInfo::Watch(name, _config_options) => {
envs::set_session_name(name.clone());
os_input.update_session_name(name);
let ipc_pipe = create_ipc_pipe();
let is_web_client = false;
(
ClientToServerMsg::AttachWatcherClient {
terminal_size: full_screen_ws,
is_web_client,
},
ipc_pipe,
)
},
ClientInfo::Resurrect(name, path_to_layout, force_run_commands, cwd) => {
envs::set_session_name(name.clone());
let cli_assets = CliAssets {
config_file_path: Config::config_file_path(&cli_args),
config_dir: cli_args.config_dir.clone(),
should_ignore_config: cli_args.is_setup_clean(),
configuration_options: Some(config_options.clone()),
layout: Some(LayoutInfo::File(path_to_layout.display().to_string())),
terminal_window_size: full_screen_ws,
data_dir: cli_args.data_dir.clone(),
is_debug: cli_args.debug,
max_panes: cli_args.max_panes,
force_run_layout_commands: force_run_commands,
cwd,
};
os_input.update_session_name(name);
let ipc_pipe = create_ipc_pipe();
spawn_server(&*ipc_pipe, cli_args.debug).unwrap();
if should_start_web_server {
if let Err(e) = spawn_web_server(&cli_args) {
log::error!("Failed to start web server: {}", e);
}
}
let is_web_client = false;
(
ClientToServerMsg::FirstClientConnected {
cli_assets,
is_web_client,
},
ipc_pipe,
)
},
ClientInfo::New(name, layout_info, layout_cwd) => {
envs::set_session_name(name.clone());
let cli_assets = CliAssets {
config_file_path: Config::config_file_path(&cli_args),
config_dir: cli_args.config_dir.clone(),
should_ignore_config: cli_args.is_setup_clean(),
configuration_options: Some(config_options.clone()),
layout: layout_info.or_else(|| {
cli_args
.layout
.as_ref()
.and_then(|l| {
LayoutInfo::from_config(&config_options.layout_dir, &Some(l.clone()))
})
.or_else(|| {
LayoutInfo::from_config(
&config_options.layout_dir,
&config_options.default_layout,
)
})
}),
terminal_window_size: full_screen_ws,
data_dir: cli_args.data_dir.clone(),
is_debug: cli_args.debug,
max_panes: cli_args.max_panes,
force_run_layout_commands: false,
cwd: layout_cwd,
};
os_input.update_session_name(name);
let ipc_pipe = create_ipc_pipe();
spawn_server(&*ipc_pipe, cli_args.debug).unwrap();
if should_start_web_server {
if let Err(e) = spawn_web_server(&cli_args) {
log::error!("Failed to start web server: {}", e);
}
}
let is_web_client = false;
(
ClientToServerMsg::FirstClientConnected {
cli_assets,
is_web_client,
},
ipc_pipe,
)
},
};
os_input.connect_to_server(&*ipc_pipe);
os_input.send_to_server(first_msg);
let mut command_is_executing = CommandIsExecuting::new();
os_input.set_raw_mode(0);
let _ = os_input
.get_stdout_writer()
.write(bracketed_paste.as_bytes())
.unwrap();
let (send_client_instructions, receive_client_instructions): ChannelWithContext<
ClientInstruction,
> = channels::bounded(50);
let send_client_instructions = SenderWithContext::new(send_client_instructions);
let (send_input_instructions, receive_input_instructions): ChannelWithContext<
InputInstruction,
> = channels::bounded(50);
let send_input_instructions = SenderWithContext::new(send_input_instructions);
std::panic::set_hook({
use zellij_utils::errors::handle_panic;
let send_client_instructions = send_client_instructions.clone();
let os_input = os_input.clone();
Box::new(move |info| {
if let Ok(()) = os_input.unset_raw_mode(0) {
handle_panic(info, Some(&send_client_instructions));
}
})
});
let on_force_close = config_options.on_force_close.unwrap_or_default();
let stdin_ansi_parser = Arc::new(Mutex::new(StdinAnsiParser::new()));
let _stdin_thread = thread::Builder::new()
.name("stdin_handler".to_string())
.spawn({
let os_input = os_input.clone();
let send_input_instructions = send_input_instructions.clone();
let stdin_ansi_parser = stdin_ansi_parser.clone();
move || {
stdin_loop(
os_input,
send_input_instructions,
stdin_ansi_parser,
explicitly_disable_kitty_keyboard_protocol,
)
}
});
let _input_thread = thread::Builder::new()
.name("input_handler".to_string())
.spawn({
let send_client_instructions = send_client_instructions.clone();
let command_is_executing = command_is_executing.clone();
let os_input = os_input.clone();
let default_mode = config_options.default_mode.unwrap_or_default();
move || {
input_loop(
os_input,
config,
config_options,
command_is_executing,
send_client_instructions,
default_mode,
receive_input_instructions,
)
}
});
let _signal_thread = thread::Builder::new()
.name("signal_listener".to_string())
.spawn({
let os_input = os_input.clone();
move || {
os_input.handle_signals(
Box::new({
let os_api = os_input.clone();
move || {
os_api.send_to_server(ClientToServerMsg::TerminalResize {
new_size: os_api.get_terminal_size_using_fd(0),
});
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/input_handler.rs | zellij-client/src/input_handler.rs | //! Main input logic.
use crate::{
os_input_output::ClientOsApi, stdin_ansi_parser::AnsiStdinInstruction, ClientId,
ClientInstruction, CommandIsExecuting, InputInstruction,
};
use termwiz::input::{InputEvent, Modifiers, MouseButtons, MouseEvent as TermwizMouseEvent};
use zellij_utils::{
channels::{Receiver, SenderWithContext, OPENCALLS},
data::{InputMode, KeyWithModifier},
errors::{ContextType, ErrorContext, FatalError},
input::{
actions::Action,
cast_termwiz_key,
config::Config,
mouse::{MouseEvent, MouseEventType},
options::Options,
},
ipc::{ClientToServerMsg, ExitReason},
position::Position,
};
/// Handles the dispatching of [`Action`]s according to the current
/// [`InputMode`], and keep tracks of the current [`InputMode`].
struct InputHandler {
/// The current input mode
mode: InputMode,
os_input: Box<dyn ClientOsApi>,
config: Config,
options: Options,
command_is_executing: CommandIsExecuting,
send_client_instructions: SenderWithContext<ClientInstruction>,
should_exit: bool,
receive_input_instructions: Receiver<(InputInstruction, ErrorContext)>,
mouse_old_event: MouseEvent,
mouse_mode_active: bool,
}
fn termwiz_mouse_convert(original_event: &mut MouseEvent, event: &TermwizMouseEvent) {
let button_bits = &event.mouse_buttons;
original_event.left = button_bits.contains(MouseButtons::LEFT);
original_event.right = button_bits.contains(MouseButtons::RIGHT);
original_event.middle = button_bits.contains(MouseButtons::MIDDLE);
original_event.wheel_up = button_bits.contains(MouseButtons::VERT_WHEEL)
&& button_bits.contains(MouseButtons::WHEEL_POSITIVE);
original_event.wheel_down = button_bits.contains(MouseButtons::VERT_WHEEL)
&& !button_bits.contains(MouseButtons::WHEEL_POSITIVE);
let mods = &event.modifiers;
original_event.shift = mods.contains(Modifiers::SHIFT);
original_event.alt = mods.contains(Modifiers::ALT);
original_event.ctrl = mods.contains(Modifiers::CTRL);
}
pub fn from_termwiz(old_event: &mut MouseEvent, event: TermwizMouseEvent) -> MouseEvent {
// We use the state of old_event vs new_event to determine if this
// event is a Press, Release, or Motion. This is an unfortunate
// side effect of the pre-SGR-encoded X10 mouse protocol design in
// which release events don't carry information about WHICH
// button(s) were released, so we have to maintain a wee bit of
// state in between events.
//
// Note that only Left, Right, and Middle are saved in between
// calls. WheelUp/WheelDown typically do not generate Release
// events.
let mut new_event = MouseEvent::new();
termwiz_mouse_convert(&mut new_event, &event);
new_event.position = Position::new(event.y.saturating_sub(1) as i32, event.x.saturating_sub(1));
if (new_event.left && !old_event.left)
|| (new_event.right && !old_event.right)
|| (new_event.middle && !old_event.middle)
|| new_event.wheel_up
|| new_event.wheel_down
{
// This is a mouse Press event.
new_event.event_type = MouseEventType::Press;
// Hang onto the button state.
*old_event = new_event;
} else if event.mouse_buttons.is_empty()
&& !old_event.left
&& !old_event.right
&& !old_event.middle
{
// This is a mouse Motion event (no buttons are down).
new_event.event_type = MouseEventType::Motion;
// Hang onto the button state.
*old_event = new_event;
} else if event.mouse_buttons.is_empty()
&& (old_event.left || old_event.right || old_event.middle)
{
// This is a mouse Release event. Note that we set
// old_event.{button} to false (to release), but set ONLY the
// new_event that were released to true before sending the
// event up.
if old_event.left {
old_event.left = false;
new_event.left = true;
}
if old_event.right {
old_event.right = false;
new_event.right = true;
}
if old_event.middle {
old_event.middle = false;
new_event.middle = true;
}
new_event.event_type = MouseEventType::Release;
} else {
// Dragging with some button down. Return it as a Motion
// event, and hang on to the button state.
new_event.event_type = MouseEventType::Motion;
*old_event = new_event;
}
new_event
}
impl InputHandler {
/// Returns a new [`InputHandler`] with the attributes specified as arguments.
fn new(
os_input: Box<dyn ClientOsApi>,
command_is_executing: CommandIsExecuting,
config: Config,
options: Options,
send_client_instructions: SenderWithContext<ClientInstruction>,
mode: InputMode, // TODO: we can probably get rid of this now that we're tracking it on the
// server instead
receive_input_instructions: Receiver<(InputInstruction, ErrorContext)>,
) -> Self {
InputHandler {
mode,
os_input,
config,
options,
command_is_executing,
send_client_instructions,
should_exit: false,
receive_input_instructions,
mouse_old_event: MouseEvent::new(),
mouse_mode_active: false,
}
}
/// Main input event loop. Interprets the terminal Event
/// as [`Action`]s according to the current [`InputMode`], and dispatches those actions.
fn handle_input(&mut self) {
let mut err_ctx = OPENCALLS.with(|ctx| *ctx.borrow());
err_ctx.add_call(ContextType::StdinHandler);
let bracketed_paste_start = vec![27, 91, 50, 48, 48, 126]; // \u{1b}[200~
let bracketed_paste_end = vec![27, 91, 50, 48, 49, 126]; // \u{1b}[201~
if self.options.mouse_mode.unwrap_or(true) {
self.os_input.enable_mouse().non_fatal();
self.mouse_mode_active = true;
}
loop {
if self.should_exit {
break;
}
match self.receive_input_instructions.recv() {
Ok((InputInstruction::KeyEvent(input_event, raw_bytes), _error_context)) => {
match input_event {
InputEvent::Key(key_event) => {
let key = cast_termwiz_key(
key_event,
&raw_bytes,
Some((&self.config.keybinds, &self.mode)),
);
self.handle_key(&key, raw_bytes, false);
},
InputEvent::Mouse(mouse_event) => {
let mouse_event = from_termwiz(&mut self.mouse_old_event, mouse_event);
self.handle_mouse_event(&mouse_event);
},
InputEvent::Paste(pasted_text) => {
if self.mode == InputMode::Normal || self.mode == InputMode::Locked {
self.dispatch_action(
Action::Write {
key_with_modifier: None,
bytes: bracketed_paste_start.clone(),
is_kitty_keyboard_protocol: false,
},
None,
);
self.dispatch_action(
Action::Write {
key_with_modifier: None,
bytes: pasted_text.as_bytes().to_vec(),
is_kitty_keyboard_protocol: false,
},
None,
);
self.dispatch_action(
Action::Write {
key_with_modifier: None,
bytes: bracketed_paste_end.clone(),
is_kitty_keyboard_protocol: false,
},
None,
);
}
if self.mode == InputMode::EnterSearch {
self.dispatch_action(
Action::SearchInput {
input: pasted_text.as_bytes().to_vec(),
},
None,
);
}
if self.mode == InputMode::RenameTab {
self.dispatch_action(
Action::TabNameInput {
input: pasted_text.as_bytes().to_vec(),
},
None,
);
}
if self.mode == InputMode::RenamePane {
self.dispatch_action(
Action::PaneNameInput {
input: pasted_text.as_bytes().to_vec(),
},
None,
);
}
},
_ => {},
}
},
Ok((
InputInstruction::KeyWithModifierEvent(key_with_modifier, raw_bytes),
_error_context,
)) => {
self.handle_key(&key_with_modifier, raw_bytes, true);
},
Ok((
InputInstruction::AnsiStdinInstructions(ansi_stdin_instructions),
_error_context,
)) => {
for ansi_instruction in ansi_stdin_instructions {
self.handle_stdin_ansi_instruction(ansi_instruction);
}
},
Ok((InputInstruction::StartedParsing, _error_context)) => {
self.send_client_instructions
.send(ClientInstruction::StartedParsingStdinQuery)
.unwrap();
},
Ok((InputInstruction::DoneParsing, _error_context)) => {
self.send_client_instructions
.send(ClientInstruction::DoneParsingStdinQuery)
.unwrap();
},
Ok((InputInstruction::Exit, _error_context)) => {
self.should_exit = true;
},
Err(err) => panic!("Encountered read error: {:?}", err),
}
}
}
fn handle_key(
&mut self,
key: &KeyWithModifier,
raw_bytes: Vec<u8>,
is_kitty_keyboard_protocol: bool,
) {
// we interpret the keys into actions on the server side so that we can change the
// keybinds at runtime
self.os_input.send_to_server(ClientToServerMsg::Key {
key: key.clone(),
raw_bytes,
is_kitty_keyboard_protocol,
});
}
fn handle_stdin_ansi_instruction(&mut self, ansi_stdin_instructions: AnsiStdinInstruction) {
match ansi_stdin_instructions {
AnsiStdinInstruction::PixelDimensions(pixel_dimensions) => {
self.os_input
.send_to_server(ClientToServerMsg::TerminalPixelDimensions {
pixel_dimensions,
});
},
AnsiStdinInstruction::BackgroundColor(background_color_instruction) => {
self.os_input
.send_to_server(ClientToServerMsg::BackgroundColor {
color: background_color_instruction,
});
},
AnsiStdinInstruction::ForegroundColor(foreground_color_instruction) => {
self.os_input
.send_to_server(ClientToServerMsg::ForegroundColor {
color: foreground_color_instruction,
});
},
AnsiStdinInstruction::ColorRegisters(color_registers) => {
let color_registers: Vec<_> = color_registers
.into_iter()
.map(|(index, color)| zellij_utils::ipc::ColorRegister { index, color })
.collect();
self.os_input
.send_to_server(ClientToServerMsg::ColorRegisters { color_registers });
},
AnsiStdinInstruction::SynchronizedOutput(enabled) => {
self.send_client_instructions
.send(ClientInstruction::SetSynchronizedOutput(enabled))
.unwrap();
},
}
}
fn handle_mouse_event(&mut self, mouse_event: &MouseEvent) {
// This dispatch handles all of the output(s) to terminal
// pane(s).
self.dispatch_action(
Action::MouseEvent {
event: *mouse_event,
},
None,
);
}
/// Dispatches an [`Action`].
///
/// This function's body dictates what each [`Action`] actually does when
/// dispatched.
///
/// # Return value
/// Currently, this function returns a boolean that indicates whether
/// [`Self::handle_input()`] should break after this action is dispatched.
/// This is a temporary measure that is only necessary due to the way that the
/// framework works, and shouldn't be necessary anymore once the test framework
/// is revised. See [issue#183](https://github.com/zellij-org/zellij/issues/183).
fn dispatch_action(&mut self, action: Action, client_id: Option<ClientId>) -> bool {
let mut should_break = false;
match action {
Action::NoOp => {},
Action::Quit => {
self.os_input.send_to_server(ClientToServerMsg::Action {
action,
terminal_id: None,
client_id,
is_cli_client: false,
});
self.exit(ExitReason::Normal);
should_break = true;
},
Action::Detach => {
self.os_input.send_to_server(ClientToServerMsg::Action {
action,
terminal_id: None,
client_id,
is_cli_client: false,
});
self.exit(ExitReason::NormalDetached);
should_break = true;
},
Action::SwitchSession { .. } => {
self.os_input.send_to_server(ClientToServerMsg::Action {
action,
terminal_id: None,
client_id,
is_cli_client: false,
});
self.exit(ExitReason::NormalDetached);
should_break = true;
},
Action::CloseFocus
| Action::SwitchToMode { .. }
| Action::ClearScreen
| Action::NewPane { .. }
| Action::Run { .. }
| Action::NewTiledPane { .. }
| Action::NewFloatingPane { .. }
| Action::ToggleFloatingPanes
| Action::TogglePaneEmbedOrFloating
| Action::NewTab { .. }
| Action::GoToNextTab
| Action::GoToPreviousTab
| Action::CloseTab
| Action::GoToTab { .. }
| Action::MoveTab { .. }
| Action::GoToTabName { .. }
| Action::ToggleTab
| Action::MoveFocusOrTab { .. } => {
self.command_is_executing.blocking_input_thread();
self.os_input.send_to_server(ClientToServerMsg::Action {
action,
terminal_id: None,
client_id,
is_cli_client: false,
});
self.command_is_executing
.wait_until_input_thread_is_unblocked();
},
Action::ToggleMouseMode => {
if self.mouse_mode_active {
self.os_input.disable_mouse().non_fatal();
self.mouse_mode_active = false;
} else {
self.os_input.enable_mouse().non_fatal();
self.mouse_mode_active = true;
}
},
_ => self.os_input.send_to_server(ClientToServerMsg::Action {
action,
terminal_id: None,
client_id,
is_cli_client: false,
}),
}
should_break
}
/// Routine to be called when the input handler exits (at the moment this is the
/// same as quitting Zellij).
fn exit(&mut self, reason: ExitReason) {
self.send_client_instructions
.send(ClientInstruction::Exit(reason))
.unwrap();
}
}
/// Entry point to the module. Instantiates an [`InputHandler`] and starts
/// its [`InputHandler::handle_input()`] loop.
pub(crate) fn input_loop(
os_input: Box<dyn ClientOsApi>,
config: Config,
options: Options,
command_is_executing: CommandIsExecuting,
send_client_instructions: SenderWithContext<ClientInstruction>,
default_mode: InputMode,
receive_input_instructions: Receiver<(InputInstruction, ErrorContext)>,
) {
let _handler = InputHandler::new(
os_input,
command_is_executing,
config,
options,
send_client_instructions,
default_mode,
receive_input_instructions,
)
.handle_input();
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/command_is_executing.rs | zellij-client/src/command_is_executing.rs | #![allow(clippy::mutex_atomic)]
use std::sync::{Arc, Condvar, Mutex};
#[derive(Clone)]
pub(crate) struct CommandIsExecuting {
input_thread: Arc<(Mutex<bool>, Condvar)>,
}
impl CommandIsExecuting {
pub fn new() -> Self {
CommandIsExecuting {
input_thread: Arc::new((Mutex::new(false), Condvar::new())),
}
}
pub fn blocking_input_thread(&mut self) {
let (lock, _cvar) = &*self.input_thread;
let mut input_thread = lock.lock().unwrap();
*input_thread = true;
}
pub fn unblock_input_thread(&mut self) {
let (lock, cvar) = &*self.input_thread;
let mut input_thread = lock.lock().unwrap();
*input_thread = false;
cvar.notify_all();
}
pub fn wait_until_input_thread_is_unblocked(&self) {
let (lock, cvar) = &*self.input_thread;
let mut input_thread = lock.lock().unwrap();
while *input_thread {
input_thread = cvar.wait(input_thread).unwrap();
}
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/stdin_ansi_parser.rs | zellij-client/src/stdin_ansi_parser.rs | use std::time::{Duration, Instant};
const STARTUP_PARSE_DEADLINE_MS: u64 = 500;
use lazy_static::lazy_static;
use regex::Regex;
use zellij_utils::{
consts::ZELLIJ_STDIN_CACHE_FILE, ipc::PixelDimensions, pane_size::SizeInPixels,
};
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
/// Describe the terminal implementation of synchronised output
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum SyncOutput {
DCS,
CSI,
}
impl SyncOutput {
pub fn start_seq(&self) -> &'static [u8] {
static CSI_BSU_SEQ: &'static [u8] = "\u{1b}[?2026h".as_bytes();
static DCS_BSU_SEQ: &'static [u8] = "\u{1b}P=1s\u{1b}".as_bytes();
match self {
SyncOutput::DCS => DCS_BSU_SEQ,
SyncOutput::CSI => CSI_BSU_SEQ,
}
}
pub fn end_seq(&self) -> &'static [u8] {
static CSI_ESU_SEQ: &'static [u8] = "\u{1b}[?2026l".as_bytes();
static DCS_ESU_SEQ: &'static [u8] = "\u{1b}P=2s\u{1b}".as_bytes();
match self {
SyncOutput::DCS => DCS_ESU_SEQ,
SyncOutput::CSI => CSI_ESU_SEQ,
}
}
}
#[derive(Debug)]
pub struct StdinAnsiParser {
raw_buffer: Vec<u8>,
pending_color_sequences: Vec<(usize, String)>,
pending_events: Vec<AnsiStdinInstruction>,
parse_deadline: Option<Instant>,
}
impl StdinAnsiParser {
pub fn new() -> Self {
StdinAnsiParser {
raw_buffer: vec![],
pending_color_sequences: vec![],
pending_events: vec![],
parse_deadline: None,
}
}
pub fn terminal_emulator_query_string(&mut self) -> String {
// note that this assumes the String will be sent to the terminal emulator and so starts a
// deadline timeout (self.parse_deadline)
// <ESC>[14t => get text area size in pixels,
// <ESC>[16t => get character cell size in pixels
// <ESC>]11;?<ESC>\ => get background color
// <ESC>]10;?<ESC>\ => get foreground color
// <ESC>[?2026$p => get synchronised output mode
let mut query_string = String::from(
"\u{1b}[14t\u{1b}[16t\u{1b}]11;?\u{1b}\u{5c}\u{1b}]10;?\u{1b}\u{5c}\u{1b}[?2026$p",
);
// query colors
// eg. <ESC>]4;5;?<ESC>\ => query color register number 5
for i in 0..256 {
query_string.push_str(&format!("\u{1b}]4;{};?\u{1b}\u{5c}", i));
}
self.parse_deadline =
Some(Instant::now() + Duration::from_millis(STARTUP_PARSE_DEADLINE_MS));
query_string
}
fn drain_pending_events(&mut self) -> Vec<AnsiStdinInstruction> {
let mut events = vec![];
events.append(&mut self.pending_events);
if let Some(color_registers) =
AnsiStdinInstruction::color_registers_from_bytes(&mut self.pending_color_sequences)
{
events.push(color_registers);
}
events
}
pub fn should_parse(&self) -> bool {
if let Some(parse_deadline) = self.parse_deadline {
if parse_deadline >= Instant::now() {
return true;
}
}
false
}
pub fn startup_query_duration(&self) -> u64 {
STARTUP_PARSE_DEADLINE_MS
}
pub fn parse(&mut self, mut raw_bytes: Vec<u8>) -> Vec<AnsiStdinInstruction> {
for byte in raw_bytes.drain(..) {
self.parse_byte(byte);
}
self.drain_pending_events()
}
pub fn read_cache(&self) -> Option<Vec<AnsiStdinInstruction>> {
match OpenOptions::new()
.read(true)
.open(ZELLIJ_STDIN_CACHE_FILE.as_path())
{
Ok(mut file) => {
let mut json_cache = String::new();
file.read_to_string(&mut json_cache).ok()?;
let instructions =
serde_json::from_str::<Vec<AnsiStdinInstruction>>(&json_cache).ok()?;
if instructions.is_empty() {
None
} else {
Some(instructions)
}
},
Err(e) => {
log::error!("Failed to open STDIN cache file: {:?}", e);
None
},
}
}
pub fn write_cache(&self, events: Vec<AnsiStdinInstruction>) {
if let Ok(serialized_events) = serde_json::to_string(&events) {
if let Ok(mut file) = File::create(ZELLIJ_STDIN_CACHE_FILE.as_path()) {
let _ = file.write_all(serialized_events.as_bytes());
}
};
}
fn parse_byte(&mut self, byte: u8) {
if byte == b't' {
self.raw_buffer.push(byte);
match AnsiStdinInstruction::pixel_dimensions_from_bytes(&self.raw_buffer) {
Ok(ansi_sequence) => {
self.pending_events.push(ansi_sequence);
self.raw_buffer.clear();
},
Err(_) => {
self.raw_buffer.clear();
},
}
} else if byte == b'\\' {
self.raw_buffer.push(byte);
if let Ok(ansi_sequence) = AnsiStdinInstruction::bg_or_fg_from_bytes(&self.raw_buffer) {
self.pending_events.push(ansi_sequence);
self.raw_buffer.clear();
} else if let Ok((color_register, color_sequence)) =
color_sequence_from_bytes(&self.raw_buffer)
{
self.raw_buffer.clear();
self.pending_color_sequences
.push((color_register, color_sequence));
} else {
self.raw_buffer.clear();
}
} else if byte == b'y' {
self.raw_buffer.push(byte);
if let Some(ansi_sequence) =
AnsiStdinInstruction::synchronized_output_from_bytes(&self.raw_buffer)
{
self.pending_events.push(ansi_sequence);
self.raw_buffer.clear();
}
} else {
self.raw_buffer.push(byte);
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AnsiStdinInstruction {
PixelDimensions(PixelDimensions),
BackgroundColor(String),
ForegroundColor(String),
ColorRegisters(Vec<(usize, String)>),
SynchronizedOutput(Option<SyncOutput>),
}
impl AnsiStdinInstruction {
pub fn pixel_dimensions_from_bytes(bytes: &[u8]) -> Result<Self, &'static str> {
// eg. <ESC>[4;21;8t
lazy_static! {
static ref RE: Regex = Regex::new(r"^\u{1b}\[(\d+);(\d+);(\d+)t$").unwrap();
}
let key_string = String::from_utf8_lossy(bytes); // TODO: handle error
let captures = RE
.captures_iter(&key_string)
.next()
.ok_or("invalid_instruction")?;
let csi_index = captures[1].parse::<usize>();
let first_field = captures[2].parse::<usize>();
let second_field = captures[3].parse::<usize>();
if csi_index.is_err() || first_field.is_err() || second_field.is_err() {
return Err("invalid_instruction");
}
match csi_index {
Ok(4) => {
// text area size
Ok(AnsiStdinInstruction::PixelDimensions(PixelDimensions {
character_cell_size: None,
text_area_size: Some(SizeInPixels {
height: first_field.unwrap(),
width: second_field.unwrap(),
}),
}))
},
Ok(6) => {
// character cell size
Ok(AnsiStdinInstruction::PixelDimensions(PixelDimensions {
character_cell_size: Some(SizeInPixels {
height: first_field.unwrap(),
width: second_field.unwrap(),
}),
text_area_size: None,
}))
},
_ => Err("invalid sequence"),
}
}
pub fn bg_or_fg_from_bytes(bytes: &[u8]) -> Result<Self, &'static str> {
// eg. <ESC>]11;rgb:0000/0000/0000\
lazy_static! {
static ref BACKGROUND_RE: Regex = Regex::new(r"\]11;(.*)\u{1b}\\$").unwrap();
}
// eg. <ESC>]10;rgb:ffff/ffff/ffff\
lazy_static! {
static ref FOREGROUND_RE: Regex = Regex::new(r"\]10;(.*)\u{1b}\\$").unwrap();
}
let key_string = String::from_utf8_lossy(bytes);
if let Some(captures) = BACKGROUND_RE.captures_iter(&key_string).next() {
let background_query_response = captures[1].parse::<String>();
match background_query_response {
Ok(background_query_response) => Ok(AnsiStdinInstruction::BackgroundColor(
background_query_response,
)),
_ => Err("invalid_instruction"),
}
} else if let Some(captures) = FOREGROUND_RE.captures_iter(&key_string).next() {
let foreground_query_response = captures[1].parse::<String>();
match foreground_query_response {
Ok(foreground_query_response) => Ok(AnsiStdinInstruction::ForegroundColor(
foreground_query_response,
)),
_ => Err("invalid_instruction"),
}
} else {
Err("invalid_instruction")
}
}
pub fn color_registers_from_bytes(color_sequences: &mut Vec<(usize, String)>) -> Option<Self> {
if color_sequences.is_empty() {
return None;
}
let mut registers = vec![];
for (color_register, color_sequence) in color_sequences.drain(..) {
registers.push((color_register, color_sequence));
}
Some(AnsiStdinInstruction::ColorRegisters(registers))
}
pub fn synchronized_output_from_bytes(bytes: &[u8]) -> Option<Self> {
lazy_static! {
static ref RE: Regex = Regex::new(r"^\u{1b}\[\?2026;([0|1|2|3|4])\$y$").unwrap();
}
let key_string = String::from_utf8_lossy(bytes);
if let Some(captures) = RE.captures_iter(&key_string).next() {
match captures[1].parse::<usize>().ok()? {
1 | 2 => Some(AnsiStdinInstruction::SynchronizedOutput(Some(
SyncOutput::CSI,
))),
0 | 4 => Some(AnsiStdinInstruction::SynchronizedOutput(None)),
_ => None,
}
} else {
None
}
}
}
fn color_sequence_from_bytes(bytes: &[u8]) -> Result<(usize, String), &'static str> {
lazy_static! {
static ref COLOR_REGISTER_RE: Regex = Regex::new(r"\]4;(.*);(.*)\u{1b}\\$").unwrap();
}
lazy_static! {
// this form is used by eg. Alacritty, where the leading 4 is dropped in the response
static ref ALTERNATIVE_COLOR_REGISTER_RE: Regex = Regex::new(r"\](.*);(.*)\u{1b}\\$").unwrap();
}
let key_string = String::from_utf8_lossy(bytes);
if let Some(captures) = COLOR_REGISTER_RE.captures_iter(&key_string).next() {
let color_register_response = captures[1].parse::<usize>();
let color_response = captures[2].parse::<String>();
match (color_register_response, color_response) {
(Ok(crr), Ok(cr)) => Ok((crr, cr)),
_ => Err("invalid_instruction"),
}
} else if let Some(captures) = ALTERNATIVE_COLOR_REGISTER_RE
.captures_iter(&key_string)
.next()
{
let color_register_response = captures[1].parse::<usize>();
let color_response = captures[2].parse::<String>();
match (color_register_response, color_response) {
(Ok(crr), Ok(cr)) => Ok((crr, cr)),
_ => Err("invalid_instruction"),
}
} else {
Err("invalid_instruction")
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/keyboard_parser.rs | zellij-client/src/keyboard_parser.rs | // for more info, please see: https://sw.kovidgoyal.net/kitty/keyboard-protocol
use zellij_utils::data::KeyWithModifier;
#[derive(Debug)]
enum KittyKeysParsingState {
Ground,
ReceivedEscapeCharacter,
ParsingNumber,
ParsingModifiers,
DoneParsingWithU,
DoneParsingWithTilde,
}
#[derive(Debug)]
pub struct KittyKeyboardParser {
state: KittyKeysParsingState,
number_bytes: Vec<u8>,
modifier_bytes: Vec<u8>,
}
impl KittyKeyboardParser {
pub fn new() -> Self {
KittyKeyboardParser {
state: KittyKeysParsingState::Ground,
number_bytes: vec![],
modifier_bytes: vec![],
}
}
pub fn parse(&mut self, buffer: &[u8]) -> Option<KeyWithModifier> {
for byte in buffer {
if !self.advance(*byte) {
return None;
}
}
match self.state {
KittyKeysParsingState::DoneParsingWithU => {
// CSI number ; modifiers u
KeyWithModifier::from_bytes_with_u(&self.number_bytes, &self.modifier_bytes)
},
KittyKeysParsingState::DoneParsingWithTilde => {
// CSI number ; modifiers ~
KeyWithModifier::from_bytes_with_tilde(&self.number_bytes, &self.modifier_bytes)
},
KittyKeysParsingState::ParsingModifiers => {
// CSI 1; modifiers [ABCDEFHPQS]
match self.modifier_bytes.pop() {
Some(last_modifier) => KeyWithModifier::from_bytes_with_no_ending_byte(
&[last_modifier],
&self.modifier_bytes,
),
None => None,
}
},
KittyKeysParsingState::ParsingNumber => {
KeyWithModifier::from_bytes_with_no_ending_byte(
&self.number_bytes,
&self.modifier_bytes,
)
},
_ => None,
}
}
pub fn advance(&mut self, byte: u8) -> bool {
// returns false if we failed parsing
match (&self.state, byte) {
(KittyKeysParsingState::Ground, 0x1b | 0x5b) => {
self.state = KittyKeysParsingState::ReceivedEscapeCharacter;
},
(KittyKeysParsingState::ReceivedEscapeCharacter, 91) => {
self.state = KittyKeysParsingState::ParsingNumber;
},
(KittyKeysParsingState::ParsingNumber, 59) => {
// semicolon
if &self.number_bytes == &[49] {
self.number_bytes.clear();
}
self.state = KittyKeysParsingState::ParsingModifiers;
},
(
KittyKeysParsingState::ParsingNumber | KittyKeysParsingState::ParsingModifiers,
117,
) => {
// u
self.state = KittyKeysParsingState::DoneParsingWithU;
},
(
KittyKeysParsingState::ParsingNumber | KittyKeysParsingState::ParsingModifiers,
126,
) => {
// ~
self.state = KittyKeysParsingState::DoneParsingWithTilde;
},
(KittyKeysParsingState::ParsingNumber, _) => {
self.number_bytes.push(byte);
},
(KittyKeysParsingState::ParsingModifiers, _) => {
self.modifier_bytes.push(byte);
},
(_, _) => {
return false;
},
}
true
}
}
#[test]
pub fn can_parse_bare_keys() {
use zellij_utils::data::BareKey;
let key = "\u{1b}[97u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Char('a'))),
"Can parse a bare 'a' keypress"
);
let key = "\u{1b}[49u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Char('1'))),
"Can parse a bare '1' keypress"
);
let key = "\u{1b}[27u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Esc)),
"Can parse a bare 'ESC' keypress"
);
let key = "\u{1b}[13u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Enter)),
"Can parse a bare 'ENTER' keypress"
);
let key = "\u{1b}[9u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Tab)),
"Can parse a bare 'Tab' keypress"
);
let key = "\u{1b}[127u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Backspace)),
"Can parse a bare 'Backspace' keypress"
);
let key = "\u{1b}[57358u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::CapsLock)),
"Can parse a bare 'CapsLock' keypress"
);
let key = "\u{1b}[57359u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::ScrollLock)),
"Can parse a bare 'ScrollLock' keypress"
);
let key = "\u{1b}[57360u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::NumLock)),
"Can parse a bare 'NumLock' keypress"
);
let key = "\u{1b}[57361u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::PrintScreen)),
"Can parse a bare 'PrintScreen' keypress"
);
let key = "\u{1b}[57362u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Pause)),
"Can parse a bare 'Pause' keypress"
);
let key = "\u{1b}[57363u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Menu)),
"Can parse a bare 'Menu' keypress"
);
let key = "\u{1b}[2~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Insert)),
"Can parse a bare 'Insert' keypress"
);
let key = "\u{1b}[3~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Delete)),
"Can parse a bare 'Delete' keypress"
);
let key = "\u{1b}[5~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::PageUp)),
"Can parse a bare 'PageUp' keypress"
);
let key = "\u{1b}[6~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::PageDown)),
"Can parse a bare 'PageDown' keypress"
);
let key = "\u{1b}[7~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Home)),
"Can parse a bare 'Home' keypress"
);
let key = "\u{1b}[8~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::End)),
"Can parse a bare 'End' keypress"
);
let key = "\u{1b}[11~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(1))),
"Can parse a bare 'F1' keypress"
);
let key = "\u{1b}[12~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(2))),
"Can parse a bare 'F2' keypress"
);
let key = "\u{1b}[13~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(3))),
"Can parse a bare 'F3' keypress"
);
let key = "\u{1b}[14~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(4))),
"Can parse a bare 'F4' keypress"
);
let key = "\u{1b}[15~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(5))),
"Can parse a bare 'F5' keypress"
);
let key = "\u{1b}[17~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(6))),
"Can parse a bare 'F6' keypress"
);
let key = "\u{1b}[18~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(7))),
"Can parse a bare 'F7' keypress"
);
let key = "\u{1b}[19~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(8))),
"Can parse a bare 'F8' keypress"
);
let key = "\u{1b}[20~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(9))),
"Can parse a bare 'F9' keypress"
);
let key = "\u{1b}[21~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(10))),
"Can parse a bare 'F10' keypress"
);
let key = "\u{1b}[23~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(11))),
"Can parse a bare 'F11' keypress"
);
let key = "\u{1b}[24~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(12))),
"Can parse a bare 'F12' keypress"
);
let key = "\u{1b}[D";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Left)),
"Can parse a bare 'Left' keypress"
);
let key = "\u{1b}[C";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Right)),
"Can parse a bare 'Right' keypress"
);
let key = "\u{1b}[A";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Up)),
"Can parse a bare 'Up' keypress"
);
let key = "\u{1b}[B";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Down)),
"Can parse a bare 'Down' keypress"
);
let key = "\u{1b}[H";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Home)),
"Can parse a bare 'Home' keypress"
);
let key = "\u{1b}[F";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::End)),
"Can parse a bare 'End' keypress"
);
let key = "\u{1b}[P";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(1))),
"Can parse a bare 'F1 (alternate)' keypress"
);
let key = "\u{1b}[Q";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(2))),
"Can parse a bare 'F2 (alternate)' keypress"
);
let key = "\u{1b}[S";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(4))),
"Can parse a bare 'F4 (alternate)' keypress"
);
}
#[test]
pub fn can_parse_keys_with_shift_modifier() {
use zellij_utils::data::BareKey;
let key = "\u{1b}[97;2u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Char('a')).with_shift_modifier()),
"Can parse a bare 'a' keypress with shift"
);
let key = "\u{1b}[49;2u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Char('1')).with_shift_modifier()),
"Can parse a bare '1' keypress with shift"
);
let key = "\u{1b}[27;2u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Esc).with_shift_modifier()),
"Can parse a bare 'ESC' keypress with shift"
);
let key = "\u{1b}[13;2u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Enter).with_shift_modifier()),
"Can parse a bare 'ENTER' keypress with shift"
);
let key = "\u{1b}[9;2u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Tab).with_shift_modifier()),
"Can parse a bare 'Tab' keypress with shift"
);
let key = "\u{1b}[127;2u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Backspace).with_shift_modifier()),
"Can parse a bare 'Backspace' keypress with shift"
);
let key = "\u{1b}[57358;2u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::CapsLock).with_shift_modifier()),
"Can parse a bare 'CapsLock' keypress with shift"
);
let key = "\u{1b}[57359;2u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::ScrollLock).with_shift_modifier()),
"Can parse a bare 'ScrollLock' keypress with shift"
);
let key = "\u{1b}[57360;2u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::NumLock).with_shift_modifier()),
"Can parse a bare 'NumLock' keypress with shift"
);
let key = "\u{1b}[57361;2u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::PrintScreen).with_shift_modifier()),
"Can parse a bare 'PrintScreen' keypress with shift"
);
let key = "\u{1b}[57362;2u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Pause).with_shift_modifier()),
"Can parse a bare 'Pause' keypress with shift"
);
let key = "\u{1b}[57363;2u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Menu).with_shift_modifier()),
"Can parse a bare 'Menu' keypress with shift"
);
let key = "\u{1b}[2;2~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Insert).with_shift_modifier()),
"Can parse a bare 'Insert' keypress with shift"
);
let key = "\u{1b}[3;2~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Delete).with_shift_modifier()),
"Can parse a bare 'Delete' keypress with shift"
);
let key = "\u{1b}[5;2~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::PageUp).with_shift_modifier()),
"Can parse a bare 'PageUp' keypress with shift"
);
let key = "\u{1b}[6;2~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::PageDown).with_shift_modifier()),
"Can parse a bare 'PageDown' keypress with shift"
);
let key = "\u{1b}[7;2~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Home).with_shift_modifier()),
"Can parse a bare 'Home' keypress with shift"
);
let key = "\u{1b}[8;2~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::End).with_shift_modifier()),
"Can parse a bare 'End' keypress with shift"
);
let key = "\u{1b}[11;2~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(1)).with_shift_modifier()),
"Can parse a bare 'F1' keypress with shift"
);
let key = "\u{1b}[12;2~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(2)).with_shift_modifier()),
"Can parse a bare 'F2' keypress with shift"
);
let key = "\u{1b}[13;2~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(3)).with_shift_modifier()),
"Can parse a bare 'F3' keypress with shift"
);
let key = "\u{1b}[14;2~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(4)).with_shift_modifier()),
"Can parse a bare 'F4' keypress with shift"
);
let key = "\u{1b}[15;2~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(5)).with_shift_modifier()),
"Can parse a bare 'F5' keypress with shift"
);
let key = "\u{1b}[17;2~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(6)).with_shift_modifier()),
"Can parse a bare 'F6' keypress with shift"
);
let key = "\u{1b}[18;2~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(7)).with_shift_modifier()),
"Can parse a bare 'F7' keypress with shift"
);
let key = "\u{1b}[19;2~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(8)).with_shift_modifier()),
"Can parse a bare 'F8' keypress with shift"
);
let key = "\u{1b}[20;2~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(9)).with_shift_modifier()),
"Can parse a bare 'F9' keypress with shift"
);
let key = "\u{1b}[21;2~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(10)).with_shift_modifier()),
"Can parse a bare 'F10' keypress with shift"
);
let key = "\u{1b}[23;2~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(11)).with_shift_modifier()),
"Can parse a bare 'F11' keypress with shift"
);
let key = "\u{1b}[24;2~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(12)).with_shift_modifier()),
"Can parse a bare 'F12' keypress with shift"
);
let key = "\u{1b}[1;2D";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Left).with_shift_modifier()),
"Can parse a bare 'Left' keypress with shift"
);
let key = "\u{1b}[1;2C";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Right).with_shift_modifier()),
"Can parse a bare 'Right' keypress with shift"
);
let key = "\u{1b}[1;2A";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Up).with_shift_modifier()),
"Can parse a bare 'Up' keypress with shift"
);
let key = "\u{1b}[1;2B";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Down).with_shift_modifier()),
"Can parse a bare 'Down' keypress with shift"
);
let key = "\u{1b}[1;2H";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Home).with_shift_modifier()),
"Can parse a bare 'Home' keypress with shift"
);
let key = "\u{1b}[1;2F";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::End).with_shift_modifier()),
"Can parse a bare 'End' keypress with shift"
);
let key = "\u{1b}[1;2P";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(1)).with_shift_modifier()),
"Can parse a bare 'F1 (alternate)' keypress with shift"
);
let key = "\u{1b}[1;2Q";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(2)).with_shift_modifier()),
"Can parse a bare 'F2 (alternate)' keypress with shift"
);
let key = "\u{1b}[1;2S";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(4)).with_shift_modifier()),
"Can parse a bare 'F4 (alternate)' keypress with shift"
);
}
#[test]
pub fn can_parse_keys_with_alt_modifier() {
use zellij_utils::data::BareKey;
let key = "\u{1b}[97;3u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Char('a')).with_alt_modifier()),
"Can parse a bare 'a' keypress with alt"
);
let key = "\u{1b}[49;3u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Char('1')).with_alt_modifier()),
"Can parse a bare '1' keypress with alt"
);
let key = "\u{1b}[27;3u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Esc).with_alt_modifier()),
"Can parse a bare 'ESC' keypress with alt"
);
let key = "\u{1b}[13;3u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Enter).with_alt_modifier()),
"Can parse a bare 'ENTER' keypress with alt"
);
let key = "\u{1b}[9;3u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Tab).with_alt_modifier()),
"Can parse a bare 'Tab' keypress with alt"
);
let key = "\u{1b}[127;3u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Backspace).with_alt_modifier()),
"Can parse a bare 'Backspace' keypress with alt"
);
let key = "\u{1b}[57358;3u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::CapsLock).with_alt_modifier()),
"Can parse a bare 'CapsLock' keypress with alt"
);
let key = "\u{1b}[57359;3u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::ScrollLock).with_alt_modifier()),
"Can parse a bare 'ScrollLock' keypress with alt"
);
let key = "\u{1b}[57360;3u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::NumLock).with_alt_modifier()),
"Can parse a bare 'NumLock' keypress with alt"
);
let key = "\u{1b}[57361;3u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::PrintScreen).with_alt_modifier()),
"Can parse a bare 'PrintScreen' keypress with alt"
);
let key = "\u{1b}[57362;3u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Pause).with_alt_modifier()),
"Can parse a bare 'Pause' keypress with alt"
);
let key = "\u{1b}[57363;3u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Menu).with_alt_modifier()),
"Can parse a bare 'Menu' keypress with alt"
);
let key = "\u{1b}[2;3~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Insert).with_alt_modifier()),
"Can parse a bare 'Insert' keypress with alt"
);
let key = "\u{1b}[3;3~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Delete).with_alt_modifier()),
"Can parse a bare 'Delete' keypress with alt"
);
let key = "\u{1b}[5;3~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::PageUp).with_alt_modifier()),
"Can parse a bare 'PageUp' keypress with alt"
);
let key = "\u{1b}[6;3~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::PageDown).with_alt_modifier()),
"Can parse a bare 'PageDown' keypress with alt"
);
let key = "\u{1b}[7;3~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Home).with_alt_modifier()),
"Can parse a bare 'Home' keypress with alt"
);
let key = "\u{1b}[8;3~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::End).with_alt_modifier()),
"Can parse a bare 'End' keypress with alt"
);
let key = "\u{1b}[11;3~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(1)).with_alt_modifier()),
"Can parse a bare 'F1' keypress with alt"
);
let key = "\u{1b}[12;3~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(2)).with_alt_modifier()),
"Can parse a bare 'F2' keypress with alt"
);
let key = "\u{1b}[13;3~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(3)).with_alt_modifier()),
"Can parse a bare 'F3' keypress with alt"
);
let key = "\u{1b}[14;3~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(4)).with_alt_modifier()),
"Can parse a bare 'F4' keypress with alt"
);
let key = "\u{1b}[15;3~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(5)).with_alt_modifier()),
"Can parse a bare 'F5' keypress with alt"
);
let key = "\u{1b}[17;3~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(6)).with_alt_modifier()),
"Can parse a bare 'F6' keypress with alt"
);
let key = "\u{1b}[18;3~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(7)).with_alt_modifier()),
"Can parse a bare 'F7' keypress with alt"
);
let key = "\u{1b}[19;3~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(8)).with_alt_modifier()),
"Can parse a bare 'F8' keypress with alt"
);
let key = "\u{1b}[20;3~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(9)).with_alt_modifier()),
"Can parse a bare 'F9' keypress with alt"
);
let key = "\u{1b}[21;3~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(10)).with_alt_modifier()),
"Can parse a bare 'F10' keypress with alt"
);
let key = "\u{1b}[23;3~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(11)).with_alt_modifier()),
"Can parse a bare 'F11' keypress with alt"
);
let key = "\u{1b}[24;3~";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(12)).with_alt_modifier()),
"Can parse a bare 'F12' keypress with alt"
);
let key = "\u{1b}[1;3D";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Left).with_alt_modifier()),
"Can parse a bare 'Left' keypress with alt"
);
let key = "\u{1b}[1;3C";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Right).with_alt_modifier()),
"Can parse a bare 'Right' keypress with alt"
);
let key = "\u{1b}[1;3A";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Up).with_alt_modifier()),
"Can parse a bare 'Up' keypress with alt"
);
let key = "\u{1b}[1;3B";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Down).with_alt_modifier()),
"Can parse a bare 'Down' keypress with alt"
);
let key = "\u{1b}[1;3H";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Home).with_alt_modifier()),
"Can parse a bare 'Home' keypress with alt"
);
let key = "\u{1b}[1;3F";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::End).with_alt_modifier()),
"Can parse a bare 'End' keypress with alt"
);
let key = "\u{1b}[1;3P";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(1)).with_alt_modifier()),
"Can parse a bare 'F1 (alternate)' keypress with alt"
);
let key = "\u{1b}[1;3Q";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(2)).with_alt_modifier()),
"Can parse a bare 'F2 (alternate)' keypress with alt"
);
let key = "\u{1b}[1;3S";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::F(4)).with_alt_modifier()),
"Can parse a bare 'F4 (alternate)' keypress with alt"
);
}
#[test]
pub fn can_parse_keys_with_ctrl_modifier() {
use zellij_utils::data::BareKey;
let key = "\u{1b}[97;5u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Char('a')).with_ctrl_modifier()),
"Can parse a bare 'a' keypress with ctrl"
);
let key = "\u{1b}[49;5u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Char('1')).with_ctrl_modifier()),
"Can parse a bare '1' keypress with ctrl"
);
let key = "\u{1b}[27;5u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Esc).with_ctrl_modifier()),
"Can parse a bare 'ESC' keypress with ctrl"
);
let key = "\u{1b}[13;5u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Enter).with_ctrl_modifier()),
"Can parse a bare 'ENTER' keypress with ctrl"
);
let key = "\u{1b}[9;5u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Tab).with_ctrl_modifier()),
"Can parse a bare 'Tab' keypress with ctrl"
);
let key = "\u{1b}[127;5u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::Backspace).with_ctrl_modifier()),
"Can parse a bare 'Backspace' keypress with ctrl"
);
let key = "\u{1b}[57358;5u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::CapsLock).with_ctrl_modifier()),
"Can parse a bare 'CapsLock' keypress with ctrl"
);
let key = "\u{1b}[57359;5u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::ScrollLock).with_ctrl_modifier()),
"Can parse a bare 'ScrollLock' keypress with ctrl"
);
let key = "\u{1b}[57360;5u";
assert_eq!(
KittyKeyboardParser::new().parse(&key.as_bytes()),
Some(KeyWithModifier::new(BareKey::NumLock).with_ctrl_modifier()),
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/cli_client.rs | zellij-client/src/cli_client.rs | //! The `[cli_client]` is used to attach to a running server session
//! and dispatch actions, that are specified through the command line.
use std::collections::BTreeMap;
use std::io::BufRead;
use std::process;
use std::{fs, path::PathBuf};
use crate::os_input_output::ClientOsApi;
use uuid::Uuid;
use zellij_utils::{
errors::prelude::*,
input::actions::Action,
ipc::{ClientToServerMsg, ExitReason, ServerToClientMsg},
};
pub fn start_cli_client(
mut os_input: Box<dyn ClientOsApi>,
session_name: &str,
actions: Vec<Action>,
) {
let zellij_ipc_pipe: PathBuf = {
let mut sock_dir = zellij_utils::consts::ZELLIJ_SOCK_DIR.clone();
fs::create_dir_all(&sock_dir).unwrap();
zellij_utils::shared::set_permissions(&sock_dir, 0o700).unwrap();
sock_dir.push(session_name);
sock_dir
};
os_input.connect_to_server(&*zellij_ipc_pipe);
let pane_id = os_input
.env_variable("ZELLIJ_PANE_ID")
.and_then(|e| e.trim().parse().ok());
for action in actions {
match action {
Action::CliPipe {
pipe_id,
name,
payload,
plugin,
args,
configuration,
launch_new,
skip_cache,
floating,
in_place,
cwd,
pane_title,
} => {
pipe_client(
&mut os_input,
pipe_id,
name,
payload,
plugin,
args,
configuration,
launch_new,
skip_cache,
floating,
in_place,
pane_id,
cwd,
pane_title,
);
},
action => {
individual_messages_client(&mut os_input, action, pane_id);
},
}
}
os_input.send_to_server(ClientToServerMsg::ClientExited);
}
fn pipe_client(
os_input: &mut Box<dyn ClientOsApi>,
pipe_id: String,
mut name: Option<String>,
mut payload: Option<String>,
plugin: Option<String>,
args: Option<BTreeMap<String, String>>,
mut configuration: Option<BTreeMap<String, String>>,
launch_new: bool,
skip_cache: bool,
floating: Option<bool>,
in_place: Option<bool>,
pane_id: Option<u32>,
cwd: Option<PathBuf>,
pane_title: Option<String>,
) {
let mut stdin = os_input.get_stdin_reader();
let name = name
// first we try to take the explicitly supplied message name
.take()
// then we use the plugin, to facilitate using aliases
.or_else(|| plugin.clone())
// then we use a uuid to at least have some sort of identifier for this message
.or_else(|| Some(Uuid::new_v4().to_string()));
if launch_new {
// we do this to make sure the plugin is unique (has a unique configuration parameter) so
// that a new one would be launched, but we'll still send it to the same instance rather
// than launching a new one in every iteration of the loop
configuration
.get_or_insert_with(BTreeMap::new)
.insert("_zellij_id".to_owned(), Uuid::new_v4().to_string());
}
let create_msg = |payload: Option<String>| -> ClientToServerMsg {
ClientToServerMsg::Action {
action: Action::CliPipe {
pipe_id: pipe_id.clone(),
name: name.clone(),
payload,
args: args.clone(),
plugin: plugin.clone(),
configuration: configuration.clone(),
floating,
in_place,
launch_new,
skip_cache,
cwd: cwd.clone(),
pane_title: pane_title.clone(),
},
terminal_id: pane_id,
client_id: None,
is_cli_client: true,
}
};
let is_piped = !os_input.stdin_is_terminal();
loop {
if let Some(payload) = payload.take() {
let msg = create_msg(Some(payload));
os_input.send_to_server(msg);
} else if !is_piped {
// here we send an empty message to trigger the plugin, because we don't have any more
// data
let msg = create_msg(None);
os_input.send_to_server(msg);
} else {
// we didn't get payload from the command line, meaning we listen on STDIN because this
// signifies the user is about to pipe more (eg. cat my-large-file | zellij pipe ...)
let mut buffer = String::new();
let _ = stdin.read_line(&mut buffer);
if buffer.is_empty() {
let msg = create_msg(None);
os_input.send_to_server(msg);
break;
} else {
// we've got data! send it down the pipe (most common)
let msg = create_msg(Some(buffer));
os_input.send_to_server(msg);
}
}
loop {
// wait for a response and act accordingly
match os_input.recv_from_server() {
Some((ServerToClientMsg::UnblockCliPipeInput { pipe_name }, _)) => {
// unblock this pipe, meaning we need to stop waiting for a response and read
// once more from STDIN
if pipe_name == pipe_id {
if !is_piped {
// if this client is not piped, we need to exit the process completely
// rather than wait for more data
process::exit(0);
} else {
break;
}
}
},
Some((ServerToClientMsg::CliPipeOutput { pipe_name, output }, _)) => {
// send data to STDOUT, this *does not* mean we need to unblock the input
let err_context = "Failed to write to stdout";
if pipe_name == pipe_id {
let mut stdout = os_input.get_stdout_writer();
stdout
.write_all(output.as_bytes())
.context(err_context)
.non_fatal();
stdout.flush().context(err_context).non_fatal();
}
},
Some((ServerToClientMsg::Log { lines: log_lines }, _)) => {
log_lines.iter().for_each(|line| println!("{line}"));
process::exit(0);
},
Some((ServerToClientMsg::LogError { lines: log_lines }, _)) => {
log_lines.iter().for_each(|line| eprintln!("{line}"));
process::exit(2);
},
Some((ServerToClientMsg::Exit { exit_reason }, _)) => match exit_reason {
ExitReason::Error(e) => {
eprintln!("{}", e);
process::exit(2);
},
_ => {
process::exit(0);
},
},
_ => {},
}
}
}
}
fn individual_messages_client(
os_input: &mut Box<dyn ClientOsApi>,
action: Action,
pane_id: Option<u32>,
) {
let msg = ClientToServerMsg::Action {
action,
terminal_id: pane_id,
client_id: None,
is_cli_client: true,
};
os_input.send_to_server(msg);
loop {
match os_input.recv_from_server() {
Some((ServerToClientMsg::UnblockInputThread, _)) => {
break;
},
Some((ServerToClientMsg::Log { lines: log_lines }, _)) => {
log_lines.iter().for_each(|line| println!("{line}"));
break;
},
Some((ServerToClientMsg::LogError { lines: log_lines }, _)) => {
log_lines.iter().for_each(|line| eprintln!("{line}"));
process::exit(2);
},
Some((ServerToClientMsg::Exit { exit_reason }, _)) => match exit_reason {
ExitReason::Error(e) => {
eprintln!("{}", e);
process::exit(2);
},
ExitReason::CustomExitStatus(exit_status) => {
process::exit(exit_status);
},
_ => {
break;
},
},
_ => {},
}
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/stdin_handler.rs | zellij-client/src/stdin_handler.rs | use crate::keyboard_parser::KittyKeyboardParser;
use crate::os_input_output::ClientOsApi;
use crate::stdin_ansi_parser::StdinAnsiParser;
use crate::InputInstruction;
use std::sync::{Arc, Mutex};
use termwiz::input::{InputEvent, InputParser, MouseButtons};
use zellij_utils::channels::SenderWithContext;
fn send_done_parsing_after_query_timeout(
send_input_instructions: SenderWithContext<InputInstruction>,
query_duration: u64,
) {
std::thread::spawn({
move || {
std::thread::sleep(std::time::Duration::from_millis(query_duration));
send_input_instructions
.send(InputInstruction::DoneParsing)
.unwrap();
}
});
}
pub(crate) fn stdin_loop(
mut os_input: Box<dyn ClientOsApi>,
send_input_instructions: SenderWithContext<InputInstruction>,
stdin_ansi_parser: Arc<Mutex<StdinAnsiParser>>,
explicitly_disable_kitty_keyboard_protocol: bool,
) {
let mut holding_mouse = false;
let mut input_parser = InputParser::new();
let mut current_buffer = vec![];
{
// on startup we send a query to the terminal emulator for stuff like the pixel size and colors
// we get a response through STDIN, so it makes sense to do this here
let mut stdin_ansi_parser = stdin_ansi_parser.lock().unwrap();
match stdin_ansi_parser.read_cache() {
Some(events) => {
let _ =
send_input_instructions.send(InputInstruction::AnsiStdinInstructions(events));
let _ = send_input_instructions
.send(InputInstruction::DoneParsing)
.unwrap();
},
None => {
send_input_instructions
.send(InputInstruction::StartedParsing)
.unwrap();
let terminal_emulator_query_string =
stdin_ansi_parser.terminal_emulator_query_string();
let _ = os_input
.get_stdout_writer()
.write(terminal_emulator_query_string.as_bytes())
.unwrap();
let query_duration = stdin_ansi_parser.startup_query_duration();
send_done_parsing_after_query_timeout(
send_input_instructions.clone(),
query_duration,
);
},
}
}
let mut ansi_stdin_events = vec![];
loop {
match os_input.read_from_stdin() {
Ok(buf) => {
{
// here we check if we need to parse specialized ANSI instructions sent over STDIN
// this happens either on startup (see above) or on SIGWINCH
//
// if we need to parse them, we do so with an internal timeout - anything else we
// receive on STDIN during that timeout is unceremoniously dropped
let mut stdin_ansi_parser = stdin_ansi_parser.lock().unwrap();
if stdin_ansi_parser.should_parse() {
let events = stdin_ansi_parser.parse(buf);
if !events.is_empty() {
ansi_stdin_events.append(&mut events.clone());
let _ = send_input_instructions
.send(InputInstruction::AnsiStdinInstructions(events));
}
continue;
}
}
if !ansi_stdin_events.is_empty() {
stdin_ansi_parser
.lock()
.unwrap()
.write_cache(ansi_stdin_events.drain(..).collect());
}
current_buffer.append(&mut buf.to_vec());
if !explicitly_disable_kitty_keyboard_protocol {
// first we try to parse with the KittyKeyboardParser
// if we fail, we try to parse normally
match KittyKeyboardParser::new().parse(&buf) {
Some(key_with_modifier) => {
send_input_instructions
.send(InputInstruction::KeyWithModifierEvent(
key_with_modifier,
current_buffer.drain(..).collect(),
))
.unwrap();
continue;
},
None => {},
}
}
let maybe_more = false; // read_from_stdin should (hopefully) always empty the STDIN buffer completely
let mut events = vec![];
input_parser.parse(
&buf,
|input_event: InputEvent| {
events.push(input_event);
},
maybe_more,
);
let event_count = events.len();
for (i, input_event) in events.into_iter().enumerate() {
if holding_mouse && is_mouse_press_or_hold(&input_event) && i == event_count - 1
{
let mut poller = os_input.stdin_poller();
loop {
if poller.ready() {
break;
}
send_input_instructions
.send(InputInstruction::KeyEvent(
input_event.clone(),
current_buffer.clone(),
))
.unwrap();
}
}
holding_mouse = is_mouse_press_or_hold(&input_event);
send_input_instructions
.send(InputInstruction::KeyEvent(
input_event,
current_buffer.drain(..).collect(),
))
.unwrap();
}
},
Err(e) => {
if e == "Session ended" {
log::debug!("Switched sessions, signing this thread off...");
} else {
log::error!("Failed to read from STDIN: {}", e);
}
let _ = send_input_instructions.send(InputInstruction::Exit);
break;
},
}
}
}
fn is_mouse_press_or_hold(input_event: &InputEvent) -> bool {
if let InputEvent::Mouse(mouse_event) = input_event {
if mouse_event.mouse_buttons.contains(MouseButtons::LEFT)
|| mouse_event.mouse_buttons.contains(MouseButtons::RIGHT)
{
return true;
}
}
false
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/web_client/control_message.rs | zellij-client/src/web_client/control_message.rs | use serde::{Deserialize, Serialize};
use zellij_utils::{input::config::Config, pane_size::Size};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct WebClientToWebServerControlMessage {
pub web_client_id: String,
pub payload: WebClientToWebServerControlMessagePayload,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(tag = "type")]
pub enum WebClientToWebServerControlMessagePayload {
TerminalResize(Size),
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(tag = "type")]
pub enum WebServerToWebClientControlMessage {
SetConfig(SetConfigPayload),
QueryTerminalSize,
Log { lines: Vec<String> },
LogError { lines: Vec<String> },
SwitchedSession { new_session_name: String },
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SetConfigPayload {
pub font: String,
pub theme: SetConfigPayloadTheme,
pub cursor_blink: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub cursor_inactive_style: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cursor_style: Option<String>,
pub mac_option_is_meta: bool,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
#[serde(rename_all = "camelCase")]
pub struct SetConfigPayloadTheme {
#[serde(skip_serializing_if = "Option::is_none")]
pub background: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub foreground: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub black: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub blue: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub bright_black: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub bright_blue: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub bright_cyan: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub bright_green: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub bright_magenta: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub bright_red: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub bright_white: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub bright_yellow: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cursor: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cursor_accent: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cyan: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub green: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub magenta: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub red: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub selection_background: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub selection_foreground: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub selection_inactive_background: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub white: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub yellow: Option<String>,
}
impl From<&Config> for SetConfigPayload {
fn from(config: &Config) -> Self {
let font = config.web_client.font.clone();
let palette = config.theme_config(config.options.theme.as_ref());
let web_client_theme_from_config = config.web_client.theme.as_ref();
let mut theme = SetConfigPayloadTheme::default();
theme.background = web_client_theme_from_config
.and_then(|theme| theme.background.clone())
.or_else(|| palette.map(|p| p.text_unselected.background.as_rgb_str()));
theme.foreground = web_client_theme_from_config
.and_then(|theme| theme.foreground.clone())
.or_else(|| palette.map(|p| p.text_unselected.base.as_rgb_str()));
theme.black = web_client_theme_from_config.and_then(|theme| theme.black.clone());
theme.blue = web_client_theme_from_config.and_then(|theme| theme.blue.clone());
theme.bright_black =
web_client_theme_from_config.and_then(|theme| theme.bright_black.clone());
theme.bright_blue =
web_client_theme_from_config.and_then(|theme| theme.bright_blue.clone());
theme.bright_cyan =
web_client_theme_from_config.and_then(|theme| theme.bright_cyan.clone());
theme.bright_green =
web_client_theme_from_config.and_then(|theme| theme.bright_green.clone());
theme.bright_magenta =
web_client_theme_from_config.and_then(|theme| theme.bright_magenta.clone());
theme.bright_red = web_client_theme_from_config.and_then(|theme| theme.bright_red.clone());
theme.bright_white =
web_client_theme_from_config.and_then(|theme| theme.bright_white.clone());
theme.bright_yellow =
web_client_theme_from_config.and_then(|theme| theme.bright_yellow.clone());
theme.cursor = web_client_theme_from_config.and_then(|theme| theme.cursor.clone());
theme.cursor_accent =
web_client_theme_from_config.and_then(|theme| theme.cursor_accent.clone());
theme.cyan = web_client_theme_from_config.and_then(|theme| theme.cyan.clone());
theme.green = web_client_theme_from_config.and_then(|theme| theme.green.clone());
theme.magenta = web_client_theme_from_config.and_then(|theme| theme.magenta.clone());
theme.red = web_client_theme_from_config.and_then(|theme| theme.red.clone());
theme.selection_background = web_client_theme_from_config
.and_then(|theme| theme.selection_background.clone())
.or_else(|| palette.map(|p| p.text_selected.background.as_rgb_str()));
theme.selection_foreground = web_client_theme_from_config
.and_then(|theme| theme.selection_foreground.clone())
.or_else(|| palette.map(|p| p.text_selected.base.as_rgb_str()));
theme.selection_inactive_background = web_client_theme_from_config
.and_then(|theme| theme.selection_inactive_background.clone());
theme.white = web_client_theme_from_config.and_then(|theme| theme.white.clone());
theme.yellow = web_client_theme_from_config.and_then(|theme| theme.yellow.clone());
let cursor_blink = config.web_client.cursor_blink;
let mac_option_is_meta = config.web_client.mac_option_is_meta;
let cursor_style = config
.web_client
.cursor_style
.as_ref()
.map(|s| s.to_string());
let cursor_inactive_style = config
.web_client
.cursor_inactive_style
.as_ref()
.map(|s| s.to_string());
SetConfigPayload {
font,
theme,
cursor_blink,
mac_option_is_meta,
cursor_style,
cursor_inactive_style,
}
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/web_client/websocket_handlers.rs | zellij-client/src/web_client/websocket_handlers.rs | use crate::web_client::control_message::{
SetConfigPayload, WebClientToWebServerControlMessage,
WebClientToWebServerControlMessagePayload, WebServerToWebClientControlMessage,
};
use crate::web_client::message_handlers::{
parse_stdin, render_to_client, send_control_messages_to_client,
};
use crate::web_client::server_listener::zellij_server_listener;
use crate::web_client::types::{AppState, TerminalParams};
use axum::{
extract::{
ws::{Message, WebSocket, WebSocketUpgrade},
Path as AxumPath, Query, State,
},
response::IntoResponse,
};
use futures::StreamExt;
use tokio_util::sync::CancellationToken;
use zellij_utils::{input::mouse::MouseEvent, ipc::ClientToServerMsg};
pub async fn ws_handler_control(
ws: WebSocketUpgrade,
_path: Option<AxumPath<String>>,
State(state): State<AppState>,
) -> impl IntoResponse {
ws.on_upgrade(move |socket| handle_ws_control(socket, state))
}
pub async fn ws_handler_terminal(
ws: WebSocketUpgrade,
session_name: Option<AxumPath<String>>,
Query(params): Query<TerminalParams>,
State(state): State<AppState>,
) -> impl IntoResponse {
ws.on_upgrade(move |socket| handle_ws_terminal(socket, session_name, params, state))
}
async fn handle_ws_control(socket: WebSocket, state: AppState) {
let payload = SetConfigPayload::from(&*state.config.lock().unwrap());
let set_config_msg = WebServerToWebClientControlMessage::SetConfig(payload);
let (control_socket_tx, mut control_socket_rx) = socket.split();
let (control_channel_tx, control_channel_rx) = tokio::sync::mpsc::unbounded_channel();
send_control_messages_to_client(control_channel_rx, control_socket_tx);
let _ = control_channel_tx.send(Message::Text(
serde_json::to_string(&set_config_msg).unwrap().into(),
));
let send_message_to_server = |deserialized_msg: WebClientToWebServerControlMessage| {
let Some(client_connection) = state
.connection_table
.lock()
.unwrap()
.get_client_os_api(&deserialized_msg.web_client_id)
.cloned()
else {
log::error!("Unknown web_client_id: {}", deserialized_msg.web_client_id);
return;
};
let client_msg = match deserialized_msg.payload {
WebClientToWebServerControlMessagePayload::TerminalResize(size) => {
ClientToServerMsg::TerminalResize { new_size: size }
},
};
let _ = client_connection.send_to_server(client_msg);
};
let mut set_client_control_channel = false;
while let Some(Ok(msg)) = control_socket_rx.next().await {
match msg {
Message::Text(msg) => {
let deserialized_msg: Result<WebClientToWebServerControlMessage, _> =
serde_json::from_str(&msg);
match deserialized_msg {
Ok(deserialized_msg) => {
if !set_client_control_channel {
set_client_control_channel = true;
state
.connection_table
.lock()
.unwrap()
.add_client_control_tx(
&deserialized_msg.web_client_id,
control_channel_tx.clone(),
);
}
send_message_to_server(deserialized_msg);
},
Err(e) => {
log::error!("Failed to deserialize client msg: {:?}", e);
},
}
},
Message::Close(_) => {
return;
},
_ => {
log::error!("Unsupported messagetype : {:?}", msg);
},
}
}
}
async fn handle_ws_terminal(
socket: WebSocket,
session_name: Option<AxumPath<String>>,
params: TerminalParams,
state: AppState,
) {
let web_client_id = params.web_client_id;
let Some(os_input) = state
.connection_table
.lock()
.unwrap()
.get_client_os_api(&web_client_id)
.cloned()
else {
log::error!("Unknown web_client_id: {}", web_client_id);
return;
};
let (client_terminal_channel_tx, mut client_terminal_channel_rx) = socket.split();
let (stdout_channel_tx, stdout_channel_rx) = tokio::sync::mpsc::unbounded_channel();
state
.connection_table
.lock()
.unwrap()
.add_client_terminal_tx(&web_client_id, stdout_channel_tx);
let (attachment_complete_tx, attachment_complete_rx) = tokio::sync::oneshot::channel();
zellij_server_listener(
os_input.clone(),
state.connection_table.clone(),
session_name.map(|p| p.0),
state.config.lock().unwrap().clone(),
state.config_options.clone(),
Some(state.config_file_path.clone()),
web_client_id.clone(),
state.session_manager.clone(),
Some(attachment_complete_tx),
);
let terminal_channel_cancellation_token = CancellationToken::new();
render_to_client(
stdout_channel_rx,
client_terminal_channel_tx,
terminal_channel_cancellation_token.clone(),
);
state
.connection_table
.lock()
.unwrap()
.add_client_terminal_channel_cancellation_token(
&web_client_id,
terminal_channel_cancellation_token,
);
let explicitly_disable_kitty_keyboard_protocol = state
.config
.lock()
.unwrap()
.options
.support_kitty_keyboard_protocol
.map(|e| !e)
.unwrap_or(false);
let _ = attachment_complete_rx.await;
let mut mouse_old_event = MouseEvent::new();
while let Some(Ok(msg)) = client_terminal_channel_rx.next().await {
match msg {
Message::Binary(buf) => {
let Some(client_connection) = state
.connection_table
.lock()
.unwrap()
.get_client_os_api(&web_client_id)
.cloned()
else {
log::error!("Unknown web_client_id: {}", web_client_id);
continue;
};
parse_stdin(
&buf,
client_connection.clone(),
&mut mouse_old_event,
explicitly_disable_kitty_keyboard_protocol,
);
},
Message::Text(msg) => {
let Some(client_connection) = state
.connection_table
.lock()
.unwrap()
.get_client_os_api(&web_client_id)
.cloned()
else {
log::error!("Unknown web_client_id: {}", web_client_id);
continue;
};
parse_stdin(
msg.as_bytes(),
client_connection.clone(),
&mut mouse_old_event,
explicitly_disable_kitty_keyboard_protocol,
);
},
Message::Close(_) => {
state
.connection_table
.lock()
.unwrap()
.remove_client(&web_client_id);
break;
},
// TODO: support Message::Binary
_ => {
log::error!("Unsupported websocket msg type");
},
}
}
os_input.send_to_server(ClientToServerMsg::ClientExited);
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/web_client/connection_manager.rs | zellij-client/src/web_client/connection_manager.rs | use crate::os_input_output::ClientOsApi;
use crate::web_client::control_message::WebServerToWebClientControlMessage;
use crate::web_client::types::{ClientChannels, ClientConnectionBus, ConnectionTable};
use axum::extract::ws::{CloseFrame, Message};
use tokio::sync::mpsc::UnboundedSender;
use tokio_util::sync::CancellationToken;
impl ConnectionTable {
pub fn add_new_client(
&mut self,
client_id: String,
client_os_api: Box<dyn ClientOsApi>,
is_read_only: bool,
) {
self.client_id_to_channels
.insert(client_id.clone(), ClientChannels::new(client_os_api));
self.client_read_only_status.insert(client_id, is_read_only);
}
pub fn is_client_read_only(&self, client_id: &str) -> bool {
self.client_read_only_status
.get(client_id)
.copied()
.unwrap_or(false)
}
pub fn add_client_control_tx(
&mut self,
client_id: &str,
control_channel_tx: UnboundedSender<Message>,
) {
self.client_id_to_channels
.get_mut(client_id)
.map(|c| c.add_control_tx(control_channel_tx));
}
pub fn add_client_terminal_tx(
&mut self,
client_id: &str,
terminal_channel_tx: UnboundedSender<String>,
) {
self.client_id_to_channels
.get_mut(client_id)
.map(|c| c.add_terminal_tx(terminal_channel_tx));
}
pub fn add_client_terminal_channel_cancellation_token(
&mut self,
client_id: &str,
terminal_channel_cancellation_token: CancellationToken,
) {
self.client_id_to_channels.get_mut(client_id).map(|c| {
c.add_terminal_channel_cancellation_token(terminal_channel_cancellation_token)
});
}
pub fn get_client_os_api(&self, client_id: &str) -> Option<&Box<dyn ClientOsApi>> {
self.client_id_to_channels.get(client_id).map(|c| &c.os_api)
}
pub fn get_client_terminal_tx(&self, client_id: &str) -> Option<UnboundedSender<String>> {
self.client_id_to_channels
.get(client_id)
.and_then(|c| c.terminal_channel_tx.clone())
}
pub fn get_client_control_tx(&self, client_id: &str) -> Option<UnboundedSender<Message>> {
self.client_id_to_channels
.get(client_id)
.and_then(|c| c.control_channel_tx.clone())
}
pub fn remove_client(&mut self, client_id: &str) {
if let Some(mut client_channels) = self.client_id_to_channels.remove(client_id).take() {
client_channels.cleanup();
}
self.client_read_only_status.remove(client_id);
}
}
impl ClientConnectionBus {
pub fn send_stdout(&mut self, stdout: String) {
match self.stdout_channel_tx.as_ref() {
Some(stdout_channel_tx) => {
let _ = stdout_channel_tx.send(stdout);
},
None => {
self.get_stdout_channel_tx();
if let Some(stdout_channel_tx) = self.stdout_channel_tx.as_ref() {
let _ = stdout_channel_tx.send(stdout);
} else {
log::error!("Failed to send STDOUT message to client");
}
},
}
}
pub fn send_control(&mut self, message: WebServerToWebClientControlMessage) {
let message = Message::Text(serde_json::to_string(&message).unwrap().into());
match self.control_channel_tx.as_ref() {
Some(control_channel_tx) => {
let _ = control_channel_tx.send(message);
},
None => {
self.get_control_channel_tx();
if let Some(control_channel_tx) = self.control_channel_tx.as_ref() {
let _ = control_channel_tx.send(message);
} else {
log::error!("Failed to send control message to client");
}
},
}
}
pub fn close_connection(&mut self) {
let close_frame = CloseFrame {
code: axum::extract::ws::close_code::NORMAL,
reason: "Connection closed".into(),
};
let close_message = Message::Close(Some(close_frame));
match self.control_channel_tx.as_ref() {
Some(control_channel_tx) => {
let _ = control_channel_tx.send(close_message);
},
None => {
self.get_control_channel_tx();
if let Some(control_channel_tx) = self.control_channel_tx.as_ref() {
let _ = control_channel_tx.send(close_message);
} else {
log::error!("Failed to send close message to client");
}
},
}
self.connection_table
.lock()
.unwrap()
.remove_client(&self.web_client_id);
}
fn get_control_channel_tx(&mut self) {
if let Some(control_channel_tx) = self
.connection_table
.lock()
.unwrap()
.get_client_control_tx(&self.web_client_id)
{
self.control_channel_tx = Some(control_channel_tx);
}
}
fn get_stdout_channel_tx(&mut self) {
if let Some(stdout_channel_tx) = self
.connection_table
.lock()
.unwrap()
.get_client_terminal_tx(&self.web_client_id)
{
self.stdout_channel_tx = Some(stdout_channel_tx);
}
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/web_client/message_handlers.rs | zellij-client/src/web_client/message_handlers.rs | use crate::input_handler::from_termwiz;
use crate::keyboard_parser::KittyKeyboardParser;
use crate::os_input_output::ClientOsApi;
use crate::web_client::types::BRACKETED_PASTE_END;
use crate::web_client::types::BRACKETED_PASTE_START;
use zellij_utils::{
input::{actions::Action, cast_termwiz_key, mouse::MouseEvent},
ipc::ClientToServerMsg,
};
use axum::extract::ws::{CloseFrame, Message, WebSocket};
use futures::{prelude::stream::SplitSink, SinkExt};
use termwiz::input::{InputEvent, InputParser};
use tokio::sync::mpsc::UnboundedReceiver;
use tokio_util::sync::CancellationToken;
pub fn render_to_client(
mut stdout_channel_rx: UnboundedReceiver<String>,
mut client_channel_tx: SplitSink<WebSocket, Message>,
cancellation_token: CancellationToken,
) {
tokio::spawn(async move {
loop {
tokio::select! {
result = stdout_channel_rx.recv() => {
match result {
Some(rendered_bytes) => {
if client_channel_tx
.send(Message::Text(rendered_bytes.into()))
.await
.is_err()
{
break;
}
}
None => break,
}
}
_ = cancellation_token.cancelled() => {
let close_frame = CloseFrame {
code: axum::extract::ws::close_code::NORMAL,
reason: "Connection closed".into(),
};
let close_message = Message::Close(Some(close_frame));
if client_channel_tx
.send(close_message)
.await
.is_err()
{
break;
}
break;
}
}
}
});
}
pub fn send_control_messages_to_client(
mut control_channel_rx: UnboundedReceiver<Message>,
mut socket_channel_tx: SplitSink<WebSocket, Message>,
) {
tokio::spawn(async move {
while let Some(message) = control_channel_rx.recv().await {
if socket_channel_tx.send(message).await.is_err() {
break;
}
}
});
}
pub fn parse_stdin(
buf: &[u8],
os_input: Box<dyn ClientOsApi>,
mouse_old_event: &mut MouseEvent,
explicitly_disable_kitty_keyboard_protocol: bool,
) {
if !explicitly_disable_kitty_keyboard_protocol {
match KittyKeyboardParser::new().parse(&buf) {
Some(key_with_modifier) => {
os_input.send_to_server(ClientToServerMsg::Key {
key: key_with_modifier.clone(),
raw_bytes: buf.to_vec(),
is_kitty_keyboard_protocol: true,
});
return;
},
None => {},
}
}
let mut input_parser = InputParser::new();
let maybe_more = false;
let mut events = vec![];
input_parser.parse(
&buf,
|input_event: InputEvent| {
events.push(input_event);
},
maybe_more,
);
for (_i, input_event) in events.into_iter().enumerate() {
match input_event {
InputEvent::Key(key_event) => {
let key = cast_termwiz_key(key_event.clone(), &buf, None);
os_input.send_to_server(ClientToServerMsg::Key {
key: key.clone(),
raw_bytes: buf.to_vec(),
is_kitty_keyboard_protocol: false,
});
},
InputEvent::Mouse(mouse_event) => {
let mouse_event = from_termwiz(mouse_old_event, mouse_event);
let action = Action::MouseEvent { event: mouse_event };
os_input.send_to_server(ClientToServerMsg::Action {
action,
terminal_id: None,
client_id: None,
is_cli_client: false,
});
},
InputEvent::Paste(pasted_text) => {
os_input.send_to_server(ClientToServerMsg::Action {
action: Action::Write {
key_with_modifier: None,
bytes: BRACKETED_PASTE_START.to_vec(),
is_kitty_keyboard_protocol: false,
},
terminal_id: None,
client_id: None,
is_cli_client: false,
});
os_input.send_to_server(ClientToServerMsg::Action {
action: Action::Write {
key_with_modifier: None,
bytes: pasted_text.as_bytes().to_vec(),
is_kitty_keyboard_protocol: false,
},
terminal_id: None,
client_id: None,
is_cli_client: false,
});
os_input.send_to_server(ClientToServerMsg::Action {
action: Action::Write {
key_with_modifier: None,
bytes: BRACKETED_PASTE_END.to_vec(),
is_kitty_keyboard_protocol: false,
},
terminal_id: None,
client_id: None,
is_cli_client: false,
});
},
_ => {
log::error!("Unsupported event: {:#?}", input_event);
},
}
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/web_client/server_listener.rs | zellij-client/src/web_client/server_listener.rs | use crate::os_input_output::ClientOsApi;
use crate::web_client::control_message::{SetConfigPayload, WebServerToWebClientControlMessage};
use crate::web_client::session_management::{
build_initial_connection, create_first_message, create_ipc_pipe,
};
use crate::web_client::types::{ClientConnectionBus, ConnectionTable, SessionManager};
use crate::web_client::utils::terminal_init_messages;
use std::{
path::PathBuf,
sync::{Arc, Mutex},
};
use zellij_utils::{
cli::CliArgs,
data::Style,
input::{config::Config, options::Options},
ipc::{ClientToServerMsg, ExitReason, ServerToClientMsg},
sessions::generate_unique_session_name,
setup::Setup,
};
pub fn zellij_server_listener(
os_input: Box<dyn ClientOsApi>,
connection_table: Arc<Mutex<ConnectionTable>>,
session_name: Option<String>,
mut config: Config,
mut config_options: Options,
config_file_path: Option<PathBuf>,
web_client_id: String,
session_manager: Arc<dyn SessionManager>,
attachment_complete_tx: Option<tokio::sync::oneshot::Sender<()>>,
) {
let _server_listener_thread = std::thread::Builder::new()
.name("server_listener".to_string())
.spawn({
move || {
let mut client_connection_bus =
ClientConnectionBus::new(&web_client_id, &connection_table);
let mut reconnect_to_session =
match build_initial_connection(session_name, &config) {
Ok(initial_session_connection) => initial_session_connection,
Err(e) => {
log::error!("{}", e);
return;
},
};
let mut attachment_complete_tx = attachment_complete_tx;
'reconnect_loop: loop {
let reconnect_info = reconnect_to_session.take();
let path = {
let Some(session_name) = reconnect_info
.as_ref()
.and_then(|r| r.name.clone())
.or_else(generate_unique_session_name)
else {
log::error!("Failed to generate unique session name, bailing.");
client_connection_bus.close_connection();
return;
};
let mut sock_dir = zellij_utils::consts::ZELLIJ_SOCK_DIR.clone();
sock_dir.push(session_name.clone());
sock_dir.to_str().unwrap().to_owned()
};
reload_config_from_disk(&mut config, &mut config_options, &config_file_path);
let full_screen_ws = os_input.get_terminal_size_using_fd(0);
let mut sent_init_messages = false;
let palette = config
.theme_config(config_options.theme.as_ref())
.unwrap_or_else(|| os_input.load_palette().into());
let client_attributes = zellij_utils::ipc::ClientAttributes {
size: full_screen_ws,
style: Style {
colors: palette,
rounded_corners: config.ui.pane_frames.rounded_corners,
hide_session_name: config.ui.pane_frames.hide_session_name,
},
};
let session_name = PathBuf::from(path.clone())
.file_name()
.unwrap()
.to_str()
.unwrap()
.to_owned();
// Look up read-only status from connection table
let is_read_only = connection_table
.lock()
.unwrap()
.is_client_read_only(&web_client_id);
let session_exists = session_manager.session_exists(&session_name).unwrap_or(false);
if is_read_only && !session_exists {
log::error!("Read only tokens cannot create new sessions.");
client_connection_bus.close_connection();
return;
}
let should_create_new_session = !session_exists;
let first_message = create_first_message(is_read_only, config_file_path.clone(), client_attributes.clone(), config_options.clone(), should_create_new_session, &session_name);
let zellij_ipc_pipe = create_ipc_pipe(&session_name);
session_manager.spawn_session_if_needed(
&session_name,
os_input.clone(),
session_exists,
&zellij_ipc_pipe,
first_message,
);
if let Some(tx) = attachment_complete_tx.take() {
let _ = tx.send(());
}
client_connection_bus.send_control(
WebServerToWebClientControlMessage::SwitchedSession {
new_session_name: session_name.clone(),
},
);
let mut unknown_message_count = 0;
loop {
let msg = os_input.recv_from_server();
if msg.is_some() {
unknown_message_count = 0;
} else {
unknown_message_count += 1;
}
match msg.map(|m| m.0) {
Some(ServerToClientMsg::UnblockInputThread) => {},
Some(ServerToClientMsg::Connected) => {},
Some(ServerToClientMsg::CliPipeOutput { .. } ) => {},
Some(ServerToClientMsg::UnblockCliPipeInput { .. } ) => {},
Some(ServerToClientMsg::StartWebServer { .. } ) => {},
Some(ServerToClientMsg::Exit{exit_reason}) => {
handle_exit_reason(&mut client_connection_bus, exit_reason);
os_input.send_to_server(ClientToServerMsg::ClientExited);
break;
},
Some(ServerToClientMsg::Render{content: bytes}) => {
if !sent_init_messages {
for message in terminal_init_messages() {
client_connection_bus.send_stdout(message.to_owned())
}
sent_init_messages = true;
}
client_connection_bus.send_stdout(bytes);
},
Some(ServerToClientMsg::SwitchSession{connect_to_session}) => {
reconnect_to_session = Some(connect_to_session);
continue 'reconnect_loop;
},
Some(ServerToClientMsg::QueryTerminalSize) => {
client_connection_bus.send_control(
WebServerToWebClientControlMessage::QueryTerminalSize,
);
},
Some(ServerToClientMsg::Log{lines}) => {
client_connection_bus.send_control(
WebServerToWebClientControlMessage::Log { lines },
);
},
Some(ServerToClientMsg::LogError{lines}) => {
client_connection_bus.send_control(
WebServerToWebClientControlMessage::LogError { lines },
);
},
Some(ServerToClientMsg::RenamedSession{name: new_session_name}) => {
client_connection_bus.send_control(
WebServerToWebClientControlMessage::SwitchedSession {
new_session_name,
},
);
},
Some(ServerToClientMsg::ConfigFileUpdated) => {
if let Some(config_file_path) = &config_file_path {
if let Ok(new_config) = Config::from_path(&config_file_path, Some(config.clone())) {
let set_config_payload = SetConfigPayload::from(&new_config);
let client_ids: Vec<String> = {
let connection_table_lock = connection_table.lock().unwrap();
connection_table_lock
.client_id_to_channels
.keys()
.cloned()
.collect()
};
let config_message =
WebServerToWebClientControlMessage::SetConfig(set_config_payload);
let config_msg_json = match serde_json::to_string(&config_message) {
Ok(json) => json,
Err(e) => {
log::error!("Failed to serialize config message: {}", e);
continue;
},
};
for client_id in client_ids {
if let Some(control_tx) = connection_table
.lock()
.unwrap()
.get_client_control_tx(&client_id)
{
let ws_message = config_msg_json.clone();
match control_tx.send(ws_message.into()) {
Ok(_) => {}, // no-op
Err(e) => {
log::error!(
"Failed to send config update to client {}: {}",
client_id,
e
);
},
}
}
}
}
}
},
None => {
if unknown_message_count >= 1000 {
log::error!("Error: Received more than 1000 consecutive unknown server messages, disconnecting.");
// this probably means we're in an infinite loop, let's
// disconnect so as not to cause 100% CPU
break;
}
},
}
}
if reconnect_to_session.is_none() {
break;
}
}
}
});
}
fn handle_exit_reason(client_connection_bus: &mut ClientConnectionBus, exit_reason: ExitReason) {
match exit_reason {
ExitReason::WebClientsForbidden => {
client_connection_bus.send_stdout(format!(
"\u{1b}[2J\n Web Clients are not allowed to attach to this session."
));
},
ExitReason::Error(e) => {
let goto_start_of_last_line = format!("\u{1b}[{};{}H", 1, 1);
let clear_client_terminal_attributes = "\u{1b}[?1l\u{1b}=\u{1b}[r\u{1b}[?1000l\u{1b}[?1002l\u{1b}[?1003l\u{1b}[?1005l\u{1b}[?1006l\u{1b}[?12l";
let disable_mouse = "\u{1b}[?1006l\u{1b}[?1015l\u{1b}[?1003l\u{1b}[?1002l\u{1b}[?1000l";
let error = format!(
"{}{}\n{}{}\n",
disable_mouse,
clear_client_terminal_attributes,
goto_start_of_last_line,
e.to_string().replace("\n", "\n\r")
);
client_connection_bus.send_stdout(format!("\u{1b}[2J\n{}", error));
},
_ => {},
}
client_connection_bus.close_connection();
}
fn reload_config_from_disk(
config_without_layout: &mut Config,
config_options_without_layout: &mut Options,
config_file_path: &Option<PathBuf>,
) {
let mut cli_args = CliArgs::default();
cli_args.config = config_file_path.clone();
match Setup::from_cli_args(&cli_args) {
Ok((_, _, _, reloaded_config_without_layout, reloaded_config_options_without_layout)) => {
*config_without_layout = reloaded_config_without_layout;
*config_options_without_layout = reloaded_config_options_without_layout;
},
Err(e) => {
log::error!("Failed to reload config: {}", e);
},
};
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/web_client/types.rs | zellij-client/src/web_client/types.rs | use axum::extract::ws::Message;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use tokio::sync::mpsc::UnboundedSender;
use tokio_util::sync::CancellationToken;
use crate::os_input_output::ClientOsApi;
use crate::web_client::session_management::spawn_new_session;
use std::path::PathBuf;
use zellij_utils::{
input::{config::Config, options::Options},
ipc::ClientToServerMsg,
};
pub trait ClientOsApiFactory: Send + Sync + std::fmt::Debug {
fn create_client_os_api(&self) -> Result<Box<dyn ClientOsApi>, Box<dyn std::error::Error>>;
}
#[derive(Debug, Clone)]
pub struct RealClientOsApiFactory;
impl ClientOsApiFactory for RealClientOsApiFactory {
fn create_client_os_api(&self) -> Result<Box<dyn ClientOsApi>, Box<dyn std::error::Error>> {
crate::os_input_output::get_client_os_input()
.map(|os_input| Box::new(os_input) as Box<dyn ClientOsApi>)
.map_err(|e| format!("Failed to create client OS API: {:?}", e).into())
}
}
pub trait SessionManager: Send + Sync + std::fmt::Debug {
fn session_exists(&self, session_name: &str) -> Result<bool, Box<dyn std::error::Error>>;
fn get_resurrection_layout(
&self,
session_name: &str,
) -> Option<zellij_utils::input::layout::Layout>;
fn spawn_session_if_needed(
&self,
session_name: &str,
os_input: Box<dyn ClientOsApi>,
session_exists: bool,
zellij_ipc_pipe: &PathBuf,
first_message: ClientToServerMsg,
);
}
#[derive(Debug, Clone)]
pub struct RealSessionManager;
impl SessionManager for RealSessionManager {
fn session_exists(&self, session_name: &str) -> Result<bool, Box<dyn std::error::Error>> {
zellij_utils::sessions::session_exists(session_name)
.map_err(|e| format!("Session check failed: {:?}", e).into())
}
fn get_resurrection_layout(
&self,
session_name: &str,
) -> Option<zellij_utils::input::layout::Layout> {
zellij_utils::sessions::resurrection_layout(session_name)
.ok()
.flatten()
}
fn spawn_session_if_needed(
&self,
session_name: &str,
os_input: Box<dyn ClientOsApi>,
session_exists: bool,
zellij_ipc_pipe: &PathBuf,
first_message: ClientToServerMsg,
) {
if !session_exists {
spawn_new_session(session_name, os_input.clone(), zellij_ipc_pipe);
}
os_input.connect_to_server(&zellij_ipc_pipe);
os_input.send_to_server(first_message);
}
}
#[derive(Debug, Default, Clone)]
pub struct ConnectionTable {
pub client_id_to_channels: HashMap<String, ClientChannels>,
pub client_read_only_status: HashMap<String, bool>,
}
#[derive(Debug, Clone)]
pub struct ClientChannels {
pub os_api: Box<dyn ClientOsApi>,
pub control_channel_tx: Option<UnboundedSender<Message>>,
pub terminal_channel_tx: Option<UnboundedSender<String>>,
terminal_channel_cancellation_token: Option<CancellationToken>,
}
impl ClientChannels {
pub fn new(os_api: Box<dyn ClientOsApi>) -> Self {
ClientChannels {
os_api,
control_channel_tx: None,
terminal_channel_tx: None,
terminal_channel_cancellation_token: None,
}
}
pub fn add_control_tx(&mut self, control_channel_tx: UnboundedSender<Message>) {
self.control_channel_tx = Some(control_channel_tx);
}
pub fn add_terminal_tx(&mut self, terminal_channel_tx: UnboundedSender<String>) {
self.terminal_channel_tx = Some(terminal_channel_tx);
}
pub fn add_terminal_channel_cancellation_token(
&mut self,
terminal_channel_cancellation_token: CancellationToken,
) {
self.terminal_channel_cancellation_token = Some(terminal_channel_cancellation_token);
}
pub fn cleanup(&mut self) {
if let Some(terminal_channel_cancellation_token) =
self.terminal_channel_cancellation_token.take()
{
terminal_channel_cancellation_token.cancel();
}
}
}
#[derive(Debug)]
pub struct ClientConnectionBus {
pub connection_table: Arc<Mutex<ConnectionTable>>,
pub stdout_channel_tx: Option<UnboundedSender<String>>,
pub control_channel_tx: Option<UnboundedSender<Message>>,
pub web_client_id: String,
}
impl ClientConnectionBus {
pub fn new(web_client_id: &str, connection_table: &Arc<Mutex<ConnectionTable>>) -> Self {
let connection_table = connection_table.clone();
let web_client_id = web_client_id.to_owned();
let (stdout_channel_tx, control_channel_tx) = {
let connection_table = connection_table.lock().unwrap();
(
connection_table.get_client_terminal_tx(&web_client_id),
connection_table.get_client_control_tx(&web_client_id),
)
};
ClientConnectionBus {
connection_table,
stdout_channel_tx,
control_channel_tx,
web_client_id,
}
}
}
#[derive(Clone)]
pub struct AppState {
pub connection_table: Arc<Mutex<ConnectionTable>>,
pub config: Arc<Mutex<Config>>,
pub config_options: Options,
pub config_file_path: PathBuf,
pub session_manager: Arc<dyn SessionManager>,
pub client_os_api_factory: Arc<dyn ClientOsApiFactory>,
pub is_https: bool,
}
#[derive(Serialize)]
pub struct CreateClientIdResponse {
pub web_client_id: String,
pub is_read_only: bool,
}
#[derive(Deserialize)]
pub struct TerminalParams {
pub web_client_id: String,
}
#[derive(Deserialize)]
pub struct LoginRequest {
pub auth_token: String,
pub remember_me: Option<bool>,
}
#[derive(Serialize)]
pub struct LoginResponse {
pub success: bool,
pub message: String,
}
pub const BRACKETED_PASTE_START: [u8; 6] = [27, 91, 50, 48, 48, 126]; // \u{1b}[200~
pub const BRACKETED_PASTE_END: [u8; 6] = [27, 91, 50, 48, 49, 126]; // \u{1b}[201~
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/web_client/utils.rs | zellij-client/src/web_client/utils.rs | use axum::http::Request;
use axum_extra::extract::cookie::Cookie;
use std::collections::HashMap;
use std::net::IpAddr;
pub fn get_mime_type(ext: Option<&str>) -> &str {
match ext {
None => "text/plain",
Some(ext) => match ext {
"html" => "text/html",
"css" => "text/css",
"js" => "application/javascript",
"wasm" => "application/wasm",
"png" => "image/png",
"ico" => "image/x-icon",
"svg" => "image/svg+xml",
_ => "text/plain",
},
}
}
pub fn should_use_https(
ip: IpAddr,
has_certificate: bool,
enforce_https_for_localhost: bool,
) -> Result<bool, String> {
let is_loopback = match ip {
IpAddr::V4(ipv4) => ipv4.is_loopback(),
IpAddr::V6(ipv6) => ipv6.is_loopback(),
};
if is_loopback && !enforce_https_for_localhost {
Ok(has_certificate)
} else if is_loopback {
Err(format!("Cannot bind without an SSL certificate."))
} else if has_certificate {
Ok(true)
} else {
Err(format!(
"Cannot bind to non-loopback IP: {} without an SSL certificate.",
ip
))
}
}
pub fn parse_cookies<T>(request: &Request<T>) -> HashMap<String, String> {
let mut cookies = HashMap::new();
for cookie_header in request.headers().get_all("cookie") {
if let Ok(cookie_str) = cookie_header.to_str() {
for cookie_part in cookie_str.split(';') {
if let Ok(cookie) = Cookie::parse(cookie_part.trim()) {
cookies.insert(cookie.name().to_string(), cookie.value().to_string());
}
}
}
}
cookies
}
pub fn terminal_init_messages() -> Vec<&'static str> {
let clear_client_terminal_attributes = "\u{1b}[?1l\u{1b}=\u{1b}[r\u{1b}[?1000l\u{1b}[?1002l\u{1b}[?1003l\u{1b}[?1005l\u{1b}[?1006l\u{1b}[?12l";
let enter_alternate_screen = "\u{1b}[?1049h";
let bracketed_paste = "\u{1b}[?2004h";
let enter_kitty_keyboard_mode = "\u{1b}[>1u";
let enable_mouse_mode = "\u{1b}[?1000h\u{1b}[?1002h\u{1b}[?1015h\u{1b}[?1006h";
vec![
clear_client_terminal_attributes,
enter_alternate_screen,
bracketed_paste,
enter_kitty_keyboard_mode,
enable_mouse_mode,
]
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/web_client/mod.rs | zellij-client/src/web_client/mod.rs | pub mod control_message;
mod authentication;
mod connection_manager;
mod http_handlers;
mod ipc_listener;
mod message_handlers;
mod server_listener;
mod session_management;
mod types;
mod utils;
mod websocket_handlers;
use std::{
net::{IpAddr, Ipv4Addr},
path::PathBuf,
sync::{Arc, Mutex},
thread,
};
use axum::{
middleware,
routing::{any, get, post},
Router,
};
use axum_server::tls_rustls::RustlsConfig;
use axum_server::Handle;
use daemonize::{self, Outcome};
use nix::sys::stat::{umask, Mode};
use interprocess::unnamed_pipe::pipe;
use std::io::{prelude::*, BufRead, BufReader};
use tokio::runtime::Runtime;
use zellij_utils::input::{config::Config, options::Options};
use authentication::auth_middleware;
use http_handlers::{
create_new_client, get_static_asset, login_handler, serve_html, version_handler,
};
use ipc_listener::listen_to_web_server_instructions;
use types::{
AppState, ClientOsApiFactory, ConnectionTable, RealClientOsApiFactory, RealSessionManager,
SessionManager,
};
use utils::should_use_https;
use uuid::Uuid;
use websocket_handlers::{ws_handler_control, ws_handler_terminal};
pub fn start_web_client(
config: Config,
config_options: Options,
config_file_path: Option<PathBuf>,
run_daemonized: bool,
custom_ip: Option<IpAddr>,
custom_port: Option<u16>,
custom_server_cert: Option<PathBuf>,
custom_server_key: Option<PathBuf>,
) {
std::panic::set_hook({
Box::new(move |info| {
let thread = thread::current();
let thread = thread.name().unwrap_or("unnamed");
let msg = match info.payload().downcast_ref::<&'static str>() {
Some(s) => Some(*s),
None => info.payload().downcast_ref::<String>().map(|s| &**s),
}
.unwrap_or("An unexpected error occurred!");
log::error!(
"Thread {} panicked: {}, location {:?}",
thread,
msg,
info.location()
);
eprintln!("{}", msg);
std::process::exit(2);
})
});
let web_server_ip = custom_ip.unwrap_or_else(|| {
config_options
.web_server_ip
.unwrap_or_else(|| IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)))
});
let web_server_port =
custom_port.unwrap_or_else(|| config_options.web_server_port.unwrap_or_else(|| 8082));
let web_server_cert = custom_server_cert.or_else(|| config.options.web_server_cert.clone());
let web_server_key = custom_server_key.or_else(|| config.options.web_server_key.clone());
let has_https_certificate = web_server_cert.is_some() && web_server_key.is_some();
if let Err(e) = should_use_https(
web_server_ip,
has_https_certificate,
config.options.enforce_https_for_localhost.unwrap_or(false),
) {
eprintln!("{}", e);
std::process::exit(2);
};
let (runtime, listener, tls_config) = if run_daemonized {
daemonize_web_server(
web_server_ip,
web_server_port,
web_server_cert,
web_server_key,
)
} else {
let runtime = Runtime::new().unwrap();
let listener = runtime.block_on(async move {
std::net::TcpListener::bind(format!("{}:{}", web_server_ip, web_server_port))
});
let tls_config = match (web_server_cert, web_server_key) {
(Some(web_server_cert), Some(web_server_key)) => {
let tls_config = runtime.block_on(async move {
RustlsConfig::from_pem_file(
PathBuf::from(web_server_cert),
PathBuf::from(web_server_key),
)
.await
});
let tls_config = match tls_config {
Ok(tls_config) => tls_config,
Err(e) => {
eprintln!("{}", e);
std::process::exit(2);
},
};
Some(tls_config)
},
(None, None) => None,
_ => {
eprintln!("Must specify both web_server_cert and web_server_key");
std::process::exit(2);
},
};
match listener {
Ok(listener) => {
println!(
"Web Server started on {} port {}",
web_server_ip, web_server_port
);
(runtime, listener, tls_config)
},
Err(e) => {
eprintln!("{}", e);
std::process::exit(2);
},
}
};
runtime.block_on(serve_web_client(
config,
config_options,
config_file_path,
listener,
tls_config,
None,
None,
));
}
pub async fn serve_web_client(
config: Config,
config_options: Options,
config_file_path: Option<PathBuf>,
listener: std::net::TcpListener,
rustls_config: Option<RustlsConfig>,
session_manager: Option<Arc<dyn SessionManager>>,
client_os_api_factory: Option<Arc<dyn ClientOsApiFactory>>,
) {
let Some(config_file_path) = config_file_path.or_else(|| Config::default_config_file_path())
else {
log::error!("Failed to find default config file path");
return;
};
let connection_table = Arc::new(Mutex::new(ConnectionTable::default()));
let server_handle = Handle::new();
let session_manager = session_manager.unwrap_or_else(|| Arc::new(RealSessionManager));
let client_os_api_factory =
client_os_api_factory.unwrap_or_else(|| Arc::new(RealClientOsApiFactory));
// we use a short version here to bypass macos socket path length limitations
// since there likely aren't going to be more than a handful of web instances on the same
// machine listening to the same ipc socket path, the collision risk here is extremely low
let id: String = Uuid::new_v4()
.simple()
.to_string()
.chars()
.take(5)
.collect();
let is_https = rustls_config.is_some();
let state = AppState {
connection_table: connection_table.clone(),
config: Arc::new(Mutex::new(config)),
config_options,
config_file_path,
session_manager,
client_os_api_factory,
is_https,
};
tokio::spawn({
let server_handle = server_handle.clone();
async move {
listen_to_web_server_instructions(server_handle, &format!("{}", id)).await;
}
});
let app = Router::new()
.route("/ws/control", any(ws_handler_control))
.route("/ws/terminal", any(ws_handler_terminal))
.route("/ws/terminal/{session}", any(ws_handler_terminal))
.route("/session", post(create_new_client))
.route_layer(middleware::from_fn(auth_middleware))
.route("/", get(serve_html))
.route("/{session}", get(serve_html))
.route("/assets/{*path}", get(get_static_asset))
.route("/command/login", post(login_handler))
.route("/info/version", get(version_handler))
.with_state(state);
match rustls_config {
Some(rustls_config) => {
let _ = axum_server::from_tcp_rustls(listener, rustls_config)
.handle(server_handle)
.serve(app.into_make_service())
.await;
},
None => {
let _ = axum_server::from_tcp(listener)
.handle(server_handle)
.serve(app.into_make_service())
.await;
},
}
}
fn daemonize_web_server(
web_server_ip: IpAddr,
web_server_port: u16,
web_server_cert: Option<PathBuf>,
web_server_key: Option<PathBuf>,
) -> (Runtime, std::net::TcpListener, Option<RustlsConfig>) {
let (mut exit_message_tx, exit_message_rx) = pipe().unwrap();
let (mut exit_status_tx, mut exit_status_rx) = pipe().unwrap();
let current_umask = umask(Mode::all());
umask(current_umask);
let web_server_key = web_server_key.clone();
let web_server_cert = web_server_cert.clone();
let daemonization_outcome = daemonize::Daemonize::new()
.working_directory(std::env::current_dir().unwrap())
.umask(current_umask.bits() as u32)
.privileged_action(
move || -> Result<(Runtime, std::net::TcpListener, Option<RustlsConfig>), String> {
let runtime = Runtime::new().map_err(|e| e.to_string())?;
let tls_config = match (web_server_cert, web_server_key) {
(Some(web_server_cert), Some(web_server_key)) => {
let tls_config = runtime.block_on(async move {
RustlsConfig::from_pem_file(
PathBuf::from(web_server_cert),
PathBuf::from(web_server_key),
)
.await
});
let tls_config = match tls_config {
Ok(tls_config) => tls_config,
Err(e) => {
return Err(e.to_string());
},
};
Some(tls_config)
},
(None, None) => None,
_ => {
return Err(
"Must specify both web_server_cert and web_server_key".to_owned()
)
},
};
let listener = runtime.block_on(async move {
std::net::TcpListener::bind(format!("{}:{}", web_server_ip, web_server_port))
});
listener
.map(|listener| (runtime, listener, tls_config))
.map_err(|e| e.to_string())
},
)
.execute();
match daemonization_outcome {
Outcome::Parent(Ok(parent)) => {
if parent.first_child_exit_code == 0 {
let mut buf = [0; 1];
match exit_status_rx.read_exact(&mut buf) {
Ok(_) => {
let exit_status = buf.iter().next().copied().unwrap_or(0) as i32;
let mut message = String::new();
let mut reader = BufReader::new(exit_message_rx);
let _ = reader.read_line(&mut message);
if exit_status == 0 {
println!("{}", message.trim());
} else {
eprintln!("{}", message.trim());
}
std::process::exit(exit_status);
},
Err(e) => {
eprintln!("{}", e);
std::process::exit(2);
},
}
} else {
std::process::exit(parent.first_child_exit_code);
}
},
Outcome::Child(Ok(child)) => match child.privileged_action_result {
Ok(listener_and_runtime) => {
let _ = writeln!(
exit_message_tx,
"Web Server started on {} port {}",
web_server_ip, web_server_port
);
let _ = exit_status_tx.write_all(&[0]);
listener_and_runtime
},
Err(e) => {
let _ = exit_status_tx.write_all(&[2]);
let _ = writeln!(exit_message_tx, "{}", e);
std::process::exit(2);
},
},
_ => {
eprintln!("Failed to start server");
std::process::exit(2);
},
}
}
#[cfg(test)]
#[path = "./unit/web_client_tests.rs"]
mod web_client_tests;
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/web_client/ipc_listener.rs | zellij-client/src/web_client/ipc_listener.rs | use axum_server::Handle;
use tokio::io::AsyncReadExt;
use tokio::net::{UnixListener, UnixStream};
use zellij_utils::consts::WEBSERVER_SOCKET_PATH;
use zellij_utils::prost::Message;
use zellij_utils::web_server_commands::InstructionForWebServer;
use zellij_utils::web_server_contract::web_server_contract::InstructionForWebServer as ProtoInstructionForWebServer;
pub async fn create_webserver_receiver(
id: &str,
) -> Result<UnixStream, Box<dyn std::error::Error + Send + Sync>> {
std::fs::create_dir_all(&WEBSERVER_SOCKET_PATH.as_path())?;
let socket_path = WEBSERVER_SOCKET_PATH.join(format!("{}", id));
if socket_path.exists() {
tokio::fs::remove_file(&socket_path).await?;
}
let listener = UnixListener::bind(&socket_path)?;
let (stream, _) = listener.accept().await?;
Ok(stream)
}
pub async fn receive_webserver_instruction(
receiver: &mut UnixStream,
) -> std::io::Result<InstructionForWebServer> {
// Read length prefix (4 bytes)
let mut len_bytes = [0u8; 4];
receiver.read_exact(&mut len_bytes).await?;
let len = u32::from_le_bytes(len_bytes) as usize;
// Read protobuf message
let mut buffer = vec![0u8; len];
receiver.read_exact(&mut buffer).await?;
// Decode protobuf message
let proto_instruction = ProtoInstructionForWebServer::decode(&buffer[..])
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
// Convert to Rust type
proto_instruction
.try_into()
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))
}
pub async fn listen_to_web_server_instructions(server_handle: Handle, id: &str) {
loop {
let receiver = create_webserver_receiver(id).await;
match receiver {
Ok(mut receiver) => {
match receive_webserver_instruction(&mut receiver).await {
Ok(instruction) => match instruction {
InstructionForWebServer::ShutdownWebServer => {
server_handle.shutdown();
break;
},
},
Err(e) => {
log::error!("Failed to process web server instruction: {}", e);
// Continue loop to recreate receiver and try again
},
}
},
Err(e) => {
log::error!("Failed to listen to ipc channel: {}", e);
break;
},
}
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/web_client/authentication.rs | zellij-client/src/web_client/authentication.rs | use crate::web_client::utils::parse_cookies;
use axum::body::Body;
use axum::http::header::SET_COOKIE;
use axum::{extract::Request, http::StatusCode, middleware::Next, response::Response};
use axum_extra::extract::cookie::{Cookie, SameSite};
use zellij_utils::web_authentication_tokens::{is_session_token_read_only, validate_session_token};
pub async fn auth_middleware(request: Request, next: Next) -> Result<Response, StatusCode> {
let cookies = parse_cookies(&request);
let session_token = match cookies.get("session_token") {
Some(token) => token.clone(),
None => return Err(StatusCode::UNAUTHORIZED),
};
match validate_session_token(&session_token) {
Ok(true) => {
// Check if this is a read-only token
let is_read_only = is_session_token_read_only(&session_token).unwrap_or(false);
// Store in request extensions for downstream handlers
let mut request = request;
request.extensions_mut().insert(is_read_only);
let response = next.run(request).await;
Ok(response)
},
Ok(false) | Err(_) => {
// revoke session_token as if it exists it's no longer valid
let mut response = Response::builder()
.status(StatusCode::UNAUTHORIZED)
.body(Body::empty())
.unwrap();
// Clear both secure and non-secure versions
// in case the user was on http before and is now on https
// or vice versa
let clear_cookies = [
Cookie::build(("session_token", ""))
.http_only(true)
.secure(false)
.same_site(SameSite::Strict)
.path("/")
.max_age(time::Duration::seconds(0))
.build(),
Cookie::build(("session_token", ""))
.http_only(true)
.secure(true)
.same_site(SameSite::Strict)
.path("/")
.max_age(time::Duration::seconds(0))
.build(),
];
for cookie in clear_cookies {
response
.headers_mut()
.append(SET_COOKIE, cookie.to_string().parse().unwrap());
}
Ok(response)
},
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/web_client/http_handlers.rs | zellij-client/src/web_client/http_handlers.rs | use crate::web_client::types::{AppState, CreateClientIdResponse, LoginRequest, LoginResponse};
use crate::web_client::utils::{get_mime_type, parse_cookies};
use axum::{
extract::{Path as AxumPath, Request, State},
http::{header, StatusCode},
response::{Html, IntoResponse},
Json,
};
use axum_extra::extract::cookie::{Cookie, SameSite};
use include_dir;
use uuid::Uuid;
use zellij_utils::{consts::VERSION, web_authentication_tokens::create_session_token};
const WEB_CLIENT_PAGE: &str = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/",
"assets/index.html"
));
const ASSETS_DIR: include_dir::Dir<'_> = include_dir::include_dir!("$CARGO_MANIFEST_DIR/assets");
pub async fn serve_html(request: Request) -> Html<String> {
let cookies = parse_cookies(&request);
let is_authenticated = cookies.get("session_token").is_some();
let auth_value = if is_authenticated { "true" } else { "false" };
let html = Html(WEB_CLIENT_PAGE.replace("IS_AUTHENTICATED", &format!("{}", auth_value)));
html
}
pub async fn login_handler(
State(state): State<AppState>,
Json(login_request): Json<LoginRequest>,
) -> impl IntoResponse {
match create_session_token(
&login_request.auth_token,
login_request.remember_me.unwrap_or(false),
) {
Ok(session_token) => {
let is_https = state.is_https;
let cookie = if login_request.remember_me.unwrap_or(false) {
// Persistent cookie for remember_me
Cookie::build(("session_token", session_token))
.http_only(true)
.secure(is_https)
.same_site(SameSite::Strict)
.path("/")
.max_age(time::Duration::weeks(4))
.build()
} else {
// Session cookie - NO max_age means it expires when browser closes/refreshes
Cookie::build(("session_token", session_token))
.http_only(true)
.secure(is_https)
.same_site(SameSite::Strict)
.path("/")
.build()
};
let mut response = Json(LoginResponse {
success: true,
message: "Login successful".to_string(),
})
.into_response();
if let Ok(cookie_header) = axum::http::HeaderValue::from_str(&cookie.to_string()) {
response.headers_mut().insert("set-cookie", cookie_header);
}
response
},
Err(_) => (
StatusCode::UNAUTHORIZED,
Json(LoginResponse {
success: false,
message: "Invalid authentication token".to_string(),
}),
)
.into_response(),
}
}
pub async fn create_new_client(
State(state): State<AppState>,
request: axum::extract::Request,
) -> Result<Json<CreateClientIdResponse>, (StatusCode, impl IntoResponse)> {
// Extract is_read_only from request extensions (set by auth middleware)
let is_read_only = request.extensions().get::<bool>().copied().unwrap_or(false);
let web_client_id = String::from(Uuid::new_v4());
let os_input = state
.client_os_api_factory
.create_client_os_api()
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, Json(e.to_string())))?;
state.connection_table.lock().unwrap().add_new_client(
web_client_id.to_owned(),
os_input,
is_read_only,
);
Ok(Json(CreateClientIdResponse {
web_client_id,
is_read_only,
}))
}
pub async fn get_static_asset(AxumPath(path): AxumPath<String>) -> impl IntoResponse {
let path = path.trim_start_matches('/');
match ASSETS_DIR.get_file(path) {
None => (
[(header::CONTENT_TYPE, "text/html")],
"Not Found".as_bytes(),
),
Some(file) => {
let ext = file.path().extension().and_then(|ext| ext.to_str());
let mime_type = get_mime_type(ext);
([(header::CONTENT_TYPE, mime_type)], file.contents())
},
}
}
pub async fn version_handler() -> &'static str {
VERSION
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/web_client/session_management.rs | zellij-client/src/web_client/session_management.rs | use crate::os_input_output::ClientOsApi;
use crate::spawn_server;
use std::{fs, path::PathBuf};
use zellij_utils::{
consts::session_layout_cache_file_name,
data::{ConnectToSession, LayoutInfo, WebSharing},
envs,
input::{cli_assets::CliAssets, config::Config, options::Options},
ipc::{ClientAttributes, ClientToServerMsg},
sessions::{generate_unique_session_name, resurrection_layout},
};
pub fn build_initial_connection(
session_name: Option<String>,
config: &Config,
) -> Result<Option<ConnectToSession>, &'static str> {
let should_start_with_welcome_screen = session_name.is_none();
let default_layout_from_config =
LayoutInfo::from_config(&config.options.layout_dir, &config.options.default_layout);
if should_start_with_welcome_screen {
let Some(initial_session_name) = session_name.clone().or_else(generate_unique_session_name)
else {
return Err("Failed to generate unique session name, bailing.");
};
Ok(Some(ConnectToSession {
name: Some(initial_session_name.clone()),
layout: Some(LayoutInfo::BuiltIn("welcome".to_owned())),
..Default::default()
}))
} else if let Some(session_name) = session_name {
Ok(Some(ConnectToSession {
name: Some(session_name.clone()),
layout: default_layout_from_config,
..Default::default()
}))
} else if default_layout_from_config.is_some() {
Ok(Some(ConnectToSession {
layout: default_layout_from_config,
..Default::default()
}))
} else {
Ok(None)
}
}
pub fn spawn_new_session(
session_name: &str,
mut os_input: Box<dyn ClientOsApi>,
zellij_ipc_pipe: &PathBuf,
) {
let debug = false;
envs::set_session_name(session_name.to_owned());
os_input.update_session_name(session_name.to_owned());
spawn_server(&*zellij_ipc_pipe, debug).unwrap();
}
pub fn create_first_message(
is_read_only: bool,
config_file_path: Option<PathBuf>,
client_attributes: ClientAttributes,
mut config_opts: Options,
should_create_session: bool,
session_name: &str,
) -> ClientToServerMsg {
let resurrection_layout = resurrection_layout(&session_name).ok().flatten();
let layout_info = if resurrection_layout.is_some() {
Some(LayoutInfo::File(
session_layout_cache_file_name(&session_name)
.display()
.to_string(),
))
} else {
None
};
config_opts.web_server = Some(true);
config_opts.web_sharing = Some(WebSharing::On);
let is_web_client = true;
if is_read_only {
// read only clients attach as watchers
ClientToServerMsg::AttachWatcherClient {
terminal_size: client_attributes.size,
is_web_client,
}
} else if should_create_session {
config_opts.web_server = Some(true);
config_opts.web_sharing = Some(WebSharing::On);
let cli_assets = CliAssets {
config_file_path,
config_dir: None,
should_ignore_config: false,
configuration_options: Some(config_opts),
layout: layout_info,
terminal_window_size: client_attributes.size,
data_dir: None,
is_debug: false,
max_panes: None,
force_run_layout_commands: false,
cwd: None,
};
ClientToServerMsg::FirstClientConnected {
cli_assets,
is_web_client,
}
} else {
let cli_assets = CliAssets {
config_file_path,
config_dir: None,
should_ignore_config: false,
configuration_options: Some(config_opts),
layout: None,
terminal_window_size: client_attributes.size,
data_dir: None,
is_debug: false,
max_panes: None,
force_run_layout_commands: false,
cwd: None,
};
let is_web_client = true;
ClientToServerMsg::AttachClient {
cli_assets,
tab_position_to_focus: None,
pane_to_focus: None,
is_web_client,
}
}
}
pub fn create_ipc_pipe(session_name: &str) -> PathBuf {
let zellij_ipc_pipe: PathBuf = {
let mut sock_dir = zellij_utils::consts::ZELLIJ_SOCK_DIR.clone();
fs::create_dir_all(&sock_dir).unwrap();
zellij_utils::shared::set_permissions(&sock_dir, 0o700).unwrap();
sock_dir.push(session_name);
sock_dir
};
zellij_ipc_pipe
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/web_client/unit/web_client_tests.rs | zellij-client/src/web_client/unit/web_client_tests.rs | use super::serve_web_client;
use super::*;
use futures_util::{SinkExt, StreamExt};
use isahc::prelude::*;
use serde_json;
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::{Arc, Mutex};
use tokio::time::timeout;
use tokio_tungstenite::tungstenite::http::Request;
use tokio_tungstenite::{connect_async, tungstenite::Message};
use zellij_utils::input::cli_assets::CliAssets;
use zellij_utils::input::layout::Layout;
use zellij_utils::{consts::VERSION, input::config::Config, input::options::Options};
use crate::os_input_output::ClientOsApi;
use crate::web_client::control_message::{
WebClientToWebServerControlMessage, WebClientToWebServerControlMessagePayload,
WebServerToWebClientControlMessage,
};
use crate::web_client::ClientOsApiFactory;
use zellij_utils::{
data::{LayoutInfo, Palette},
errors::ErrorContext,
ipc::{ClientAttributes, ClientToServerMsg, ServerToClientMsg},
pane_size::Size,
web_authentication_tokens::{create_token, delete_db, revoke_token},
};
use serial_test::serial;
mod web_client_tests {
use super::*;
use std::time::{Duration, Instant};
async fn wait_for_server(port: u16, timeout: Duration) -> Result<(), String> {
let start = Instant::now();
let url = format!("http://127.0.0.1:{}/info/version", port);
while start.elapsed() < timeout {
match tokio::task::spawn_blocking({
let url = url.clone();
move || isahc::get(&url)
})
.await
{
Ok(Ok(_)) => {
// server ready
return Ok(());
},
Ok(Err(e)) => {
eprintln!("HTTP request failed: {:?}", e);
},
Err(e) => {
eprintln!("Task spawn failed: {:?}", e);
},
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
Err(format!(
"HTTP server failed to start on port {} within {:?}",
port, timeout
))
}
#[tokio::test]
#[serial]
async fn test_version_endpoint() {
let _ = delete_db();
let session_manager = Arc::new(MockSessionManager::new());
let client_os_api_factory = Arc::new(MockClientOsApiFactory::new());
let config = Config::default();
let options = Options::default();
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let port = addr.port();
let temp_config_path = std::env::temp_dir().join("test_config.kdl");
let server_handle = tokio::spawn(serve_web_client(
config,
options,
Some(temp_config_path),
listener,
None,
Some(session_manager),
Some(client_os_api_factory),
));
wait_for_server(port, Duration::from_secs(5))
.await
.expect("Server failed to start");
let url = format!("http://127.0.0.1:{}/info/version", port);
let mut response = timeout(
Duration::from_secs(5),
tokio::task::spawn_blocking(move || isahc::get(&url)),
)
.await
.expect("Request timed out")
.expect("Spawn blocking failed")
.expect("Request failed");
assert!(response.status().is_success());
let version_text = response.text().expect("Failed to read response body");
assert_eq!(version_text, VERSION);
server_handle.abort();
// time for cleanup
tokio::time::sleep(Duration::from_millis(100)).await;
}
#[tokio::test]
#[serial]
async fn test_login_endpoint() {
let _ = delete_db();
let test_token_name = "test_token_login";
let read_only = false;
let (auth_token, _) = create_token(Some(test_token_name.to_string()), read_only)
.expect("Failed to create test token");
let session_manager = Arc::new(MockSessionManager::new());
let client_os_api_factory = Arc::new(MockClientOsApiFactory::new());
let config = Config::default();
let options = Options::default();
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let port = addr.port();
let temp_config_path = std::env::temp_dir().join("test_config.kdl");
let server_handle = tokio::spawn(async move {
serve_web_client(
config,
options,
Some(temp_config_path),
listener,
None,
Some(session_manager),
Some(client_os_api_factory),
)
.await;
});
wait_for_server(port, Duration::from_secs(5))
.await
.expect("Server failed to start");
let login_url = format!("http://127.0.0.1:{}/command/login", port);
let login_payload = serde_json::json!({
"auth_token": auth_token,
"remember_me": true
});
let mut response = timeout(
Duration::from_secs(5),
tokio::task::spawn_blocking(move || {
isahc::Request::post(&login_url)
.header("Content-Type", "application/json")
.body(login_payload.to_string())
.unwrap()
.send()
}),
)
.await
.expect("Login request timed out")
.expect("Spawn blocking failed")
.expect("Login request failed");
assert!(response.status().is_success());
let response_text = response.text().expect("Failed to read response body");
let response_json: serde_json::Value =
serde_json::from_str(&response_text).expect("Failed to parse JSON");
assert_eq!(response_json["success"], true);
assert_eq!(response_json["message"], "Login successful");
server_handle.abort();
revoke_token(test_token_name).expect("Failed to revoke test token");
// time for cleanup
tokio::time::sleep(Duration::from_millis(100)).await;
}
#[tokio::test]
#[serial]
async fn test_invalid_auth_token_login() {
let _ = delete_db();
let session_manager = Arc::new(MockSessionManager::new());
let client_os_api_factory = Arc::new(MockClientOsApiFactory::new());
let config = Config::default();
let options = Options::default();
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let port = addr.port();
let temp_config_path = std::env::temp_dir().join("test_config.kdl");
let server_handle = tokio::spawn(async move {
serve_web_client(
config,
options,
Some(temp_config_path),
listener,
None,
Some(session_manager),
Some(client_os_api_factory),
)
.await;
});
wait_for_server(port, Duration::from_secs(5))
.await
.expect("Server failed to start");
let login_url = format!("http://127.0.0.1:{}/command/login", port);
let login_payload = serde_json::json!({
"auth_token": "invalid_token_123",
"remember_me": false
});
let response = timeout(
Duration::from_secs(5),
tokio::task::spawn_blocking(move || {
isahc::Request::post(&login_url)
.header("Content-Type", "application/json")
.body(login_payload.to_string())
.unwrap()
.send()
}),
)
.await
.expect("Login request timed out")
.expect("Spawn blocking failed")
.expect("Login request failed");
assert_eq!(response.status(), 401);
server_handle.abort();
}
#[tokio::test]
#[serial]
async fn test_full_session_flow() {
let _ = delete_db();
let test_token_name = "test_token_session_flow";
let read_only = false;
let (auth_token, _) = create_token(Some(test_token_name.to_string()), read_only)
.expect("Failed to create test token");
let session_manager = Arc::new(MockSessionManager::new());
let client_os_api_factory = Arc::new(MockClientOsApiFactory::new());
let factory_for_verification = client_os_api_factory.clone();
let config = Config::default();
let options = Options::default();
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let port = addr.port();
let temp_config_path = std::env::temp_dir().join("test_config.kdl");
let server_handle = tokio::spawn(async move {
serve_web_client(
config,
options,
Some(temp_config_path),
listener,
None,
Some(session_manager),
Some(client_os_api_factory),
)
.await;
});
wait_for_server(port, Duration::from_secs(5))
.await
.expect("Server failed to start");
let login_url = format!("http://127.0.0.1:{}/command/login", port);
let login_payload = serde_json::json!({
"auth_token": auth_token,
"remember_me": true
});
let login_response = timeout(
Duration::from_secs(5),
tokio::task::spawn_blocking(move || {
isahc::Request::post(&login_url)
.header("Content-Type", "application/json")
.body(login_payload.to_string())
.unwrap()
.send()
}),
)
.await
.unwrap()
.unwrap()
.unwrap();
assert!(login_response.status().is_success());
let set_cookie_header = login_response.headers().get("set-cookie");
assert!(
set_cookie_header.is_some(),
"Should have received session cookie"
);
let cookie_value = set_cookie_header.unwrap().to_str().unwrap();
let session_token = cookie_value
.split(';')
.next()
.and_then(|part| part.split('=').nth(1))
.unwrap();
let session_url = format!("http://127.0.0.1:{}/session", port);
let mut client_response = timeout(
Duration::from_secs(5),
tokio::task::spawn_blocking({
let session_token = session_token.to_string();
move || {
isahc::Request::post(&session_url)
.header("Cookie", format!("session_token={}", session_token))
.header("Content-Type", "application/json")
.body("{}")
.unwrap()
.send()
}
}),
)
.await
.unwrap()
.unwrap()
.unwrap();
assert!(client_response.status().is_success());
let client_data: serde_json::Value =
serde_json::from_str(&client_response.text().unwrap()).unwrap();
let web_client_id = client_data["web_client_id"].as_str().unwrap().to_string();
let control_ws_url = format!("ws://127.0.0.1:{}/ws/control", port);
let (control_ws, _) = timeout(
Duration::from_secs(5),
connect_async_with_cookie(&control_ws_url, session_token),
)
.await
.expect("Control WebSocket connection timed out")
.expect("Failed to connect to control WebSocket");
let (mut control_sink, mut control_stream) = control_ws.split();
let control_message = timeout(Duration::from_secs(2), control_stream.next())
.await
.expect("Timeout waiting for control message")
.expect("Control stream ended")
.expect("Error receiving control message");
if let Message::Text(text) = control_message {
let parsed: WebServerToWebClientControlMessage =
serde_json::from_str(&text).expect("Failed to parse control message");
match parsed {
WebServerToWebClientControlMessage::SetConfig(_) => {},
_ => panic!("Expected SetConfig message, got: {:?}", parsed),
}
} else {
panic!("Expected text message, got: {:?}", control_message);
}
let resize_msg = WebClientToWebServerControlMessage {
web_client_id: web_client_id.clone(),
payload: WebClientToWebServerControlMessagePayload::TerminalResize(Size {
rows: 30,
cols: 100,
}),
};
control_sink
.send(Message::Text(serde_json::to_string(&resize_msg).unwrap()))
.await
.expect("Failed to send resize message");
let terminal_ws_url = format!(
"ws://127.0.0.1:{}/ws/terminal?web_client_id={}",
port, web_client_id
);
let (terminal_ws, _) = timeout(
Duration::from_secs(5),
connect_async_with_cookie(&terminal_ws_url, session_token),
)
.await
.expect("Terminal WebSocket connection timed out")
.expect("Failed to connect to terminal WebSocket");
let (mut terminal_sink, _terminal_stream) = terminal_ws.split();
terminal_sink
.send(Message::Text("echo hello\n".to_string()))
.await
.expect("Failed to send terminal input");
tokio::time::sleep(Duration::from_millis(500)).await;
let mock_apis = factory_for_verification.mock_apis.lock().unwrap();
let mut found_resize = false;
let mut found_terminal_input = false;
for (_, mock_api) in mock_apis.iter() {
let messages = mock_api.get_sent_messages();
for msg in messages {
match msg {
ClientToServerMsg::TerminalResize { new_size: _ } => {
found_resize = true;
},
ClientToServerMsg::Key { .. }
| ClientToServerMsg::Action {
action: _,
terminal_id: _,
client_id: _,
is_cli_client: _,
} => {
found_terminal_input = true;
},
_ => {},
}
}
}
assert!(
found_resize,
"Terminal resize message was not received by mock OS API"
);
assert!(
found_terminal_input,
"Terminal input message was not received by mock OS API"
);
let _ = control_sink.close().await;
let _ = terminal_sink.close().await;
server_handle.abort();
revoke_token(test_token_name).expect("Failed to revoke test token");
tokio::time::sleep(Duration::from_millis(100)).await;
}
#[tokio::test]
#[serial]
async fn test_unauthorized_access_without_session() {
let _ = delete_db();
let session_manager = Arc::new(MockSessionManager::new());
let client_os_api_factory = Arc::new(MockClientOsApiFactory::new());
let config = Config::default();
let options = Options::default();
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let port = addr.port();
let temp_config_path = std::env::temp_dir().join("test_config.kdl");
let server_handle = tokio::spawn(async move {
serve_web_client(
config,
options,
Some(temp_config_path),
listener,
None,
Some(session_manager),
Some(client_os_api_factory),
)
.await;
});
wait_for_server(port, Duration::from_secs(5))
.await
.expect("Server failed to start");
let session_url = format!("http://127.0.0.1:{}/session", port);
let response = timeout(
Duration::from_secs(5),
tokio::task::spawn_blocking(move || isahc::post(&session_url, "{}")),
)
.await
.expect("Session request timed out")
.expect("Spawn blocking failed")
.expect("Session request failed");
assert_eq!(response.status(), 401);
server_handle.abort();
}
#[tokio::test]
#[serial]
async fn test_invalid_session_token() {
let _ = delete_db();
let session_manager = Arc::new(MockSessionManager::new());
let client_os_api_factory = Arc::new(MockClientOsApiFactory::new());
let config = Config::default();
let options = Options::default();
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let port = addr.port();
let temp_config_path = std::env::temp_dir().join("test_config.kdl");
let server_handle = tokio::spawn(async move {
serve_web_client(
config,
options,
Some(temp_config_path),
listener,
None,
Some(session_manager),
Some(client_os_api_factory),
)
.await;
});
wait_for_server(port, Duration::from_secs(5))
.await
.expect("Server failed to start");
let session_url = format!("http://127.0.0.1:{}/session", port);
let response = timeout(
Duration::from_secs(5),
tokio::task::spawn_blocking(move || {
isahc::Request::post(&session_url)
.header("Cookie", "session_token=invalid_session_token_123")
.header("Content-Type", "application/json")
.body("{}")
.unwrap()
.send()
}),
)
.await
.expect("Session request timed out")
.expect("Spawn blocking failed")
.expect("Session request failed");
assert_eq!(response.status(), 401);
server_handle.abort();
}
#[tokio::test]
#[serial]
async fn test_server_shutdown_closes_websocket_connections() {
let _ = delete_db();
let test_token_name = "test_token_server_shutdown";
let read_only = false;
let (auth_token, _) = create_token(Some(test_token_name.to_string()), read_only)
.expect("Failed to create test token");
let session_manager = Arc::new(MockSessionManager::new());
let client_os_api_factory = Arc::new(MockClientOsApiFactory::new());
let config = Config::default();
let options = Options::default();
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let port = addr.port();
let temp_config_path = std::env::temp_dir().join("test_config.kdl");
let server_handle = tokio::spawn(async move {
serve_web_client(
config,
options,
Some(temp_config_path),
listener,
None,
Some(session_manager),
Some(client_os_api_factory),
)
.await;
});
wait_for_server(port, Duration::from_secs(5))
.await
.expect("Server failed to start");
// Login and get session token
let session_token = login_and_get_session_token(port, &auth_token).await;
// Create client session
let web_client_id = create_client_session(port, &session_token).await;
// Establish control WebSocket connection
let control_ws_url = format!("ws://127.0.0.1:{}/ws/control", port);
let (control_ws, _) = timeout(
Duration::from_secs(5),
connect_async_with_cookie(&control_ws_url, &session_token),
)
.await
.expect("Control WebSocket connection timed out")
.expect("Failed to connect to control WebSocket");
let (mut control_sink, mut control_stream) = control_ws.split();
// Wait for initial SetConfig message
let _initial_msg = timeout(Duration::from_secs(2), control_stream.next())
.await
.expect("Timeout waiting for initial control message");
// Send resize message to establish proper connection
let resize_msg = WebClientToWebServerControlMessage {
web_client_id: web_client_id.clone(),
payload: WebClientToWebServerControlMessagePayload::TerminalResize(Size {
rows: 30,
cols: 100,
}),
};
control_sink
.send(Message::Text(serde_json::to_string(&resize_msg).unwrap()))
.await
.expect("Failed to send resize message");
// Establish terminal WebSocket connection
let terminal_ws_url = format!(
"ws://127.0.0.1:{}/ws/terminal?web_client_id={}",
port, web_client_id
);
let (terminal_ws, _) = timeout(
Duration::from_secs(5),
connect_async_with_cookie(&terminal_ws_url, &session_token),
)
.await
.expect("Terminal WebSocket connection timed out")
.expect("Failed to connect to terminal WebSocket");
let (_terminal_sink, mut terminal_stream) = terminal_ws.split();
// Trigger server shutdown
server_handle.abort();
// Verify control WebSocket receives close frame
let control_close_result = timeout(Duration::from_secs(3), control_stream.next()).await;
match control_close_result {
Ok(Some(Ok(Message::Close(_)))) => {
println!("✓ Control WebSocket received close frame");
},
Ok(Some(Ok(msg))) => {
println!("Control WebSocket received unexpected message: {:?}", msg);
},
Ok(Some(Err(e))) => {
println!(
"Control WebSocket error (expected during shutdown): {:?}",
e
);
},
Ok(None) => {
println!("✓ Control WebSocket stream ended (connection closed)");
},
Err(_) => {
println!("✓ Control WebSocket timed out (connection likely closed)");
},
}
// Verify terminal WebSocket receives close frame or connection ends
let terminal_close_result = timeout(Duration::from_secs(3), terminal_stream.next()).await;
match terminal_close_result {
Ok(Some(Ok(Message::Close(_)))) => {
println!("✓ Terminal WebSocket received close frame");
},
Ok(Some(Ok(msg))) => {
println!("Terminal WebSocket received unexpected message: {:?}", msg);
},
Ok(Some(Err(e))) => {
println!(
"Terminal WebSocket error (expected during shutdown): {:?}",
e
);
},
Ok(None) => {
println!("✓ Terminal WebSocket stream ended (connection closed)");
},
Err(_) => {
println!("✓ Terminal WebSocket timed out (connection likely closed)");
},
}
revoke_token(test_token_name).expect("Failed to revoke test token");
// time for cleanup
tokio::time::sleep(Duration::from_millis(100)).await;
}
#[tokio::test]
#[serial]
async fn test_client_cleanup_removes_from_connection_table() {
let _ = delete_db();
let test_token_name = "test_token_client_cleanup";
let read_only = false;
let (auth_token, _) = create_token(Some(test_token_name.to_string()), read_only)
.expect("Failed to create test token");
let session_manager = Arc::new(MockSessionManager::new());
let client_os_api_factory = Arc::new(MockClientOsApiFactory::new());
let factory_for_verification = client_os_api_factory.clone();
let config = Config::default();
let options = Options::default();
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let port = addr.port();
let temp_config_path = std::env::temp_dir().join("test_config.kdl");
let server_handle = tokio::spawn(async move {
serve_web_client(
config,
options,
Some(temp_config_path),
listener,
None,
Some(session_manager),
Some(client_os_api_factory),
)
.await;
});
wait_for_server(port, Duration::from_secs(5))
.await
.expect("Server failed to start");
// Login and get session token
let session_token = login_and_get_session_token(port, &auth_token).await;
// Create multiple client sessions
let client_id_1 = create_client_session(port, &session_token).await;
let client_id_2 = create_client_session(port, &session_token).await;
// Establish WebSocket connections for both clients
let control_ws_url_1 = format!("ws://127.0.0.1:{}/ws/control", port);
let (control_ws_1, _) = timeout(
Duration::from_secs(5),
connect_async_with_cookie(&control_ws_url_1, &session_token),
)
.await
.expect("Client 1 control WebSocket connection timed out")
.expect("Failed to connect client 1 to control WebSocket");
let (mut control_sink_1, mut control_stream_1) = control_ws_1.split();
let control_ws_url_2 = format!("ws://127.0.0.1:{}/ws/control", port);
let (control_ws_2, _) = timeout(
Duration::from_secs(5),
connect_async_with_cookie(&control_ws_url_2, &session_token),
)
.await
.expect("Client 2 control WebSocket connection timed out")
.expect("Failed to connect client 2 to control WebSocket");
let (mut control_sink_2, mut control_stream_2) = control_ws_2.split();
// Wait for initial messages and establish connections
let _initial_msg_1 = timeout(Duration::from_secs(2), control_stream_1.next()).await;
let _initial_msg_2 = timeout(Duration::from_secs(2), control_stream_2.next()).await;
// Send messages to establish proper connections
let resize_msg_1 = WebClientToWebServerControlMessage {
web_client_id: client_id_1.clone(),
payload: WebClientToWebServerControlMessagePayload::TerminalResize(Size {
rows: 30,
cols: 100,
}),
};
let resize_msg_2 = WebClientToWebServerControlMessage {
web_client_id: client_id_2.clone(),
payload: WebClientToWebServerControlMessagePayload::TerminalResize(Size {
rows: 25,
cols: 80,
}),
};
control_sink_1
.send(Message::Text(serde_json::to_string(&resize_msg_1).unwrap()))
.await
.expect("Failed to send resize message for client 1");
control_sink_2
.send(Message::Text(serde_json::to_string(&resize_msg_2).unwrap()))
.await
.expect("Failed to send resize message for client 2");
// Establish terminal connections
let terminal_ws_url_1 = format!(
"ws://127.0.0.1:{}/ws/terminal?web_client_id={}",
port, client_id_1
);
let (terminal_ws_1, _) = timeout(
Duration::from_secs(5),
connect_async_with_cookie(&terminal_ws_url_1, &session_token),
)
.await
.expect("Client 1 terminal WebSocket connection timed out")
.expect("Failed to connect client 1 to terminal WebSocket");
let (_terminal_sink_1, _terminal_stream_1) = terminal_ws_1.split();
// Verify both clients are initially present by checking mock APIs
tokio::time::sleep(Duration::from_millis(200)).await;
let initial_api_count = factory_for_verification.mock_apis.lock().unwrap().len();
assert!(
initial_api_count >= 2,
"Should have at least 2 client APIs created"
);
// Close connection for client 1 by closing WebSocket
let _ = control_sink_1.close().await;
// Allow time for cleanup
tokio::time::sleep(Duration::from_millis(500)).await;
// Verify client 2 is still functional by sending another message
let resize_msg_2_again = WebClientToWebServerControlMessage {
web_client_id: client_id_2.clone(),
payload: WebClientToWebServerControlMessagePayload::TerminalResize(Size {
rows: 40,
cols: 120,
}),
};
let send_result = control_sink_2
.send(Message::Text(
serde_json::to_string(&resize_msg_2_again).unwrap(),
))
.await;
match send_result {
Ok(_) => println!("✓ Client 2 is still functional after client 1 cleanup"),
Err(e) => println!("Client 2 send failed (may be expected): {:?}", e),
}
// Verify messages were received by checking mock APIs
let mock_apis = factory_for_verification.mock_apis.lock().unwrap();
let mut total_resize_messages: usize = 0;
for (_, mock_api) in mock_apis.iter() {
let messages = mock_api.get_sent_messages();
for msg in messages {
if matches!(msg, ClientToServerMsg::TerminalResize { .. }) {
total_resize_messages = total_resize_messages.saturating_add(1);
}
}
}
assert!(
total_resize_messages >= 2,
"Should have received at least 2 resize messages"
);
let _ = control_sink_2.close().await;
server_handle.abort();
revoke_token(test_token_name).expect("Failed to revoke test token");
tokio::time::sleep(Duration::from_millis(100)).await;
}
#[tokio::test]
#[serial]
async fn test_cancellation_token_triggers_on_shutdown() {
let _ = delete_db();
let test_token_name = "test_token_cancellation";
let read_only = false;
let (auth_token, _) = create_token(Some(test_token_name.to_string()), read_only)
.expect("Failed to create test token");
let session_manager = Arc::new(MockSessionManager::new());
let client_os_api_factory = Arc::new(MockClientOsApiFactory::new());
let config = Config::default();
let options = Options::default();
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let port = addr.port();
let temp_config_path = std::env::temp_dir().join("test_config.kdl");
let server_handle = tokio::spawn(async move {
serve_web_client(
config,
options,
Some(temp_config_path),
listener,
None,
Some(session_manager),
Some(client_os_api_factory),
)
.await;
});
wait_for_server(port, Duration::from_secs(5))
.await
.expect("Server failed to start");
// Login and create session
let session_token = login_and_get_session_token(port, &auth_token).await;
let web_client_id = create_client_session(port, &session_token).await;
// Establish terminal WebSocket connection
let terminal_ws_url = format!(
"ws://127.0.0.1:{}/ws/terminal?web_client_id={}",
port, web_client_id
);
let (terminal_ws, _) = timeout(
Duration::from_secs(5),
connect_async_with_cookie(&terminal_ws_url, &session_token),
)
.await
.expect("Terminal WebSocket connection timed out")
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/old_config_converter/old_layout.rs | zellij-client/src/old_config_converter/old_layout.rs | // This is a converter from the old yaml layout to the new KDL layout.
//
// It is supposed to be mostly self containing - please refrain from adding to it, importing
// from it or changing it
use super::old_config::{config_yaml_to_config_kdl, OldConfigFromYaml, OldRunCommand};
use serde::{Deserialize, Serialize};
use std::vec::Vec;
use std::{fmt, path::PathBuf};
use url::Url;
fn pane_line(
pane_name: Option<&String>,
split_size: Option<OldSplitSize>,
focus: Option<bool>,
borderless: bool,
) -> String {
let mut pane_line = format!("pane");
if let Some(pane_name) = pane_name {
// we use debug print here so that quotes and backslashes will be escaped
pane_line.push_str(&format!(" name={:?}", pane_name));
}
if let Some(split_size) = split_size {
pane_line.push_str(&format!(" size={}", split_size));
}
if let Some(focus) = focus {
pane_line.push_str(&format!(" focus={}", focus));
}
if borderless {
pane_line.push_str(" borderless=true");
}
pane_line
}
fn tab_line(
pane_name: Option<&String>,
split_size: Option<OldSplitSize>,
focus: Option<bool>,
borderless: bool,
) -> String {
let mut pane_line = format!("tab");
if let Some(pane_name) = pane_name {
// we use debug print here so that quotes and backslashes will be escaped
pane_line.push_str(&format!(" name={:?}", pane_name));
}
if let Some(split_size) = split_size {
pane_line.push_str(&format!(" size={}", split_size));
}
if let Some(focus) = focus {
pane_line.push_str(&format!(" focus={}", focus));
}
if borderless {
pane_line.push_str(" borderless=true");
}
pane_line
}
fn pane_line_with_children(
pane_name: Option<&String>,
split_size: Option<OldSplitSize>,
focus: Option<bool>,
borderless: bool,
split_direction: OldDirection,
) -> String {
let mut pane_line = format!("pane");
if let Some(pane_name) = pane_name {
// we use debug print here so that quotes and backslashes will be escaped
pane_line.push_str(&format!(" name={:?}", pane_name));
}
if let Some(split_size) = split_size {
pane_line.push_str(&format!(" size={}", split_size));
}
if let Some(focus) = focus {
pane_line.push_str(&format!(" focus={}", focus));
}
pane_line.push_str(&format!(" split_direction=\"{}\"", split_direction));
if borderless {
pane_line.push_str(" borderless=true");
}
pane_line
}
fn pane_command_line(
pane_name: Option<&String>,
split_size: Option<OldSplitSize>,
focus: Option<bool>,
borderless: bool,
command: &PathBuf,
) -> String {
let mut pane_line = format!("pane command={:?}", command);
if let Some(pane_name) = pane_name {
// we use debug print here so that quotes and backslashes will be escaped
pane_line.push_str(&format!(" name={:?}", pane_name));
}
if let Some(split_size) = split_size {
pane_line.push_str(&format!(" size={}", split_size));
}
if let Some(focus) = focus {
pane_line.push_str(&format!(" focus={}", focus));
}
if borderless {
pane_line.push_str(" borderless=true");
}
pane_line
}
fn tab_line_with_children(
pane_name: Option<&String>,
split_size: Option<OldSplitSize>,
focus: Option<bool>,
borderless: bool,
split_direction: OldDirection,
) -> String {
let mut pane_line = format!("tab");
if let Some(pane_name) = pane_name {
// we use debug print here so that quotes and backslashes will be escaped
pane_line.push_str(&format!(" name={:?}", pane_name));
}
if let Some(split_size) = split_size {
pane_line.push_str(&format!(" size={}", split_size));
}
if let Some(focus) = focus {
pane_line.push_str(&format!(" focus={}", focus));
}
pane_line.push_str(&format!(" split_direction=\"{}\"", split_direction));
if borderless {
pane_line.push_str(" borderless=true");
}
pane_line
}
fn stringify_template(
template: &OldLayoutTemplate,
indentation: String,
has_no_tabs: bool,
is_base: bool,
) -> String {
let mut stringified = if is_base {
String::new()
} else {
String::from("\n")
};
if is_base && !template.parts.is_empty() && template.direction == OldDirection::Vertical {
// we don't support specifying the split direction in the layout node
// eg. layout split_direction="Vertical" { .. } <== this is not supported!!
// so we need to add a child wrapper with the split direction instead:
// layout {
// pane split_direction="Vertical" { .. }
// }
let child_indentation = format!("{} ", &indentation);
stringified.push_str(&stringify_template(
template,
child_indentation,
has_no_tabs,
false,
));
} else if !template.parts.is_empty() {
if !is_base {
stringified.push_str(&format!(
"{}{} {{",
indentation,
pane_line_with_children(
template.pane_name.as_ref(),
template.split_size,
template.focus,
template.borderless,
template.direction
)
));
}
for part in &template.parts {
let child_indentation = format!("{} ", &indentation);
stringified.push_str(&stringify_template(
&part,
child_indentation,
has_no_tabs,
false,
));
}
if !is_base {
stringified.push_str(&format!("\n{}}}", indentation));
}
} else if template.body && !has_no_tabs {
stringified.push_str(&format!("{}children", indentation));
} else {
match template.run.as_ref() {
Some(OldRunFromYaml::Plugin(plugin_from_yaml)) => {
stringified.push_str(&format!(
"{}{} {{\n",
&indentation,
pane_line(
template.pane_name.as_ref(),
template.split_size,
template.focus,
template.borderless
)
));
stringified.push_str(&format!(
"{} plugin location=\"{}\"\n",
&indentation, plugin_from_yaml.location
));
stringified.push_str(&format!("{}}}", &indentation));
},
Some(OldRunFromYaml::Command(command_from_yaml)) => {
stringified.push_str(&format!(
"{}{}",
&indentation,
&pane_command_line(
template.pane_name.as_ref(),
template.split_size,
template.focus,
template.borderless,
&command_from_yaml.command
)
));
if let Some(cwd) = command_from_yaml.cwd.as_ref() {
stringified.push_str(&format!(" cwd={:?}", cwd));
}
if !command_from_yaml.args.is_empty() {
stringified.push_str(" {\n");
stringified.push_str(&format!(
"{} args {}\n",
&indentation,
command_from_yaml
.args
.iter()
// we use debug print here so that quotes and backslashes will be
// escaped
.map(|s| format!("{:?}", s))
.collect::<Vec<String>>()
.join(" ")
));
stringified.push_str(&format!("{}}}", &indentation));
}
},
None => {
stringified.push_str(&format!(
"{}{}",
&indentation,
pane_line(
template.pane_name.as_ref(),
template.split_size,
template.focus,
template.borderless
)
));
},
};
}
stringified
}
fn stringify_tabs(tabs: Vec<OldTabLayout>) -> String {
let mut stringified = String::new();
for tab in tabs {
let child_indentation = String::from(" ");
if !tab.parts.is_empty() {
stringified.push_str(&format!(
"\n{}{} {{",
child_indentation,
tab_line_with_children(
tab.pane_name.as_ref(),
tab.split_size,
tab.focus,
tab.borderless,
tab.direction
)
));
let tab_template = OldLayoutTemplate::from(tab);
stringified.push_str(&stringify_template(
&tab_template,
child_indentation.clone(),
true,
true,
));
stringified.push_str(&format!("\n{}}}", child_indentation));
} else {
stringified.push_str(&format!(
"\n{}{}",
child_indentation,
tab_line(
tab.pane_name.as_ref(),
tab.split_size,
tab.focus,
tab.borderless
)
));
}
}
stringified
}
pub fn layout_yaml_to_layout_kdl(raw_yaml_layout: &str) -> Result<String, String> {
// returns the raw kdl config
let layout_from_yaml: OldLayoutFromYamlIntermediate = serde_yaml::from_str(raw_yaml_layout)
.map_err(|e| format!("Failed to parse yaml: {:?}", e))?;
let mut kdl_layout = String::new();
kdl_layout.push_str("layout {");
let template = layout_from_yaml.template;
let tabs = layout_from_yaml.tabs;
let has_no_tabs = tabs.is_empty()
|| tabs.len() == 1 && tabs.get(0).map(|t| t.parts.is_empty()).unwrap_or(false);
if has_no_tabs {
let indentation = String::from("");
kdl_layout.push_str(&stringify_template(
&template,
indentation,
has_no_tabs,
true,
));
} else {
kdl_layout.push_str("\n default_tab_template {");
let indentation = String::from(" ");
kdl_layout.push_str(&stringify_template(
&template,
indentation,
has_no_tabs,
true,
));
kdl_layout.push_str("\n }");
kdl_layout.push_str(&stringify_tabs(tabs));
}
kdl_layout.push_str("\n}");
let layout_config = config_yaml_to_config_kdl(raw_yaml_layout, true)?;
if let Some(session_name) = layout_from_yaml.session.name {
// we use debug print here so that quotes and backslashes will be escaped
kdl_layout.push_str(&format!("\nsession_name {:?}", session_name));
if let Some(attach_to_session) = layout_from_yaml.session.attach {
kdl_layout.push_str(&format!("\nattach_to_session {}", attach_to_session));
}
}
if !layout_config.is_empty() {
kdl_layout.push('\n');
}
kdl_layout.push_str(&layout_config);
Ok(kdl_layout)
}
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone, Copy)]
pub enum OldDirection {
#[serde(alias = "horizontal")]
Horizontal,
#[serde(alias = "vertical")]
Vertical,
}
impl fmt::Display for OldDirection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
match self {
Self::Horizontal => write!(f, "Horizontal"),
Self::Vertical => write!(f, "Vertical"),
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
pub enum OldSplitSize {
#[serde(alias = "percent")]
Percent(u64), // 1 to 100
#[serde(alias = "fixed")]
Fixed(usize), // An absolute number of columns or rows
}
impl fmt::Display for OldSplitSize {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
match self {
Self::Percent(percent) => write!(f, "\"{}%\"", percent),
Self::Fixed(fixed_size) => write!(f, "{}", fixed_size),
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub enum OldRunFromYaml {
#[serde(rename = "plugin")]
Plugin(OldRunPluginFromYaml),
#[serde(rename = "command")]
Command(OldRunCommand),
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct OldRunPluginFromYaml {
#[serde(default)]
pub _allow_exec_host_cmd: bool,
pub location: Url,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(default)]
pub struct OldLayoutFromYamlIntermediate {
#[serde(default)]
pub template: OldLayoutTemplate,
#[serde(default)]
pub borderless: bool,
#[serde(default)]
pub tabs: Vec<OldTabLayout>,
#[serde(default)]
pub session: OldSessionFromYaml,
#[serde(flatten)]
pub config: Option<OldConfigFromYaml>,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(default)]
pub struct OldLayoutFromYaml {
#[serde(default)]
pub session: OldSessionFromYaml,
#[serde(default)]
pub template: OldLayoutTemplate,
#[serde(default)]
pub borderless: bool,
#[serde(default)]
pub tabs: Vec<OldTabLayout>,
}
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq)]
pub struct OldSessionFromYaml {
pub name: Option<String>,
#[serde(default = "default_as_some_true")]
pub attach: Option<bool>,
}
fn default_as_some_true() -> Option<bool> {
Some(true)
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct OldLayoutTemplate {
pub direction: OldDirection,
#[serde(default)]
pub pane_name: Option<String>,
#[serde(default)]
pub borderless: bool,
#[serde(default)]
pub parts: Vec<OldLayoutTemplate>,
#[serde(default)]
pub body: bool,
pub split_size: Option<OldSplitSize>,
pub focus: Option<bool>,
pub run: Option<OldRunFromYaml>,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct OldTabLayout {
#[serde(default)]
pub direction: OldDirection,
pub pane_name: Option<String>,
#[serde(default)]
pub borderless: bool,
#[serde(default)]
pub parts: Vec<OldTabLayout>,
pub split_size: Option<OldSplitSize>,
#[serde(default)]
pub name: String,
pub focus: Option<bool>,
pub run: Option<OldRunFromYaml>,
}
impl From<OldTabLayout> for OldLayoutTemplate {
fn from(old_tab_layout: OldTabLayout) -> Self {
OldLayoutTemplate {
direction: old_tab_layout.direction,
pane_name: old_tab_layout.pane_name.clone(),
borderless: old_tab_layout.borderless,
parts: old_tab_layout.parts.iter().map(|o| o.into()).collect(),
split_size: old_tab_layout.split_size,
focus: old_tab_layout.focus,
run: old_tab_layout.run.clone(),
body: false,
}
}
}
impl From<&OldTabLayout> for OldLayoutTemplate {
fn from(old_tab_layout: &OldTabLayout) -> Self {
OldLayoutTemplate {
direction: old_tab_layout.direction,
pane_name: old_tab_layout.pane_name.clone(),
borderless: old_tab_layout.borderless,
parts: old_tab_layout.parts.iter().map(|o| o.into()).collect(),
split_size: old_tab_layout.split_size,
focus: old_tab_layout.focus,
run: old_tab_layout.run.clone(),
body: false,
}
}
}
impl From<&mut OldTabLayout> for OldLayoutTemplate {
fn from(old_tab_layout: &mut OldTabLayout) -> Self {
OldLayoutTemplate {
direction: old_tab_layout.direction,
pane_name: old_tab_layout.pane_name.clone(),
borderless: old_tab_layout.borderless,
parts: old_tab_layout.parts.iter().map(|o| o.into()).collect(),
split_size: old_tab_layout.split_size,
focus: old_tab_layout.focus,
run: old_tab_layout.run.clone(),
body: false,
}
}
}
impl From<OldLayoutFromYamlIntermediate> for OldLayoutFromYaml {
fn from(layout_from_yaml_intermediate: OldLayoutFromYamlIntermediate) -> Self {
Self {
template: layout_from_yaml_intermediate.template,
borderless: layout_from_yaml_intermediate.borderless,
tabs: layout_from_yaml_intermediate.tabs,
session: layout_from_yaml_intermediate.session,
}
}
}
impl From<OldLayoutFromYaml> for OldLayoutFromYamlIntermediate {
fn from(layout_from_yaml: OldLayoutFromYaml) -> Self {
Self {
template: layout_from_yaml.template,
borderless: layout_from_yaml.borderless,
tabs: layout_from_yaml.tabs,
config: None,
session: layout_from_yaml.session,
}
}
}
impl Default for OldLayoutFromYamlIntermediate {
fn default() -> Self {
OldLayoutFromYaml::default().into()
}
}
impl Default for OldLayoutTemplate {
fn default() -> Self {
Self {
direction: OldDirection::Horizontal,
pane_name: None,
body: false,
borderless: false,
parts: vec![OldLayoutTemplate {
direction: OldDirection::Horizontal,
pane_name: None,
body: true,
borderless: false,
split_size: None,
focus: None,
run: None,
parts: vec![],
}],
split_size: None,
focus: None,
run: None,
}
}
}
impl Default for OldDirection {
fn default() -> Self {
OldDirection::Horizontal
}
}
// The unit test location.
#[path = "./unit/convert_layout_tests.rs"]
#[cfg(test)]
mod convert_layout_test;
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/old_config_converter/convert_old_yaml_files.rs | zellij-client/src/old_config_converter/convert_old_yaml_files.rs | use super::{config_yaml_to_config_kdl, layout_yaml_to_layout_kdl};
use std::path::PathBuf;
use zellij_utils::{
cli::CliArgs,
home::{find_default_config_dir, get_layout_dir, get_theme_dir},
};
const OLD_CONFIG_NAME: &str = "config.yaml";
pub fn convert_old_yaml_files(opts: &CliArgs) {
let config_dir = opts.config_dir.clone().or_else(find_default_config_dir);
let layout_dir = get_layout_dir(config_dir.clone());
let theme_dir = get_theme_dir(find_default_config_dir());
let specified_config_location = opts.config.as_ref();
let mut layout_files_to_convert = vec![];
let mut theme_files_to_convert = vec![];
if let Some(layout) = opts.layout.as_ref() {
if layout.extension().map(|s| s.to_string_lossy().to_string()) == Some("yaml".into()) {
if layout.exists() {
layout_files_to_convert.push((layout.clone(), true));
}
}
}
layout_files_to_convert.dedup();
if let Some(layout_dir) = layout_dir {
if let Ok(files) = std::fs::read_dir(layout_dir) {
for file in files {
if let Ok(file) = file {
if file
.path()
.extension()
.map(|s| s.to_string_lossy().to_string())
== Some("yaml".into())
{
let mut new_file_path = file.path().clone();
new_file_path.set_extension("kdl");
if !new_file_path.exists() {
layout_files_to_convert.push((file.path().clone(), false));
}
}
}
}
}
}
if let Some(theme_dir) = theme_dir {
if theme_dir.is_dir() {
if let Ok(files) = std::fs::read_dir(theme_dir) {
for entry in files.flatten() {
if let Some(extension) = entry.path().extension() {
if extension == "yaml" {
let mut new_file_path = entry.path().clone();
new_file_path.set_extension("kdl");
if !new_file_path.exists() {
theme_files_to_convert.push(entry.path())
}
}
}
}
}
}
}
if let Some(config_dir) = config_dir {
let yaml_config_location = specified_config_location.cloned().filter(|c| {
c.extension().map(|s| s.to_string_lossy().to_string()) == Some("yaml".into())
});
let specified_yaml_config_location = yaml_config_location.is_some();
let config_location =
yaml_config_location.unwrap_or_else(|| config_dir.join(OLD_CONFIG_NAME));
match convert_yaml(
config_location,
layout_files_to_convert,
theme_files_to_convert,
specified_yaml_config_location,
) {
Ok(should_exit) => {
if should_exit {
std::process::exit(0);
}
},
Err(e) => {
eprintln!("");
eprintln!("\u{1b}[1;31mFailed to convert yaml config\u{1b}[m: {}", e);
eprintln!("");
std::process::exit(1);
},
}
}
}
fn print_conversion_title_message() {
println!("");
println!("\u{1b}[1mZellij has moved to a new configuration format (KDL - https://kdl.dev) and has now been run with an old YAML configuration/layout/theme file.\u{1b}[m");
}
fn print_converting_config_message(old_file_name: String, new_file_name: String) {
println!(
"- Converting configuration file: \u{1b}[1;36m{}\u{1b}[m to the new configuration format at the same location: \u{1b}[1;36m{}\u{1b}[m",
old_file_name,
new_file_name
);
}
fn print_conversion_layouts_message(layout_files_to_convert: Vec<(PathBuf, bool)>) {
println!("- Converting the following layout YAML files to KDL files in the same location:");
for (layout_file, _was_explicitly_set) in layout_files_to_convert.iter() {
let mut new_layout_file_name = layout_file.clone();
new_layout_file_name.set_extension("kdl");
println!(
"\u{1b}[1;36m{}\u{1b}[m => \u{1b}[1;36m{}\u{1b}[m",
layout_file.as_path().as_os_str().to_string_lossy(),
new_layout_file_name.as_path().as_os_str().to_string_lossy()
);
}
}
fn print_conversion_themes_message(theme_files_to_convert: Vec<PathBuf>) {
println!("- Converting the following theme YAML files to KDL files in the same location:");
for theme_file in theme_files_to_convert.iter() {
let mut new_theme_file_name = theme_file.clone();
new_theme_file_name.set_extension("kdl");
println!(
"\u{1b}[1;36m{}\u{1b}[m => \u{1b}[1;36m{}\u{1b}[m",
theme_file.as_path().as_os_str().to_string_lossy(),
new_theme_file_name.as_path().as_os_str().to_string_lossy()
);
}
}
fn print_no_actions_and_wait_for_user_input() -> Result<(), String> {
println!("\u{1b}[1;32mNo actions are required of you. Press ENTER to continue.\u{1b}[m");
std::io::stdin()
.read_line(&mut String::new())
.map_err(|e| format!("Failed to read from STDIN: {:?}", e))?;
Ok(())
}
fn print_remain_unmodified_message(will_exit: bool) {
println!("The original file(s) will remain unmodified.");
if !will_exit {
println!("Will then use the new converted file(s) for this and the next runs.");
}
println!("");
}
fn print_flag_help_message(
layout_files_to_convert: Vec<(PathBuf, bool)>,
yaml_config_file: &PathBuf,
yaml_config_was_explicitly_set: bool,
) -> Result<(), String> {
println!("\u{1b}[1;32mWhat do you need to do?\u{1b}[m");
match layout_files_to_convert
.iter()
.find(|(_f, explicit)| *explicit)
{
Some((explicitly_specified_layout, _)) => {
let mut kdl_config_file_path = yaml_config_file.clone();
let mut kdl_explicitly_specified_layout = explicitly_specified_layout.clone();
kdl_config_file_path.set_extension("kdl");
kdl_explicitly_specified_layout.set_extension("kdl");
if yaml_config_was_explicitly_set {
println!("Since both the YAML config and a YAML layout file were explicitly specified, you'll need to re-run Zellij and point it to the new files:");
println!(
"\u{1b}[1;33mzellij --config {} --layout {}\u{1b}[m",
kdl_config_file_path
.as_path()
.as_os_str()
.to_string_lossy()
.to_string(),
kdl_explicitly_specified_layout
.as_path()
.as_os_str()
.to_string_lossy()
.to_string(),
);
} else {
println!("Since a YAML layout was explicitly specified, you'll need to re-run Zellij and point it to the new layout:");
println!(
"\u{1b}[1;33mzellij --layout {}\u{1b}[m",
kdl_explicitly_specified_layout
.as_path()
.as_os_str()
.to_string_lossy()
.to_string(),
);
}
},
None => {
if yaml_config_was_explicitly_set {
let mut kdl_config_file_path = yaml_config_file.clone();
kdl_config_file_path.set_extension("kdl");
println!("Since the YAML config was explicitly specified, you'll need to re-run Zellij and point it to the new config:");
println!(
"\u{1b}[1;33mzellij --config {}\u{1b}[m",
kdl_config_file_path
.as_path()
.as_os_str()
.to_string_lossy()
.to_string(),
);
}
},
}
println!("");
println!("\u{1b}[1;32mPress ENTER to continue.\u{1b}[m");
std::io::stdin()
.read_line(&mut String::new())
.map_err(|e| format!("Failed to read from STDIN: {:?}", e))?;
Ok(())
}
fn convert_layouts(layout_files_to_convert: Vec<(PathBuf, bool)>) -> Result<(), String> {
for (layout_file, _was_explicitly_set) in layout_files_to_convert {
let raw_layout_file = std::fs::read_to_string(&layout_file)
.map_err(|e| format!("Failed to read layout file {:?}: {:?}", layout_file, e))?;
let kdl_layout = layout_yaml_to_layout_kdl(&raw_layout_file)?;
let mut new_layout_file = layout_file.clone();
new_layout_file.set_extension("kdl");
std::fs::write(&new_layout_file, kdl_layout).map_err(|e| {
format!(
"Failed to write new layout file to {:?}: {:?}",
new_layout_file, e
)
})?;
}
Ok(())
}
fn convert_themes(theme_files_to_convert: Vec<PathBuf>) -> Result<(), String> {
for theme_file in theme_files_to_convert {
let raw_theme_file = std::fs::read_to_string(&theme_file)
.map_err(|e| format!("Failed to read theme file {:?}: {:?}", theme_file, e))?;
let kdl_theme = config_yaml_to_config_kdl(&raw_theme_file, true)?;
let mut new_theme_file = theme_file.clone();
new_theme_file.set_extension("kdl");
std::fs::write(&new_theme_file, kdl_theme).map_err(|e| {
format!(
"Failed to write new theme file to {:?}: {:?}",
new_theme_file, e
)
})?;
}
Ok(())
}
fn convert_config(yaml_config_file: PathBuf, new_config_file: PathBuf) -> Result<(), String> {
if yaml_config_file.exists() && !new_config_file.exists() {
let raw_config_file = std::fs::read_to_string(&yaml_config_file)
.map_err(|e| format!("Failed to read config file {:?}: {:?}", yaml_config_file, e))?;
let kdl_config = config_yaml_to_config_kdl(&raw_config_file, false)?;
std::fs::write(&new_config_file, kdl_config).map_err(|e| {
format!(
"Failed to write new config file to {:?}: {:?}",
new_config_file, e
)
})?;
}
Ok(())
}
fn convert_yaml(
yaml_config_file: PathBuf,
layout_files_to_convert: Vec<(PathBuf, bool)>,
theme_files_to_convert: Vec<PathBuf>,
yaml_config_was_explicitly_set: bool,
) -> Result<bool, String> {
let mut should_exit = false;
let mut new_config_file = yaml_config_file.clone();
new_config_file.set_extension("kdl");
let yaml_config_file_exists = yaml_config_file.exists();
let explicitly_set_layout_file = layout_files_to_convert
.iter()
.find(|(_l, was_explicitly_set)| *was_explicitly_set);
let layout_was_explicitly_set = explicitly_set_layout_file.is_some();
let explicitly_set_layout_files_kdl_equivalent_exists = explicitly_set_layout_file
.map(|(layout_file, _)| {
let mut layout_file = layout_file.clone();
layout_file.set_extension("kdl");
if layout_file.exists() {
Some(true)
} else {
None
}
})
.is_some();
let new_config_file_exists = new_config_file.exists();
let no_need_to_convert_config =
(new_config_file_exists && !yaml_config_was_explicitly_set) || !yaml_config_file_exists;
if no_need_to_convert_config
&& layout_files_to_convert.is_empty()
&& theme_files_to_convert.is_empty()
&& !layout_was_explicitly_set
{
// Nothing to do...
return Ok(should_exit);
}
print_conversion_title_message();
if yaml_config_file_exists && !new_config_file_exists {
print_converting_config_message(
yaml_config_file
.as_path()
.as_os_str()
.to_string_lossy()
.to_string(),
new_config_file
.as_path()
.as_os_str()
.to_string_lossy()
.to_string(),
);
} else if yaml_config_file_exists && new_config_file_exists && yaml_config_was_explicitly_set {
return Err(
format!(
"Specified old YAML format config (--config {}) but a new KDL file exists in that location. To fix, point to it the new file instead: zellij --config {}",
yaml_config_file.as_path().as_os_str().to_string_lossy().to_string(),
new_config_file.as_path().as_os_str().to_string_lossy().to_string()
)
);
} else if layout_was_explicitly_set && explicitly_set_layout_files_kdl_equivalent_exists {
let explicitly_set_layout_file = explicitly_set_layout_file.unwrap().0.clone();
let mut explicitly_set_layout_file_kdl_equivalent = explicitly_set_layout_file.clone();
explicitly_set_layout_file_kdl_equivalent.set_extension("kdl");
return Err(
format!(
"Specified old YAML format layout (--layout {}) but a new KDL file exists in that location. To fix, point to it the new file instead: zellij --layout {}",
explicitly_set_layout_file.display(),
explicitly_set_layout_file_kdl_equivalent.display()
)
);
}
if !layout_files_to_convert.is_empty() {
print_conversion_layouts_message(layout_files_to_convert.clone());
}
if !theme_files_to_convert.is_empty() {
print_conversion_themes_message(theme_files_to_convert.clone());
}
print_remain_unmodified_message(layout_was_explicitly_set || yaml_config_was_explicitly_set);
if layout_was_explicitly_set || yaml_config_was_explicitly_set {
print_flag_help_message(
layout_files_to_convert.clone(),
&yaml_config_file,
yaml_config_was_explicitly_set,
)?;
should_exit = true;
} else {
print_no_actions_and_wait_for_user_input()?;
}
convert_layouts(layout_files_to_convert)?;
convert_themes(theme_files_to_convert)?;
convert_config(yaml_config_file, new_config_file)?;
Ok(should_exit)
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/old_config_converter/old_config.rs | zellij-client/src/old_config_converter/old_config.rs | // This is a converter from the old yaml config to the new KDL config.
//
// It is supposed to be mostly self containing - please refrain from adding to it, importing
// from it or changing it
use std::fmt;
use std::path::PathBuf;
use serde::de::{Error, Visitor};
use serde::{Deserialize, Deserializer, Serialize};
use std::collections::HashMap;
use url::Url;
const ON_FORCE_CLOSE_DESCRIPTION: &'static str = "
// Choose what to do when zellij receives SIGTERM, SIGINT, SIGQUIT or SIGHUP
// eg. when terminal window with an active zellij session is closed
// Options:
// - detach (Default)
// - quit
//
";
const SIMPLIFIED_UI_DESCRIPTION: &'static str = "
// Send a request for a simplified ui (without arrow fonts) to plugins
// Options:
// - true
// - false (Default)
//
";
const DEFAULT_SHELL_DESCRIPTION: &'static str = "
// Choose the path to the default shell that zellij will use for opening new panes
// Default: $SHELL
//
";
const PANE_FRAMES_DESCRIPTION: &'static str = "
// Toggle between having pane frames around the panes
// Options:
// - true (default)
// - false
//
";
const DEFAULT_THEME_DESCRIPTION: &'static str = "
// Choose the theme that is specified in the themes section.
// Default: default
//
";
const DEFAULT_MODE_DESCRIPTION: &'static str = "
// Choose the mode that zellij uses when starting up.
// Default: normal
//
";
const MOUSE_MODE_DESCRIPTION: &'static str = "
// Toggle enabling the mouse mode.
// On certain configurations, or terminals this could
// potentially interfere with copying text.
// Options:
// - true (default)
// - false
//
";
const SCROLL_BUFFER_SIZE_DESCRIPTION: &'static str = "
// Configure the scroll back buffer size
// This is the number of lines zellij stores for each pane in the scroll back
// buffer. Excess number of lines are discarded in a FIFO fashion.
// Valid values: positive integers
// Default value: 10000
//
";
const COPY_COMMAND_DESCRIPTION: &'static str = "
// Provide a command to execute when copying text. The text will be piped to
// the stdin of the program to perform the copy. This can be used with
// terminal emulators which do not support the OSC 52 ANSI control sequence
// that will be used by default if this option is not set.
// Examples:
//
// copy_command \"xclip -selection clipboard\" // x11
// copy_command \"wl-copy\" // wayland
// copy_command \"pbcopy\" // osx
";
const COPY_CLIPBOARD_DESCRIPTION: &'static str = "
// Choose the destination for copied text
// Allows using the primary selection buffer (on x11/wayland) instead of the system clipboard.
// Does not apply when using copy_command.
// Options:
// - system (default)
// - primary
//
";
const COPY_ON_SELECT_DESCRIPTION: &'static str = "
// Enable or disable automatic copy (and clear) of selection when releasing mouse
// Default: true
//
";
const SCROLLBACK_EDITOR_DESCRIPTION: &'static str = "
// Path to the default editor to use to edit pane scrollbuffer
// Default: $EDITOR or $VISUAL
//
";
const MIRROR_SESSION_DESCRIPTION: &'static str = "
// When attaching to an existing session with other users,
// should the session be mirrored (true)
// or should each user have their own cursor (false)
// Default: false
//
";
const DEFAULT_LAYOUT_DESCRIPTION: &'static str = "
// The name of the default layout to load on startup
// Default: \"default\"
//
";
const LAYOUT_DIR_DESCRIPTION: &'static str = "
// The folder in which Zellij will look for layouts
//
";
const THEME_DIR_DESCRIPTION: &'static str = "
// The folder in which Zellij will look for themes
//
";
fn options_yaml_to_options_kdl(options_yaml: &OldOptions, no_comments: bool) -> String {
let mut options_kdl = String::new();
macro_rules! push_option {
($attribute_name:ident, $description_text:ident, $present_pattern:expr) => {
if !no_comments {
options_kdl.push_str($description_text);
}
if let Some($attribute_name) = &options_yaml.$attribute_name {
options_kdl.push_str(&format!($present_pattern, $attribute_name));
options_kdl.push('\n');
};
};
($attribute_name:ident, $description_text:ident, $present_pattern:expr, $absent_pattern:expr) => {
if !no_comments {
options_kdl.push_str($description_text);
}
match &options_yaml.$attribute_name {
Some($attribute_name) => {
options_kdl.push_str(&format!($present_pattern, $attribute_name));
},
None => {
if !no_comments {
options_kdl.push_str(&format!($absent_pattern));
}
},
};
if !no_comments || options_yaml.$attribute_name.is_some() {
options_kdl.push('\n');
}
};
}
push_option!(
on_force_close,
ON_FORCE_CLOSE_DESCRIPTION,
"on_force_close \"{}\"",
"// on_force_close \"quit\""
);
push_option!(
simplified_ui,
SIMPLIFIED_UI_DESCRIPTION,
"simplified_ui {}",
"// simplified_ui true"
);
push_option!(
default_shell,
DEFAULT_SHELL_DESCRIPTION,
"default_shell {:?}",
"// default_shell \"fish\""
);
push_option!(
pane_frames,
PANE_FRAMES_DESCRIPTION,
"pane_frames {}",
"// pane_frames true"
);
push_option!(
theme,
DEFAULT_THEME_DESCRIPTION,
"theme {:?} ",
"// theme \"default\""
);
push_option!(
default_layout,
DEFAULT_LAYOUT_DESCRIPTION,
"default_layout {:?}",
"// default_layout \"compact\""
);
push_option!(
default_mode,
DEFAULT_MODE_DESCRIPTION,
"default_mode \"{}\"",
"// default_mode \"locked\""
);
push_option!(
mouse_mode,
MOUSE_MODE_DESCRIPTION,
"mouse_mode {}",
"// mouse_mode false"
);
push_option!(
scroll_buffer_size,
SCROLL_BUFFER_SIZE_DESCRIPTION,
"scroll_buffer_size {}",
"// scroll_buffer_size 10000"
);
push_option!(copy_command, COPY_COMMAND_DESCRIPTION, "copy_command {:?}");
push_option!(
copy_clipboard,
COPY_CLIPBOARD_DESCRIPTION,
"copy_clipboard \"{}\"",
"// copy_clipboard \"primary\""
);
push_option!(
copy_on_select,
COPY_ON_SELECT_DESCRIPTION,
"copy_on_select {}",
"// copy_on_select false"
);
push_option!(
scrollback_editor,
SCROLLBACK_EDITOR_DESCRIPTION,
"scrollback_editor {:?}",
"// scrollback_editor \"/usr/bin/vim\""
);
push_option!(
mirror_session,
MIRROR_SESSION_DESCRIPTION,
"mirror_session {}",
"// mirror_session true"
);
push_option!(
layout_dir,
LAYOUT_DIR_DESCRIPTION,
"layout_dir {:?}",
"// layout_dir /path/to/my/layout_dir"
);
push_option!(
theme_dir,
THEME_DIR_DESCRIPTION,
"theme_dir {:?}",
"// theme_dir \"/path/to/my/theme_dir\""
);
options_kdl
}
fn env_yaml_to_env_kdl(env_yaml: &OldEnvironmentVariablesFromYaml) -> String {
let mut env_kdl = String::new();
let mut env_vars: Vec<(String, String)> = env_yaml
.env
.iter()
.map(|(name, val)| (name.clone(), val.clone()))
.collect();
env_vars.sort_unstable();
env_kdl.push_str("env {\n");
for (name, val) in env_vars {
env_kdl.push_str(&format!(" {} \"{}\"\n", name, val));
}
env_kdl.push_str("}\n");
env_kdl
}
fn plugins_yaml_to_plugins_kdl(plugins_yaml_to_plugins_kdl: &OldPluginsConfigFromYaml) -> String {
let mut plugins_kdl = String::new();
if !&plugins_yaml_to_plugins_kdl.0.is_empty() {
plugins_kdl.push_str("\n");
plugins_kdl.push_str("plugins {\n")
}
for plugin_config in &plugins_yaml_to_plugins_kdl.0 {
if plugin_config._allow_exec_host_cmd {
plugins_kdl.push_str(&format!(
" {} {{ path {:?}; _allow_exec_host_cmd true; }}\n",
plugin_config.tag.0, plugin_config.path
));
} else {
plugins_kdl.push_str(&format!(
" {} {{ path {:?}; }}\n",
plugin_config.tag.0, plugin_config.path
));
}
}
if !&plugins_yaml_to_plugins_kdl.0.is_empty() {
plugins_kdl.push_str("}\n")
}
plugins_kdl
}
fn ui_config_yaml_to_ui_config_kdl(ui_config_yaml: &OldUiConfigFromYaml) -> String {
let mut kdl_ui_config = String::new();
if ui_config_yaml.pane_frames.rounded_corners {
kdl_ui_config.push_str("\n");
kdl_ui_config.push_str("ui {\n");
kdl_ui_config.push_str(" pane_frames {\n");
kdl_ui_config.push_str(" rounded_corners true\n");
kdl_ui_config.push_str(" }\n");
kdl_ui_config.push_str("}\n");
} else {
// I'm not sure this is a thing, but since it's possible, why not?
kdl_ui_config.push_str("\n");
kdl_ui_config.push_str("ui {\n");
kdl_ui_config.push_str(" pane_frames {\n");
kdl_ui_config.push_str(" rounded_corners false\n");
kdl_ui_config.push_str(" }\n");
kdl_ui_config.push_str("}\n");
}
kdl_ui_config
}
fn theme_config_yaml_to_theme_config_kdl(
theme_config_yaml: &OldThemesFromYamlIntermediate,
) -> String {
macro_rules! theme_color {
($theme:ident, $color:ident, $color_name:expr, $kdl_theme_config:expr) => {
match $theme.palette.$color {
OldPaletteColorFromYaml::Rgb((r, g, b)) => {
$kdl_theme_config
.push_str(&format!(" {} {} {} {}\n", $color_name, r, g, b));
},
OldPaletteColorFromYaml::EightBit(eight_bit_color) => {
$kdl_theme_config
.push_str(&format!(" {} {}\n", $color_name, eight_bit_color));
},
OldPaletteColorFromYaml::Hex(OldHexColor(r, g, b)) => {
$kdl_theme_config
.push_str(&format!(" {} {} {} {}\n", $color_name, r, g, b));
},
}
};
}
let mut kdl_theme_config = String::new();
if !theme_config_yaml.0.is_empty() {
kdl_theme_config.push_str("themes {\n")
}
let mut themes: Vec<(String, OldTheme)> = theme_config_yaml
.0
.iter()
.map(|(theme_name, theme)| (theme_name.clone(), theme.clone()))
.collect();
themes.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
for (theme_name, theme) in themes {
kdl_theme_config.push_str(&format!(" {} {{\n", theme_name));
theme_color!(theme, fg, "fg", kdl_theme_config);
theme_color!(theme, bg, "bg", kdl_theme_config);
theme_color!(theme, black, "black", kdl_theme_config);
theme_color!(theme, red, "red", kdl_theme_config);
theme_color!(theme, green, "green", kdl_theme_config);
theme_color!(theme, yellow, "yellow", kdl_theme_config);
theme_color!(theme, blue, "blue", kdl_theme_config);
theme_color!(theme, magenta, "magenta", kdl_theme_config);
theme_color!(theme, cyan, "cyan", kdl_theme_config);
theme_color!(theme, white, "white", kdl_theme_config);
theme_color!(theme, orange, "orange", kdl_theme_config);
kdl_theme_config.push_str(" }\n");
}
if !theme_config_yaml.0.is_empty() {
kdl_theme_config.push_str("}\n")
}
kdl_theme_config
}
fn keybinds_yaml_to_keybinds_kdl(keybinds_yaml: &OldKeybindsFromYaml) -> String {
let mut kdl_keybinds = String::new();
let modes = vec![
// mode sort order
OldInputMode::Normal,
OldInputMode::Locked,
OldInputMode::Pane,
OldInputMode::Tab,
OldInputMode::Resize,
OldInputMode::Move,
OldInputMode::Scroll,
OldInputMode::Session,
OldInputMode::Search,
OldInputMode::EnterSearch,
OldInputMode::RenameTab,
OldInputMode::RenamePane,
OldInputMode::Prompt,
OldInputMode::Tmux,
];
// title and global unbinds / clear-defaults
match &keybinds_yaml.unbind {
OldUnbind::Keys(keys_to_unbind) => {
kdl_keybinds.push_str("keybinds {\n");
let key_string: String = keys_to_unbind
.iter()
.map(|k| format!("\"{}\"", k))
.collect::<Vec<String>>()
.join(" ");
kdl_keybinds.push_str(&format!(" unbind {}\n", key_string));
},
OldUnbind::All(should_unbind_all_defaults) => {
if *should_unbind_all_defaults {
kdl_keybinds.push_str("keybinds clear-defaults=true {\n");
} else {
kdl_keybinds.push_str("keybinds {\n");
}
},
}
for mode in modes {
if let Some(mode_keybinds) = keybinds_yaml.keybinds.get(&mode) {
let mut should_clear_mode_defaults = false;
let mut kdl_mode_keybinds = String::new();
for key_action_unbind in mode_keybinds {
match key_action_unbind {
OldKeyActionUnbind::KeyAction(key_action) => {
let keys = &key_action.key;
let actions = &key_action.action;
let key_string: String = keys
.iter()
.map(|k| {
if k == &OldKey::Char('\\') {
format!("r\"{}\"", k)
} else {
format!("\"{}\"", k)
}
})
.collect::<Vec<String>>()
.join(" ");
let actions_string: String = actions
.iter()
.map(|a| format!("{};", a))
.collect::<Vec<String>>()
.join(" ");
kdl_mode_keybinds.push_str(&format!(
" bind {} {{ {} }}\n",
key_string, actions_string
));
},
OldKeyActionUnbind::Unbind(unbind) => match &unbind.unbind {
OldUnbind::Keys(keys_to_unbind) => {
let key_string: String = keys_to_unbind
.iter()
.map(|k| format!("\"{}\"", k))
.collect::<Vec<String>>()
.join(" ");
kdl_mode_keybinds.push_str(&format!(" unbind {}\n", key_string));
},
OldUnbind::All(unbind_all) => {
if *unbind_all {
should_clear_mode_defaults = true;
}
},
},
}
}
if should_clear_mode_defaults {
kdl_keybinds.push_str(&format!(" {} clear-defaults=true {{\n", mode));
} else {
kdl_keybinds.push_str(&format!(" {} {{\n", mode));
}
kdl_keybinds.push_str(&kdl_mode_keybinds);
kdl_keybinds.push_str(" }\n");
}
}
kdl_keybinds.push_str("}\n");
kdl_keybinds
}
pub fn config_yaml_to_config_kdl(
raw_yaml_config: &str,
no_comments: bool,
) -> Result<String, String> {
// returns the raw kdl config
let config_from_yaml: OldConfigFromYaml = serde_yaml::from_str(raw_yaml_config)
.map_err(|e| format!("Failed to parse yaml: {:?}", e))?;
let mut kdl_config = String::new();
if let Some(old_config_keybinds) = config_from_yaml.keybinds.as_ref() {
kdl_config.push_str(&keybinds_yaml_to_keybinds_kdl(old_config_keybinds));
}
if let Some(old_config_options) = config_from_yaml.options.as_ref() {
kdl_config.push_str(&options_yaml_to_options_kdl(
old_config_options,
no_comments,
));
}
if let Some(old_config_env_variables) = config_from_yaml.env.as_ref() {
kdl_config.push_str(&env_yaml_to_env_kdl(old_config_env_variables));
}
kdl_config.push_str(&plugins_yaml_to_plugins_kdl(&config_from_yaml.plugins));
if let Some(old_ui_config) = config_from_yaml.ui.as_ref() {
kdl_config.push_str(&ui_config_yaml_to_ui_config_kdl(old_ui_config));
}
if let Some(old_themes_config) = config_from_yaml.themes.as_ref() {
kdl_config.push_str(&theme_config_yaml_to_theme_config_kdl(old_themes_config));
}
Ok(kdl_config)
}
#[derive(Clone, Default, Debug, Deserialize, Serialize, PartialEq)]
pub struct OldConfigFromYaml {
#[serde(flatten)]
pub options: Option<OldOptions>,
pub keybinds: Option<OldKeybindsFromYaml>,
pub themes: Option<OldThemesFromYamlIntermediate>,
#[serde(flatten)]
pub env: Option<OldEnvironmentVariablesFromYaml>,
#[serde(default)]
pub plugins: OldPluginsConfigFromYaml,
pub ui: Option<OldUiConfigFromYaml>,
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct OldKeybindsFromYaml {
#[serde(flatten)]
keybinds: HashMap<OldInputMode, Vec<OldKeyActionUnbind>>,
#[serde(default)]
unbind: OldUnbind,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[serde(untagged)]
enum OldUnbind {
// This is the correct order, don't rearrange!
// Suspected Bug in the untagged macro.
// 1. Keys
Keys(Vec<OldKey>),
// 2. All
All(bool),
}
impl Default for OldUnbind {
fn default() -> OldUnbind {
OldUnbind::All(false)
}
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
#[serde(untagged)]
enum OldKeyActionUnbind {
KeyAction(OldKeyActionFromYaml),
Unbind(OldUnbindFromYaml),
}
/// Intermediate struct used for deserialisation
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
struct OldKeyActionFromYaml {
action: Vec<OldAction>,
key: Vec<OldKey>,
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
struct OldUnbindFromYaml {
unbind: OldUnbind,
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct OldThemesFromYamlIntermediate(HashMap<String, OldTheme>);
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash, Default)]
struct OldPaletteFromYaml {
pub fg: OldPaletteColorFromYaml,
pub bg: OldPaletteColorFromYaml,
pub black: OldPaletteColorFromYaml,
pub red: OldPaletteColorFromYaml,
pub green: OldPaletteColorFromYaml,
pub yellow: OldPaletteColorFromYaml,
pub blue: OldPaletteColorFromYaml,
pub magenta: OldPaletteColorFromYaml,
pub cyan: OldPaletteColorFromYaml,
pub white: OldPaletteColorFromYaml,
pub orange: OldPaletteColorFromYaml,
}
/// Intermediate deserialization enum
// This is here in order to make the untagged enum work
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(untagged)]
enum OldPaletteColorFromYaml {
Rgb((u8, u8, u8)),
EightBit(u8),
Hex(OldHexColor),
}
impl From<OldHexColor> for (u8, u8, u8) {
fn from(e: OldHexColor) -> (u8, u8, u8) {
let OldHexColor(r, g, b) = e;
(r, g, b)
}
}
struct OldHexColorVisitor();
impl<'de> Visitor<'de> for OldHexColorVisitor {
type Value = OldHexColor;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "a hex color in the format #RGB or #RRGGBB")
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: Error,
{
if let Some(stripped) = s.strip_prefix('#') {
return self.visit_str(stripped);
}
if s.len() == 3 {
Ok(OldHexColor(
u8::from_str_radix(&s[0..1], 16).map_err(E::custom)? * 0x11,
u8::from_str_radix(&s[1..2], 16).map_err(E::custom)? * 0x11,
u8::from_str_radix(&s[2..3], 16).map_err(E::custom)? * 0x11,
))
} else if s.len() == 6 {
Ok(OldHexColor(
u8::from_str_radix(&s[0..2], 16).map_err(E::custom)?,
u8::from_str_radix(&s[2..4], 16).map_err(E::custom)?,
u8::from_str_radix(&s[4..6], 16).map_err(E::custom)?,
))
} else {
Err(Error::custom(
"Hex color must be of form \"#RGB\" or \"#RRGGBB\"",
))
}
}
}
impl<'de> Deserialize<'de> for OldHexColor {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_str(OldHexColorVisitor())
}
}
impl Default for OldPaletteColorFromYaml {
fn default() -> Self {
OldPaletteColorFromYaml::EightBit(0)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]
struct OldHexColor(u8, u8, u8);
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
struct OldTheme {
#[serde(flatten)]
palette: OldPaletteFromYaml,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Deserialize, Serialize)]
pub struct OldUiConfigFromYaml {
pub pane_frames: OldFrameConfigFromYaml,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Deserialize, Serialize)]
pub struct OldFrameConfigFromYaml {
pub rounded_corners: bool,
}
#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
pub struct OldEnvironmentVariablesFromYaml {
env: HashMap<String, String>,
}
#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
pub struct OldPluginsConfigFromYaml(Vec<OldPluginConfigFromYaml>);
#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
struct OldPluginConfigFromYaml {
pub path: PathBuf,
pub tag: OldPluginTag,
#[serde(default)]
pub run: OldPluginTypeFromYaml,
#[serde(default)]
pub config: serde_yaml::Value,
#[serde(default)]
pub _allow_exec_host_cmd: bool,
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
enum OldPluginTypeFromYaml {
Headless,
Pane,
}
impl Default for OldPluginTypeFromYaml {
fn default() -> Self {
Self::Pane
}
}
/// Tag used to identify the plugin in layout and config yaml files
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
struct OldPluginTag(String);
#[derive(Copy, Clone, Debug, PartialEq, Deserialize, Serialize)]
pub enum OldOnForceClose {
#[serde(alias = "quit")]
Quit,
#[serde(alias = "detach")]
Detach,
}
impl std::fmt::Display for OldOnForceClose {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
match self {
Self::Quit => write!(f, "quit"),
Self::Detach => write!(f, "detach"),
}
}
}
impl Default for OldOnForceClose {
fn default() -> Self {
Self::Detach
}
}
#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq)]
pub enum OldClipboard {
#[serde(alias = "system")]
System,
#[serde(alias = "primary")]
Primary,
}
impl std::fmt::Display for OldClipboard {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
match self {
Self::System => write!(f, "system"),
Self::Primary => write!(f, "primary"),
}
}
}
impl Default for OldClipboard {
fn default() -> Self {
Self::System
}
}
#[derive(Clone, Default, Debug, PartialEq, Deserialize, Serialize)]
pub struct OldOptions {
#[serde(default)]
pub simplified_ui: Option<bool>,
pub theme: Option<String>,
pub default_mode: Option<OldInputMode>,
pub default_shell: Option<PathBuf>,
pub default_layout: Option<PathBuf>,
pub layout_dir: Option<PathBuf>,
pub theme_dir: Option<PathBuf>,
#[serde(default)]
pub mouse_mode: Option<bool>,
#[serde(default)]
pub pane_frames: Option<bool>,
#[serde(default)]
pub mirror_session: Option<bool>,
pub on_force_close: Option<OldOnForceClose>,
pub scroll_buffer_size: Option<usize>,
#[serde(default)]
pub copy_command: Option<String>,
#[serde(default)]
pub copy_clipboard: Option<OldClipboard>,
#[serde(default)]
pub copy_on_select: Option<bool>,
pub scrollback_editor: Option<PathBuf>,
}
/// Describes the different input modes, which change the way that keystrokes will be interpreted.
#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone, Serialize, Deserialize)]
pub enum OldInputMode {
/// In `Normal` mode, input is always written to the terminal, except for the shortcuts leading
/// to other modes
#[serde(alias = "normal")]
Normal,
/// In `Locked` mode, input is always written to the terminal and all shortcuts are disabled
/// except the one leading back to normal mode
#[serde(alias = "locked")]
Locked,
/// `Resize` mode allows resizing the different existing panes.
#[serde(alias = "resize")]
Resize,
/// `Pane` mode allows creating and closing panes, as well as moving between them.
#[serde(alias = "pane")]
Pane,
/// `Tab` mode allows creating and closing tabs, as well as moving between them.
#[serde(alias = "tab")]
Tab,
/// `Scroll` mode allows scrolling up and down within a pane.
#[serde(alias = "scroll")]
Scroll,
/// `EnterSearch` mode allows for typing in the needle for a search in the scroll buffer of a pane.
#[serde(alias = "entersearch")]
EnterSearch,
/// `Search` mode allows for searching a term in a pane (superset of `Scroll`).
#[serde(alias = "search")]
Search,
/// `RenameTab` mode allows assigning a new name to a tab.
#[serde(alias = "renametab")]
RenameTab,
/// `RenamePane` mode allows assigning a new name to a pane.
#[serde(alias = "renamepane")]
RenamePane,
/// `Session` mode allows detaching sessions
#[serde(alias = "session")]
Session,
/// `Move` mode allows moving the different existing panes within a tab
#[serde(alias = "move")]
Move,
/// `Prompt` mode allows interacting with active prompts.
#[serde(alias = "prompt")]
Prompt,
/// `Tmux` mode allows for basic tmux keybindings functionality
#[serde(alias = "tmux")]
Tmux,
}
impl std::fmt::Display for OldInputMode {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
match self {
Self::Normal => write!(f, "normal"),
Self::Locked => write!(f, "locked"),
Self::Resize => write!(f, "resize"),
Self::Pane => write!(f, "pane"),
Self::Tab => write!(f, "tab"),
Self::Scroll => write!(f, "scroll"),
Self::EnterSearch => write!(f, "entersearch"),
Self::Search => write!(f, "search"),
Self::RenameTab => write!(f, "RenameTab"),
Self::RenamePane => write!(f, "RenamePane"),
Self::Session => write!(f, "session"),
Self::Move => write!(f, "move"),
Self::Prompt => write!(f, "prompt"),
Self::Tmux => write!(f, "tmux"),
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, PartialOrd, Ord)]
enum OldKey {
PageDown,
PageUp,
Left,
Down,
Up,
Right,
Home,
End,
Backspace,
Delete,
Insert,
F(u8),
Char(char),
Alt(OldCharOrArrow),
Ctrl(char),
BackTab,
Null,
Esc,
}
impl std::fmt::Display for OldKey {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
match self {
Self::PageDown => write!(f, "PageDown"),
Self::PageUp => write!(f, "PageUp"),
Self::Left => write!(f, "Left"),
Self::Down => write!(f, "Down"),
Self::Up => write!(f, "Up"),
Self::Right => write!(f, "Right"),
Self::Home => write!(f, "Home"),
Self::End => write!(f, "End"),
Self::Backspace => write!(f, "Backspace"),
Self::Delete => write!(f, "Delete"),
Self::Insert => write!(f, "Insert"),
Self::F(index) => write!(f, "F{}", index),
Self::Char(c) => match c {
'\n' => write!(f, "Enter"),
'\t' => write!(f, "Tab"),
'\"' => write!(f, "\\\""), // make sure it is escaped because otherwise it will be
// seen as a KDL string starter/terminator
' ' => write!(f, "Space"),
_ => write!(f, "{}", c),
},
Self::Alt(char_or_arrow) => match char_or_arrow {
OldCharOrArrow::Char(c) => write!(f, "Alt {}", c),
OldCharOrArrow::Direction(direction) => match direction {
OldDirection::Left => write!(f, "Alt Left"),
OldDirection::Right => write!(f, "Alt Right"),
OldDirection::Up => write!(f, "Alt Up"),
OldDirection::Down => write!(f, "Alt Down"),
},
},
Self::Ctrl(c) => write!(f, "Ctrl {}", c),
Self::BackTab => write!(f, "Tab"),
Self::Null => write!(f, "Null"),
Self::Esc => write!(f, "Esc"),
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, PartialOrd, Ord)]
#[serde(untagged)]
enum OldCharOrArrow {
Char(char),
Direction(OldDirection),
}
/// The four directions (left, right, up, down).
#[derive(Eq, Clone, Copy, Debug, PartialEq, Hash, Deserialize, Serialize, PartialOrd, Ord)]
enum OldDirection {
Left,
Right,
Up,
Down,
}
impl std::fmt::Display for OldDirection {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
match self {
Self::Left => write!(f, "Left"),
Self::Right => write!(f, "Right"),
Self::Up => write!(f, "Up"),
Self::Down => write!(f, "Down"),
}
}
}
impl Default for OldDirection {
fn default() -> Self {
OldDirection::Left
}
}
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
enum OldAction {
Quit,
Write(Vec<u8>),
WriteChars(String),
SwitchToMode(OldInputMode),
Resize(OldResizeDirection),
FocusNextPane,
FocusPreviousPane,
SwitchFocus,
MoveFocus(OldDirection),
MoveFocusOrTab(OldDirection),
MovePane(Option<OldDirection>),
DumpScreen(String),
EditScrollback,
ScrollUp,
ScrollUpAt(OldPosition),
ScrollDown,
ScrollDownAt(OldPosition),
ScrollToBottom,
PageScrollUp,
PageScrollDown,
HalfPageScrollUp,
HalfPageScrollDown,
ToggleFocusFullscreen,
TogglePaneFrames,
ToggleActiveSyncTab,
NewPane(Option<OldDirection>),
TogglePaneEmbedOrFloating,
ToggleFloatingPanes,
CloseFocus,
PaneNameInput(Vec<u8>),
UndoRenamePane,
NewTab(Option<OldTabLayout>),
NoOp,
GoToNextTab,
GoToPreviousTab,
CloseTab,
GoToTab(u32),
ToggleTab,
TabNameInput(Vec<u8>),
UndoRenameTab,
Run(OldRunCommandAction),
Detach,
LeftClick(OldPosition),
RightClick(OldPosition),
MiddleClick(OldPosition),
LeftMouseRelease(OldPosition),
RightMouseRelease(OldPosition),
MiddleMouseRelease(OldPosition),
MouseHoldLeft(OldPosition),
MouseHoldRight(OldPosition),
MouseHoldMiddle(OldPosition),
Copy,
Confirm,
Deny,
SkipConfirm(Box<OldAction>),
SearchInput(Vec<u8>),
Search(OldSearchDirection),
SearchToggleOption(OldSearchOption),
}
impl std::fmt::Display for OldAction {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
match self {
Self::Quit => write!(f, "Quit"),
Self::Write(bytes) => write!(
f,
"Write {}",
bytes
.iter()
.map(|c| format!("{}", *c))
.collect::<Vec<String>>()
.join(" ")
),
Self::WriteChars(chars) => write!(f, "WriteChars \"{}\"", chars),
Self::SwitchToMode(input_mode) => write!(f, "SwitchToMode \"{}\"", input_mode),
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/old_config_converter/mod.rs | zellij-client/src/old_config_converter/mod.rs | mod convert_old_yaml_files;
mod old_config;
mod old_layout;
pub use convert_old_yaml_files::convert_old_yaml_files;
pub use old_config::config_yaml_to_config_kdl;
pub use old_layout::layout_yaml_to_layout_kdl;
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/old_config_converter/unit/convert_layout_tests.rs | zellij-client/src/old_config_converter/unit/convert_layout_tests.rs | use crate::old_config_converter::layout_yaml_to_layout_kdl;
use insta::assert_snapshot;
use std::path::PathBuf;
use std::{fs::File, io::prelude::*};
#[test]
fn properly_convert_default_layout() -> Result<(), String> {
let fixture = PathBuf::from(format!(
"{}/src/old_config_converter/unit/fixtures/old_default_yaml_layout.yaml",
env!("CARGO_MANIFEST_DIR")
));
let mut handle = File::open(&fixture).map_err(|e| format!("{}", e))?;
let mut raw_config_file = String::new();
handle
.read_to_string(&mut raw_config_file)
.map_err(|e| format!("{}", e))?;
let kdl_config = layout_yaml_to_layout_kdl(&raw_config_file)?;
assert_snapshot!(format!("{}", kdl_config));
Ok(())
}
#[test]
fn properly_convert_layout_with_session_name() -> Result<(), String> {
let fixture = PathBuf::from(format!(
"{}/src/old_config_converter/unit/fixtures/old_yaml_layout_with_session_name.yaml",
env!("CARGO_MANIFEST_DIR")
));
let mut handle = File::open(&fixture).map_err(|e| format!("{}", e))?;
let mut raw_config_file = String::new();
handle
.read_to_string(&mut raw_config_file)
.map_err(|e| format!("{}", e))?;
let kdl_config = layout_yaml_to_layout_kdl(&raw_config_file)?;
assert_snapshot!(format!("{}", kdl_config));
Ok(())
}
#[test]
fn properly_convert_layout_with_session_name_and_attach_false() -> Result<(), String> {
let fixture = PathBuf::from(format!("{}/src/old_config_converter/unit/fixtures/old_yaml_layout_with_session_name_and_attach_false.yaml", env!("CARGO_MANIFEST_DIR")));
let mut handle = File::open(&fixture).map_err(|e| format!("{}", e))?;
let mut raw_config_file = String::new();
handle
.read_to_string(&mut raw_config_file)
.map_err(|e| format!("{}", e))?;
let kdl_config = layout_yaml_to_layout_kdl(&raw_config_file)?;
assert_snapshot!(format!("{}", kdl_config));
Ok(())
}
#[test]
fn properly_convert_layout_with_config() -> Result<(), String> {
let fixture = PathBuf::from(format!(
"{}/src/old_config_converter/unit/fixtures/old_yaml_layout_with_config.yaml",
env!("CARGO_MANIFEST_DIR")
));
let mut handle = File::open(&fixture).map_err(|e| format!("{}", e))?;
let mut raw_config_file = String::new();
handle
.read_to_string(&mut raw_config_file)
.map_err(|e| format!("{}", e))?;
let kdl_config = layout_yaml_to_layout_kdl(&raw_config_file)?;
assert_snapshot!(format!("{}", kdl_config));
Ok(())
}
#[test]
fn properly_convert_layout_with_config_and_session_name() -> Result<(), String> {
let fixture = PathBuf::from(format!("{}/src/old_config_converter/unit/fixtures/old_yaml_layout_with_config_and_session_name.yaml", env!("CARGO_MANIFEST_DIR")));
let mut handle = File::open(&fixture).map_err(|e| format!("{}", e))?;
let mut raw_config_file = String::new();
handle
.read_to_string(&mut raw_config_file)
.map_err(|e| format!("{}", e))?;
let kdl_config = layout_yaml_to_layout_kdl(&raw_config_file)?;
assert_snapshot!(format!("{}", kdl_config));
Ok(())
}
#[test]
fn properly_convert_layout_example_1() -> Result<(), String> {
let fixture = PathBuf::from(format!(
"{}/src/old_config_converter/unit/fixtures/multiple_tabs_layout.yaml",
env!("CARGO_MANIFEST_DIR")
));
let mut handle = File::open(&fixture).map_err(|e| format!("{}", e))?;
let mut raw_config_file = String::new();
handle
.read_to_string(&mut raw_config_file)
.map_err(|e| format!("{}", e))?;
let kdl_config = layout_yaml_to_layout_kdl(&raw_config_file)?;
assert_snapshot!(format!("{}", kdl_config));
Ok(())
}
#[test]
fn properly_convert_layout_example_2() -> Result<(), String> {
let fixture = PathBuf::from(format!(
"{}/src/old_config_converter/unit/fixtures/multiple_tabs_layout_htop_command.yaml",
env!("CARGO_MANIFEST_DIR")
));
let mut handle = File::open(&fixture).map_err(|e| format!("{}", e))?;
let mut raw_config_file = String::new();
handle
.read_to_string(&mut raw_config_file)
.map_err(|e| format!("{}", e))?;
let kdl_config = layout_yaml_to_layout_kdl(&raw_config_file)?;
assert_snapshot!(format!("{}", kdl_config));
Ok(())
}
#[test]
fn properly_convert_layout_example_3() -> Result<(), String> {
let fixture = PathBuf::from(format!(
"{}/src/old_config_converter/unit/fixtures/run_htop_layout.yaml",
env!("CARGO_MANIFEST_DIR")
));
let mut handle = File::open(&fixture).map_err(|e| format!("{}", e))?;
let mut raw_config_file = String::new();
handle
.read_to_string(&mut raw_config_file)
.map_err(|e| format!("{}", e))?;
let kdl_config = layout_yaml_to_layout_kdl(&raw_config_file)?;
assert_snapshot!(format!("{}", kdl_config));
Ok(())
}
#[test]
fn properly_convert_layout_example_4() -> Result<(), String> {
let fixture = PathBuf::from(format!(
"{}/src/old_config_converter/unit/fixtures/run_htop_layout_with_plugins.yaml",
env!("CARGO_MANIFEST_DIR")
));
let mut handle = File::open(&fixture).map_err(|e| format!("{}", e))?;
let mut raw_config_file = String::new();
handle
.read_to_string(&mut raw_config_file)
.map_err(|e| format!("{}", e))?;
let kdl_config = layout_yaml_to_layout_kdl(&raw_config_file)?;
assert_snapshot!(format!("{}", kdl_config));
Ok(())
}
#[test]
fn properly_convert_layout_with_command_quoted_args() -> Result<(), String> {
let fixture = PathBuf::from(format!(
"{}/src/old_config_converter/unit/fixtures/old_yaml_layout_with_quoted_args.yaml",
env!("CARGO_MANIFEST_DIR")
));
let mut handle = File::open(&fixture).map_err(|e| format!("{}", e))?;
let mut raw_config_file = String::new();
handle
.read_to_string(&mut raw_config_file)
.map_err(|e| format!("{}", e))?;
let kdl_config = layout_yaml_to_layout_kdl(&raw_config_file)?;
assert_snapshot!(format!("{}", kdl_config));
Ok(())
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/old_config_converter/unit/convert_config_tests.rs | zellij-client/src/old_config_converter/unit/convert_config_tests.rs | use crate::old_config_converter::config_yaml_to_config_kdl;
use insta::assert_snapshot;
use std::path::PathBuf;
use std::{fs::File, io::prelude::*};
#[test]
fn properly_convert_default_config() -> Result<(), String> {
let fixture = PathBuf::from(format!(
"{}/src/old_config_converter/unit/fixtures/old_default_yaml_config.yaml",
env!("CARGO_MANIFEST_DIR")
));
let mut handle = File::open(&fixture).map_err(|e| format!("{}", e))?;
let mut raw_config_file = String::new();
handle
.read_to_string(&mut raw_config_file)
.map_err(|e| format!("{}", e))?;
let kdl_config = config_yaml_to_config_kdl(&raw_config_file, false)?;
assert_snapshot!(format!("{}", kdl_config));
Ok(())
}
#[test]
fn convert_config_with_custom_options() -> Result<(), String> {
let fixture = PathBuf::from(format!(
"{}/src/old_config_converter/unit/fixtures/old_yaml_config_with_custom_options.yaml",
env!("CARGO_MANIFEST_DIR")
));
let mut handle = File::open(&fixture).map_err(|e| format!("{}", e))?;
let mut raw_config_file = String::new();
handle
.read_to_string(&mut raw_config_file)
.map_err(|e| format!("{}", e))?;
let kdl_config = config_yaml_to_config_kdl(&raw_config_file, false)?;
assert_snapshot!(format!("{}", kdl_config));
Ok(())
}
#[test]
fn convert_config_with_keybind_unbinds_in_mode() -> Result<(), String> {
let fixture = PathBuf::from(format!(
"{}/src/old_config_converter/unit/fixtures/old_yaml_config_with_unbinds_in_mode.yaml",
env!("CARGO_MANIFEST_DIR")
));
let mut handle = File::open(&fixture).map_err(|e| format!("{}", e))?;
let mut raw_config_file = String::new();
handle
.read_to_string(&mut raw_config_file)
.map_err(|e| format!("{}", e))?;
let kdl_config = config_yaml_to_config_kdl(&raw_config_file, false)?;
assert_snapshot!(format!("{}", kdl_config));
Ok(())
}
#[test]
fn convert_config_with_global_keybind_unbinds() -> Result<(), String> {
let fixture = PathBuf::from(format!("{}/src/old_config_converter/unit/fixtures/old_yaml_config_with_global_keybind_unbinds.yaml", env!("CARGO_MANIFEST_DIR")));
let mut handle = File::open(&fixture).map_err(|e| format!("{}", e))?;
let mut raw_config_file = String::new();
handle
.read_to_string(&mut raw_config_file)
.map_err(|e| format!("{}", e))?;
let kdl_config = config_yaml_to_config_kdl(&raw_config_file, false)?;
assert_snapshot!(format!("{}", kdl_config));
Ok(())
}
#[test]
fn convert_config_with_unbind_all_keys_per_mode() -> Result<(), String> {
let fixture = PathBuf::from(format!("{}/src/old_config_converter/unit/fixtures/old_yaml_config_with_unbind_all_keys_per_mode.yaml", env!("CARGO_MANIFEST_DIR")));
let mut handle = File::open(&fixture).map_err(|e| format!("{}", e))?;
let mut raw_config_file = String::new();
handle
.read_to_string(&mut raw_config_file)
.map_err(|e| format!("{}", e))?;
let kdl_config = config_yaml_to_config_kdl(&raw_config_file, false)?;
assert_snapshot!(format!("{}", kdl_config));
Ok(())
}
#[test]
fn convert_config_with_env_variables() -> Result<(), String> {
let fixture = PathBuf::from(format!(
"{}/src/old_config_converter/unit/fixtures/old_yaml_config_with_env_variables.yaml",
env!("CARGO_MANIFEST_DIR")
));
let mut handle = File::open(&fixture).map_err(|e| format!("{}", e))?;
let mut raw_config_file = String::new();
handle
.read_to_string(&mut raw_config_file)
.map_err(|e| format!("{}", e))?;
let kdl_config = config_yaml_to_config_kdl(&raw_config_file, false)?;
assert_snapshot!(format!("{}", kdl_config));
Ok(())
}
#[test]
fn convert_config_with_ui_config() -> Result<(), String> {
let fixture = PathBuf::from(format!(
"{}/src/old_config_converter/unit/fixtures/old_yaml_config_with_ui.yaml",
env!("CARGO_MANIFEST_DIR")
));
let mut handle = File::open(&fixture).map_err(|e| format!("{}", e))?;
let mut raw_config_file = String::new();
handle
.read_to_string(&mut raw_config_file)
.map_err(|e| format!("{}", e))?;
let kdl_config = config_yaml_to_config_kdl(&raw_config_file, false)?;
assert_snapshot!(format!("{}", kdl_config));
Ok(())
}
#[test]
fn convert_config_with_themes_config() -> Result<(), String> {
let fixture = PathBuf::from(format!(
"{}/src/old_config_converter/unit/fixtures/old_yaml_config_with_themes.yaml",
env!("CARGO_MANIFEST_DIR")
));
let mut handle = File::open(&fixture).map_err(|e| format!("{}", e))?;
let mut raw_config_file = String::new();
handle
.read_to_string(&mut raw_config_file)
.map_err(|e| format!("{}", e))?;
let kdl_config = config_yaml_to_config_kdl(&raw_config_file, false)?;
assert_snapshot!(format!("{}", kdl_config));
Ok(())
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/unit/terminal_loop_tests.rs | zellij-client/src/unit/terminal_loop_tests.rs | use crate::os_input_output::{AsyncSignals, AsyncStdin, ClientOsApi, SignalEvent};
use crate::remote_attach::WebSocketConnections;
use crate::run_remote_client_terminal_loop;
use crate::web_client::control_message::{
WebClientToWebServerControlMessage, WebClientToWebServerControlMessagePayload,
WebServerToWebClientControlMessage,
};
use async_trait::async_trait;
use futures_util::{SinkExt, StreamExt};
use serial_test::serial;
use std::io::{self, Write};
use std::os::unix::io::RawFd;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::sync::mpsc;
use tokio_tungstenite::connect_async;
use tokio_tungstenite::tungstenite::Message;
use zellij_utils::data::Palette;
use zellij_utils::errors::ErrorContext;
use zellij_utils::ipc::{ClientToServerMsg, ServerToClientMsg};
use zellij_utils::pane_size::Size;
/// Mock stdin that allows tests to inject input data
struct MockAsyncStdin {
rx: Arc<tokio::sync::Mutex<mpsc::UnboundedReceiver<Vec<u8>>>>,
}
#[async_trait]
impl AsyncStdin for MockAsyncStdin {
async fn read(&mut self) -> io::Result<Vec<u8>> {
match self.rx.lock().await.recv().await {
Some(data) => Ok(data),
None => Ok(Vec::new()), // EOF
}
}
}
/// Mock signal listener that allows tests to inject signals
struct MockAsyncSignals {
rx: Arc<tokio::sync::Mutex<mpsc::UnboundedReceiver<SignalEvent>>>,
}
#[async_trait]
impl AsyncSignals for MockAsyncSignals {
async fn recv(&mut self) -> Option<SignalEvent> {
self.rx.lock().await.recv().await
}
}
/// Mock ClientOsApi for testing
#[derive(Clone)]
struct TestClientOsApi {
stdout_buffer: Arc<Mutex<Vec<u8>>>,
stdin_rx: Arc<tokio::sync::Mutex<mpsc::UnboundedReceiver<Vec<u8>>>>,
signal_rx: Arc<tokio::sync::Mutex<mpsc::UnboundedReceiver<SignalEvent>>>,
terminal_size: Size,
}
impl TestClientOsApi {
fn new(
stdin_rx: mpsc::UnboundedReceiver<Vec<u8>>,
signal_rx: mpsc::UnboundedReceiver<SignalEvent>,
) -> Self {
Self {
stdout_buffer: Arc::new(Mutex::new(Vec::new())),
stdin_rx: Arc::new(tokio::sync::Mutex::new(stdin_rx)),
signal_rx: Arc::new(tokio::sync::Mutex::new(signal_rx)),
terminal_size: Size { rows: 24, cols: 80 },
}
}
}
impl std::fmt::Debug for TestClientOsApi {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TestClientOsApi").finish()
}
}
impl ClientOsApi for TestClientOsApi {
fn get_terminal_size_using_fd(&self, _fd: RawFd) -> Size {
self.terminal_size
}
fn set_raw_mode(&mut self, _fd: RawFd) {}
fn unset_raw_mode(&self, _fd: RawFd) -> Result<(), nix::Error> {
Ok(())
}
fn get_stdout_writer(&self) -> Box<dyn Write> {
Box::new(TestWriter {
buffer: self.stdout_buffer.clone(),
})
}
fn get_stdin_reader(&self) -> Box<dyn io::BufRead> {
Box::new(io::Cursor::new(Vec::new()))
}
fn update_session_name(&mut self, _new_session_name: String) {}
fn read_from_stdin(&mut self) -> Result<Vec<u8>, &'static str> {
Ok(Vec::new())
}
fn box_clone(&self) -> Box<dyn ClientOsApi> {
Box::new(self.clone())
}
fn send_to_server(&self, _msg: ClientToServerMsg) {}
fn recv_from_server(&self) -> Option<(ServerToClientMsg, ErrorContext)> {
None
}
fn handle_signals(&self, _sigwinch_cb: Box<dyn Fn()>, _quit_cb: Box<dyn Fn()>) {}
fn connect_to_server(&self, _path: &std::path::Path) {}
fn load_palette(&self) -> Palette {
Palette::default()
}
fn enable_mouse(&self) -> anyhow::Result<()> {
Ok(())
}
fn disable_mouse(&self) -> anyhow::Result<()> {
Ok(())
}
fn stdin_poller(&self) -> crate::os_input_output::StdinPoller {
crate::os_input_output::StdinPoller::default()
}
fn get_async_stdin_reader(&self) -> Box<dyn AsyncStdin> {
Box::new(MockAsyncStdin {
rx: self.stdin_rx.clone(),
})
}
fn get_async_signal_listener(&self) -> io::Result<Box<dyn AsyncSignals>> {
Ok(Box::new(MockAsyncSignals {
rx: self.signal_rx.clone(),
}))
}
}
struct TestWriter {
buffer: Arc<Mutex<Vec<u8>>>,
}
impl Write for TestWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.buffer.lock().unwrap().extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
mod mock_ws_server {
use super::*;
use axum::{
extract::{
ws::{WebSocket, WebSocketUpgrade},
State,
},
routing::get,
Router,
};
use tokio::net::TcpListener;
use tokio::task::JoinHandle;
#[derive(Clone)]
struct WsState {
client_tx: Arc<Mutex<mpsc::UnboundedSender<Message>>>,
server_rx: Arc<Mutex<mpsc::UnboundedReceiver<Message>>>,
}
pub struct MockWsServer {
pub terminal_to_client_tx: mpsc::UnboundedSender<Message>,
pub control_to_client_tx: mpsc::UnboundedSender<Message>,
pub client_to_terminal_rx: Arc<Mutex<mpsc::UnboundedReceiver<Message>>>,
pub client_to_control_rx: Arc<Mutex<mpsc::UnboundedReceiver<Message>>>,
}
impl MockWsServer {
pub async fn start() -> (u16, Self, JoinHandle<()>) {
let (terminal_to_client_tx, terminal_to_client_rx) = mpsc::unbounded_channel();
let (client_to_terminal_tx, client_to_terminal_rx) = mpsc::unbounded_channel();
let (control_to_client_tx, control_to_client_rx) = mpsc::unbounded_channel();
let (client_to_control_tx, client_to_control_rx) = mpsc::unbounded_channel();
let terminal_state = WsState {
client_tx: Arc::new(Mutex::new(client_to_terminal_tx)),
server_rx: Arc::new(Mutex::new(terminal_to_client_rx)),
};
let control_state = WsState {
client_tx: Arc::new(Mutex::new(client_to_control_tx)),
server_rx: Arc::new(Mutex::new(control_to_client_rx)),
};
let app = Router::new()
.route(
"/ws/terminal",
get(terminal_handler).with_state(terminal_state.clone()),
)
.route(
"/ws/control",
get(control_handler).with_state(control_state.clone()),
);
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let server_handle = tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
// Wait for server to start
tokio::time::sleep(Duration::from_millis(100)).await;
let server = MockWsServer {
terminal_to_client_tx,
control_to_client_tx,
client_to_terminal_rx: Arc::new(Mutex::new(client_to_terminal_rx)),
client_to_control_rx: Arc::new(Mutex::new(client_to_control_rx)),
};
(port, server, server_handle)
}
}
async fn terminal_handler(
ws: WebSocketUpgrade,
State(state): State<WsState>,
) -> impl axum::response::IntoResponse {
ws.on_upgrade(move |socket| handle_websocket(socket, state))
}
async fn control_handler(
ws: WebSocketUpgrade,
State(state): State<WsState>,
) -> impl axum::response::IntoResponse {
ws.on_upgrade(move |socket| handle_websocket(socket, state))
}
async fn handle_websocket(socket: WebSocket, state: WsState) {
let (mut ws_tx, mut ws_rx) = socket.split();
let client_tx = state.client_tx.clone();
let recv_task = tokio::spawn(async move {
while let Some(Ok(axum_msg)) = ws_rx.next().await {
// Convert axum::extract::ws::Message to tokio_tungstenite::tungstenite::Message
let tungstenite_msg = match axum_msg {
axum::extract::ws::Message::Text(text) => Message::Text(text.to_string()),
axum::extract::ws::Message::Binary(data) => Message::Binary(data.to_vec()),
axum::extract::ws::Message::Ping(data) => Message::Ping(data.to_vec()),
axum::extract::ws::Message::Pong(data) => Message::Pong(data.to_vec()),
axum::extract::ws::Message::Close(frame) => {
if let Some(f) = frame {
Message::Close(Some(tokio_tungstenite::tungstenite::protocol::CloseFrame {
code: tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode::from(f.code),
reason: std::borrow::Cow::Owned(f.reason.to_string()),
}))
} else {
Message::Close(None)
}
},
};
let _ = client_tx.lock().unwrap().send(tungstenite_msg);
}
});
loop {
let msg = state.server_rx.lock().unwrap().try_recv();
match msg {
Ok(tungstenite_msg) => {
// Convert tokio_tungstenite::tungstenite::Message to axum::extract::ws::Message
let axum_msg = match tungstenite_msg {
Message::Text(text) => axum::extract::ws::Message::Text(text.into()),
Message::Binary(data) => axum::extract::ws::Message::Binary(data.into()),
Message::Ping(data) => axum::extract::ws::Message::Ping(data.into()),
Message::Pong(data) => axum::extract::ws::Message::Pong(data.into()),
Message::Close(frame) => {
if let Some(f) = frame {
axum::extract::ws::Message::Close(Some(
axum::extract::ws::CloseFrame {
code: f.code.into(),
reason: f.reason.to_string().into(),
},
))
} else {
axum::extract::ws::Message::Close(None)
}
},
Message::Frame(_) => continue, // Skip raw frames
};
if ws_tx.send(axum_msg).await.is_err() {
break;
}
},
Err(_) => {
tokio::time::sleep(Duration::from_millis(10)).await;
},
}
}
recv_task.abort();
}
}
#[tokio::test]
#[serial]
async fn test_stdin_forwarded_to_terminal_websocket() {
// Setup mock WebSocket server
let (port, server, _server_handle) = mock_ws_server::MockWsServer::start().await;
// Create WebSocket connections
let terminal_url = format!("ws://127.0.0.1:{}/ws/terminal", port);
let control_url = format!("ws://127.0.0.1:{}/ws/control", port);
let (terminal_ws, _) = connect_async(&terminal_url).await.unwrap();
let (control_ws, _) = connect_async(&control_url).await.unwrap();
let connections = WebSocketConnections {
terminal_ws,
control_ws,
web_client_id: "test-stdin".to_string(),
};
// Create mock OS API with controllable stdin
let (stdin_tx, stdin_rx) = mpsc::unbounded_channel();
let (_signal_tx, signal_rx) = mpsc::unbounded_channel();
let os_input = Box::new(TestClientOsApi::new(stdin_rx, signal_rx));
// Spawn the async loop
let loop_handle =
tokio::spawn(async move { run_remote_client_terminal_loop(os_input, connections).await });
// Send stdin data
let test_data = b"hello from stdin\n".to_vec();
stdin_tx.send(test_data.clone()).unwrap();
// Verify terminal WebSocket received the data
tokio::time::sleep(Duration::from_millis(200)).await;
let received = tokio::time::timeout(
Duration::from_secs(1),
server.client_to_terminal_rx.lock().unwrap().recv(),
)
.await
.expect("Timeout")
.expect("No message");
match received {
Message::Binary(data) => assert_eq!(data, test_data),
_ => panic!("Expected Binary message, got: {:?}", received),
}
// Cleanup: send EOF via stdin
drop(stdin_tx);
let _ = tokio::time::timeout(Duration::from_secs(2), loop_handle)
.await
.expect("Loop didn't exit")
.unwrap();
}
#[tokio::test]
#[serial]
async fn test_terminal_output_written_to_stdout() {
let (port, server, _server_handle) = mock_ws_server::MockWsServer::start().await;
let terminal_url = format!("ws://127.0.0.1:{}/ws/terminal", port);
let control_url = format!("ws://127.0.0.1:{}/ws/control", port);
let (terminal_ws, _) = connect_async(&terminal_url).await.unwrap();
let (control_ws, _) = connect_async(&control_url).await.unwrap();
let connections = WebSocketConnections {
terminal_ws,
control_ws,
web_client_id: "test-stdout".to_string(),
};
let (_stdin_tx, stdin_rx) = mpsc::unbounded_channel();
let (_signal_tx, signal_rx) = mpsc::unbounded_channel();
let os_input = TestClientOsApi::new(stdin_rx, signal_rx);
let stdout_buffer = os_input.stdout_buffer.clone();
let os_input = Box::new(os_input);
let loop_handle =
tokio::spawn(async move { run_remote_client_terminal_loop(os_input, connections).await });
// Send terminal output from server
let test_output = "Hello from terminal";
server
.terminal_to_client_tx
.send(Message::Text(test_output.to_string()))
.unwrap();
tokio::time::sleep(Duration::from_millis(200)).await;
// Verify stdout received the output
let stdout = stdout_buffer.lock().unwrap().clone();
let stdout_str = String::from_utf8_lossy(&stdout);
assert!(
stdout_str.contains(test_output),
"Expected stdout to contain '{}', got: '{}'",
test_output,
stdout_str
);
// Cleanup
server
.terminal_to_client_tx
.send(Message::Close(None))
.unwrap();
let _ = tokio::time::timeout(Duration::from_secs(2), loop_handle)
.await
.expect("Loop didn't exit")
.unwrap();
}
#[tokio::test]
#[serial]
async fn test_resize_signal_sends_control_message() {
let (port, server, _server_handle) = mock_ws_server::MockWsServer::start().await;
let terminal_url = format!("ws://127.0.0.1:{}/ws/terminal", port);
let control_url = format!("ws://127.0.0.1:{}/ws/control", port);
let (terminal_ws, _) = connect_async(&terminal_url).await.unwrap();
let (control_ws, _) = connect_async(&control_url).await.unwrap();
let connections = WebSocketConnections {
terminal_ws,
control_ws,
web_client_id: "test-resize".to_string(),
};
let (_stdin_tx, stdin_rx) = mpsc::unbounded_channel();
let (signal_tx, signal_rx) = mpsc::unbounded_channel();
let os_input = Box::new(TestClientOsApi::new(stdin_rx, signal_rx));
let loop_handle =
tokio::spawn(async move { run_remote_client_terminal_loop(os_input, connections).await });
// Wait for initial resize message to be sent on startup
tokio::time::sleep(Duration::from_millis(200)).await;
// Consume the initial resize message
let _ = tokio::time::timeout(
Duration::from_millis(500),
server.client_to_control_rx.lock().unwrap().recv(),
)
.await;
// Send resize signal
signal_tx.send(SignalEvent::Resize).unwrap();
tokio::time::sleep(Duration::from_millis(200)).await;
// Verify control WebSocket received resize message
let received = tokio::time::timeout(
Duration::from_secs(1),
server.client_to_control_rx.lock().unwrap().recv(),
)
.await
.expect("Timeout")
.expect("No message");
match received {
Message::Text(text) => {
let parsed: WebClientToWebServerControlMessage =
serde_json::from_str(&text).expect("Failed to parse");
assert!(
matches!(
parsed.payload,
WebClientToWebServerControlMessagePayload::TerminalResize(_)
),
"Expected TerminalResize, got: {:?}",
parsed.payload
);
},
_ => panic!("Expected Text message, got: {:?}", received),
}
// Cleanup
signal_tx.send(SignalEvent::Quit).unwrap();
let _ = tokio::time::timeout(Duration::from_secs(2), loop_handle)
.await
.expect("Loop didn't exit")
.unwrap();
}
#[tokio::test]
#[serial]
async fn test_quit_signal_exits_loop() {
let (port, _server, _server_handle) = mock_ws_server::MockWsServer::start().await;
let terminal_url = format!("ws://127.0.0.1:{}/ws/terminal", port);
let control_url = format!("ws://127.0.0.1:{}/ws/control", port);
let (terminal_ws, _) = connect_async(&terminal_url).await.unwrap();
let (control_ws, _) = connect_async(&control_url).await.unwrap();
let connections = WebSocketConnections {
terminal_ws,
control_ws,
web_client_id: "test-quit".to_string(),
};
let (_stdin_tx, stdin_rx) = mpsc::unbounded_channel();
let (signal_tx, signal_rx) = mpsc::unbounded_channel();
let os_input = Box::new(TestClientOsApi::new(stdin_rx, signal_rx));
let loop_handle =
tokio::spawn(async move { run_remote_client_terminal_loop(os_input, connections).await });
// Send quit signal
signal_tx.send(SignalEvent::Quit).unwrap();
// Verify loop exits cleanly
let result = tokio::time::timeout(Duration::from_secs(2), loop_handle)
.await
.expect("Loop didn't exit within timeout")
.expect("Loop panicked");
assert!(result.is_ok(), "Expected Ok result, got: {:?}", result);
}
#[tokio::test]
#[serial]
async fn test_websocket_close_exits_loop() {
let (port, server, _server_handle) = mock_ws_server::MockWsServer::start().await;
let terminal_url = format!("ws://127.0.0.1:{}/ws/terminal", port);
let control_url = format!("ws://127.0.0.1:{}/ws/control", port);
let (terminal_ws, _) = connect_async(&terminal_url).await.unwrap();
let (control_ws, _) = connect_async(&control_url).await.unwrap();
let connections = WebSocketConnections {
terminal_ws,
control_ws,
web_client_id: "test-close".to_string(),
};
let (_stdin_tx, stdin_rx) = mpsc::unbounded_channel();
let (_signal_tx, signal_rx) = mpsc::unbounded_channel();
let os_input = Box::new(TestClientOsApi::new(stdin_rx, signal_rx));
let loop_handle =
tokio::spawn(async move { run_remote_client_terminal_loop(os_input, connections).await });
// Send close message
server
.terminal_to_client_tx
.send(Message::Close(None))
.unwrap();
// Verify loop exits cleanly
let result = tokio::time::timeout(Duration::from_secs(2), loop_handle)
.await
.expect("Loop didn't exit within timeout")
.expect("Loop panicked");
assert!(result.is_ok(), "Expected Ok result, got: {:?}", result);
}
#[tokio::test]
#[serial]
async fn test_control_message_handling() {
let (port, server, _server_handle) = mock_ws_server::MockWsServer::start().await;
let terminal_url = format!("ws://127.0.0.1:{}/ws/terminal", port);
let control_url = format!("ws://127.0.0.1:{}/ws/control", port);
let (terminal_ws, _) = connect_async(&terminal_url).await.unwrap();
let (control_ws, _) = connect_async(&control_url).await.unwrap();
let connections = WebSocketConnections {
terminal_ws,
control_ws,
web_client_id: "test-control".to_string(),
};
let (_stdin_tx, stdin_rx) = mpsc::unbounded_channel();
let (_signal_tx, signal_rx) = mpsc::unbounded_channel();
let os_input = TestClientOsApi::new(stdin_rx, signal_rx);
let terminal_size = os_input.terminal_size;
let os_input = Box::new(os_input);
let loop_handle =
tokio::spawn(async move { run_remote_client_terminal_loop(os_input, connections).await });
// Wait for initial resize message to be sent on startup
tokio::time::sleep(Duration::from_millis(200)).await;
// Consume the initial resize message
let _ = tokio::time::timeout(
Duration::from_millis(500),
server.client_to_control_rx.lock().unwrap().recv(),
)
.await;
// Send QueryTerminalSize control message
let query_msg = WebServerToWebClientControlMessage::QueryTerminalSize;
server
.control_to_client_tx
.send(Message::Text(serde_json::to_string(&query_msg).unwrap()))
.unwrap();
tokio::time::sleep(Duration::from_millis(200)).await;
// Verify we receive a resize response
let received = tokio::time::timeout(
Duration::from_secs(1),
server.client_to_control_rx.lock().unwrap().recv(),
)
.await
.expect("Timeout")
.expect("No message");
match received {
Message::Text(text) => {
let parsed: WebClientToWebServerControlMessage =
serde_json::from_str(&text).expect("Failed to parse");
let WebClientToWebServerControlMessagePayload::TerminalResize(size) = parsed.payload;
assert_eq!(size, terminal_size);
},
_ => panic!("Expected Text message, got: {:?}", received),
}
// Test Log message (should not crash)
let log_msg = WebServerToWebClientControlMessage::Log {
lines: vec!["Test log".to_string()],
};
server
.control_to_client_tx
.send(Message::Text(serde_json::to_string(&log_msg).unwrap()))
.unwrap();
tokio::time::sleep(Duration::from_millis(100)).await;
// Cleanup
server
.terminal_to_client_tx
.send(Message::Close(None))
.unwrap();
let _ = tokio::time::timeout(Duration::from_secs(2), loop_handle)
.await
.expect("Loop didn't exit")
.unwrap();
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/unit/mod.rs | zellij-client/src/unit/mod.rs | #[cfg(test)]
#[cfg(feature = "web_server_capability")]
mod terminal_loop_tests;
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/remote_attach/config.rs | zellij-client/src/remote_attach/config.rs | use std::time::Duration;
// API endpoints
pub const LOGIN_ENDPOINT: &str = "/command/login";
pub const SESSION_ENDPOINT: &str = "/session";
pub const WS_TERMINAL_ENDPOINT: &str = "/ws/terminal";
pub const WS_CONTROL_ENDPOINT: &str = "/ws/control";
// Connection settings
pub const CONNECTION_TIMEOUT_SECS: u64 = 30;
pub fn connection_timeout() -> Duration {
Duration::from_secs(CONNECTION_TIMEOUT_SECS)
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/remote_attach/http_client.rs | zellij-client/src/remote_attach/http_client.rs | use super::config::connection_timeout;
use isahc::prelude::*;
use isahc::{config::RedirectPolicy, AsyncBody, HttpClient, Request, Response};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
pub fn create_http_client() -> Result<HttpClient, isahc::Error> {
HttpClient::builder()
.redirect_policy(RedirectPolicy::Follow)
.ssl_options(isahc::config::SslOption::DANGER_ACCEPT_INVALID_CERTS)
.timeout(connection_timeout())
.build()
}
pub struct HttpClientWithCookies {
client: HttpClient,
cookies: Arc<Mutex<HashMap<String, String>>>,
}
impl HttpClientWithCookies {
pub fn new() -> Result<Self, isahc::Error> {
Ok(Self {
client: create_http_client()?,
cookies: Arc::new(Mutex::new(HashMap::new())),
})
}
pub async fn send_with_cookies<T: Into<Request<Vec<u8>>>>(
&self,
request: T,
) -> Result<Response<AsyncBody>, isahc::Error> {
let mut req = request.into();
// Add cookies to request
if let Ok(cookies) = self.cookies.lock() {
if !cookies.is_empty() {
let cookie_header = cookies
.iter()
.map(|(k, v)| format!("{}={}", k, v))
.collect::<Vec<_>>()
.join("; ");
req.headers_mut()
.insert("cookie", cookie_header.parse().unwrap());
}
}
let response = self.client.send_async(req).await?;
// Extract and store cookies from response
if let Some(set_cookie_headers) = response.headers().get_all("set-cookie").iter().next() {
if let Ok(cookie_str) = set_cookie_headers.to_str() {
self.parse_and_store_cookies(cookie_str);
}
}
Ok(response)
}
fn parse_and_store_cookies(&self, cookie_header: &str) {
if let Ok(mut cookies) = self.cookies.lock() {
// Simple cookie parsing - just extract name=value pairs
for cookie_part in cookie_header.split(';') {
let cookie_part = cookie_part.trim();
if let Some((name, value)) = cookie_part.split_once('=') {
// Skip cookie attributes like Path, Domain, HttpOnly, etc.
if ![
"path", "domain", "httponly", "secure", "samesite", "expires", "max-age",
]
.contains(&name.to_lowercase().as_str())
{
cookies.insert(name.trim().to_string(), value.trim().to_string());
}
}
}
}
}
pub fn get_cookie_header(&self) -> Option<String> {
if let Ok(cookies) = self.cookies.lock() {
if !cookies.is_empty() {
let cookie_header = cookies
.iter()
.map(|(k, v)| format!("{}={}", k, v))
.collect::<Vec<_>>()
.join("; ");
return Some(cookie_header);
}
}
None
}
/// Extract a specific cookie value
pub fn get_cookie(&self, name: &str) -> Option<String> {
if let Ok(cookies) = self.cookies.lock() {
return cookies.get(name).cloned();
}
None
}
/// Pre-populate a cookie (for saved session tokens)
pub fn set_cookie(&self, name: String, value: String) {
if let Ok(mut cookies) = self.cookies.lock() {
cookies.insert(name, value);
}
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/remote_attach/websockets.rs | zellij-client/src/remote_attach/websockets.rs | use super::config::{WS_CONTROL_ENDPOINT, WS_TERMINAL_ENDPOINT};
use super::http_client::HttpClientWithCookies;
use tokio::net::TcpStream;
use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream};
pub struct WebSocketConnections {
pub terminal_ws: WebSocketStream<MaybeTlsStream<TcpStream>>,
pub control_ws: WebSocketStream<MaybeTlsStream<TcpStream>>,
pub web_client_id: String,
}
impl std::fmt::Debug for WebSocketConnections {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WebSocketConnections")
.field("web_client_id", &self.web_client_id)
.finish()
}
}
pub async fn establish_websocket_connections(
web_client_id: &str,
http_client: &HttpClientWithCookies,
server_base_url: &str,
session_name: &str,
) -> Result<WebSocketConnections, Box<dyn std::error::Error>> {
let ws_protocol = if server_base_url.starts_with("https") {
"wss"
} else {
"ws"
};
let base_host = server_base_url
.replace("https://", "")
.replace("http://", "");
let terminal_url = if session_name.is_empty() {
format!(
"{}://{}{WS_TERMINAL_ENDPOINT}?web_client_id={}",
ws_protocol,
base_host,
urlencoding::encode(web_client_id)
)
} else {
format!(
"{}://{}{WS_TERMINAL_ENDPOINT}/{}?web_client_id={}",
ws_protocol,
base_host,
urlencoding::encode(session_name),
urlencoding::encode(web_client_id)
)
};
let control_url = format!("{}://{}{WS_CONTROL_ENDPOINT}", ws_protocol, base_host);
log::info!("Connecting to terminal WebSocket: {}", terminal_url);
log::info!("Connecting to control WebSocket: {}", control_url);
// Create WebSocket request with cookies
let mut terminal_request = tokio_tungstenite::tungstenite::http::Request::builder()
.uri(&terminal_url)
.header("Host", &base_host)
.header("Upgrade", "websocket")
.header("Connection", "Upgrade")
.header(
"Sec-WebSocket-Key",
tokio_tungstenite::tungstenite::handshake::client::generate_key(),
)
.header("Sec-WebSocket-Version", "13");
let mut control_request = tokio_tungstenite::tungstenite::http::Request::builder()
.uri(&control_url)
.header("Host", &base_host)
.header("Upgrade", "websocket")
.header("Connection", "Upgrade")
.header(
"Sec-WebSocket-Key",
tokio_tungstenite::tungstenite::handshake::client::generate_key(),
)
.header("Sec-WebSocket-Version", "13");
// Add cookies if available
if let Some(cookie_header) = http_client.get_cookie_header() {
terminal_request = terminal_request.header("Cookie", &cookie_header);
control_request = control_request.header("Cookie", &cookie_header);
}
let terminal_request = terminal_request.body(())?;
let control_request = control_request.body(())?;
// Connect to both WebSockets concurrently
// tokio-tungstenite handles TLS automatically for wss:// URLs
let (terminal_ws, _) = connect_async(terminal_request).await?;
let (control_ws, _) = connect_async(control_request).await?;
Ok(WebSocketConnections {
terminal_ws,
control_ws,
web_client_id: web_client_id.to_owned(),
})
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/remote_attach/auth.rs | zellij-client/src/remote_attach/auth.rs | use super::config::{LOGIN_ENDPOINT, SESSION_ENDPOINT};
use super::http_client::HttpClientWithCookies;
use crate::RemoteClientError;
use isahc::{AsyncReadResponseExt, Request};
use serde::{Deserialize, Serialize};
#[derive(Serialize)]
struct LoginRequest {
auth_token: String,
remember_me: bool,
}
#[derive(Deserialize)]
pub struct SessionResponse {
pub web_client_id: String,
}
pub async fn authenticate(
server_base_url: &str,
auth_token: &str,
remember_me: bool,
) -> Result<(String, HttpClientWithCookies, Option<String>), RemoteClientError> {
let http_client =
HttpClientWithCookies::new().map_err(|e| RemoteClientError::Other(Box::new(e)))?;
// Step 1: Login with auth token
let login_url = format!("{}{}", server_base_url, LOGIN_ENDPOINT);
let login_request = LoginRequest {
auth_token: auth_token.to_string(),
remember_me,
};
let response = http_client
.send_with_cookies(
Request::post(login_url)
.header("Content-Type", "application/json")
.header("User-Agent", "http-terminal-client/1.0")
.header("Accept", "application/json")
.body(
serde_json::to_vec(&login_request)
.map_err(|e| RemoteClientError::Other(Box::new(e)))?,
)
.map_err(|e| RemoteClientError::Other(Box::new(e)))?,
)
.await
.map_err(|e| RemoteClientError::ConnectionFailed(e.to_string()))?;
// Handle HTTP status codes
match response.status().as_u16() {
401 => return Err(RemoteClientError::InvalidAuthToken),
status if !response.status().is_success() => {
return Err(RemoteClientError::ConnectionFailed(format!(
"Server returned status {}",
status
)));
},
_ => {},
}
// Step 2: Get session/client ID
let session_url = format!("{}{}", server_base_url, SESSION_ENDPOINT);
let mut session_response = http_client
.send_with_cookies(
Request::post(session_url)
.header("Content-Type", "application/json")
.header("User-Agent", "http-terminal-client/1.0")
.header("Accept", "application/json")
.body("{}".as_bytes().to_vec())
.map_err(|e| RemoteClientError::Other(Box::new(e)))?,
)
.await
.map_err(|e| RemoteClientError::ConnectionFailed(e.to_string()))?;
// Handle session response
match session_response.status().as_u16() {
401 => return Err(RemoteClientError::Unauthorized),
status if !session_response.status().is_success() => {
return Err(RemoteClientError::ConnectionFailed(format!(
"Server returned status {}",
status
)));
},
_ => {},
}
let response_body = session_response
.text()
.await
.map_err(|e| RemoteClientError::Other(Box::new(e)))?;
let session_data: SessionResponse =
serde_json::from_str(&response_body).map_err(|e| RemoteClientError::Other(Box::new(e)))?;
// Extract session_token if remember_me was true
let session_token = if remember_me {
http_client.get_cookie("session_token")
} else {
None
};
Ok((session_data.web_client_id, http_client, session_token))
}
pub async fn validate_session_token(
server_base_url: &str,
session_token: &str,
) -> Result<(String, HttpClientWithCookies), RemoteClientError> {
let http_client =
HttpClientWithCookies::new().map_err(|e| RemoteClientError::Other(Box::new(e)))?;
// Pre-populate the session_token cookie
http_client.set_cookie("session_token".to_string(), session_token.to_string());
// Skip /login, go directly to /session endpoint
let session_url = format!("{}{}", server_base_url, SESSION_ENDPOINT);
let mut session_response = http_client
.send_with_cookies(
Request::post(session_url)
.header("Content-Type", "application/json")
.header("User-Agent", "http-terminal-client/1.0")
.header("Accept", "application/json")
.body("{}".as_bytes().to_vec())
.map_err(|e| RemoteClientError::Other(Box::new(e)))?,
)
.await
.map_err(|e| RemoteClientError::ConnectionFailed(e.to_string()))?;
match session_response.status().as_u16() {
401 => Err(RemoteClientError::SessionTokenExpired),
status if !session_response.status().is_success() => Err(
RemoteClientError::ConnectionFailed(format!("Server returned status {}", status)),
),
_ => {
let response_body = session_response
.text()
.await
.map_err(|e| RemoteClientError::Other(Box::new(e)))?;
let session_data: SessionResponse = serde_json::from_str(&response_body)
.map_err(|e| RemoteClientError::Other(Box::new(e)))?;
Ok((session_data.web_client_id, http_client))
},
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/remote_attach/mod.rs | zellij-client/src/remote_attach/mod.rs | mod auth;
mod config;
mod http_client;
mod websockets;
#[cfg(test)]
mod unit;
pub use websockets::WebSocketConnections;
use crate::os_input_output::ClientOsApi;
use crate::RemoteClientError;
use tokio::runtime::Runtime;
use zellij_utils::remote_session_tokens;
// In tests, only attempt once (no retries) to avoid interactive prompts
// In production, allow up to 3 attempts (initial + 2 retries)
#[cfg(test)]
const MAX_AUTH_ATTEMPTS: u32 = 1;
#[cfg(not(test))]
const MAX_AUTH_ATTEMPTS: u32 = 3;
/// Attach to a remote Zellij session via HTTP(S)
///
/// This function handles the complete authentication flow including:
/// - URL validation
/// - Session token management (--forget, --token flags)
/// - Trying saved session tokens
/// - Interactive authentication with retry logic
/// - Saving session tokens when --remember is used
///
/// Returns WebSocketConnections on success
pub fn attach_to_remote_session(
runtime: &Runtime,
_os_input: Box<dyn ClientOsApi>,
remote_session_url: &str,
token: Option<String>,
remember: bool,
forget: bool,
) -> Result<WebSocketConnections, RemoteClientError> {
// Extract server URL for token management
let server_url = extract_server_url(remote_session_url)?;
// Handle --forget flag
if forget {
let _ = remote_session_tokens::delete_session_token(&server_url);
}
// If --token provided, delete saved session token
if token.is_some() {
let _ = remote_session_tokens::delete_session_token(&server_url);
}
if token.is_none() {
if let Some(connections) =
try_to_connect_with_saved_session_token(runtime, remote_session_url, &server_url)?
{
return Ok(connections);
}
}
// Normal auth flow with retry logic
authenticate_with_retry(runtime, remote_session_url, token, remember)
}
/// Try to connect using a saved session token
/// Returns Ok(Some(connections)) on success, Ok(None) if should retry with auth
fn try_to_connect_with_saved_session_token(
runtime: &Runtime,
remote_session_url: &str,
server_url: &str,
) -> Result<Option<WebSocketConnections>, RemoteClientError> {
if let Ok(Some(saved_session_token)) = remote_session_tokens::get_session_token(server_url) {
// we have a saved session token, let's try to authenticate with it
match runtime.block_on(async move {
remote_attach_with_session_token(remote_session_url, &saved_session_token).await
}) {
Ok(connections) => {
return Ok(Some(connections));
},
Err(RemoteClientError::SessionTokenExpired) => {
// Session expired - delete and return to retry
let _ = remote_session_tokens::delete_session_token(server_url);
eprintln!("Session expired, please re-authenticate");
return Ok(None);
},
Err(e) => {
return Err(e);
},
}
}
Ok(None)
}
fn authenticate_with_retry(
runtime: &Runtime,
remote_session_url: &str,
initial_token: Option<String>,
remember: bool,
) -> Result<WebSocketConnections, RemoteClientError> {
use dialoguer::{Confirm, Password};
let mut attempt = 0;
let mut current_token = initial_token;
loop {
attempt += 1;
let auth_token = match ¤t_token {
Some(t) => t.clone(),
None => Password::new()
.with_prompt("Enter authentication token")
.interact()
.map_err(|e| RemoteClientError::IoError(e))?,
};
match runtime
.block_on(async move { remote_attach(remote_session_url, &auth_token, remember).await })
{
Ok((connections, session_token_opt)) => {
// Save session token if we got one
if let Some(session_token) = session_token_opt {
let server_url = extract_server_url(remote_session_url)?;
let _ = remote_session_tokens::save_session_token(&server_url, &session_token);
}
return Ok(connections);
},
Err(RemoteClientError::InvalidAuthToken) => {
eprintln!("Invalid authentication token");
if attempt >= MAX_AUTH_ATTEMPTS {
eprintln!(
"Maximum authentication attempts ({}) exceeded.",
MAX_AUTH_ATTEMPTS
);
return Err(RemoteClientError::InvalidAuthToken);
}
match Confirm::new()
.with_prompt("Try again?")
.default(true)
.interact()
{
Ok(true) => {
current_token = None;
continue;
},
Ok(false) => {
return Err(RemoteClientError::InvalidAuthToken);
},
Err(e) => {
return Err(RemoteClientError::IoError(e));
},
}
},
Err(e) => {
return Err(e);
},
}
}
}
async fn remote_attach(
server_url: &str,
auth_token: &str,
remember_me: bool,
) -> Result<(websockets::WebSocketConnections, Option<String>), RemoteClientError> {
let server_base_url = extract_server_url(server_url)?;
let session_name = extract_session_name(server_url)?;
let (web_client_id, http_client, session_token) =
auth::authenticate(&server_base_url, auth_token, remember_me).await?;
let connections = websockets::establish_websocket_connections(
&web_client_id,
&http_client,
&server_base_url,
&session_name,
)
.await
.map_err(|e| RemoteClientError::ConnectionFailed(e.to_string()))?;
Ok((connections, session_token))
}
async fn remote_attach_with_session_token(
server_url: &str,
session_token: &str,
) -> Result<websockets::WebSocketConnections, RemoteClientError> {
let server_base_url = extract_server_url(server_url)?;
let session_name = extract_session_name(server_url)?;
let (web_client_id, http_client) =
auth::validate_session_token(&server_base_url, session_token).await?;
let connections = websockets::establish_websocket_connections(
&web_client_id,
&http_client,
&server_base_url,
&session_name,
)
.await
.map_err(|e| RemoteClientError::ConnectionFailed(e.to_string()))?;
Ok(connections)
}
pub fn extract_server_url(full_url: &str) -> Result<String, RemoteClientError> {
let parsed = url::Url::parse(full_url)?;
let mut base_url = parsed.clone();
base_url.set_path("");
base_url.set_query(None);
base_url.set_fragment(None);
Ok(base_url.to_string().trim_end_matches('/').to_string())
}
fn extract_session_name(server_url: &str) -> Result<String, RemoteClientError> {
let parsed_url = url::Url::parse(server_url)?;
let path = parsed_url.path();
// Extract session name from path (everything after the first /)
if path.len() > 1 && path.starts_with('/') {
Ok(path[1..].trim_end_matches('/').to_string())
} else {
Ok(String::new())
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/remote_attach/unit/mod.rs | zellij-client/src/remote_attach/unit/mod.rs | mod remote_attach_tests;
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-client/src/remote_attach/unit/remote_attach_tests.rs | zellij-client/src/remote_attach/unit/remote_attach_tests.rs | use super::super::*;
use crate::RemoteClientError;
use serial_test::serial;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use zellij_utils::remote_session_tokens;
// Mock server infrastructure
#[cfg(feature = "web_server_capability")]
mod mock_server {
use super::*;
use axum::{
extract::State,
http::StatusCode,
response::Response,
routing::{get, post},
Json, Router,
};
use axum_extra::extract::cookie::{Cookie, CookieJar};
use serde::Deserialize;
use serde_json::json;
use tokio::net::TcpListener;
use uuid::Uuid;
#[derive(Clone)]
pub struct MockRemoteServerState {
pub valid_auth_tokens: Arc<Mutex<HashMap<String, ()>>>,
pub session_tokens: Arc<Mutex<HashMap<String, String>>>, // token -> web_client_id
pub endpoints_called: Arc<Mutex<Vec<String>>>,
}
impl MockRemoteServerState {
pub fn new() -> Self {
Self {
valid_auth_tokens: Arc::new(Mutex::new(HashMap::new())),
session_tokens: Arc::new(Mutex::new(HashMap::new())),
endpoints_called: Arc::new(Mutex::new(Vec::new())),
}
}
pub fn add_valid_token(&self, token: &str) {
self.valid_auth_tokens
.lock()
.unwrap()
.insert(token.to_string(), ());
}
fn record_endpoint(&self, endpoint: &str) {
self.endpoints_called
.lock()
.unwrap()
.push(endpoint.to_string());
}
pub fn get_endpoints_called(&self) -> Vec<String> {
self.endpoints_called.lock().unwrap().clone()
}
}
#[derive(Deserialize)]
struct LoginRequest {
auth_token: String,
}
async fn handle_login(
State(state): State<MockRemoteServerState>,
jar: CookieJar,
Json(payload): Json<LoginRequest>,
) -> Result<(CookieJar, Json<serde_json::Value>), StatusCode> {
state.record_endpoint("/command/login");
let valid_tokens = state.valid_auth_tokens.lock().unwrap();
if !valid_tokens.contains_key(&payload.auth_token) {
return Err(StatusCode::UNAUTHORIZED);
}
drop(valid_tokens);
// Always create a session token (cookie is always set)
let session_token = Uuid::new_v4().to_string();
let web_client_id = Uuid::new_v4().to_string();
state
.session_tokens
.lock()
.unwrap()
.insert(session_token.clone(), web_client_id);
let cookie = Cookie::build(("session_token", session_token))
.path("/")
.http_only(true)
.build();
let jar = jar.add(cookie);
Ok((
jar,
Json(json!({
"success": true,
"message": "Login successful"
})),
))
}
async fn handle_session(
State(state): State<MockRemoteServerState>,
jar: CookieJar,
) -> Result<Json<serde_json::Value>, StatusCode> {
state.record_endpoint("/session");
let session_token = jar
.get("session_token")
.map(|c| c.value().to_string())
.ok_or(StatusCode::UNAUTHORIZED)?;
let session_tokens = state.session_tokens.lock().unwrap();
let web_client_id = session_tokens
.get(&session_token)
.ok_or(StatusCode::UNAUTHORIZED)?
.clone();
drop(session_tokens);
Ok(Json(json!({
"web_client_id": web_client_id
})))
}
async fn handle_ws_terminal(
ws: axum::extract::ws::WebSocketUpgrade,
State(state): State<MockRemoteServerState>,
jar: CookieJar,
) -> Result<Response, StatusCode> {
state.record_endpoint("/ws/terminal");
// Validate session token
let session_token = jar
.get("session_token")
.map(|c| c.value().to_string())
.ok_or(StatusCode::UNAUTHORIZED)?;
let session_tokens = state.session_tokens.lock().unwrap();
if !session_tokens.contains_key(&session_token) {
return Err(StatusCode::UNAUTHORIZED);
}
drop(session_tokens);
Ok(ws.on_upgrade(|socket| async move {
// Basic echo WebSocket handler
use axum::extract::ws::Message;
use futures_util::{SinkExt, StreamExt};
let (mut sender, mut receiver) = socket.split();
while let Some(Ok(msg)) = receiver.next().await {
if let Message::Text(text) = msg {
let _ = sender.send(Message::Text(text)).await;
}
}
}))
}
async fn handle_ws_control(
ws: axum::extract::ws::WebSocketUpgrade,
State(state): State<MockRemoteServerState>,
jar: CookieJar,
) -> Result<Response, StatusCode> {
state.record_endpoint("/ws/control");
// Validate session token
let session_token = jar
.get("session_token")
.map(|c| c.value().to_string())
.ok_or(StatusCode::UNAUTHORIZED)?;
let session_tokens = state.session_tokens.lock().unwrap();
if !session_tokens.contains_key(&session_token) {
return Err(StatusCode::UNAUTHORIZED);
}
drop(session_tokens);
Ok(ws.on_upgrade(|socket| async move {
// Basic echo WebSocket handler
use axum::extract::ws::Message;
use futures_util::{SinkExt, StreamExt};
let (mut sender, mut receiver) = socket.split();
while let Some(Ok(msg)) = receiver.next().await {
if let Message::Text(text) = msg {
let _ = sender.send(Message::Text(text)).await;
}
}
}))
}
pub async fn start_mock_server(
state: MockRemoteServerState,
) -> (u16, tokio::task::JoinHandle<()>) {
let app = Router::new()
.route("/command/login", post(handle_login))
.route("/session", post(handle_session))
.route("/ws/terminal", get(handle_ws_terminal))
.route("/ws/terminal/{session_name}", get(handle_ws_terminal))
.route("/ws/control", get(handle_ws_control))
.with_state(state);
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let server_handle = tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
// Wait for server to be ready
tokio::time::sleep(Duration::from_millis(100)).await;
(port, server_handle)
}
}
// Database test helpers
fn setup_test_db(server_url: &str) {
let _ = remote_session_tokens::delete_session_token(server_url);
}
fn cleanup_test_db(server_url: &str) {
let _ = remote_session_tokens::delete_session_token(server_url);
}
// Mock ClientOsApi for testing
#[derive(Debug, Clone)]
struct MockClientOsApi;
impl crate::os_input_output::ClientOsApi for MockClientOsApi {
fn get_terminal_size_using_fd(&self, _fd: i32) -> zellij_utils::pane_size::Size {
zellij_utils::pane_size::Size { rows: 24, cols: 80 }
}
fn set_raw_mode(&mut self, _fd: i32) {}
fn unset_raw_mode(&self, _fd: i32) -> Result<(), nix::Error> {
Ok(())
}
fn box_clone(&self) -> Box<dyn crate::os_input_output::ClientOsApi> {
Box::new(MockClientOsApi)
}
fn read_from_stdin(&mut self) -> Result<Vec<u8>, &'static str> {
Ok(Vec::new())
}
fn get_stdin_reader(&self) -> Box<dyn std::io::BufRead> {
Box::new(std::io::BufReader::new(std::io::empty()))
}
fn get_stdout_writer(&self) -> Box<dyn std::io::Write> {
Box::new(std::io::sink())
}
fn update_session_name(&mut self, _new_session_name: String) {}
fn send_to_server(&self, _msg: zellij_utils::ipc::ClientToServerMsg) {}
fn recv_from_server(
&self,
) -> Option<(
zellij_utils::ipc::ServerToClientMsg,
zellij_utils::errors::ErrorContext,
)> {
None
}
fn handle_signals(&self, _sigwinch_cb: Box<dyn Fn()>, _quit_cb: Box<dyn Fn()>) {}
fn connect_to_server(&self, _path: &std::path::Path) {}
fn load_palette(&self) -> zellij_utils::data::Palette {
zellij_utils::shared::default_palette()
}
fn enable_mouse(&self) -> anyhow::Result<()> {
Ok(())
}
fn disable_mouse(&self) -> anyhow::Result<()> {
Ok(())
}
fn stdin_poller(&self) -> crate::os_input_output::StdinPoller {
crate::os_input_output::StdinPoller::default()
}
}
// Tests
#[cfg(feature = "web_server_capability")]
mod tests {
use super::mock_server::*;
use super::*;
// Helper function to call attach_to_remote_session from async context
async fn call_attach_to_remote_session(
remote_session_url: String,
token: Option<String>,
remember: bool,
forget: bool,
) -> Result<WebSocketConnections, RemoteClientError> {
tokio::task::spawn_blocking(move || {
let runtime = tokio::runtime::Runtime::new().unwrap();
let os_input: Box<dyn crate::os_input_output::ClientOsApi> = Box::new(MockClientOsApi);
attach_to_remote_session(
&runtime,
os_input,
&remote_session_url,
token,
remember,
forget,
)
})
.await
.unwrap()
}
#[tokio::test]
#[serial]
async fn test_successful_authentication_with_valid_token() {
let server_state = MockRemoteServerState::new();
let auth_token = "test-auth-token-123";
server_state.add_valid_token(auth_token);
let (port, server_handle) = start_mock_server(server_state.clone()).await;
let server_url = format!("http://127.0.0.1:{}/session-name", port);
setup_test_db(&format!("http://127.0.0.1:{}", port));
let result =
call_attach_to_remote_session(server_url, Some(auth_token.to_string()), false, false)
.await;
assert!(
result.is_ok(),
"Should successfully authenticate: {:?}",
result.err()
);
let endpoints = server_state.get_endpoints_called();
assert!(
endpoints.contains(&"/command/login".to_string()),
"Should call login endpoint"
);
assert!(
endpoints.contains(&"/session".to_string()),
"Should call session endpoint"
);
assert!(
endpoints.contains(&"/ws/terminal".to_string()),
"Should establish terminal WebSocket"
);
assert!(
endpoints.contains(&"/ws/control".to_string()),
"Should establish control WebSocket"
);
server_handle.abort();
cleanup_test_db(&format!("http://127.0.0.1:{}", port));
}
#[tokio::test]
#[serial]
async fn test_failed_authentication_with_invalid_token() {
let server_state = MockRemoteServerState::new();
// Don't add the token to valid tokens - server will reject it
let (port, server_handle) = start_mock_server(server_state.clone()).await;
let server_url = format!("http://127.0.0.1:{}/session-name", port);
setup_test_db(&format!("http://127.0.0.1:{}", port));
let result = call_attach_to_remote_session(
server_url,
Some("invalid-token".to_string()),
false,
false,
)
.await;
assert!(result.is_err(), "Should fail with invalid token");
assert!(
matches!(result.unwrap_err(), RemoteClientError::InvalidAuthToken),
"Should return InvalidAuthToken error"
);
server_handle.abort();
cleanup_test_db(&format!("http://127.0.0.1:{}", port));
}
#[tokio::test]
#[serial]
async fn test_save_session_token_with_remember_true() {
let server_state = MockRemoteServerState::new();
let auth_token = "test-token-remember";
server_state.add_valid_token(auth_token);
let (port, server_handle) = start_mock_server(server_state.clone()).await;
let server_url = format!("http://127.0.0.1:{}/session-name", port);
let base_url = format!("http://127.0.0.1:{}", port);
setup_test_db(&base_url);
let result = call_attach_to_remote_session(
server_url,
Some(auth_token.to_string()),
true, // remember = true
false,
)
.await;
assert!(result.is_ok(), "Connection should succeed");
// Verify token was saved
let saved_token = remote_session_tokens::get_session_token(&base_url);
assert!(saved_token.is_ok());
assert!(
saved_token.unwrap().is_some(),
"Session token should be saved"
);
server_handle.abort();
cleanup_test_db(&base_url);
}
#[tokio::test]
#[serial]
async fn test_dont_save_token_with_remember_false() {
let server_state = MockRemoteServerState::new();
let auth_token = "test-token-no-remember";
server_state.add_valid_token(auth_token);
let (port, server_handle) = start_mock_server(server_state.clone()).await;
let server_url = format!("http://127.0.0.1:{}/session-name", port);
let base_url = format!("http://127.0.0.1:{}", port);
setup_test_db(&base_url);
let result = call_attach_to_remote_session(
server_url,
Some(auth_token.to_string()),
false, // remember = false
false,
)
.await;
assert!(result.is_ok(), "Connection should succeed");
// Verify token was NOT saved
let saved_token = remote_session_tokens::get_session_token(&base_url);
assert!(saved_token.is_ok());
assert!(
saved_token.unwrap().is_none(),
"Session token should NOT be saved"
);
server_handle.abort();
cleanup_test_db(&base_url);
}
#[tokio::test]
#[serial]
async fn test_load_and_use_saved_session_token() {
let server_state = MockRemoteServerState::new();
// Pre-create a session token
let session_token = uuid::Uuid::new_v4().to_string();
let web_client_id = uuid::Uuid::new_v4().to_string();
server_state
.session_tokens
.lock()
.unwrap()
.insert(session_token.clone(), web_client_id);
let (port, server_handle) = start_mock_server(server_state.clone()).await;
let server_url = format!("http://127.0.0.1:{}/session-name", port);
let base_url = format!("http://127.0.0.1:{}", port);
setup_test_db(&base_url);
// Save the session token
remote_session_tokens::save_session_token(&base_url, &session_token).unwrap();
let result = call_attach_to_remote_session(
server_url, None, // No auth token provided
false, false,
)
.await;
assert!(result.is_ok(), "Should successfully use saved token");
// Verify we did NOT call login endpoint (used saved token directly)
let endpoints = server_state.get_endpoints_called();
assert!(
!endpoints.contains(&"/command/login".to_string()),
"Should NOT call login endpoint"
);
assert!(
endpoints.contains(&"/session".to_string()),
"Should call session endpoint"
);
server_handle.abort();
cleanup_test_db(&base_url);
}
#[tokio::test]
#[serial]
async fn test_token_flag_deletes_saved_token() {
let server_state = MockRemoteServerState::new();
let auth_token = "new-auth-token";
server_state.add_valid_token(auth_token);
let (port, server_handle) = start_mock_server(server_state.clone()).await;
let server_url = format!("http://127.0.0.1:{}/session-name", port);
let base_url = format!("http://127.0.0.1:{}", port);
setup_test_db(&base_url);
// Pre-save an old token
remote_session_tokens::save_session_token(&base_url, "old-token").unwrap();
let result = call_attach_to_remote_session(
server_url,
Some(auth_token.to_string()), // Providing new token
false,
false,
)
.await;
assert!(result.is_ok(), "Should succeed with new token");
// The old token should have been deleted before using new one
// (New token won't be saved because remember=false)
// Verify by checking that session endpoint was called (not using saved token)
let endpoints = server_state.get_endpoints_called();
assert!(
endpoints.contains(&"/command/login".to_string()),
"Should use new auth token, not saved token"
);
server_handle.abort();
cleanup_test_db(&base_url);
}
#[tokio::test]
#[serial]
async fn test_successful_websocket_establishment() {
let server_state = MockRemoteServerState::new();
let auth_token = "test-ws-token";
server_state.add_valid_token(auth_token);
let (port, server_handle) = start_mock_server(server_state.clone()).await;
let server_url = format!("http://127.0.0.1:{}/test-session", port);
let base_url = format!("http://127.0.0.1:{}", port);
setup_test_db(&base_url);
let result =
call_attach_to_remote_session(server_url, Some(auth_token.to_string()), false, false)
.await;
assert!(
result.is_ok(),
"WebSocket connections should be established"
);
let connections = result.unwrap();
assert!(
!connections.web_client_id.is_empty(),
"Should have web_client_id"
);
// Verify both WebSocket endpoints were called
let endpoints = server_state.get_endpoints_called();
assert!(
endpoints.contains(&"/ws/terminal".to_string()),
"Terminal WebSocket should be established"
);
assert!(
endpoints.contains(&"/ws/control".to_string()),
"Control WebSocket should be established"
);
server_handle.abort();
cleanup_test_db(&base_url);
}
#[tokio::test]
async fn test_url_parsing_for_session_name() {
// Test various URL formats
let test_cases = vec![
("https://example.com/my-session", "my-session"),
("https://example.com/", ""),
("https://example.com/path/to/session", "path/to/session"),
("http://localhost:8080/test", "test"),
];
for (url, expected_name) in test_cases {
let result = extract_session_name(url);
assert!(result.is_ok(), "Failed to parse URL: {}", url);
assert_eq!(
result.unwrap(),
expected_name,
"Wrong session name for URL: {}",
url
);
}
}
#[tokio::test]
async fn test_server_url_extraction() {
// Test various URL formats
let test_cases = vec![
(
"https://example.com:8080/session?foo=bar",
"https://example.com:8080",
),
("http://localhost/test", "http://localhost"),
(
"https://example.com/path/to/session#anchor",
"https://example.com",
),
];
for (url, expected_base) in test_cases {
let result = extract_server_url(url);
assert!(result.is_ok(), "Failed to extract server URL: {}", url);
assert_eq!(
result.unwrap(),
expected_base,
"Wrong base URL for: {}",
url
);
}
}
#[tokio::test]
async fn test_invalid_url_format() {
let result = call_attach_to_remote_session(
"not-a-valid-url".to_string(),
Some("token".to_string()),
false,
false,
)
.await;
assert!(result.is_err(), "Should fail with malformed URL");
assert!(matches!(
result.unwrap_err(),
RemoteClientError::UrlParseError(_)
));
}
}
// Tests that don't require the web_server_capability feature
#[cfg(not(feature = "web_server_capability"))]
mod tests {
use super::*;
#[test]
fn test_url_parsing_without_server() {
// Basic URL parsing tests that don't require a server
let result = extract_session_name("https://example.com/my-session");
assert!(result.is_ok());
assert_eq!(result.unwrap(), "my-session");
let result = extract_server_url("https://example.com:8080/session?foo=bar");
assert!(result.is_ok());
assert_eq!(result.unwrap(), "https://example.com:8080");
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/xtask/src/test.rs | xtask/src/test.rs | use crate::{build, flags, metadata, WorkspaceMember};
use anyhow::{anyhow, Context};
use std::path::Path;
use xshell::{cmd, Shell};
pub fn test(sh: &Shell, flags: flags::Test) -> anyhow::Result<()> {
let err_context = "failed to run task 'test'";
let _pdo = sh.push_dir(crate::project_root());
let cargo = crate::cargo().context(err_context)?;
let host_triple = host_target_triple(sh).context(err_context)?;
build::build(
sh,
flags::Build {
release: false,
no_plugins: false,
plugins_only: true,
no_web: flags.no_web,
},
)
.context(err_context)?;
for WorkspaceMember { crate_name, .. } in crate::workspace_members().iter() {
let _pd = sh.push_dir(Path::new(crate_name));
println!();
let msg = format!(">> Testing '{}'", crate_name);
crate::status(&msg);
println!("{}", msg);
let cmd = if crate_name.contains("plugins") {
cmd!(sh, "{cargo} test --target {host_triple} --")
} else if flags.no_web {
// Check if this crate has web features that need modification
match metadata::get_no_web_features(sh, crate_name)
.context("Failed to check web features")?
{
Some(features) => {
if features.is_empty() {
// Crate has web_server_capability but no other applicable features
cmd!(sh, "{cargo} test --no-default-features --")
} else {
cmd!(sh, "{cargo} test --no-default-features --features")
.arg(features)
.arg("--")
}
},
None => {
// Crate doesn't have web features, use normal test
cmd!(sh, "{cargo} test --all-features --")
},
}
} else {
cmd!(sh, "{cargo} test --all-features --")
};
cmd.args(&flags.args)
.run()
.with_context(|| format!("Failed to run tests for '{}'", crate_name))?;
}
Ok(())
}
pub fn host_target_triple(sh: &Shell) -> anyhow::Result<String> {
let rustc_ver = cmd!(sh, "rustc -vV")
.read()
.context("Failed to determine host triple")?;
let maybe_triple = rustc_ver
.lines()
.filter_map(|line| {
if !line.starts_with("host") {
return None;
}
if let Some((_, triple)) = line.split_once(": ") {
Some(triple.to_string())
} else {
None
}
})
.collect::<Vec<String>>();
match maybe_triple.len() {
0 => Err(anyhow!("rustc didn't output the 'host' triple")),
1 => Ok(maybe_triple.into_iter().next().unwrap()),
_ => Err(anyhow!(
"rustc provided multiple host triples: {:?}",
maybe_triple
)),
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/xtask/src/ci.rs | xtask/src/ci.rs | //! Tasks related to zellij CI
use crate::{
build,
flags::{self, CiCmd, Cross, E2e},
metadata,
};
use anyhow::Context;
use std::{
ffi::OsString,
path::{Path, PathBuf},
};
use xshell::{cmd, Shell};
pub fn main(sh: &Shell, flags: flags::Ci) -> anyhow::Result<()> {
let err_context = "failed to run CI task";
match flags.subcommand {
CiCmd::E2e(E2e {
build: false,
test: false,
..
}) => Err(anyhow::anyhow!(
"either '--build' or '--test' must be provided!"
)),
CiCmd::E2e(E2e {
build: true,
test: true,
..
}) => Err(anyhow::anyhow!(
"flags '--build' and '--test' are mutually exclusive!"
)),
CiCmd::E2e(E2e {
build: true,
test: false,
..
}) => e2e_build(sh),
CiCmd::E2e(E2e {
build: false,
test: true,
args,
}) => e2e_test(sh, args),
CiCmd::Cross(Cross { triple, no_web }) => cross_compile(sh, &triple, no_web),
}
.context(err_context)
}
fn e2e_build(sh: &Shell) -> anyhow::Result<()> {
let err_context = "failed to build E2E binary";
build::build(
sh,
flags::Build {
release: true,
no_plugins: false,
plugins_only: true,
no_web: false,
},
)
.context(err_context)?;
// Copy plugins to e2e data-dir
let plugin_dir = crate::asset_dir().join("plugins");
let project_root = crate::project_root();
let data_dir = project_root.join("target").join("e2e-data");
let plugins: Vec<_> = std::fs::read_dir(plugin_dir)
.context(err_context)?
.filter_map(|dir_entry| {
if let Ok(entry) = dir_entry {
entry
.file_name()
.to_string_lossy()
.ends_with(".wasm")
.then_some(entry.path())
} else {
None
}
})
.collect();
sh.remove_path(&data_dir)
.and_then(|_| sh.create_dir(&data_dir))
.and_then(|_| sh.create_dir(data_dir.join("plugins")))
.context(err_context)?;
for plugin in plugins {
sh.copy_file(plugin, data_dir.join("plugins"))
.context(err_context)?;
}
let _pd = sh.push_dir(project_root);
crate::cargo()
.and_then(|cargo| {
cmd!(
sh,
"{cargo} build --release --target x86_64-unknown-linux-musl"
)
.run()
.map_err(anyhow::Error::new)
})
.context(err_context)
}
fn e2e_test(sh: &Shell, args: Vec<OsString>) -> anyhow::Result<()> {
let err_context = "failed to run E2E tests";
e2e_build(sh).context(err_context)?;
let _pd = sh.push_dir(crate::project_root());
// set --no-default-features so the test binary gets built with the plugins from assets/plugins that just got built
crate::cargo()
.and_then(|cargo| {
// e2e tests
cmd!(
sh,
"{cargo} test --no-default-features -- --ignored --nocapture --test-threads 1"
)
.args(args.clone())
.run()
.map_err(anyhow::Error::new)?;
// plugin system tests are run here because they're medium-slow
let _pd = sh.push_dir(Path::new("zellij-server"));
println!();
let msg = ">> Testing Plugin System".to_string();
crate::status(&msg);
println!("{}", msg);
cmd!(sh, "{cargo} test -- --ignored --nocapture --test-threads 1")
.args(args.clone())
.run()
.with_context(|| "Failed to run tests for the Plugin System".to_string())?;
Ok(())
})
.context(err_context)
}
fn cross_compile(sh: &Shell, target: &OsString, no_web: bool) -> anyhow::Result<()> {
let err_context = || format!("failed to cross-compile for {target:?}");
crate::cargo()
.and_then(|cargo| {
cmd!(sh, "{cargo} install mandown").run()?;
Ok(cargo)
})
.and_then(|cargo| {
cmd!(sh, "{cargo} install cross")
.run()
.map_err(anyhow::Error::new)
})
.with_context(err_context)?;
build::build(
sh,
flags::Build {
release: true,
no_plugins: false,
plugins_only: true,
no_web,
},
)
.and_then(|_| build::manpage(sh))
.with_context(err_context)?;
cross()
.and_then(|cross| {
if no_web {
match metadata::get_no_web_features(sh, ".")
.context("Failed to check web features for cross compilation")?
{
Some(features) => {
let mut cmd = cmd!(sh, "{cross} build --verbose --release --target {target} --no-default-features");
if !features.is_empty() {
cmd = cmd.arg("--features").arg(features);
}
cmd.run().map_err(anyhow::Error::new)
},
None => {
// Main crate doesn't have web_server_capability, build normally
cmd!(sh, "{cross} build --verbose --release --target {target}")
.run()
.map_err(anyhow::Error::new)
},
}
} else {
cmd!(sh, "{cross} build --verbose --release --target {target}")
.run()
.map_err(anyhow::Error::new)
}
})
.with_context(err_context)
}
fn cross() -> anyhow::Result<PathBuf> {
match which::which("cross") {
Ok(path) => Ok(path),
Err(e) => {
eprintln!("!! 'cross' wasn't found but is needed for this build step.");
eprintln!("!! Please install it with: `cargo install cross`");
Err(e).context("couldn't find 'cross' executable")
},
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/xtask/src/flags.rs | xtask/src/flags.rs | //! CLI flags for `cargo xtask`
use std::ffi::OsString;
use std::path::PathBuf;
xflags::xflags! {
src "./src/flags.rs"
/// Custom build commands for zellij
cmd xtask {
/// Deprecation warning. Compatibility to transition from `cargo make`.
cmd deprecated {
repeated _args: OsString
}
/// Tasks for the CI
cmd ci {
/// end-to-end tests
cmd e2e {
/// Build E2E binary of zellij
optional --build
/// Run the E2E tests
optional --test
/// Additional arguments for `--test`
repeated args: OsString
}
/// Perform cross-compiled release builds
cmd cross {
/// Target-triple to compile the application for
required triple: OsString
/// Compile without web server support
optional --no-web
}
}
/// Build the manpage
cmd manpage {}
/// Publish zellij and all the sub-crates
cmd publish {
/// Perform a dry-run (don't push/publish anything)
optional --dry-run
/// Publish but don't push a commit to git (only works with '--cargo-registry')
optional --no-push
/// Push commit to custom git remote
optional --git-remote remote: OsString
/// Publish crates to custom registry
optional --cargo-registry registry: OsString
}
/// Package zellij for distribution (result found in ./target/dist)
cmd dist {}
/// Run `cargo clippy` on all crates
cmd clippy {}
/// Sequentially call: format, build, test, clippy
cmd make {
/// Build in release mode without debug symbols
optional -r, --release
/// Clean project before building
optional -c, --clean
/// Compile without web server support
optional --no-web
}
/// Generate a runnable `zellij` executable with plugins bundled
cmd install {
required destination: PathBuf
/// Compile without web server support
optional --no-web
}
/// Run debug version of zellij
cmd run {
/// Take plugins from asset folder, skip building plugins.
optional --quick-run
/// Take plugins from here, skip building plugins. Passed to zellij verbatim
optional --data-dir path: PathBuf
/// Disable optimizing dependencies
optional --disable-deps-optimize
/// Compile without web server support
optional --no-web
/// Arguments to pass after `cargo run --`
repeated args: OsString
}
/// Run `cargo fmt` on all crates
cmd format {
/// Run `cargo fmt` in check mode
optional --check
}
/// Run application tests
cmd test {
/// Compile without web server support
optional --no-web
/// Arguments to pass after `cargo test --`
repeated args: OsString
}
/// Build the application and all plugins
cmd build {
/// Build in release mode without debug symbols
optional -r, --release
/// Build only the plugins
optional -p, --plugins-only
/// Build everything except the plugins
optional --no-plugins
/// Compile without web support
optional --no-web
}
}
}
// generated start
// The following code is generated by `xflags` macro.
// Run `env UPDATE_XFLAGS=1 cargo build` to regenerate.
#[derive(Debug)]
pub struct Xtask {
pub subcommand: XtaskCmd,
}
#[derive(Debug)]
pub enum XtaskCmd {
Deprecated(Deprecated),
Ci(Ci),
Manpage(Manpage),
Publish(Publish),
Dist(Dist),
Clippy(Clippy),
Make(Make),
Install(Install),
Run(Run),
Format(Format),
Test(Test),
Build(Build),
}
#[derive(Debug)]
pub struct Deprecated {
pub _args: Vec<OsString>,
}
#[derive(Debug)]
pub struct Ci {
pub subcommand: CiCmd,
}
#[derive(Debug)]
pub enum CiCmd {
E2e(E2e),
Cross(Cross),
}
#[derive(Debug)]
pub struct E2e {
pub args: Vec<OsString>,
pub build: bool,
pub test: bool,
}
#[derive(Debug)]
pub struct Cross {
pub triple: OsString,
pub no_web: bool,
}
#[derive(Debug)]
pub struct Manpage;
#[derive(Debug)]
pub struct Publish {
pub dry_run: bool,
pub no_push: bool,
pub git_remote: Option<OsString>,
pub cargo_registry: Option<OsString>,
}
#[derive(Debug)]
pub struct Dist;
#[derive(Debug)]
pub struct Clippy;
#[derive(Debug)]
pub struct Make {
pub release: bool,
pub clean: bool,
pub no_web: bool,
}
#[derive(Debug)]
pub struct Install {
pub destination: PathBuf,
pub no_web: bool,
}
#[derive(Debug)]
pub struct Run {
pub args: Vec<OsString>,
pub quick_run: bool,
pub data_dir: Option<PathBuf>,
pub disable_deps_optimize: bool,
pub no_web: bool,
}
#[derive(Debug)]
pub struct Format {
pub check: bool,
}
#[derive(Debug)]
pub struct Test {
pub args: Vec<OsString>,
pub no_web: bool,
}
#[derive(Debug)]
pub struct Build {
pub release: bool,
pub plugins_only: bool,
pub no_plugins: bool,
pub no_web: bool,
}
impl Xtask {
#[allow(dead_code)]
pub fn from_env_or_exit() -> Self {
Self::from_env_or_exit_()
}
#[allow(dead_code)]
pub fn from_env() -> xflags::Result<Self> {
Self::from_env_()
}
#[allow(dead_code)]
pub fn from_vec(args: Vec<std::ffi::OsString>) -> xflags::Result<Self> {
Self::from_vec_(args)
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/xtask/src/build.rs | xtask/src/build.rs | //! Subcommands for building.
//!
//! Currently has the following functions:
//!
//! - [`build`]: Builds general cargo projects (i.e. zellij components) with `cargo build`
//! - [`manpage`]: Builds the manpage with `mandown`
use crate::{flags, metadata, WorkspaceMember};
use anyhow::Context;
use std::path::{Path, PathBuf};
use xshell::{cmd, Shell};
/// Build members of the zellij workspace.
///
/// Build behavior is controlled by the [`flags`](flags::Build). Calls some variation of `cargo
/// build` under the hood.
pub fn build(sh: &Shell, flags: flags::Build) -> anyhow::Result<()> {
let _pd = sh.push_dir(crate::project_root());
let cargo = crate::cargo()?;
if flags.no_plugins && flags.plugins_only {
eprintln!("Cannot use both '--no-plugins' and '--plugins-only'");
std::process::exit(1);
}
for WorkspaceMember { crate_name, .. } in crate::workspace_members()
.iter()
.filter(|member| member.build)
{
let err_context = || format!("failed to build '{crate_name}'");
if crate_name.contains("plugins") {
if flags.no_plugins {
continue;
}
} else if flags.plugins_only {
continue;
}
// zellij-utils requires protobuf definition files to be present. Usually these are
// auto-generated with `build.rs`-files, but this is currently broken for us.
// See [this PR][1] for details.
//
// [1]: https://github.com/zellij-org/zellij/pull/2711#issuecomment-1695015818
{
let zellij_utils_basedir = crate::project_root().join("zellij-utils");
let _pd = sh.push_dir(zellij_utils_basedir);
let prost_asset_dir = sh.current_dir().join("assets").join("prost");
let protobuf_source_dir = sh.current_dir().join("src").join("plugin_api");
std::fs::create_dir_all(&prost_asset_dir).unwrap();
let mut prost = prost_build::Config::new();
let last_generated = prost_asset_dir
.join("generated_plugin_api.rs")
.metadata()
.and_then(|m| m.modified());
let mut needs_regeneration = false;
prost.out_dir(prost_asset_dir);
prost.include_file("generated_plugin_api.rs");
let mut proto_files = vec![];
for entry in std::fs::read_dir(&protobuf_source_dir).unwrap() {
let entry_path = entry.unwrap().path();
if entry_path.is_file() {
if !entry_path
.extension()
.map(|e| e == "proto")
.unwrap_or(false)
{
continue;
}
proto_files.push(entry_path.display().to_string());
let modified = entry_path.metadata().and_then(|m| m.modified());
needs_regeneration |= match (&last_generated, modified) {
(Ok(last_generated), Ok(modified)) => modified >= *last_generated,
// Couldn't read some metadata, assume needs update
_ => true,
}
}
}
if needs_regeneration {
prost
.compile_protos(&proto_files, &[protobuf_source_dir])
.unwrap();
}
}
// Build client-server IPC protobuf definitions
{
let zellij_utils_basedir = crate::project_root().join("zellij-utils");
let _pd = sh.push_dir(zellij_utils_basedir);
let prost_ipc_dir = sh.current_dir().join("assets").join("prost_ipc");
let client_server_contract_dir =
sh.current_dir().join("src").join("client_server_contract");
std::fs::create_dir_all(&prost_ipc_dir).unwrap();
let mut prost = prost_build::Config::new();
let last_generated = prost_ipc_dir
.join("generated_client_server_api.rs")
.metadata()
.and_then(|m| m.modified());
let mut needs_regeneration = false;
prost.out_dir(prost_ipc_dir);
prost.include_file("generated_client_server_api.rs");
let mut proto_files = vec![];
for entry in std::fs::read_dir(&client_server_contract_dir).unwrap() {
let entry_path = entry.unwrap().path();
if entry_path.is_file() {
if !entry_path
.extension()
.map(|e| e == "proto")
.unwrap_or(false)
{
continue;
}
proto_files.push(entry_path.display().to_string());
let modified = entry_path.metadata().and_then(|m| m.modified());
needs_regeneration |= match (&last_generated, modified) {
(Ok(last_generated), Ok(modified)) => modified >= *last_generated,
// Couldn't read some metadata, assume needs update
_ => true,
}
}
}
if needs_regeneration {
prost
.compile_protos(&proto_files, &[client_server_contract_dir])
.unwrap();
}
}
// Build web server protobuf definitions
{
let zellij_utils_basedir = crate::project_root().join("zellij-utils");
let _pd = sh.push_dir(zellij_utils_basedir);
let prost_web_server_dir = sh.current_dir().join("assets").join("prost_web_server");
let web_server_contract_dir = sh.current_dir().join("src").join("web_server_contract");
std::fs::create_dir_all(&prost_web_server_dir).unwrap();
let mut prost = prost_build::Config::new();
let last_generated = prost_web_server_dir
.join("generated_web_server_api.rs")
.metadata()
.and_then(|m| m.modified());
let mut needs_regeneration = false;
prost.out_dir(prost_web_server_dir);
prost.include_file("generated_web_server_api.rs");
let mut proto_files = vec![];
for entry in std::fs::read_dir(&web_server_contract_dir).unwrap() {
let entry_path = entry.unwrap().path();
if entry_path.is_file() {
if !entry_path
.extension()
.map(|e| e == "proto")
.unwrap_or(false)
{
continue;
}
proto_files.push(entry_path.display().to_string());
let modified = entry_path.metadata().and_then(|m| m.modified());
needs_regeneration |= match (&last_generated, modified) {
(Ok(last_generated), Ok(modified)) => modified >= *last_generated,
// Couldn't read some metadata, assume needs update
_ => true,
}
}
}
if needs_regeneration {
prost
.compile_protos(&proto_files, &[web_server_contract_dir])
.unwrap();
}
}
let _pd = sh.push_dir(Path::new(crate_name));
// Tell the user where we are now
println!();
let msg = format!(">> Building '{crate_name}'");
crate::status(&msg);
println!("{}", msg);
let mut base_cmd = cmd!(sh, "{cargo} build");
if flags.release {
base_cmd = base_cmd.arg("--release");
}
if flags.no_web {
// Check if this crate has web features that need modification
match metadata::get_no_web_features(sh, crate_name)
.context("Failed to check web features")?
{
Some(features) => {
base_cmd = base_cmd.arg("--no-default-features");
if !features.is_empty() {
base_cmd = base_cmd.arg("--features");
base_cmd = base_cmd.arg(features);
}
},
None => {
// Crate doesn't have web features, build normally
},
}
}
base_cmd.run().with_context(err_context)?;
if crate_name.contains("plugins") {
let (_, plugin_name) = crate_name
.rsplit_once('/')
.context("Cannot determine plugin name from '{subcrate}'")?;
if flags.release {
// Move plugin into assets folder
move_plugin_to_assets(sh, plugin_name)?;
}
}
}
Ok(())
}
fn move_plugin_to_assets(sh: &Shell, plugin_name: &str) -> anyhow::Result<()> {
let err_context = || format!("failed to move plugin '{plugin_name}' to assets folder");
// Get asset path
let asset_name = crate::asset_dir()
.join("plugins")
.join(plugin_name)
.with_extension("wasm");
// Get plugin path
let plugin = PathBuf::from(
std::env::var_os("CARGO_TARGET_DIR")
.unwrap_or(crate::project_root().join("target").into_os_string()),
)
.join("wasm32-wasip1")
.join("release")
.join(plugin_name)
.with_extension("wasm");
if !plugin.is_file() {
return Err(anyhow::anyhow!("No plugin found at '{}'", plugin.display()))
.with_context(err_context);
}
// This is a plugin we want to move
let from = plugin.as_path();
let to = asset_name.as_path();
sh.copy_file(from, to).with_context(err_context)
}
/// Build the manpage with `mandown`.
// mkdir -p ${root_dir}/assets/man
// mandown ${root_dir}/docs/MANPAGE.md 1 > ${root_dir}/assets/man/zellij.1
pub fn manpage(sh: &Shell) -> anyhow::Result<()> {
let err_context = "failed to generate manpage";
let mandown = mandown(sh).context(err_context)?;
let project_root = crate::project_root();
let asset_dir = &project_root.join("assets").join("man");
sh.create_dir(asset_dir).context(err_context)?;
let _pd = sh.push_dir(asset_dir);
cmd!(sh, "{mandown} {project_root}/docs/MANPAGE.md 1")
.read()
.and_then(|text| sh.write_file("zellij.1", text))
.context(err_context)
}
/// Get the path to a `mandown` executable.
///
/// If the executable isn't found, an error is returned instead.
fn mandown(_sh: &Shell) -> anyhow::Result<PathBuf> {
match which::which("mandown") {
Ok(path) => Ok(path),
Err(e) => {
eprintln!("!! 'mandown' wasn't found but is needed for this build step.");
eprintln!("!! Please install it with: `cargo install mandown`");
Err(e).context("Couldn't find 'mandown' executable")
},
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/xtask/src/format.rs | xtask/src/format.rs | //! Handle running `cargo fmt` on the sources.
use crate::{flags, WorkspaceMember};
use anyhow::Context;
use std::path::{Path, PathBuf};
use xshell::{cmd, Shell};
pub fn format(sh: &Shell, flags: flags::Format) -> anyhow::Result<()> {
let _pd = sh.push_dir(crate::project_root());
let cargo = check_rustfmt()
.and_then(|_| crate::cargo())
.context("failed to run task 'format'")?;
for WorkspaceMember { crate_name, .. } in crate::workspace_members().iter() {
let _pd = sh.push_dir(Path::new(crate_name));
// Tell the user where we are now
println!();
let msg = format!(">> Formatting '{crate_name}'");
crate::status(&msg);
println!("{}", msg);
let mut cmd = cmd!(sh, "{cargo} fmt");
if flags.check {
cmd = cmd.arg("--check");
}
cmd.run()
.with_context(|| format!("Failed to format '{crate_name}'"))?;
}
Ok(())
}
fn check_rustfmt() -> anyhow::Result<PathBuf> {
which::which("rustfmt").context(
"Couldn't find 'rustfmt' executable. Please install it with `cargo install rustfmt`",
)
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/xtask/src/dist.rs | xtask/src/dist.rs | rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false | |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/xtask/src/pipelines.rs | xtask/src/pipelines.rs | //! Composite pipelines for the build system.
//!
//! Defines multiple "pipelines" that run specific individual steps in sequence.
use crate::{build, clippy, format, metadata, test};
use crate::{flags, WorkspaceMember};
use anyhow::Context;
use xshell::{cmd, Shell};
/// Perform a default build.
///
/// Runs the following steps in sequence:
///
/// - format
/// - build
/// - test
/// - clippy
pub fn make(sh: &Shell, flags: flags::Make) -> anyhow::Result<()> {
let err_context = || format!("failed to run pipeline 'make' with args {flags:?}");
if flags.clean {
crate::cargo()
.and_then(|cargo| cmd!(sh, "{cargo} clean").run().map_err(anyhow::Error::new))
.with_context(err_context)?;
}
format::format(sh, flags::Format { check: false })
.and_then(|_| {
build::build(
sh,
flags::Build {
release: flags.release,
no_plugins: false,
plugins_only: false,
no_web: flags.no_web,
},
)
})
.and_then(|_| {
test::test(
sh,
flags::Test {
args: vec![],
no_web: flags.no_web,
},
)
})
.and_then(|_| clippy::clippy(sh, flags::Clippy {}))
.with_context(err_context)
}
/// Generate a runnable executable.
///
/// Runs the following steps in sequence:
///
/// - [`build`](build::build) (release, plugins only)
/// - [`build`](build::build) (release, without plugins)
/// - [`manpage`](build::manpage)
/// - Copy the executable to [target file](flags::Install::destination)
pub fn install(sh: &Shell, flags: flags::Install) -> anyhow::Result<()> {
let err_context = || format!("failed to run pipeline 'install' with args {flags:?}");
// Build and optimize plugins
build::build(
sh,
flags::Build {
release: true,
no_plugins: false,
plugins_only: true,
no_web: flags.no_web,
},
)
.and_then(|_| {
// Build the main executable
build::build(
sh,
flags::Build {
release: true,
no_plugins: true,
plugins_only: false,
no_web: flags.no_web,
},
)
})
.and_then(|_| {
// Generate man page
build::manpage(sh)
})
.with_context(err_context)?;
// Copy binary to destination
let destination = if flags.destination.is_absolute() {
flags.destination.clone()
} else {
std::env::current_dir()
.context("Can't determine current working directory")?
.join(&flags.destination)
};
sh.change_dir(crate::project_root());
sh.copy_file("target/release/zellij", &destination)
.with_context(err_context)
}
/// Run zellij debug build.
pub fn run(sh: &Shell, mut flags: flags::Run) -> anyhow::Result<()> {
let err_context =
|flags: &flags::Run| format!("failed to run pipeline 'run' with args {:?}", flags);
if flags.quick_run {
if flags.data_dir.is_some() {
eprintln!("cannot use '--data-dir' and '--quick-run' at the same time!");
std::process::exit(1);
}
flags.data_dir.replace(crate::asset_dir());
}
let profile = if flags.disable_deps_optimize {
"dev"
} else {
"dev-opt"
};
if let Some(ref data_dir) = flags.data_dir {
let data_dir = sh.current_dir().join(data_dir);
let features = if flags.no_web {
"disable_automatic_asset_installation"
} else {
"disable_automatic_asset_installation web_server_capability"
};
crate::cargo()
.and_then(|cargo| {
cmd!(sh, "{cargo} run")
.args(["--package", "zellij"])
.arg("--no-default-features")
.args(["--features", features])
.args(["--profile", profile])
.args(["--", "--data-dir", &format!("{}", data_dir.display())])
.args(&flags.args)
.run()
.map_err(anyhow::Error::new)
})
.with_context(|| err_context(&flags))
} else {
build::build(
sh,
flags::Build {
release: false,
no_plugins: false,
plugins_only: true,
no_web: flags.no_web,
},
)
.and_then(|_| crate::cargo())
.and_then(|cargo| {
if flags.no_web {
// Use dynamic metadata approach to get the correct features
match metadata::get_no_web_features(sh, ".")
.context("Failed to check web features for main crate")?
{
Some(features) => {
let mut cmd = cmd!(sh, "{cargo} run").args(["--no-default-features"]);
if !features.is_empty() {
cmd = cmd.args(["--features", &features]);
}
cmd.args(["--profile", profile])
.args(["--"])
.args(&flags.args)
.run()
.map_err(anyhow::Error::new)
},
None => {
// Main crate doesn't have web_server_capability, run normally
cmd!(sh, "{cargo} run")
.args(["--profile", profile])
.args(["--"])
.args(&flags.args)
.run()
.map_err(anyhow::Error::new)
},
}
} else {
cmd!(sh, "{cargo} run")
.args(["--profile", profile])
.args(["--"])
.args(&flags.args)
.run()
.map_err(anyhow::Error::new)
}
})
.with_context(|| err_context(&flags))
}
}
/// Bundle all distributable content to `target/dist`.
///
/// This includes the optimized zellij executable from the [`install`] pipeline, the man page, the
/// `.desktop` file and the application logo.
pub fn dist(sh: &Shell, _flags: flags::Dist) -> anyhow::Result<()> {
let err_context = || "failed to run pipeline 'dist'";
sh.change_dir(crate::project_root());
if sh.path_exists("target/dist") {
sh.remove_path("target/dist").with_context(err_context)?;
}
sh.create_dir("target/dist")
.map_err(anyhow::Error::new)
.and_then(|_| {
install(
sh,
flags::Install {
destination: crate::project_root().join("./target/dist/zellij"),
no_web: false,
},
)
})
.with_context(err_context)?;
sh.create_dir("target/dist/man")
.and_then(|_| sh.copy_file("assets/man/zellij.1", "target/dist/man/zellij.1"))
.and_then(|_| sh.copy_file("assets/zellij.desktop", "target/dist/zellij.desktop"))
.and_then(|_| sh.copy_file("assets/logo.png", "target/dist/logo.png"))
.with_context(err_context)
}
/// Actions for the user to choose from to resolve publishing errors/conflicts.
enum UserAction {
Retry,
Abort,
Ignore,
}
/// Make a zellij release and publish all crates.
pub fn publish(sh: &Shell, flags: flags::Publish) -> anyhow::Result<()> {
let err_context = "failed to publish zellij";
// Process flags
let dry_run = if flags.dry_run {
Some("--dry-run")
} else {
None
};
let remote = flags.git_remote.unwrap_or("origin".into());
let registry = if let Some(ref registry) = flags.cargo_registry {
Some(format!(
"--registry={}",
registry
.clone()
.into_string()
.map_err(|registry| anyhow::Error::msg(format!(
"failed to convert '{:?}' to valid registry name",
registry
)))
.context(err_context)?
))
} else {
None
};
let registry = registry.as_ref();
if flags.no_push && flags.cargo_registry.is_none() {
anyhow::bail!("flag '--no-push' can only be used with '--cargo-registry'");
}
sh.change_dir(crate::project_root());
let cargo = crate::cargo().context(err_context)?;
let project_dir = crate::project_root();
let manifest = sh
.read_file(project_dir.join("Cargo.toml"))
.context(err_context)?
.parse::<toml::Value>()
.context(err_context)?;
// Version of the core crate
let version = manifest
.get("workspace")
.and_then(|workspace| workspace.get("package"))
.and_then(|package| package["version"].as_str())
.context("failed to read package version from manifest")
.context(err_context)?;
let mut skip_build = false;
if cmd!(sh, "git tag -l")
.read()
.context(err_context)?
.contains(version)
{
println!();
println!("Git tag 'v{version}' is already present.");
println!("If this is a mistake, delete it with: git tag -d 'v{version}'");
println!("Skip build phase and continue to publish? [y/n]");
let stdin = std::io::stdin();
loop {
let mut buffer = String::new();
stdin.read_line(&mut buffer).context(err_context)?;
match buffer.trim_end() {
"y" | "Y" => {
skip_build = true;
break;
},
"n" | "N" => {
skip_build = false;
break;
},
_ => {
println!(" --> Unknown input '{buffer}', ignoring...");
println!();
println!("Skip build phase and continue to publish? [y/n]");
},
}
}
}
if !skip_build {
// Clean project
cmd!(sh, "{cargo} clean").run().context(err_context)?;
// Build plugins
build::build(
sh,
flags::Build {
release: true,
no_plugins: false,
plugins_only: true,
no_web: false,
},
)
.context(err_context)?;
// Update default config
sh.copy_file(
project_dir
.join("zellij-utils")
.join("assets")
.join("config")
.join("default.kdl"),
project_dir.join("example").join("default.kdl"),
)
.context(err_context)?;
// Commit changes
cmd!(sh, "git commit -aem")
.arg(format!("chore(release): v{}", version))
.run()
.context(err_context)?;
// Tag release
cmd!(sh, "git tag --annotate --message")
.arg(format!("Version {}", version))
.arg(format!("v{}", version))
.run()
.context(err_context)?;
}
let closure = || -> anyhow::Result<()> {
// Push commit and tag
if flags.dry_run {
println!("Skipping push due to dry-run");
} else if flags.no_push {
println!("Skipping push due to no-push");
} else {
cmd!(sh, "git push --atomic {remote} main v{version}")
.run()
.context(err_context)?;
}
// Publish all the crates
for WorkspaceMember { crate_name, .. } in crate::workspace_members().iter() {
if crate_name.contains("plugin") || crate_name.contains("xtask") {
continue;
}
let _pd = sh.push_dir(project_dir.join(crate_name));
loop {
let msg = format!(">> Publishing '{crate_name}'");
crate::status(&msg);
println!("{}", msg);
let more_args = match *crate_name {
// This is needed for zellij to pick up the plugins from the assets included in
// the released zellij-utils binary
"." => Some("--no-default-features"),
_ => None,
};
if let Err(err) = cmd!(
sh,
"{cargo} publish --locked {registry...} {more_args...} {dry_run...}"
)
.run()
.context(err_context)
{
println!();
println!("Publishing crate '{crate_name}' failed with error:");
println!("{:?}", err);
println!();
println!("Please choose what to do: [r]etry/[a]bort/[i]gnore");
let stdin = std::io::stdin();
let action;
loop {
let mut buffer = String::new();
stdin.read_line(&mut buffer).context(err_context)?;
match buffer.trim_end() {
"r" | "R" => {
action = UserAction::Retry;
break;
},
"a" | "A" => {
action = UserAction::Abort;
break;
},
"i" | "I" => {
action = UserAction::Ignore;
break;
},
_ => {
println!(" --> Unknown input '{buffer}', ignoring...");
println!();
println!("Please choose what to do: [r]etry/[a]bort/[i]gnore");
},
}
}
match action {
UserAction::Retry => continue,
UserAction::Ignore => break,
UserAction::Abort => {
eprintln!("Aborting publish for crate '{crate_name}'");
return Err::<(), _>(err);
},
}
} else {
// publish successful, continue to next crate
break;
}
}
}
println!();
println!(" +-----------------------------------------------+");
println!(" | PRAISE THE DEVS, WE HAVE A NEW ZELLIJ RELEASE |");
println!(" +-----------------------------------------------+");
Ok(())
};
// We run this in a closure so that a failure in any of the commands doesn't abort the whole
// program. When dry-running we need to undo the release commit first!
let result = closure();
if flags.dry_run && !skip_build {
cmd!(sh, "git reset --hard HEAD~1")
.run()
.context(err_context)?;
}
result
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/xtask/src/main.rs | xtask/src/main.rs | //! See <https://github.com/matklad/cargo-xtask/>.
//!
//! This binary defines various auxiliary build commands, which are not expressible with just
//! `cargo`. Notably, it provides tests via `cargo test -p xtask` for code generation and `cargo
//! xtask install` for installation of rust-analyzer server and client.
//!
//! This binary is integrated into the `cargo` command line by using an alias in `.cargo/config`.
mod build;
mod ci;
mod clippy;
mod dist;
mod flags;
mod format;
mod metadata;
mod pipelines;
mod test;
use anyhow::Context;
use std::{
env,
path::{Path, PathBuf},
sync::OnceLock,
time::Instant,
};
use xshell::Shell;
pub struct WorkspaceMember {
crate_name: &'static str,
build: bool,
}
fn workspace_members() -> &'static Vec<WorkspaceMember> {
static WORKSPACE_MEMBERS: OnceLock<Vec<WorkspaceMember>> = OnceLock::new();
WORKSPACE_MEMBERS.get_or_init(|| {
vec![
WorkspaceMember {
crate_name: "default-plugins/compact-bar",
build: true,
},
WorkspaceMember {
crate_name: "default-plugins/status-bar",
build: true,
},
WorkspaceMember {
crate_name: "default-plugins/strider",
build: true,
},
WorkspaceMember {
crate_name: "default-plugins/tab-bar",
build: true,
},
WorkspaceMember {
crate_name: "default-plugins/fixture-plugin-for-tests",
build: true,
},
WorkspaceMember {
crate_name: "default-plugins/session-manager",
build: true,
},
WorkspaceMember {
crate_name: "default-plugins/configuration",
build: true,
},
WorkspaceMember {
crate_name: "default-plugins/plugin-manager",
build: true,
},
WorkspaceMember {
crate_name: "default-plugins/about",
build: true,
},
WorkspaceMember {
crate_name: "default-plugins/multiple-select",
build: true,
},
WorkspaceMember {
crate_name: "default-plugins/share",
build: true,
},
WorkspaceMember {
crate_name: "default-plugins/sequence",
build: true,
},
WorkspaceMember {
crate_name: "zellij-utils",
build: false,
},
WorkspaceMember {
crate_name: "zellij-tile-utils",
build: false,
},
WorkspaceMember {
crate_name: "zellij-tile",
build: false,
},
WorkspaceMember {
crate_name: "zellij-client",
build: false,
},
WorkspaceMember {
crate_name: "zellij-server",
build: false,
},
WorkspaceMember {
crate_name: ".",
build: true,
},
]
})
}
fn main() -> anyhow::Result<()> {
let shell = &Shell::new()?;
let flags = flags::Xtask::from_env()?;
let now = Instant::now();
match flags.subcommand {
flags::XtaskCmd::Deprecated(_flags) => deprecation_notice(),
flags::XtaskCmd::Dist(flags) => pipelines::dist(shell, flags),
flags::XtaskCmd::Build(flags) => build::build(shell, flags),
flags::XtaskCmd::Clippy(flags) => clippy::clippy(shell, flags),
flags::XtaskCmd::Format(flags) => format::format(shell, flags),
flags::XtaskCmd::Test(flags) => test::test(shell, flags),
flags::XtaskCmd::Manpage(_flags) => build::manpage(shell),
// Pipelines
// These are composite commands, made up of multiple "stages" defined above.
flags::XtaskCmd::Make(flags) => pipelines::make(shell, flags),
flags::XtaskCmd::Install(flags) => pipelines::install(shell, flags),
flags::XtaskCmd::Run(flags) => pipelines::run(shell, flags),
flags::XtaskCmd::Ci(flags) => ci::main(shell, flags),
flags::XtaskCmd::Publish(flags) => pipelines::publish(shell, flags),
}?;
let elapsed = now.elapsed().as_secs();
status(&format!("xtask (done after {} s)", elapsed));
println!("\n\n>> Command took {} s", elapsed);
Ok(())
}
fn project_root() -> PathBuf {
Path::new(
&env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| env!("CARGO_MANIFEST_DIR").to_owned()),
)
.ancestors()
.nth(1)
.unwrap()
.to_path_buf()
}
fn asset_dir() -> PathBuf {
crate::project_root().join("zellij-utils").join("assets")
}
pub fn cargo() -> anyhow::Result<PathBuf> {
std::env::var_os("CARGO")
.map_or_else(|| which::which("cargo"), |exe| Ok(PathBuf::from(exe)))
.context("Couldn't find 'cargo' executable")
}
// Set terminal title to 'msg'
pub fn status(msg: &str) {
print!("\u{1b}]0;{}\u{07}", msg);
}
fn deprecation_notice() -> anyhow::Result<()> {
Err(anyhow::anyhow!(
" !!! cargo make has been deprecated by zellij !!!
Our build system is now `cargo xtask`. Don't worry, you won't have to install
anything!
- To get an overview of the new build tasks, run `cargo xtask --help`
- Quick compatibility table:
| cargo make task | cargo xtask equivalent |
| ------------------------------- | ----------------------------- |
| make | xtask |
| make format | xtask format |
| make build | xtask build |
| make test | xtask test |
| make run | xtask run |
| make run -l strider | xtask run -- -l strider |
| make clippy | xtask clippy |
| make clippy -W clippy::pedantic | N/A |
| make install /path/to/binary | xtask install /path/to/binary |
| make publish | xtask publish |
| make manpage | xtask manpage |
In order to disable xtask during the transitioning period: Delete/comment the
`[alias]` section in `.cargo/config.toml` and use `cargo make` as before.
If you're unhappy with `xtask` and decide to disable it, please tell us why so
we can discuss this before making it final for the next release. Thank you!
"
))
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/xtask/src/metadata.rs | xtask/src/metadata.rs | //! Helper functions for querying cargo metadata
use anyhow::Context;
use serde_json::Value;
use xshell::{cmd, Shell};
/// Get cargo metadata for the workspace
pub fn get_cargo_metadata(sh: &Shell) -> anyhow::Result<Value> {
let cargo = crate::cargo().context("Failed to find cargo executable")?;
let metadata_json = cmd!(sh, "{cargo} metadata --format-version 1 --no-deps")
.read()
.context("Failed to run cargo metadata")?;
serde_json::from_str(&metadata_json).context("Failed to parse cargo metadata JSON")
}
/// Get the appropriate features string for a crate when --no-web is enabled
/// Returns Some(features_string) if the crate has web_server_capability and should use --no-default-features
/// Returns None if the crate doesn't have web_server_capability and should use normal build
pub fn get_no_web_features(sh: &Shell, crate_name: &str) -> anyhow::Result<Option<String>> {
let metadata = get_cargo_metadata(sh)?;
let packages = metadata["packages"]
.as_array()
.context("Expected packages array in metadata")?;
// First, find the main zellij crate to get the default features
let mut main_default_features = Vec::new();
for package in packages {
let name = package["name"]
.as_str()
.context("Expected package name as string")?;
if name == "zellij" {
let features = package["features"]
.as_object()
.context("Expected features object")?;
if let Some(default_features) = features.get("default").and_then(|v| v.as_array()) {
for feature_value in default_features {
if let Some(feature_name) = feature_value.as_str() {
if feature_name != "web_server_capability" {
main_default_features.push(feature_name);
}
}
}
}
break;
}
}
// Now check if the target crate has web_server_capability and filter features
for package in packages {
let name = package["name"]
.as_str()
.context("Expected package name as string")?;
// Handle the root crate case
let matches_crate = if crate_name == "." {
name == "zellij"
} else {
name == crate_name
};
if matches_crate {
let features = package["features"]
.as_object()
.context("Expected features object")?;
// Check if this crate has web_server_capability feature
if !features.contains_key("web_server_capability") {
return Ok(None);
}
// This crate has web_server_capability, so we need to use --no-default-features
// Only include features that this crate actually has
let mut applicable_features = Vec::new();
for feature_name in &main_default_features {
if features.contains_key(*feature_name) {
applicable_features.push(*feature_name);
}
}
// Return the feature string (even if empty) to indicate we should use --no-default-features
return Ok(Some(applicable_features.join(" ")));
}
}
Ok(None)
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/xtask/src/clippy.rs | xtask/src/clippy.rs | //! Handle running `cargo clippy` on the sources.
use crate::{build, flags, WorkspaceMember};
use anyhow::Context;
use std::path::{Path, PathBuf};
use xshell::{cmd, Shell};
pub fn clippy(sh: &Shell, _flags: flags::Clippy) -> anyhow::Result<()> {
let _pd = sh.push_dir(crate::project_root());
build::build(
sh,
flags::Build {
release: false,
no_plugins: false,
plugins_only: true,
no_web: false,
},
)
.context("failed to run task 'clippy'")?;
let cargo = check_clippy()
.and_then(|_| crate::cargo())
.context("failed to run task 'clippy'")?;
for WorkspaceMember { crate_name, .. } in crate::workspace_members().iter() {
let _pd = sh.push_dir(Path::new(crate_name));
// Tell the user where we are now
println!();
let msg = format!(">> Running clippy on '{crate_name}'");
crate::status(&msg);
println!("{}", msg);
cmd!(sh, "{cargo} clippy --all-targets --all-features")
.run()
.with_context(|| format!("failed to run task 'clippy' on '{crate_name}'"))?;
}
Ok(())
}
fn check_clippy() -> anyhow::Result<PathBuf> {
which::which("cargo-clippy").context(
"Couldn't find 'clippy' executable. Please install it with `rustup component add clippy`",
)
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/os_input_output.rs | zellij-server/src/os_input_output.rs | use crate::{panes::PaneId, ClientId};
use async_std::{fs::File as AsyncFile, io::ReadExt, os::unix::io::FromRawFd};
use interprocess::local_socket::LocalSocketStream;
use nix::{
pty::{openpty, OpenptyResult, Winsize},
sys::{
signal::{kill, Signal},
termios,
},
unistd,
};
use async_std;
use interprocess;
use libc;
use nix;
use signal_hook;
use signal_hook::consts::*;
use sysinfo::{ProcessExt, ProcessRefreshKind, System, SystemExt};
use tempfile::tempfile;
use zellij_utils::{
channels,
channels::TrySendError,
data::Palette,
errors::prelude::*,
input::command::{RunCommand, TerminalAction},
ipc::{
ClientToServerMsg, ExitReason, IpcReceiverWithContext, IpcSenderWithContext,
ServerToClientMsg,
},
shared::default_palette,
};
use std::{
collections::{BTreeMap, BTreeSet, HashMap},
env,
fs::File,
io::Write,
os::unix::{io::RawFd, process::CommandExt},
path::PathBuf,
process::{Child, Command},
sync::{Arc, Mutex},
};
pub use async_trait::async_trait;
pub use nix::unistd::Pid;
fn set_terminal_size_using_fd(
fd: RawFd,
columns: u16,
rows: u16,
width_in_pixels: Option<u16>,
height_in_pixels: Option<u16>,
) {
// TODO: do this with the nix ioctl
use libc::ioctl;
use libc::TIOCSWINSZ;
let ws_xpixel = width_in_pixels.unwrap_or(0);
let ws_ypixel = height_in_pixels.unwrap_or(0);
let winsize = Winsize {
ws_col: columns,
ws_row: rows,
ws_xpixel,
ws_ypixel,
};
// TIOCGWINSZ is an u32, but the second argument to ioctl is u64 on
// some platforms. When checked on Linux, clippy will complain about
// useless conversion.
#[allow(clippy::useless_conversion)]
unsafe {
ioctl(fd, TIOCSWINSZ.into(), &winsize)
};
}
/// Handle some signals for the child process. This will loop until the child
/// process exits.
fn handle_command_exit(mut child: Child) -> Result<Option<i32>> {
let id = child.id();
let err_context = || {
format!(
"failed to handle signals and command exit for child process pid {}",
id
)
};
// returns the exit status, if any
let mut should_exit = false;
let mut attempts = 3;
let mut signals =
signal_hook::iterator::Signals::new(&[SIGINT, SIGTERM]).with_context(err_context)?;
'handle_exit: loop {
// test whether the child process has exited
match child.try_wait() {
Ok(Some(status)) => {
// if the child process has exited, break outside of the loop
// and exit this function
// TODO: handle errors?
break 'handle_exit Ok(status.code());
},
Ok(None) => {
::std::thread::sleep(::std::time::Duration::from_millis(10));
},
Err(e) => panic!("error attempting to wait: {}", e),
}
if !should_exit {
for signal in signals.pending() {
if signal == SIGINT || signal == SIGTERM {
should_exit = true;
}
}
} else if attempts > 0 {
// let's try nicely first...
attempts -= 1;
kill(Pid::from_raw(child.id() as i32), Some(Signal::SIGTERM))
.with_context(err_context)?;
continue;
} else {
// when I say whoa, I mean WHOA!
let _ = child.kill();
break 'handle_exit Ok(None);
}
}
}
fn command_exists(cmd: &RunCommand) -> bool {
let command = &cmd.command;
match cmd.cwd.as_ref() {
Some(cwd) => {
let full_command = cwd.join(&command);
if full_command.exists() && full_command.is_file() {
return true;
}
},
None => {
if command.exists() && command.is_file() {
return true;
}
},
}
if let Some(paths) = env::var_os("PATH") {
for path in env::split_paths(&paths) {
let full_command = path.join(command);
if full_command.exists() && full_command.is_file() {
return true;
}
}
}
false
}
fn handle_openpty(
open_pty_res: OpenptyResult,
cmd: RunCommand,
quit_cb: Box<dyn Fn(PaneId, Option<i32>, RunCommand) + Send>, // u32 is the exit status
terminal_id: u32,
) -> Result<(RawFd, RawFd)> {
let err_context = |cmd: &RunCommand| {
format!(
"failed to open PTY for command '{}'",
cmd.command.to_string_lossy().to_string()
)
};
// primary side of pty and child fd
let pid_primary = open_pty_res.master;
let pid_secondary = open_pty_res.slave;
if command_exists(&cmd) {
let mut child = unsafe {
let cmd = cmd.clone();
let command = &mut Command::new(cmd.command);
if let Some(current_dir) = cmd.cwd {
if current_dir.exists() && current_dir.is_dir() {
command.current_dir(current_dir);
} else {
log::error!(
"Failed to set CWD for new pane. '{}' does not exist or is not a folder",
current_dir.display()
);
}
}
command
.args(&cmd.args)
.env("ZELLIJ_PANE_ID", &format!("{}", terminal_id))
.pre_exec(move || -> std::io::Result<()> {
if libc::login_tty(pid_secondary) != 0 {
panic!("failed to set controlling terminal");
}
close_fds::close_open_fds(3, &[]);
Ok(())
})
.spawn()
.expect("failed to spawn")
};
let child_id = child.id();
std::thread::spawn(move || {
child.wait().with_context(|| err_context(&cmd)).fatal();
let exit_status = handle_command_exit(child)
.with_context(|| err_context(&cmd))
.fatal();
let _ = nix::unistd::close(pid_secondary);
quit_cb(PaneId::Terminal(terminal_id), exit_status, cmd);
});
Ok((pid_primary, child_id as RawFd))
} else {
Err(ZellijError::CommandNotFound {
terminal_id,
command: cmd.command.to_string_lossy().to_string(),
})
.with_context(|| err_context(&cmd))
}
}
/// Spawns a new terminal from the parent terminal with [`termios`](termios::Termios)
/// `orig_termios`.
///
fn handle_terminal(
cmd: RunCommand,
failover_cmd: Option<RunCommand>,
orig_termios: Option<termios::Termios>,
quit_cb: Box<dyn Fn(PaneId, Option<i32>, RunCommand) + Send>,
terminal_id: u32,
) -> Result<(RawFd, RawFd)> {
let err_context = || "failed to spawn child terminal".to_string();
// Create a pipe to allow the child the communicate the shell's pid to its
// parent.
match openpty(None, &orig_termios) {
Ok(open_pty_res) => handle_openpty(open_pty_res, cmd, quit_cb, terminal_id),
Err(e) => match failover_cmd {
Some(failover_cmd) => {
handle_terminal(failover_cmd, None, orig_termios, quit_cb, terminal_id)
.with_context(err_context)
},
None => Err::<(i32, i32), _>(e)
.context("failed to start pty")
.with_context(err_context)
.to_log(),
},
}
}
// this is a utility method to separate the arguments from a pathbuf before we turn it into a
// Command. eg. "/usr/bin/vim -e" ==> "/usr/bin/vim" + "-e" (the latter will be pushed to args)
fn separate_command_arguments(command: &mut PathBuf, args: &mut Vec<String>) {
let mut parts = vec![];
let mut current_part = String::new();
for part in command.display().to_string().split_ascii_whitespace() {
current_part.push_str(part);
if current_part.ends_with('\\') {
let _ = current_part.pop();
current_part.push(' ');
} else {
let current_part = std::mem::replace(&mut current_part, String::new());
parts.push(current_part);
}
}
if !parts.is_empty() {
*command = PathBuf::from(parts.remove(0));
args.append(&mut parts);
}
}
/// If a [`TerminalAction::OpenFile(file)`] is given, the text editor specified by environment variable `EDITOR`
/// (or `VISUAL`, if `EDITOR` is not set) will be started in the new terminal, with the given
/// file open.
/// If [`TerminalAction::RunCommand(RunCommand)`] is given, the command will be started
/// in the new terminal.
/// If None is given, the shell specified by environment variable `SHELL` will
/// be started in the new terminal.
///
/// # Panics
///
/// This function will panic if both the `EDITOR` and `VISUAL` environment variables are not
/// set.
fn spawn_terminal(
terminal_action: TerminalAction,
orig_termios: Option<termios::Termios>,
quit_cb: Box<dyn Fn(PaneId, Option<i32>, RunCommand) + Send>, // u32 is the exit_status
default_editor: Option<PathBuf>,
terminal_id: u32,
) -> Result<(RawFd, RawFd)> {
// returns the terminal_id, the primary fd and the
// secondary fd
let mut failover_cmd_args = None;
let cmd = match terminal_action {
TerminalAction::OpenFile(mut payload) => {
if payload.path.is_relative() {
if let Some(cwd) = payload.cwd.as_ref() {
payload.path = cwd.join(payload.path);
}
}
let mut command = default_editor.unwrap_or_else(|| {
PathBuf::from(
env::var("EDITOR")
.unwrap_or_else(|_| env::var("VISUAL").unwrap_or_else(|_| "vi".into())),
)
});
let mut args = vec![];
if !command.is_dir() {
separate_command_arguments(&mut command, &mut args);
}
let file_to_open = payload
.path
.into_os_string()
.into_string()
.expect("Not valid Utf8 Encoding");
if let Some(line_number) = payload.line_number {
if command.ends_with("vim")
|| command.ends_with("nvim")
|| command.ends_with("emacs")
|| command.ends_with("nano")
|| command.ends_with("kak")
{
failover_cmd_args = Some(vec![file_to_open.clone()]);
args.push(format!("+{}", line_number));
args.push(file_to_open);
} else if command.ends_with("hx") || command.ends_with("helix") {
// at the time of writing, helix only supports this syntax
// and it might be a good idea to leave this here anyway
// to keep supporting old versions
args.push(format!("{}:{}", file_to_open, line_number));
} else {
args.push(file_to_open);
}
} else {
args.push(file_to_open);
}
RunCommand {
command,
args,
cwd: payload.cwd,
hold_on_close: false,
hold_on_start: false,
..Default::default()
}
},
TerminalAction::RunCommand(command) => command,
};
let failover_cmd = if let Some(failover_cmd_args) = failover_cmd_args {
let mut cmd = cmd.clone();
cmd.args = failover_cmd_args;
Some(cmd)
} else {
None
};
handle_terminal(cmd, failover_cmd, orig_termios, quit_cb, terminal_id)
}
// The ClientSender is in charge of sending messages to the client on a special thread
// This is done so that when the unix socket buffer is full, we won't block the entire router
// thread
// When the above happens, the ClientSender buffers messages in hopes that the congestion will be
// freed until we runs out of buffer space.
// If we run out of buffer space, we bubble up an error sot hat the router thread will give up on
// this client and we'll stop sending messages to it.
// If the client ever becomes responsive again, we'll send one final "Buffer full" message so it
// knows what happened.
#[derive(Clone)]
struct ClientSender {
client_id: ClientId,
client_buffer_sender: channels::Sender<ServerToClientMsg>,
}
impl ClientSender {
pub fn new(client_id: ClientId, mut sender: IpcSenderWithContext<ServerToClientMsg>) -> Self {
// FIXME(hartan): This queue is responsible for buffering messages between server and
// client. If it fills up, the client is disconnected with a "Buffer full" sort of error
// message. It was previously found to be too small (with depth 50), so it was increased to
// 5000 instead. This decision was made because it was found that a queue of depth 5000
// doesn't cause noticable increase in RAM usage, but there's no reason beyond that. If in
// the future this is found to fill up too quickly again, it may be worthwhile to increase
// the size even further (or better yet, implement a redraw-on-backpressure mechanism).
// We, the zellij maintainers, have decided against an unbounded
// queue for the time being because we want to prevent e.g. the whole session being killed
// (by OOM-killers or some other mechanism) just because a single client doesn't respond.
let (client_buffer_sender, client_buffer_receiver) = channels::bounded(5000);
std::thread::spawn(move || {
let err_context = || format!("failed to send message to client {client_id}");
for msg in client_buffer_receiver.iter() {
sender
.send_server_msg(msg)
.with_context(err_context)
.non_fatal();
}
let _ = sender.send_server_msg(ServerToClientMsg::Exit {
exit_reason: ExitReason::Disconnect,
});
});
ClientSender {
client_id,
client_buffer_sender,
}
}
pub fn send_or_buffer(&self, msg: ServerToClientMsg) -> Result<()> {
let err_context = || {
format!(
"failed to send or buffer message for client {}",
self.client_id
)
};
self.client_buffer_sender
.try_send(msg)
.or_else(|err| {
if let TrySendError::Full(_) = err {
log::warn!(
"client {} is processing server messages too slow",
self.client_id
);
}
Err(err)
})
.with_context(err_context)
}
}
#[derive(Clone)]
pub struct ServerOsInputOutput {
orig_termios: Arc<Mutex<Option<termios::Termios>>>,
client_senders: Arc<Mutex<HashMap<ClientId, ClientSender>>>,
terminal_id_to_raw_fd: Arc<Mutex<BTreeMap<u32, Option<RawFd>>>>, // A value of None means the
// terminal_id exists but is
// not connected to an fd (eg.
// a command pane with a
// non-existing command)
cached_resizes: Arc<Mutex<Option<BTreeMap<u32, (u16, u16, Option<u16>, Option<u16>)>>>>, // <terminal_id, (cols, rows, width_in_pixels, height_in_pixels)>
}
// async fn in traits is not supported by rust, so dtolnay's excellent async_trait macro is being
// used. See https://smallcultfollowing.com/babysteps/blog/2019/10/26/async-fn-in-traits-are-hard/
#[async_trait]
pub trait AsyncReader: Send + Sync {
async fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error>;
}
/// An `AsyncReader` that wraps a `RawFd`
struct RawFdAsyncReader {
fd: async_std::fs::File,
}
impl RawFdAsyncReader {
fn new(fd: RawFd) -> RawFdAsyncReader {
RawFdAsyncReader {
// The supplied `RawFd` is consumed by the created `RawFdAsyncReader`, closing it when dropped
fd: unsafe { AsyncFile::from_raw_fd(fd) },
}
}
}
#[async_trait]
impl AsyncReader for RawFdAsyncReader {
async fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> {
self.fd.read(buf).await
}
}
/// The `ServerOsApi` trait represents an abstract interface to the features of an operating system that
/// Zellij server requires.
pub trait ServerOsApi: Send + Sync {
fn set_terminal_size_using_terminal_id(
&self,
id: u32,
cols: u16,
rows: u16,
width_in_pixels: Option<u16>,
height_in_pixels: Option<u16>,
) -> Result<()>;
/// Spawn a new terminal, with a terminal action. The returned tuple contains the master file
/// descriptor of the forked pseudo terminal and a [ChildId] struct containing process id's for
/// the forked child process.
fn spawn_terminal(
&self,
terminal_action: TerminalAction,
quit_cb: Box<dyn Fn(PaneId, Option<i32>, RunCommand) + Send>, // u32 is the exit status
default_editor: Option<PathBuf>,
) -> Result<(u32, RawFd, RawFd)>;
// reserves a terminal id without actually opening a terminal
fn reserve_terminal_id(&self) -> Result<u32> {
unimplemented!()
}
/// Read bytes from the standard output of the virtual terminal referred to by `fd`.
fn read_from_tty_stdout(&self, fd: RawFd, buf: &mut [u8]) -> Result<usize>;
/// Creates an `AsyncReader` that can be used to read from `fd` in an async context
fn async_file_reader(&self, fd: RawFd) -> Box<dyn AsyncReader>;
/// Write bytes to the standard input of the virtual terminal referred to by `fd`.
fn write_to_tty_stdin(&self, terminal_id: u32, buf: &[u8]) -> Result<usize>;
/// Wait until all output written to the object referred to by `fd` has been transmitted.
fn tcdrain(&self, terminal_id: u32) -> Result<()>;
/// Terminate the process with process ID `pid`. (SIGTERM)
fn kill(&self, pid: Pid) -> Result<()>;
/// Terminate the process with process ID `pid`. (SIGKILL)
fn force_kill(&self, pid: Pid) -> Result<()>;
/// Send SIGINT to the process with process ID `pid`
fn send_sigint(&self, pid: Pid) -> Result<()>;
/// Returns a [`Box`] pointer to this [`ServerOsApi`] struct.
fn box_clone(&self) -> Box<dyn ServerOsApi>;
fn send_to_client(&self, client_id: ClientId, msg: ServerToClientMsg) -> Result<()>;
fn new_client(
&mut self,
client_id: ClientId,
stream: LocalSocketStream,
) -> Result<IpcReceiverWithContext<ClientToServerMsg>>;
fn remove_client(&mut self, client_id: ClientId) -> Result<()>;
fn load_palette(&self) -> Palette;
/// Returns the current working directory for a given pid
fn get_cwd(&self, pid: Pid) -> Option<PathBuf>;
/// Returns the current working directory for multiple pids
fn get_cwds(&self, _pids: Vec<Pid>) -> (HashMap<Pid, PathBuf>, HashMap<Pid, Vec<String>>) {
(HashMap::new(), HashMap::new())
}
/// Get a list of all running commands by their parent process id
fn get_all_cmds_by_ppid(&self, _post_hook: &Option<String>) -> HashMap<String, Vec<String>> {
HashMap::new()
}
/// Writes the given buffer to a string
fn write_to_file(&mut self, buf: String, file: Option<String>) -> Result<()>;
fn re_run_command_in_terminal(
&self,
terminal_id: u32,
run_command: RunCommand,
quit_cb: Box<dyn Fn(PaneId, Option<i32>, RunCommand) + Send>, // u32 is the exit status
) -> Result<(RawFd, RawFd)>;
fn clear_terminal_id(&self, terminal_id: u32) -> Result<()>;
fn cache_resizes(&mut self) {}
fn apply_cached_resizes(&mut self) {}
}
impl ServerOsApi for ServerOsInputOutput {
fn set_terminal_size_using_terminal_id(
&self,
id: u32,
cols: u16,
rows: u16,
width_in_pixels: Option<u16>,
height_in_pixels: Option<u16>,
) -> Result<()> {
let err_context = || {
format!(
"failed to set terminal id {} to size ({}, {})",
id, rows, cols
)
};
if let Some(cached_resizes) = self.cached_resizes.lock().unwrap().as_mut() {
cached_resizes.insert(id, (cols, rows, width_in_pixels, height_in_pixels));
return Ok(());
}
match self
.terminal_id_to_raw_fd
.lock()
.to_anyhow()
.with_context(err_context)?
.get(&id)
{
Some(Some(fd)) => {
if cols > 0 && rows > 0 {
set_terminal_size_using_fd(*fd, cols, rows, width_in_pixels, height_in_pixels);
}
},
_ => {
Err::<(), _>(anyhow!("failed to find terminal fd for id {id}"))
.with_context(err_context)
.non_fatal();
},
}
Ok(())
}
#[allow(unused_assignments)]
fn spawn_terminal(
&self,
terminal_action: TerminalAction,
quit_cb: Box<dyn Fn(PaneId, Option<i32>, RunCommand) + Send>, // u32 is the exit status
default_editor: Option<PathBuf>,
) -> Result<(u32, RawFd, RawFd)> {
let err_context = || "failed to spawn terminal".to_string();
let orig_termios = self
.orig_termios
.lock()
.to_anyhow()
.with_context(err_context)?;
let terminal_id = self
.terminal_id_to_raw_fd
.lock()
.to_anyhow()
.with_context(err_context)?
.keys()
.copied()
.collect::<BTreeSet<u32>>()
.last()
.map(|l| l + 1)
.or(Some(0));
match terminal_id {
Some(terminal_id) => {
self.terminal_id_to_raw_fd
.lock()
.to_anyhow()
.with_context(err_context)?
.insert(terminal_id, None);
spawn_terminal(
terminal_action,
orig_termios.clone(),
quit_cb,
default_editor,
terminal_id,
)
.and_then(|(pid_primary, pid_secondary)| {
self.terminal_id_to_raw_fd
.lock()
.to_anyhow()?
.insert(terminal_id, Some(pid_primary));
Ok((terminal_id, pid_primary, pid_secondary))
})
.with_context(err_context)
},
None => Err(anyhow!("no more terminal IDs left to allocate")),
}
}
#[allow(unused_assignments)]
fn reserve_terminal_id(&self) -> Result<u32> {
let err_context = || "failed to reserve a terminal ID".to_string();
let terminal_id = self
.terminal_id_to_raw_fd
.lock()
.to_anyhow()
.with_context(err_context)?
.keys()
.copied()
.collect::<BTreeSet<u32>>()
.last()
.map(|l| l + 1)
.or(Some(0));
match terminal_id {
Some(terminal_id) => {
self.terminal_id_to_raw_fd
.lock()
.to_anyhow()
.with_context(err_context)?
.insert(terminal_id, None);
Ok(terminal_id)
},
None => Err(anyhow!("no more terminal IDs available")),
}
}
fn read_from_tty_stdout(&self, fd: RawFd, buf: &mut [u8]) -> Result<usize> {
unistd::read(fd, buf).with_context(|| format!("failed to read stdout of raw FD {}", fd))
}
fn async_file_reader(&self, fd: RawFd) -> Box<dyn AsyncReader> {
Box::new(RawFdAsyncReader::new(fd))
}
fn write_to_tty_stdin(&self, terminal_id: u32, buf: &[u8]) -> Result<usize> {
let err_context = || format!("failed to write to stdin of TTY ID {}", terminal_id);
match self
.terminal_id_to_raw_fd
.lock()
.to_anyhow()
.with_context(err_context)?
.get(&terminal_id)
{
Some(Some(fd)) => unistd::write(*fd, buf).with_context(err_context),
_ => Err(anyhow!("could not find raw file descriptor")).with_context(err_context),
}
}
fn tcdrain(&self, terminal_id: u32) -> Result<()> {
let err_context = || format!("failed to tcdrain to TTY ID {}", terminal_id);
match self
.terminal_id_to_raw_fd
.lock()
.to_anyhow()
.with_context(err_context)?
.get(&terminal_id)
{
Some(Some(fd)) => termios::tcdrain(*fd).with_context(err_context),
_ => Err(anyhow!("could not find raw file descriptor")).with_context(err_context),
}
}
fn box_clone(&self) -> Box<dyn ServerOsApi> {
Box::new((*self).clone())
}
fn kill(&self, pid: Pid) -> Result<()> {
let _ = kill(pid, Some(Signal::SIGHUP));
Ok(())
}
fn force_kill(&self, pid: Pid) -> Result<()> {
let _ = kill(pid, Some(Signal::SIGKILL));
Ok(())
}
fn send_sigint(&self, pid: Pid) -> Result<()> {
let _ = kill(pid, Some(Signal::SIGINT));
Ok(())
}
fn send_to_client(&self, client_id: ClientId, msg: ServerToClientMsg) -> Result<()> {
let err_context = || format!("failed to send message to client {client_id}");
if let Some(sender) = self
.client_senders
.lock()
.to_anyhow()
.with_context(err_context)?
.get_mut(&client_id)
{
sender.send_or_buffer(msg).with_context(err_context)
} else {
Ok(())
}
}
fn new_client(
&mut self,
client_id: ClientId,
stream: LocalSocketStream,
) -> Result<IpcReceiverWithContext<ClientToServerMsg>> {
let receiver = IpcReceiverWithContext::new(stream);
let sender = ClientSender::new(client_id, receiver.get_sender());
self.client_senders
.lock()
.to_anyhow()
.with_context(|| format!("failed to create new client {client_id}"))?
.insert(client_id, sender);
Ok(receiver)
}
fn remove_client(&mut self, client_id: ClientId) -> Result<()> {
let mut client_senders = self
.client_senders
.lock()
.to_anyhow()
.with_context(|| format!("failed to remove client {client_id}"))?;
if client_senders.contains_key(&client_id) {
client_senders.remove(&client_id);
}
Ok(())
}
fn load_palette(&self) -> Palette {
default_palette()
}
fn get_cwd(&self, pid: Pid) -> Option<PathBuf> {
let mut system_info = System::new();
// Update by minimizing information.
// See https://docs.rs/sysinfo/0.22.5/sysinfo/struct.ProcessRefreshKind.html#
system_info.refresh_process_specifics(pid.into(), ProcessRefreshKind::default());
if let Some(process) = system_info.process(pid.into()) {
let cwd = process.cwd();
let cwd_is_empty = cwd.iter().next().is_none();
if !cwd_is_empty {
return Some(process.cwd().to_path_buf());
}
}
None
}
fn get_cwds(&self, pids: Vec<Pid>) -> (HashMap<Pid, PathBuf>, HashMap<Pid, Vec<String>>) {
let mut system_info = System::new();
let mut cwds = HashMap::new();
let mut cmds = HashMap::new();
for pid in pids {
// Update by minimizing information.
// See https://docs.rs/sysinfo/0.22.5/sysinfo/struct.ProcessRefreshKind.html#
let is_found =
system_info.refresh_process_specifics(pid.into(), ProcessRefreshKind::default());
if is_found {
if let Some(process) = system_info.process(pid.into()) {
let cwd = process.cwd();
let cmd = process.cmd();
let cwd_is_empty = cwd.iter().next().is_none();
if !cwd_is_empty {
cwds.insert(pid, process.cwd().to_path_buf());
}
let cmd_is_empty = cmd.iter().next().is_none();
if !cmd_is_empty {
cmds.insert(pid, process.cmd().to_vec());
}
}
}
}
(cwds, cmds)
}
fn get_all_cmds_by_ppid(&self, post_hook: &Option<String>) -> HashMap<String, Vec<String>> {
// the key is the stringified ppid
let mut cmds = HashMap::new();
if let Some(output) = Command::new("ps")
.args(vec!["-ao", "ppid,args"])
.output()
.ok()
{
let output = String::from_utf8(output.stdout.clone())
.unwrap_or_else(|_| String::from_utf8_lossy(&output.stdout).to_string());
for line in output.lines() {
let line_parts: Vec<String> = line
.trim()
.split_ascii_whitespace()
.map(|p| p.to_owned())
.collect();
let mut line_parts = line_parts.into_iter();
let ppid = line_parts.next();
if let Some(ppid) = ppid {
match &post_hook {
Some(post_hook) => {
let command: Vec<String> = line_parts.clone().collect();
let stringified = command.join(" ");
let cmd = match run_command_hook(&stringified, post_hook) {
Ok(command) => command,
Err(e) => {
log::error!("Post command hook failed to run: {}", e);
stringified.to_owned()
},
};
let line_parts: Vec<String> = cmd
.trim()
.split_ascii_whitespace()
.map(|p| p.to_owned())
.collect();
cmds.insert(ppid.into(), line_parts);
},
None => {
cmds.insert(ppid.into(), line_parts.collect());
},
}
}
}
}
cmds
}
fn write_to_file(&mut self, buf: String, name: Option<String>) -> Result<()> {
let err_context = || "failed to write to file".to_string();
let mut f: File = match name {
Some(x) => File::create(x).with_context(err_context)?,
None => tempfile().with_context(err_context)?,
};
write!(f, "{}", buf).with_context(err_context)
}
fn re_run_command_in_terminal(
&self,
terminal_id: u32,
run_command: RunCommand,
quit_cb: Box<dyn Fn(PaneId, Option<i32>, RunCommand) + Send>, // u32 is the exit status
) -> Result<(RawFd, RawFd)> {
let default_editor = None; // no need for a default editor when running an explicit command
self.orig_termios
.lock()
.to_anyhow()
.and_then(|orig_termios| {
spawn_terminal(
TerminalAction::RunCommand(run_command),
orig_termios.clone(),
quit_cb,
default_editor,
terminal_id,
)
})
.and_then(|(pid_primary, pid_secondary)| {
self.terminal_id_to_raw_fd
.lock()
.to_anyhow()?
.insert(terminal_id, Some(pid_primary));
Ok((pid_primary, pid_secondary))
})
.with_context(|| format!("failed to rerun command in terminal id {}", terminal_id))
}
fn clear_terminal_id(&self, terminal_id: u32) -> Result<()> {
self.terminal_id_to_raw_fd
.lock()
.to_anyhow()
.with_context(|| format!("failed to clear terminal ID {}", terminal_id))?
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/background_jobs.rs | zellij-server/src/background_jobs.rs | use async_std::task;
use zellij_utils::consts::{
session_info_cache_file_name, session_info_folder_for_session, session_layout_cache_file_name,
VERSION, ZELLIJ_SESSION_INFO_CACHE_DIR, ZELLIJ_SOCK_DIR,
};
use zellij_utils::data::{Event, HttpVerb, SessionInfo, WebServerStatus};
use zellij_utils::errors::{prelude::*, BackgroundJobContext, ContextType};
use zellij_utils::input::layout::RunPlugin;
use isahc::prelude::*;
use isahc::AsyncReadResponseExt;
use isahc::{config::RedirectPolicy, HttpClient, Request};
use std::collections::{BTreeMap, HashMap};
use std::fs;
use std::io::Write;
use std::os::unix::fs::FileTypeExt;
use std::path::PathBuf;
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc, Mutex,
};
use std::time::{Duration, Instant};
use crate::panes::PaneId;
use crate::plugins::{PluginId, PluginInstruction};
use crate::pty::PtyInstruction;
use crate::screen::ScreenInstruction;
use crate::thread_bus::Bus;
use crate::ClientId;
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum BackgroundJob {
DisplayPaneError(Vec<PaneId>, String),
AnimatePluginLoading(u32), // u32 - plugin_id
StopPluginLoadingAnimation(u32), // u32 - plugin_id
ReadAllSessionInfosOnMachine, // u32 - plugin_id
ReportSessionInfo(String, SessionInfo), // String - session name
ReportPluginList(BTreeMap<PluginId, RunPlugin>), // String - session name
ReportLayoutInfo((String, BTreeMap<String, String>)), // BTreeMap<file_name, pane_contents>
RunCommand(
PluginId,
ClientId,
String,
Vec<String>,
BTreeMap<String, String>,
PathBuf,
BTreeMap<String, String>,
), // command, args, env_variables, cwd, context
WebRequest(
PluginId,
ClientId,
String, // url
HttpVerb,
BTreeMap<String, String>, // headers
Vec<u8>, // body
BTreeMap<String, String>, // context
),
HighlightPanesWithMessage(Vec<PaneId>, String),
RenderToClients,
QueryZellijWebServerStatus,
Exit,
}
impl From<&BackgroundJob> for BackgroundJobContext {
fn from(background_job: &BackgroundJob) -> Self {
match *background_job {
BackgroundJob::DisplayPaneError(..) => BackgroundJobContext::DisplayPaneError,
BackgroundJob::AnimatePluginLoading(..) => BackgroundJobContext::AnimatePluginLoading,
BackgroundJob::StopPluginLoadingAnimation(..) => {
BackgroundJobContext::StopPluginLoadingAnimation
},
BackgroundJob::ReadAllSessionInfosOnMachine => {
BackgroundJobContext::ReadAllSessionInfosOnMachine
},
BackgroundJob::ReportSessionInfo(..) => BackgroundJobContext::ReportSessionInfo,
BackgroundJob::ReportLayoutInfo(..) => BackgroundJobContext::ReportLayoutInfo,
BackgroundJob::RunCommand(..) => BackgroundJobContext::RunCommand,
BackgroundJob::WebRequest(..) => BackgroundJobContext::WebRequest,
BackgroundJob::ReportPluginList(..) => BackgroundJobContext::ReportPluginList,
BackgroundJob::RenderToClients => BackgroundJobContext::ReportPluginList,
BackgroundJob::HighlightPanesWithMessage(..) => {
BackgroundJobContext::HighlightPanesWithMessage
},
BackgroundJob::QueryZellijWebServerStatus => {
BackgroundJobContext::QueryZellijWebServerStatus
},
BackgroundJob::Exit => BackgroundJobContext::Exit,
}
}
}
static LONG_FLASH_DURATION_MS: u64 = 1000;
static FLASH_DURATION_MS: u64 = 400; // Doherty threshold
static PLUGIN_ANIMATION_OFFSET_DURATION_MD: u64 = 500;
static SESSION_READ_DURATION: u64 = 1000;
static DEFAULT_SERIALIZATION_INTERVAL: u64 = 60000;
static REPAINT_DELAY_MS: u64 = 10;
pub(crate) fn background_jobs_main(
bus: Bus<BackgroundJob>,
serialization_interval: Option<u64>,
disable_session_metadata: bool,
web_server_base_url: String,
) -> Result<()> {
let err_context = || "failed to write to pty".to_string();
let mut running_jobs: HashMap<BackgroundJob, Instant> = HashMap::new();
let mut loading_plugins: HashMap<u32, Arc<AtomicBool>> = HashMap::new(); // u32 - plugin_id
let current_session_name = Arc::new(Mutex::new(String::default()));
let current_session_info = Arc::new(Mutex::new(SessionInfo::default()));
let current_session_plugin_list: Arc<Mutex<BTreeMap<PluginId, RunPlugin>>> =
Arc::new(Mutex::new(BTreeMap::new()));
let current_session_layout = Arc::new(Mutex::new((String::new(), BTreeMap::new())));
let last_serialization_time = Arc::new(Mutex::new(Instant::now()));
let serialization_interval = serialization_interval.map(|s| s * 1000); // convert to
// milliseconds
let last_render_request: Arc<Mutex<Option<Instant>>> = Arc::new(Mutex::new(None));
let http_client = HttpClient::builder()
// TODO: timeout?
.redirect_policy(RedirectPolicy::Follow)
.build()
.ok();
loop {
let (event, mut err_ctx) = bus.recv().with_context(err_context)?;
err_ctx.add_call(ContextType::BackgroundJob((&event).into()));
let job = event.clone();
match event {
BackgroundJob::DisplayPaneError(pane_ids, text) => {
if job_already_running(job, &mut running_jobs) {
continue;
}
task::spawn({
let senders = bus.senders.clone();
async move {
let _ = senders.send_to_screen(
ScreenInstruction::AddRedPaneFrameColorOverride(
pane_ids.clone(),
Some(text),
),
);
task::sleep(std::time::Duration::from_millis(LONG_FLASH_DURATION_MS)).await;
let _ = senders.send_to_screen(
ScreenInstruction::ClearPaneFrameColorOverride(pane_ids),
);
}
});
},
BackgroundJob::AnimatePluginLoading(pid) => {
let loading_plugin = Arc::new(AtomicBool::new(true));
if job_already_running(job, &mut running_jobs) {
continue;
}
task::spawn({
let senders = bus.senders.clone();
let loading_plugin = loading_plugin.clone();
async move {
while loading_plugin.load(Ordering::SeqCst) {
let _ = senders.send_to_screen(
ScreenInstruction::ProgressPluginLoadingOffset(pid),
);
task::sleep(std::time::Duration::from_millis(
PLUGIN_ANIMATION_OFFSET_DURATION_MD,
))
.await;
}
}
});
loading_plugins.insert(pid, loading_plugin);
},
BackgroundJob::StopPluginLoadingAnimation(pid) => {
if let Some(loading_plugin) = loading_plugins.remove(&pid) {
loading_plugin.store(false, Ordering::SeqCst);
}
},
BackgroundJob::ReportSessionInfo(session_name, session_info) => {
*current_session_name.lock().unwrap() = session_name;
*current_session_info.lock().unwrap() = session_info;
},
BackgroundJob::ReportPluginList(plugin_list) => {
*current_session_plugin_list.lock().unwrap() = plugin_list;
},
BackgroundJob::ReportLayoutInfo(session_layout) => {
*current_session_layout.lock().unwrap() = session_layout;
},
BackgroundJob::ReadAllSessionInfosOnMachine => {
// this job should only be run once and it keeps track of other sessions (as well
// as this one's) infos (metadata mostly) and sends it to the screen which in turn
// forwards it to plugins and other places it needs to be
if running_jobs.get(&job).is_some() {
continue;
}
running_jobs.insert(job, Instant::now());
task::spawn({
let senders = bus.senders.clone();
let current_session_info = current_session_info.clone();
let current_session_name = current_session_name.clone();
let current_session_layout = current_session_layout.clone();
let current_session_plugin_list = current_session_plugin_list.clone();
let last_serialization_time = last_serialization_time.clone();
async move {
loop {
let current_session_name =
current_session_name.lock().unwrap().to_string();
let current_session_info = current_session_info.lock().unwrap().clone();
let current_session_layout =
current_session_layout.lock().unwrap().clone();
if !disable_session_metadata {
write_session_state_to_disk(
current_session_name.clone(),
current_session_info,
current_session_layout,
);
}
let mut session_infos_on_machine =
read_other_live_session_states(¤t_session_name);
for (session_name, session_info) in session_infos_on_machine.iter_mut()
{
if session_name == ¤t_session_name {
let current_session_plugin_list =
current_session_plugin_list.lock().unwrap().clone();
session_info.populate_plugin_list(current_session_plugin_list);
}
}
let resurrectable_sessions =
find_resurrectable_sessions(&session_infos_on_machine);
let _ = senders.send_to_screen(ScreenInstruction::UpdateSessionInfos(
session_infos_on_machine,
resurrectable_sessions,
));
let _ = senders.send_to_pty(PtyInstruction::UpdateAndReportCwds);
if last_serialization_time
.lock()
.unwrap()
.elapsed()
.as_millis()
>= serialization_interval
.unwrap_or(DEFAULT_SERIALIZATION_INTERVAL)
.into()
{
let _ = senders.send_to_screen(
ScreenInstruction::SerializeLayoutForResurrection,
);
*last_serialization_time.lock().unwrap() = Instant::now();
}
task::sleep(std::time::Duration::from_millis(SESSION_READ_DURATION))
.await;
}
}
});
},
BackgroundJob::RunCommand(
plugin_id,
client_id,
command,
args,
env_variables,
cwd,
context,
) => {
// when async_std::process stabilizes, we should change this to be async
std::thread::spawn({
let senders = bus.senders.clone();
move || {
let output = std::process::Command::new(&command)
.args(&args)
.envs(env_variables)
.current_dir(cwd)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output();
match output {
Ok(output) => {
let stdout = output.stdout.to_vec();
let stderr = output.stderr.to_vec();
let exit_code = output.status.code();
let _ = senders.send_to_plugin(PluginInstruction::Update(vec![(
Some(plugin_id),
Some(client_id),
Event::RunCommandResult(exit_code, stdout, stderr, context),
)]));
},
Err(e) => {
log::error!("Failed to run command: {}", e);
let stdout = vec![];
let stderr = format!("{}", e).as_bytes().to_vec();
let exit_code = Some(2);
let _ = senders.send_to_plugin(PluginInstruction::Update(vec![(
Some(plugin_id),
Some(client_id),
Event::RunCommandResult(exit_code, stdout, stderr, context),
)]));
},
}
}
});
},
BackgroundJob::WebRequest(plugin_id, client_id, url, verb, headers, body, context) => {
task::spawn({
let senders = bus.senders.clone();
let http_client = http_client.clone();
async move {
async fn web_request(
url: String,
verb: HttpVerb,
headers: BTreeMap<String, String>,
body: Vec<u8>,
http_client: HttpClient,
) -> Result<
(u16, BTreeMap<String, String>, Vec<u8>), // status_code, headers, body
isahc::Error,
> {
let mut request = match verb {
HttpVerb::Get => Request::get(url),
HttpVerb::Post => Request::post(url),
HttpVerb::Put => Request::put(url),
HttpVerb::Delete => Request::delete(url),
};
for (header, value) in headers {
request = request.header(header.as_str(), value);
}
let mut res = if !body.is_empty() {
let req = request.body(body)?;
http_client.send_async(req).await?
} else {
let req = request.body(())?;
http_client.send_async(req).await?
};
let status_code = res.status();
let headers: BTreeMap<String, String> = res
.headers()
.iter()
.filter_map(|(name, value)| match value.to_str() {
Ok(value) => Some((name.to_string(), value.to_string())),
Err(e) => {
log::error!(
"Failed to convert header {:?} to string: {:?}",
name,
e
);
None
},
})
.collect();
let body = res.bytes().await?;
Ok((status_code.as_u16(), headers, body))
}
let Some(http_client) = http_client else {
log::error!("Cannot perform http request, likely due to a misconfigured http client");
return;
};
match web_request(url, verb, headers, body, http_client).await {
Ok((status, headers, body)) => {
let _ = senders.send_to_plugin(PluginInstruction::Update(vec![(
Some(plugin_id),
Some(client_id),
Event::WebRequestResult(status, headers, body, context),
)]));
},
Err(e) => {
log::error!("Failed to send web request: {}", e);
let error_body = e.to_string().as_bytes().to_vec();
let _ = senders.send_to_plugin(PluginInstruction::Update(vec![(
Some(plugin_id),
Some(client_id),
Event::WebRequestResult(
400,
BTreeMap::new(),
error_body,
context,
),
)]));
},
}
}
});
},
BackgroundJob::QueryZellijWebServerStatus => {
if !cfg!(feature = "web_server_capability") {
// no web server capability, no need to query
continue;
}
task::spawn({
let http_client = http_client.clone();
let senders = bus.senders.clone();
let web_server_base_url = web_server_base_url.clone();
async move {
async fn web_request(
http_client: HttpClient,
web_server_base_url: &str,
) -> Result<
(u16, Vec<u8>), // status_code, body
isahc::Error,
> {
let request =
Request::get(format!("{}/info/version", web_server_base_url,));
let req = request.body(())?;
let mut res = http_client.send_async(req).await?;
let status_code = res.status();
let body = res.bytes().await?;
Ok((status_code.as_u16(), body))
}
let Some(http_client) = http_client else {
log::error!("Cannot perform http request, likely due to a misconfigured http client");
return;
};
let http_client = http_client.clone();
match web_request(http_client, &web_server_base_url).await {
Ok((status, body)) => {
if status == 200 && &body == VERSION.as_bytes() {
// online
let _ =
senders.send_to_plugin(PluginInstruction::Update(vec![(
None,
None,
Event::WebServerStatus(WebServerStatus::Online(
web_server_base_url.clone(),
)),
)]));
} else if status == 200 {
let _ =
senders.send_to_plugin(PluginInstruction::Update(vec![(
None,
None,
Event::WebServerStatus(
WebServerStatus::DifferentVersion(
String::from_utf8_lossy(&body).to_string(),
),
),
)]));
} else {
// offline/error
let _ =
senders.send_to_plugin(PluginInstruction::Update(vec![(
None,
None,
Event::WebServerStatus(WebServerStatus::Offline),
)]));
}
},
Err(e) => {
if e.kind() == isahc::error::ErrorKind::ConnectionFailed {
let _ =
senders.send_to_plugin(PluginInstruction::Update(vec![(
None,
None,
Event::WebServerStatus(WebServerStatus::Offline),
)]));
} else {
// no-op - otherwise we'll get errors if we were mid-request
// (eg. when the server was shut down by a user action)
}
},
}
}
});
},
BackgroundJob::RenderToClients => {
// last_render_request being Some() represents a render request that is pending
// last_render_request is only ever set to Some() if an async task is spawned to
// send the actual render instruction
//
// given this:
// - if last_render_request is None and we received this job, we should spawn an
// async task to send the render instruction and log the current task time
// - if last_render_request is Some(), it means we're currently waiting to render,
// so we should log the render request and do nothing, once the async task has
// finished running, it will check to see if the render time was updated while it
// was running, and if so send this instruction again so the process can start anew
let (should_run_task, current_time) = {
let mut last_render_request = last_render_request.lock().unwrap();
let should_run_task = last_render_request.is_none();
let current_time = Instant::now();
*last_render_request = Some(current_time);
(should_run_task, current_time)
};
if should_run_task {
task::spawn({
let senders = bus.senders.clone();
let last_render_request = last_render_request.clone();
let task_start_time = current_time;
async move {
task::sleep(std::time::Duration::from_millis(REPAINT_DELAY_MS)).await;
let _ = senders.send_to_screen(ScreenInstruction::RenderToClients);
{
let mut last_render_request = last_render_request.lock().unwrap();
if let Some(last_render_request) = *last_render_request {
if last_render_request > task_start_time {
// another render request was received while we were
// sleeping, schedule this job again so that we can also
// render that request
let _ = senders.send_to_background_jobs(
BackgroundJob::RenderToClients,
);
}
}
// reset the last_render_request so that the task will be spawned
// again once a new request is received
*last_render_request = None;
}
}
});
}
},
BackgroundJob::HighlightPanesWithMessage(pane_ids, text) => {
if job_already_running(job, &mut running_jobs) {
continue;
}
task::spawn({
let senders = bus.senders.clone();
async move {
let _ = senders.send_to_screen(
ScreenInstruction::AddHighlightPaneFrameColorOverride(
pane_ids.clone(),
Some(text),
),
);
task::sleep(std::time::Duration::from_millis(FLASH_DURATION_MS)).await;
let _ = senders.send_to_screen(
ScreenInstruction::ClearPaneFrameColorOverride(pane_ids),
);
}
});
},
BackgroundJob::Exit => {
for loading_plugin in loading_plugins.values() {
loading_plugin.store(false, Ordering::SeqCst);
}
let cache_file_name =
session_info_cache_file_name(¤t_session_name.lock().unwrap().to_owned());
let _ = std::fs::remove_file(cache_file_name);
return Ok(());
},
}
}
}
fn job_already_running(
job: BackgroundJob,
running_jobs: &mut HashMap<BackgroundJob, Instant>,
) -> bool {
match running_jobs.get_mut(&job) {
Some(current_running_job_start_time) => {
if current_running_job_start_time.elapsed()
> Duration::from_millis(LONG_FLASH_DURATION_MS)
{
*current_running_job_start_time = Instant::now();
false
} else {
true
}
},
None => {
running_jobs.insert(job.clone(), Instant::now());
false
},
}
}
fn write_session_state_to_disk(
current_session_name: String,
current_session_info: SessionInfo,
current_session_layout: (String, BTreeMap<String, String>),
) {
let metadata_cache_file_name = session_info_cache_file_name(¤t_session_name);
let (current_session_layout, layout_files_to_write) = current_session_layout;
let _wrote_metadata_file =
std::fs::create_dir_all(session_info_folder_for_session(¤t_session_name).as_path())
.and_then(|_| std::fs::File::create(metadata_cache_file_name))
.and_then(|mut f| write!(f, "{}", current_session_info.to_string()));
if !current_session_layout.is_empty() {
let layout_cache_file_name = session_layout_cache_file_name(¤t_session_name);
let _wrote_layout_file = std::fs::create_dir_all(
session_info_folder_for_session(¤t_session_name).as_path(),
)
.and_then(|_| std::fs::File::create(layout_cache_file_name))
.and_then(|mut f| write!(f, "{}", current_session_layout))
.and_then(|_| {
let session_info_folder = session_info_folder_for_session(¤t_session_name);
for (external_file_name, external_file_contents) in layout_files_to_write {
std::fs::File::create(session_info_folder.join(external_file_name))
.and_then(|mut f| write!(f, "{}", external_file_contents))
.unwrap_or_else(|e| {
log::error!("Failed to write layout metadata file: {:?}", e);
});
}
Ok(())
});
}
}
fn read_other_live_session_states(current_session_name: &str) -> BTreeMap<String, SessionInfo> {
let mut other_session_names = vec![];
let mut session_infos_on_machine = BTreeMap::new();
// we do this so that the session infos will be actual and we're
// reasonably sure their session is running
if let Ok(files) = fs::read_dir(&*ZELLIJ_SOCK_DIR) {
files.for_each(|file| {
if let Ok(file) = file {
if let Ok(file_name) = file.file_name().into_string() {
if file.file_type().unwrap().is_socket() {
other_session_names.push(file_name);
}
}
}
});
}
for session_name in other_session_names {
let session_cache_file_name = session_info_cache_file_name(&session_name);
if let Ok(raw_session_info) = fs::read_to_string(&session_cache_file_name) {
if let Ok(session_info) =
SessionInfo::from_string(&raw_session_info, ¤t_session_name)
{
session_infos_on_machine.insert(session_name, session_info);
}
}
}
session_infos_on_machine
}
fn find_resurrectable_sessions(
session_infos_on_machine: &BTreeMap<String, SessionInfo>,
) -> BTreeMap<String, Duration> {
match fs::read_dir(&*ZELLIJ_SESSION_INFO_CACHE_DIR) {
Ok(files_in_session_info_folder) => {
let files_that_are_folders = files_in_session_info_folder
.filter_map(|f| f.ok().map(|f| f.path()))
.filter(|f| f.is_dir());
files_that_are_folders
.filter_map(|folder_name| {
let session_name = folder_name.file_name()?.to_str()?.to_owned();
if session_infos_on_machine.contains_key(&session_name) {
// this is not a dead session...
return None;
}
let layout_file_name = session_layout_cache_file_name(&session_name);
let ctime = match std::fs::metadata(&layout_file_name)
.and_then(|metadata| metadata.created())
{
Ok(created) => Some(created),
Err(e) => {
if e.kind() == std::io::ErrorKind::NotFound {
return None; // no layout file, cannot resurrect session, let's not
// list it
} else {
log::error!(
"Failed to read created stamp of resurrection file: {:?}",
e
);
}
None
},
};
let elapsed_duration = ctime
.map(|ctime| {
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/lib.rs | zellij-server/src/lib.rs | pub mod os_input_output;
pub mod output;
pub mod panes;
pub mod tab;
mod background_jobs;
mod global_async_runtime;
mod logging_pipe;
mod pane_groups;
mod plugins;
mod pty;
mod pty_writer;
mod route;
mod screen;
mod session_layout_metadata;
mod terminal_bytes;
mod thread_bus;
mod ui;
pub use daemonize;
use background_jobs::{background_jobs_main, BackgroundJob};
use log::info;
use nix::sys::stat::{umask, Mode};
use pty_writer::{pty_writer_main, PtyWriteInstruction};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::{
net::{IpAddr, Ipv4Addr},
path::PathBuf,
sync::{Arc, RwLock},
thread,
};
use zellij_utils::envs;
use zellij_utils::pane_size::Size;
use zellij_utils::input::cli_assets::CliAssets;
use wasmi::Engine;
use crate::{
os_input_output::ServerOsApi,
plugins::{plugin_thread_main, PluginInstruction},
pty::{get_default_shell, pty_thread_main, Pty, PtyInstruction},
screen::{screen_thread_main, ScreenInstruction},
thread_bus::{Bus, ThreadSenders},
};
use route::{route_thread_main, NotificationEnd};
use zellij_utils::{
channels::{self, ChannelWithContext, SenderWithContext},
consts::{
DEFAULT_SCROLL_BUFFER_SIZE, SCROLL_BUFFER_SIZE, ZELLIJ_SEEN_RELEASE_NOTES_CACHE_FILE,
},
data::{
ConnectToSession, Event, InputMode, KeyWithModifier, LayoutInfo, PluginCapabilities, Style,
WebSharing,
},
errors::{prelude::*, ContextType, ErrorInstruction, FatalError, ServerContext},
home::{default_layout_dir, get_default_data_dir},
input::{
actions::Action,
command::{RunCommand, TerminalAction},
config::{watch_config_file_changes, Config},
get_mode_info,
keybinds::Keybinds,
layout::{FloatingPaneLayout, Layout, PluginAlias, Run, RunPluginOrAlias},
options::Options,
plugins::PluginAliases,
},
ipc::{ClientAttributes, ExitReason, ServerToClientMsg},
shared::{default_palette, web_server_base_url},
};
pub type ClientId = u16;
/// Instructions related to server-side application
#[derive(Debug, Clone)]
pub enum ServerInstruction {
FirstClientConnected(
CliAssets,
bool, // is_web_client
ClientId,
),
Render(Option<HashMap<ClientId, String>>),
UnblockInputThread,
ClientExit(ClientId, Option<NotificationEnd>),
RemoveClient(ClientId),
Error(String),
KillSession,
DetachSession(Vec<ClientId>, Option<NotificationEnd>),
AttachClient(
CliAssets,
Option<usize>, // tab position to focus
Option<(u32, bool)>, // (pane_id, is_plugin) => pane_id to focus
bool, // is_web_client
ClientId,
),
AttachWatcherClient(ClientId, Size, bool), // bool -> is_web_client
ConnStatus(ClientId),
Log(Vec<String>, ClientId, Option<NotificationEnd>),
LogError(Vec<String>, ClientId, Option<NotificationEnd>),
SwitchSession(ConnectToSession, ClientId, Option<NotificationEnd>),
UnblockCliPipeInput(String), // String -> Pipe name
CliPipeOutput(String, String), // String -> Pipe name, String -> Output
AssociatePipeWithClient {
pipe_id: String,
client_id: ClientId,
},
DisconnectAllClientsExcept(ClientId),
ChangeMode(ClientId, InputMode),
ChangeModeForAllClients(InputMode),
Reconfigure {
client_id: ClientId,
config: String,
write_config_to_disk: bool,
},
ConfigWrittenToDisk(Config),
FailedToWriteConfigToDisk(ClientId, Option<PathBuf>), // Pathbuf - file we failed to write
RebindKeys {
client_id: ClientId,
keys_to_rebind: Vec<(InputMode, KeyWithModifier, Vec<Action>)>,
keys_to_unbind: Vec<(InputMode, KeyWithModifier)>,
write_config_to_disk: bool,
},
StartWebServer(ClientId),
ShareCurrentSession(ClientId),
StopSharingCurrentSession(ClientId),
SendWebClientsForbidden(ClientId),
WebServerStarted(String), // String -> base_url
FailedToStartWebServer(String),
}
impl From<&ServerInstruction> for ServerContext {
fn from(server_instruction: &ServerInstruction) -> Self {
match *server_instruction {
ServerInstruction::FirstClientConnected(..) => ServerContext::NewClient,
ServerInstruction::Render(..) => ServerContext::Render,
ServerInstruction::UnblockInputThread => ServerContext::UnblockInputThread,
ServerInstruction::ClientExit(..) => ServerContext::ClientExit,
ServerInstruction::RemoveClient(..) => ServerContext::RemoveClient,
ServerInstruction::Error(_) => ServerContext::Error,
ServerInstruction::KillSession => ServerContext::KillSession,
ServerInstruction::DetachSession(..) => ServerContext::DetachSession,
ServerInstruction::AttachClient(..) => ServerContext::AttachClient,
ServerInstruction::AttachWatcherClient(..) => ServerContext::AttachClient,
ServerInstruction::ConnStatus(..) => ServerContext::ConnStatus,
ServerInstruction::Log(..) => ServerContext::Log,
ServerInstruction::LogError(..) => ServerContext::LogError,
ServerInstruction::SwitchSession(..) => ServerContext::SwitchSession,
ServerInstruction::UnblockCliPipeInput(..) => ServerContext::UnblockCliPipeInput,
ServerInstruction::CliPipeOutput(..) => ServerContext::CliPipeOutput,
ServerInstruction::AssociatePipeWithClient { .. } => {
ServerContext::AssociatePipeWithClient
},
ServerInstruction::DisconnectAllClientsExcept(..) => {
ServerContext::DisconnectAllClientsExcept
},
ServerInstruction::ChangeMode(..) => ServerContext::ChangeMode,
ServerInstruction::ChangeModeForAllClients(..) => {
ServerContext::ChangeModeForAllClients
},
ServerInstruction::Reconfigure { .. } => ServerContext::Reconfigure,
ServerInstruction::FailedToWriteConfigToDisk(..) => {
ServerContext::FailedToWriteConfigToDisk
},
ServerInstruction::RebindKeys { .. } => ServerContext::RebindKeys,
ServerInstruction::StartWebServer(..) => ServerContext::StartWebServer,
ServerInstruction::ShareCurrentSession(..) => ServerContext::ShareCurrentSession,
ServerInstruction::StopSharingCurrentSession(..) => {
ServerContext::StopSharingCurrentSession
},
ServerInstruction::WebServerStarted(..) => ServerContext::WebServerStarted,
ServerInstruction::FailedToStartWebServer(..) => ServerContext::FailedToStartWebServer,
ServerInstruction::ConfigWrittenToDisk(..) => ServerContext::ConfigWrittenToDisk,
ServerInstruction::SendWebClientsForbidden(..) => {
ServerContext::SendWebClientsForbidden
},
}
}
}
impl ErrorInstruction for ServerInstruction {
fn error(err: String) -> Self {
ServerInstruction::Error(err)
}
}
#[derive(Debug, Clone, Default)]
pub(crate) struct SessionConfiguration {
runtime_config: HashMap<ClientId, Config>, // if present, overrides the saved_config
saved_config: Config, // the config as it is on disk (not guaranteed),
// when changed, this resets the runtime config to
// be identical to it and override any previous
// changes
}
impl SessionConfiguration {
pub fn change_saved_config(&mut self, new_saved_config: Config) -> Vec<(ClientId, Config)> {
self.saved_config = new_saved_config.clone();
let mut config_changes = vec![];
for (client_id, current_runtime_config) in self.runtime_config.iter_mut() {
if *current_runtime_config != new_saved_config {
*current_runtime_config = new_saved_config.clone();
config_changes.push((*client_id, new_saved_config.clone()))
}
}
config_changes
}
pub fn set_saved_configuration(&mut self, config: Config) {
self.saved_config = config;
}
pub fn set_client_runtime_configuration(&mut self, client_id: ClientId, client_config: Config) {
self.runtime_config.insert(client_id, client_config);
}
pub fn get_client_keybinds(&self, client_id: &ClientId) -> Keybinds {
self.runtime_config
.get(client_id)
.or_else(|| Some(&self.saved_config))
.map(|c| c.keybinds.clone())
.unwrap_or_default()
}
pub fn get_client_default_input_mode(&self, client_id: &ClientId) -> InputMode {
self.runtime_config
.get(client_id)
.or_else(|| Some(&self.saved_config))
.and_then(|c| c.options.default_mode.clone())
.unwrap_or_default()
}
pub fn get_client_configuration(&self, client_id: &ClientId) -> Config {
self.runtime_config
.get(client_id)
.or_else(|| Some(&self.saved_config))
.cloned()
.unwrap_or_default()
}
pub fn reconfigure_runtime_config(
&mut self,
client_id: &ClientId,
stringified_config: String,
) -> (Option<Config>, bool) {
// bool is whether the config changed
let mut full_reconfigured_config = None;
let mut config_changed = false;
let current_client_configuration = self.get_client_configuration(client_id);
match Config::from_kdl(
&stringified_config,
Some(current_client_configuration.clone()),
) {
Ok(new_config) => {
config_changed = current_client_configuration != new_config;
full_reconfigured_config = Some(new_config.clone());
self.runtime_config.insert(*client_id, new_config);
},
Err(e) => {
log::error!("Failed to reconfigure runtime config: {}", e);
},
}
(full_reconfigured_config, config_changed)
}
pub fn rebind_keys(
&mut self,
client_id: &ClientId,
keys_to_rebind: Vec<(InputMode, KeyWithModifier, Vec<Action>)>,
keys_to_unbind: Vec<(InputMode, KeyWithModifier)>,
) -> (Option<Config>, bool) {
let mut full_reconfigured_config = None;
let mut config_changed = false;
if self.runtime_config.get(client_id).is_none() {
self.runtime_config
.insert(*client_id, self.saved_config.clone());
}
match self.runtime_config.get_mut(client_id) {
Some(config) => {
for (input_mode, key_with_modifier) in keys_to_unbind {
let keys_in_mode = config
.keybinds
.0
.entry(input_mode)
.or_insert_with(Default::default);
let removed = keys_in_mode.remove(&key_with_modifier);
if removed.is_some() {
config_changed = true;
}
}
for (input_mode, key_with_modifier, actions) in keys_to_rebind {
let keys_in_mode = config
.keybinds
.0
.entry(input_mode)
.or_insert_with(Default::default);
if keys_in_mode.get(&key_with_modifier) != Some(&actions) {
config_changed = true;
keys_in_mode.insert(key_with_modifier, actions);
}
}
if config_changed {
full_reconfigured_config = Some(config.clone());
}
},
None => {
log::error!(
"Could not find runtime or saved configuration for client, cannot rebind keys"
);
},
}
(full_reconfigured_config, config_changed)
}
}
pub(crate) struct SessionMetaData {
pub senders: ThreadSenders,
pub capabilities: PluginCapabilities,
pub client_attributes: ClientAttributes,
pub default_shell: Option<TerminalAction>,
pub layout: Box<Layout>,
pub current_input_modes: HashMap<ClientId, InputMode>,
pub session_configuration: SessionConfiguration,
pub web_sharing: WebSharing, // this is a special attribute explicitly set on session
// initialization because we don't want it to be overridden by
// configuration changes, the only way it can be overwritten is by
// explicit plugin action
screen_thread: Option<thread::JoinHandle<()>>,
pty_thread: Option<thread::JoinHandle<()>>,
plugin_thread: Option<thread::JoinHandle<()>>,
pty_writer_thread: Option<thread::JoinHandle<()>>,
background_jobs_thread: Option<thread::JoinHandle<()>>,
config_file_path: Option<PathBuf>,
}
impl SessionMetaData {
pub fn get_client_keybinds_and_mode(
&self,
client_id: &ClientId,
) -> Option<(Keybinds, &InputMode, InputMode)> {
// (keybinds, current_input_mode,
// default_input_mode)
let client_keybinds = self.session_configuration.get_client_keybinds(client_id);
let default_input_mode = self
.session_configuration
.get_client_default_input_mode(client_id);
match self.current_input_modes.get(client_id) {
Some(client_input_mode) => {
Some((client_keybinds, client_input_mode, default_input_mode))
},
_ => None,
}
}
pub fn change_mode_for_all_clients(&mut self, input_mode: InputMode) {
let all_clients: Vec<ClientId> = self.current_input_modes.keys().copied().collect();
for client_id in all_clients {
self.current_input_modes.insert(client_id, input_mode);
}
}
pub fn propagate_configuration_changes(
&mut self,
config_changes: Vec<(ClientId, Config)>,
config_was_written_to_disk: bool,
) {
for (client_id, new_config) in config_changes {
self.default_shell = new_config.options.default_shell.as_ref().map(|shell| {
TerminalAction::RunCommand(RunCommand {
command: shell.clone(),
cwd: new_config.options.default_cwd.clone(),
use_terminal_title: true,
..Default::default()
})
});
self.senders
.send_to_screen(ScreenInstruction::Reconfigure {
client_id,
keybinds: new_config.keybinds.clone(),
default_mode: new_config
.options
.default_mode
.unwrap_or_else(Default::default),
theme: new_config
.theme_config(new_config.options.theme.as_ref())
.unwrap_or_else(|| default_palette().into()),
simplified_ui: new_config.options.simplified_ui.unwrap_or(false),
default_shell: new_config.options.default_shell,
pane_frames: new_config.options.pane_frames.unwrap_or(true),
copy_command: new_config.options.copy_command,
copy_to_clipboard: new_config.options.copy_clipboard,
copy_on_select: new_config.options.copy_on_select.unwrap_or(true),
auto_layout: new_config.options.auto_layout.unwrap_or(true),
rounded_corners: new_config.ui.pane_frames.rounded_corners,
hide_session_name: new_config.ui.pane_frames.hide_session_name,
stacked_resize: new_config.options.stacked_resize.unwrap_or(true),
default_editor: new_config.options.scrollback_editor.clone(),
advanced_mouse_actions: new_config
.options
.advanced_mouse_actions
.unwrap_or(true),
})
.unwrap();
self.senders
.send_to_plugin(PluginInstruction::Reconfigure {
client_id,
keybinds: Some(new_config.keybinds),
default_mode: new_config.options.default_mode,
default_shell: self.default_shell.clone(),
was_written_to_disk: config_was_written_to_disk,
})
.unwrap();
self.senders
.send_to_pty(PtyInstruction::Reconfigure {
client_id,
default_editor: new_config.options.scrollback_editor,
post_command_discovery_hook: new_config.options.post_command_discovery_hook,
})
.unwrap();
}
}
}
impl Drop for SessionMetaData {
fn drop(&mut self) {
let _ = self.senders.send_to_pty(PtyInstruction::Exit);
let _ = self.senders.send_to_screen(ScreenInstruction::Exit);
let _ = self.senders.send_to_plugin(PluginInstruction::Exit);
let _ = self.senders.send_to_pty_writer(PtyWriteInstruction::Exit);
let _ = self.senders.send_to_background_jobs(BackgroundJob::Exit);
if let Some(screen_thread) = self.screen_thread.take() {
let _ = screen_thread.join();
}
if let Some(pty_thread) = self.pty_thread.take() {
let _ = pty_thread.join();
}
if let Some(plugin_thread) = self.plugin_thread.take() {
let _ = plugin_thread.join();
}
if let Some(pty_writer_thread) = self.pty_writer_thread.take() {
let _ = pty_writer_thread.join();
}
if let Some(background_jobs_thread) = self.background_jobs_thread.take() {
let _ = background_jobs_thread.join();
}
}
}
macro_rules! remove_client {
($client_id:expr, $os_input:expr, $session_state:expr) => {
$os_input.remove_client($client_id).unwrap();
$session_state.write().unwrap().remove_client($client_id);
};
}
macro_rules! remove_watcher {
($client_id:expr, $os_input:expr, $session_state:expr) => {
$os_input.remove_client($client_id).unwrap();
$session_state.write().unwrap().remove_watcher($client_id);
};
}
macro_rules! send_to_client {
($client_id:expr, $os_input:expr, $msg:expr, $session_state:expr) => {
let send_to_client_res = $os_input.send_to_client($client_id, $msg);
if let Err(e) = send_to_client_res {
// Try to recover the message
let context = match e.downcast_ref::<ZellijError>() {
Some(ZellijError::ClientTooSlow { .. }) => {
format!(
"client {} is processing server messages too slow",
$client_id
)
},
_ => {
format!("failed to route server message to client {}", $client_id)
},
};
// Log it so it isn't lost
Err::<(), _>(e).context(context).non_fatal();
// failed to send to client, remove it
remove_client!($client_id, $os_input, $session_state);
}
};
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct SessionState {
clients: HashMap<ClientId, Option<(Size, bool)>>, // bool -> is_web_client
pipes: HashMap<String, ClientId>, // String => pipe_id
watchers: HashMap<ClientId, bool>, // watcher clients (read-only observers) bool -> is_web_client
last_active_client: Option<ClientId>, // last client that sent a Key message
}
impl SessionState {
pub fn new() -> Self {
SessionState {
clients: HashMap::new(),
pipes: HashMap::new(),
watchers: HashMap::new(),
last_active_client: None,
}
}
pub fn new_client(&mut self) -> ClientId {
let all_ids: HashSet<ClientId> = self
.clients
.keys()
.copied()
.chain(self.watchers.keys().copied())
.collect();
let mut next_client_id = 1;
loop {
if all_ids.contains(&next_client_id) {
next_client_id += 1;
} else {
break;
}
}
self.clients.insert(next_client_id, None);
next_client_id
}
pub fn associate_pipe_with_client(&mut self, pipe_id: String, client_id: ClientId) {
self.pipes.insert(pipe_id, client_id);
}
pub fn remove_client(&mut self, client_id: ClientId) {
self.clients.remove(&client_id);
self.pipes.retain(|_p_id, c_id| c_id != &client_id);
self.clear_last_active_client(client_id);
}
pub fn set_client_size(&mut self, client_id: ClientId, size: Size) {
self.clients
.entry(client_id)
.or_insert_with(Default::default)
.as_mut()
.map(|(s, _is_web_client)| *s = size);
}
pub fn set_client_data(&mut self, client_id: ClientId, size: Size, is_web_client: bool) {
self.clients.insert(client_id, Some((size, is_web_client)));
}
pub fn min_client_terminal_size(&self) -> Option<Size> {
// None if there are no client sizes
let mut rows: Vec<usize> = self
.clients
.values()
.filter_map(|size_and_is_web_client| {
size_and_is_web_client.map(|(size, _is_web_client)| size.rows)
})
.collect();
rows.sort_unstable();
let mut cols: Vec<usize> = self
.clients
.values()
.filter_map(|size_and_is_web_client| {
size_and_is_web_client.map(|(size, _is_web_client)| size.cols)
})
.collect();
cols.sort_unstable();
let min_rows = rows.first();
let min_cols = cols.first();
match (min_rows, min_cols) {
(Some(min_rows), Some(min_cols)) => Some(Size {
rows: *min_rows,
cols: *min_cols,
}),
_ => None,
}
}
pub fn client_ids(&self) -> Vec<ClientId> {
self.clients.keys().copied().collect()
}
pub fn watcher_client_ids(&self) -> Vec<ClientId> {
self.watchers.keys().copied().collect()
}
pub fn web_client_ids(&self) -> Vec<ClientId> {
self.clients
.iter()
.filter_map(|(c_id, size_and_is_web_client)| {
size_and_is_web_client
.and_then(|(_s, is_web_client)| if is_web_client { Some(*c_id) } else { None })
})
.collect()
}
pub fn web_watcher_client_ids(&self) -> Vec<ClientId> {
self.watchers
.iter()
.filter_map(
|(&c_id, &is_web_client)| {
if is_web_client {
Some(c_id)
} else {
None
}
},
)
.collect()
}
pub fn get_pipe(&self, pipe_name: &str) -> Option<ClientId> {
self.pipes.get(pipe_name).copied()
}
pub fn active_clients_are_connected(&self) -> bool {
let ids_of_pipe_clients: HashSet<ClientId> = self.pipes.values().copied().collect();
let mut active_clients_connected = false;
for client_id in self.clients.keys() {
if ids_of_pipe_clients.contains(client_id) {
continue;
}
active_clients_connected = true;
}
active_clients_connected
}
pub fn convert_client_to_watcher(&mut self, client_id: ClientId, is_web_client: bool) {
self.clients.remove(&client_id);
self.watchers.insert(client_id, is_web_client);
}
pub fn is_watcher(&self, client_id: &ClientId) -> bool {
self.watchers.get(client_id).is_some()
}
pub fn remove_watcher(&mut self, client_id: ClientId) {
self.watchers.remove(&client_id);
}
pub fn set_last_active_client(&mut self, client_id: ClientId) {
self.last_active_client = Some(client_id);
}
pub fn get_last_active_client(&self) -> Option<ClientId> {
self.last_active_client
}
pub fn clear_last_active_client(&mut self, client_id: ClientId) {
if self.last_active_client == Some(client_id) {
self.last_active_client = None;
}
}
}
pub fn start_server(mut os_input: Box<dyn ServerOsApi>, socket_path: PathBuf) {
info!("Starting Zellij server!");
// preserve the current umask: read current value by setting to another mode, and then restoring it
let current_umask = umask(Mode::all());
umask(current_umask);
daemonize::Daemonize::new()
.working_directory(std::env::current_dir().unwrap())
.umask(current_umask.bits() as u32)
.start()
.expect("could not daemonize the server process");
envs::set_zellij("0".to_string());
let (to_server, server_receiver): ChannelWithContext<ServerInstruction> = channels::bounded(50);
let to_server = SenderWithContext::new(to_server);
let session_data: Arc<RwLock<Option<SessionMetaData>>> = Arc::new(RwLock::new(None));
let session_state = Arc::new(RwLock::new(SessionState::new()));
std::panic::set_hook({
use zellij_utils::errors::handle_panic;
let to_server = to_server.clone();
Box::new(move |info| {
handle_panic(info, Some(&to_server));
})
});
let _ = thread::Builder::new()
.name("server_listener".to_string())
.spawn({
use interprocess::local_socket::LocalSocketListener;
use zellij_utils::shared::set_permissions;
let os_input = os_input.clone();
let session_data = session_data.clone();
let session_state = session_state.clone();
let to_server = to_server.clone();
let socket_path = socket_path.clone();
move || {
drop(std::fs::remove_file(&socket_path));
let listener = LocalSocketListener::bind(&*socket_path).unwrap();
// set the sticky bit to avoid the socket file being potentially cleaned up
// https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html states that for XDG_RUNTIME_DIR:
// "To ensure that your files are not removed, they should have their access time timestamp modified at least once every 6 hours of monotonic time or the 'sticky' bit should be set on the file. "
// It is not guaranteed that all platforms allow setting the sticky bit on sockets!
drop(set_permissions(&socket_path, 0o1700));
for stream in listener.incoming() {
match stream {
Ok(stream) => {
let mut os_input = os_input.clone();
let client_id = session_state.write().unwrap().new_client();
let receiver = os_input.new_client(client_id, stream).unwrap();
let session_data = session_data.clone();
let session_state = session_state.clone();
let to_server = to_server.clone();
thread::Builder::new()
.name("server_router".to_string())
.spawn(move || {
route_thread_main(
session_data,
session_state,
os_input,
to_server,
receiver,
client_id,
)
.fatal()
})
.unwrap();
},
Err(err) => {
panic!("err {:?}", err);
},
}
}
}
});
loop {
let (instruction, mut err_ctx) = server_receiver.recv().unwrap();
err_ctx.add_call(ContextType::IPCServer((&instruction).into()));
match instruction {
ServerInstruction::FirstClientConnected(cli_assets, is_web_client, client_id) => {
let (config, layout) = cli_assets.load_config_and_layout();
let layout_is_welcome_screen = cli_assets.layout
== Some(LayoutInfo::BuiltIn("welcome".to_owned()))
|| config.options.default_layout == Some(PathBuf::from("welcome"));
let successfully_written_config = Config::write_config_to_disk_if_it_does_not_exist(
config.to_string(true),
&cli_assets.config_file_path,
);
// if we successfully wrote the config to disk, it means two things:
// 1. It did not exist beforehand
// 2. The config folder is writeable
//
// If these two are true, we should launch the setup wizard, if even one of them is
// false, we should never launch it.
let should_launch_setup_wizard = successfully_written_config;
let runtime_config_options = match &cli_assets.configuration_options {
Some(configuration_options) => {
config.options.merge(configuration_options.clone())
},
None => config.options.clone(),
};
let client_attributes = ClientAttributes {
size: cli_assets.terminal_window_size,
style: Style {
colors: config
.theme_config(runtime_config_options.theme.as_ref())
.unwrap_or_else(|| default_palette().into()),
rounded_corners: config.ui.pane_frames.rounded_corners,
hide_session_name: config.ui.pane_frames.hide_session_name,
},
};
let mut session = init_session(
os_input.clone(),
to_server.clone(),
client_attributes.clone(),
Box::new(runtime_config_options.clone()), // TODO: no box
Box::new(layout.clone()), // TODO: no box
cli_assets.clone(),
config.clone(),
config.plugins.clone(),
client_id,
);
let mut runtime_configuration = config.clone();
runtime_configuration.options = runtime_config_options.clone();
session
.session_configuration
.set_saved_configuration(config.clone());
session
.session_configuration
.set_client_runtime_configuration(client_id, runtime_configuration);
let default_input_mode = runtime_config_options.default_mode.unwrap_or_default();
session
.current_input_modes
.insert(client_id, default_input_mode);
*session_data.write().unwrap() = Some(session);
session_state.write().unwrap().set_client_data(
client_id,
client_attributes.size,
is_web_client,
);
let default_shell = runtime_config_options.default_shell.map(|shell| {
TerminalAction::RunCommand(RunCommand {
command: shell,
cwd: config.options.default_cwd.clone(),
use_terminal_title: true,
..Default::default()
})
});
let cwd = cli_assets
.cwd
.or_else(|| runtime_config_options.default_cwd);
let spawn_tabs = |tab_layout,
floating_panes_layout,
tab_name,
swap_layouts,
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/global_async_runtime.rs | zellij-server/src/global_async_runtime.rs | use once_cell::sync::OnceCell;
use tokio::runtime::Runtime;
// Global tokio runtime for async I/O operations
// Shared between plugin downloads, timers, and action completion tracking
static TOKIO_RUNTIME: OnceCell<Runtime> = OnceCell::new();
pub fn get_tokio_runtime() -> &'static Runtime {
TOKIO_RUNTIME.get_or_init(|| {
tokio::runtime::Builder::new_multi_thread()
.worker_threads(4)
.thread_name("async-runtime")
.enable_all()
.build()
.expect("Failed to create tokio runtime")
})
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/logging_pipe.rs | zellij-server/src/logging_pipe.rs | use std::{collections::VecDeque, io::Write};
use crate::plugins::PluginId;
use log::{debug, error};
use zellij_utils::errors::prelude::*;
use serde::{Deserialize, Serialize};
// 16kB log buffer
const ZELLIJ_MAX_PIPE_BUFFER_SIZE: usize = 16_384;
#[derive(Debug, Serialize, Deserialize)]
pub struct LoggingPipe {
buffer: VecDeque<u8>,
plugin_name: String,
plugin_id: PluginId,
}
impl LoggingPipe {
pub fn new(plugin_name: &str, plugin_id: PluginId) -> LoggingPipe {
LoggingPipe {
buffer: VecDeque::new(),
plugin_name: String::from(plugin_name),
plugin_id,
}
}
fn log_message(&self, message: &str) {
debug!(
"|{:<25.25}| {} [{:<10.15}] {}",
self.plugin_name,
chrono::Local::now().format("%Y-%m-%d %H:%M:%S.%3f"),
format!("id: {}", self.plugin_id),
message
);
}
}
impl Write for LoggingPipe {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
if self.buffer.len() + buf.len() > ZELLIJ_MAX_PIPE_BUFFER_SIZE {
let error_msg =
"Exceeded log buffer size. Make sure that your plugin calls flush on stderr on \
valid UTF-8 symbol boundary. Additionally, make sure that your log message contains \
endline \\n symbol.";
error!("{}: {}", self.plugin_name, error_msg);
self.buffer.clear();
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
error_msg,
));
}
self.buffer.extend(buf);
self.flush()?;
Ok(buf.len())
}
// When we flush, check if current buffer is valid utf8 string, split by '\n' and truncate buffer in the process.
// We assume that eventually, flush will be called on valid string boundary (i.e. std::str::from_utf8(..).is_ok() returns true at some point).
// Above assumption might not be true, in which case we'll have to think about it. Make it simple for now.
fn flush(&mut self) -> std::io::Result<()> {
self.buffer.make_contiguous();
match std::str::from_utf8(self.buffer.as_slices().0) {
Ok(converted_buffer) => {
if converted_buffer.contains('\n') {
let mut consumed_bytes = 0;
let mut split_converted_buffer = converted_buffer.split('\n').peekable();
while let Some(msg) = split_converted_buffer.next() {
if split_converted_buffer.peek().is_none() {
// Log last chunk iff the last char is endline. Otherwise do not do it.
if converted_buffer.ends_with('\n') && !msg.is_empty() {
self.log_message(msg);
consumed_bytes += msg.len() + 1;
}
} else {
self.log_message(msg);
consumed_bytes += msg.len() + 1;
}
}
drop(self.buffer.drain(..consumed_bytes));
}
},
Err(e) => Err::<(), _>(e)
.context("failed to flush logging pipe buffer")
.non_fatal(),
}
Ok(())
}
}
// Unit tests
#[cfg(test)]
mod logging_pipe_test {
use super::*;
#[test]
fn write_without_endl_does_not_consume_buffer_after_flush() {
let mut pipe = LoggingPipe::new("TestPipe", 0);
let test_buffer = b"Testing write";
pipe.write_all(test_buffer).expect("Err write");
pipe.flush().expect("Err flush");
assert_eq!(pipe.buffer.len(), test_buffer.len());
}
#[test]
fn write_with_single_endl_at_the_end_consumes_whole_buffer_after_flush() {
let mut pipe = LoggingPipe::new("TestPipe", 0);
let test_buffer = b"Testing write \n";
pipe.write_all(test_buffer).expect("Err write");
pipe.flush().expect("Err flush");
assert_eq!(pipe.buffer.len(), 0);
}
#[test]
fn write_with_endl_in_the_middle_consumes_buffer_up_to_endl_after_flush() {
let mut pipe = LoggingPipe::new("TestPipe", 0);
let test_buffer = b"Testing write \n";
let test_buffer2: &[_] = b"And the rest";
pipe.write_all(
[
test_buffer,
test_buffer,
test_buffer,
test_buffer,
test_buffer2,
]
.concat()
.as_slice(),
)
.expect("Err write");
pipe.flush().expect("Err flush");
assert_eq!(pipe.buffer.len(), test_buffer2.len());
}
#[test]
fn write_with_many_endl_consumes_whole_buffer_after_flush() {
let mut pipe = LoggingPipe::new("TestPipe", 0);
let test_buffer: &[_] = b"Testing write \n";
pipe.write_all(
[
test_buffer,
test_buffer,
test_buffer,
test_buffer,
test_buffer,
]
.concat()
.as_slice(),
)
.expect("Err write");
pipe.flush().expect("Err flush");
assert_eq!(pipe.buffer.len(), 0);
}
#[test]
fn write_with_incorrect_byte_boundary_does_not_crash() {
let mut pipe = LoggingPipe::new("TestPipe", 0);
let test_buffer = "😱".as_bytes();
// make sure it's not valid utf-8 string if we drop last symbol
assert!(std::str::from_utf8(&test_buffer[..test_buffer.len() - 1]).is_err());
pipe.write_all(&test_buffer[..test_buffer.len() - 1])
.expect("Err write");
pipe.flush().expect("Err flush");
assert_eq!(pipe.buffer.len(), test_buffer.len() - 1);
println!("len: {}, buf: {:?}", test_buffer.len(), test_buffer);
}
#[test]
fn write_with_many_endls_consumes_everything_after_flush() {
let mut pipe = LoggingPipe::new("TestPipe", 0);
let test_buffer: &[_] = b"Testing write \n";
pipe.write_all(
[test_buffer, test_buffer, b"\n", b"\n", b"\n"]
.concat()
.as_slice(),
)
.expect("Err write");
pipe.flush().expect("Err flush");
assert_eq!(pipe.buffer.len(), 0);
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/pane_groups.rs | zellij-server/src/pane_groups.rs | use std::collections::{HashMap, HashSet};
use zellij_utils::data::FloatingPaneCoordinates;
use zellij_utils::input::layout::{RunPluginOrAlias, SplitSize};
use zellij_utils::pane_size::Size;
use crate::{panes::PaneId, pty::PtyInstruction, thread_bus::ThreadSenders, ClientId};
pub struct PaneGroups {
panes_in_group: HashMap<ClientId, Vec<PaneId>>,
senders: ThreadSenders,
}
impl std::fmt::Debug for PaneGroups {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PaneGroups")
.field("panes_in_group", &self.panes_in_group)
.finish_non_exhaustive()
}
}
impl PaneGroups {
pub fn new(senders: ThreadSenders) -> Self {
PaneGroups {
panes_in_group: HashMap::new(),
senders,
}
}
pub fn clone_inner(&self) -> HashMap<ClientId, Vec<PaneId>> {
self.panes_in_group.clone()
}
pub fn get_client_pane_group(&self, client_id: &ClientId) -> HashSet<PaneId> {
self.panes_in_group
.get(client_id)
.map(|p| p.iter().copied().collect())
.unwrap_or_else(|| HashSet::new())
}
pub fn clear_pane_group(&mut self, client_id: &ClientId) {
self.panes_in_group.get_mut(client_id).map(|p| p.clear());
}
pub fn toggle_pane_id_in_group(
&mut self,
pane_id: PaneId,
screen_size: Size,
client_id: &ClientId,
) {
let previous_groups = self.clone_inner();
let client_pane_group = self
.panes_in_group
.entry(*client_id)
.or_insert_with(|| vec![]);
if client_pane_group.contains(&pane_id) {
client_pane_group.retain(|p| p != &pane_id);
} else {
client_pane_group.push(pane_id);
};
if self.should_launch_plugin(&previous_groups, client_id) {
self.launch_plugin(screen_size, client_id);
}
}
pub fn add_pane_id_to_group(
&mut self,
pane_id: PaneId,
screen_size: Size,
client_id: &ClientId,
) {
let previous_groups = self.clone_inner();
let client_pane_group = self
.panes_in_group
.entry(*client_id)
.or_insert_with(|| vec![]);
if !client_pane_group.contains(&pane_id) {
client_pane_group.push(pane_id);
}
if self.should_launch_plugin(&previous_groups, client_id) {
self.launch_plugin(screen_size, client_id);
}
}
pub fn group_and_ungroup_panes(
&mut self,
mut pane_ids_to_group: Vec<PaneId>,
pane_ids_to_ungroup: Vec<PaneId>,
screen_size: Size,
client_id: &ClientId,
) {
let previous_groups = self.clone_inner();
let client_pane_group = self
.panes_in_group
.entry(*client_id)
.or_insert_with(|| vec![]);
client_pane_group.append(&mut pane_ids_to_group);
client_pane_group.retain(|p| !pane_ids_to_ungroup.contains(p));
if self.should_launch_plugin(&previous_groups, client_id) {
self.launch_plugin(screen_size, client_id);
}
}
pub fn group_and_ungroup_panes_for_all_clients(
&mut self,
pane_ids_to_group: Vec<PaneId>,
pane_ids_to_ungroup: Vec<PaneId>,
screen_size: Size,
) {
let previous_groups = self.clone_inner();
let mut should_launch = false;
let all_connected_clients: Vec<ClientId> = self.panes_in_group.keys().copied().collect();
for client_id in &all_connected_clients {
let client_pane_group = self
.panes_in_group
.entry(*client_id)
.or_insert_with(|| vec![]);
client_pane_group.append(&mut pane_ids_to_group.clone());
client_pane_group.retain(|p| !pane_ids_to_ungroup.contains(p));
if self.should_launch_plugin(&previous_groups, &client_id) {
should_launch = true;
}
}
if should_launch {
if let Some(first_client) = all_connected_clients.first() {
self.launch_plugin(screen_size, first_client);
}
}
}
pub fn override_groups_with(&mut self, new_pane_groups: HashMap<ClientId, Vec<PaneId>>) {
self.panes_in_group = new_pane_groups;
}
fn should_launch_plugin(
&self,
previous_groups: &HashMap<ClientId, Vec<PaneId>>,
client_id: &ClientId,
) -> bool {
let mut should_launch = false;
for (client_id, previous_panes) in previous_groups {
let previous_panes_has_panes = !previous_panes.is_empty();
let current_panes_has_panes = self
.panes_in_group
.get(&client_id)
.map(|g| !g.is_empty())
.unwrap_or(false);
if !previous_panes_has_panes && current_panes_has_panes {
should_launch = true;
}
}
should_launch || previous_groups.get(&client_id).is_none()
}
fn launch_plugin(&self, screen_size: Size, client_id: &ClientId) {
if let Ok(run_plugin) =
RunPluginOrAlias::from_url("zellij:multiple-select", &None, None, None)
{
let tab_index = 1;
let size = Size::default();
let should_float = Some(true);
let should_be_opened_in_place = false;
let pane_title = None;
let skip_cache = false;
let cwd = None;
let should_focus_plugin = Some(false);
let width_30_percent = (screen_size.cols as f64 * 0.3) as usize;
let height_30_percent = (screen_size.rows as f64 * 0.3) as usize;
let width = std::cmp::max(width_30_percent, 48);
let height = std::cmp::max(height_30_percent, 10);
let y_position = screen_size.rows.saturating_sub(height + 2);
let floating_pane_coordinates = FloatingPaneCoordinates {
x: Some(SplitSize::Fixed(2)),
y: Some(SplitSize::Fixed(y_position)),
width: Some(SplitSize::Fixed(width)),
height: Some(SplitSize::Fixed(height)),
pinned: Some(true),
};
let _ = self.senders.send_to_pty(PtyInstruction::FillPluginCwd(
should_float,
should_be_opened_in_place,
pane_title,
run_plugin,
tab_index,
None,
*client_id,
size,
skip_cache,
cwd,
should_focus_plugin,
Some(floating_pane_coordinates),
None,
));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
fn create_mock_senders() -> ThreadSenders {
let mut mock = ThreadSenders::default();
mock.should_silently_fail = true;
mock
}
fn create_test_pane_groups() -> PaneGroups {
PaneGroups::new(create_mock_senders())
}
fn create_test_screen_size() -> Size {
Size { rows: 24, cols: 80 }
}
#[test]
fn new_creates_empty_pane_groups() {
let pane_groups = create_test_pane_groups();
assert!(pane_groups.panes_in_group.is_empty());
}
#[test]
fn clone_inner_returns_copy_of_internal_map() {
let mut pane_groups = create_test_pane_groups();
let client_id: ClientId = 1;
let pane_id = PaneId::Terminal(10);
let screen_size = create_test_screen_size();
pane_groups.add_pane_id_to_group(pane_id, screen_size, &client_id);
let cloned = pane_groups.clone_inner();
assert_eq!(cloned.len(), 1);
assert!(cloned.contains_key(&client_id));
assert_eq!(cloned[&client_id], vec![pane_id]);
}
#[test]
fn get_client_pane_group_returns_empty_set_for_nonexistent_client() {
let pane_groups = create_test_pane_groups();
let client_id: ClientId = 999;
let result = pane_groups.get_client_pane_group(&client_id);
assert!(result.is_empty());
}
#[test]
fn get_client_pane_group_returns_correct_panes() {
let mut pane_groups = create_test_pane_groups();
let client_id: ClientId = 1;
let pane_ids = vec![
PaneId::Terminal(10),
PaneId::Plugin(20),
PaneId::Terminal(30),
];
let screen_size = create_test_screen_size();
for pane_id in &pane_ids {
pane_groups.add_pane_id_to_group(*pane_id, screen_size, &client_id);
}
let result = pane_groups.get_client_pane_group(&client_id);
assert_eq!(result.len(), 3);
for pane_id in pane_ids {
assert!(result.contains(&pane_id));
}
}
#[test]
fn clear_pane_group_clears_existing_group() {
let mut pane_groups = create_test_pane_groups();
let client_id: ClientId = 1;
let pane_ids = vec![
PaneId::Terminal(10),
PaneId::Plugin(20),
PaneId::Terminal(30),
];
let screen_size = create_test_screen_size();
for pane_id in pane_ids {
pane_groups.add_pane_id_to_group(pane_id, screen_size, &client_id);
}
assert!(!pane_groups.get_client_pane_group(&client_id).is_empty());
pane_groups.clear_pane_group(&client_id);
assert!(pane_groups.get_client_pane_group(&client_id).is_empty());
}
#[test]
fn clear_pane_group_handles_nonexistent_client() {
let mut pane_groups = create_test_pane_groups();
let client_id: ClientId = 999;
pane_groups.clear_pane_group(&client_id);
assert!(pane_groups.get_client_pane_group(&client_id).is_empty());
}
#[test]
fn toggle_pane_id_adds_new_pane() {
let mut pane_groups = create_test_pane_groups();
let client_id: ClientId = 1;
let pane_id = PaneId::Terminal(10);
let screen_size = create_test_screen_size();
pane_groups.toggle_pane_id_in_group(pane_id, screen_size, &client_id);
let result = pane_groups.get_client_pane_group(&client_id);
assert!(result.contains(&pane_id));
}
#[test]
fn toggle_pane_id_removes_existing_pane() {
let mut pane_groups = create_test_pane_groups();
let client_id: ClientId = 1;
let pane_id = PaneId::Plugin(10);
let screen_size = create_test_screen_size();
pane_groups.add_pane_id_to_group(pane_id, screen_size, &client_id);
assert!(pane_groups
.get_client_pane_group(&client_id)
.contains(&pane_id));
pane_groups.toggle_pane_id_in_group(pane_id, screen_size, &client_id);
assert!(!pane_groups
.get_client_pane_group(&client_id)
.contains(&pane_id));
}
#[test]
fn add_pane_id_to_group_adds_new_pane() {
let mut pane_groups = create_test_pane_groups();
let client_id: ClientId = 1;
let pane_id = PaneId::Terminal(10);
let screen_size = create_test_screen_size();
pane_groups.add_pane_id_to_group(pane_id, screen_size, &client_id);
let result = pane_groups.get_client_pane_group(&client_id);
assert!(result.contains(&pane_id));
}
#[test]
fn add_pane_id_to_group_does_not_duplicate() {
let mut pane_groups = create_test_pane_groups();
let client_id: ClientId = 1;
let pane_id = PaneId::Plugin(10);
let screen_size = create_test_screen_size();
pane_groups.add_pane_id_to_group(pane_id, screen_size, &client_id);
pane_groups.add_pane_id_to_group(pane_id, screen_size, &client_id);
let result = pane_groups.get_client_pane_group(&client_id);
assert_eq!(result.len(), 1);
assert!(result.contains(&pane_id));
}
#[test]
fn group_and_ungroup_panes_adds_and_removes_correctly() {
let mut pane_groups = create_test_pane_groups();
let client_id: ClientId = 1;
let screen_size = create_test_screen_size();
let initial_panes = vec![PaneId::Terminal(1), PaneId::Plugin(2), PaneId::Terminal(3)];
for pane_id in &initial_panes {
pane_groups.add_pane_id_to_group(*pane_id, screen_size, &client_id);
}
let panes_to_add = vec![PaneId::Plugin(4), PaneId::Terminal(5)];
let panes_to_remove = vec![PaneId::Plugin(2), PaneId::Terminal(3)];
pane_groups.group_and_ungroup_panes(panes_to_add, panes_to_remove, screen_size, &client_id);
let result = pane_groups.get_client_pane_group(&client_id);
assert!(result.contains(&PaneId::Terminal(1)));
assert!(result.contains(&PaneId::Plugin(4)));
assert!(result.contains(&PaneId::Terminal(5)));
assert!(!result.contains(&PaneId::Plugin(2)));
assert!(!result.contains(&PaneId::Terminal(3)));
assert_eq!(result.len(), 3);
}
#[test]
fn override_groups_with_replaces_all_groups() {
let mut pane_groups = create_test_pane_groups();
let client_id1: ClientId = 1;
let client_id2: ClientId = 2;
let screen_size = create_test_screen_size();
pane_groups.add_pane_id_to_group(PaneId::Terminal(10), screen_size, &client_id1);
let mut new_groups = HashMap::new();
new_groups.insert(client_id2, vec![PaneId::Plugin(20), PaneId::Terminal(30)]);
pane_groups.override_groups_with(new_groups);
assert!(pane_groups.get_client_pane_group(&client_id1).is_empty());
let result = pane_groups.get_client_pane_group(&client_id2);
assert!(result.contains(&PaneId::Plugin(20)));
assert!(result.contains(&PaneId::Terminal(30)));
assert_eq!(result.len(), 2);
}
#[test]
fn multiple_clients_independent_groups() {
let mut pane_groups = create_test_pane_groups();
let client_id1: ClientId = 1;
let client_id2: ClientId = 2;
let screen_size = create_test_screen_size();
pane_groups.add_pane_id_to_group(PaneId::Terminal(10), screen_size, &client_id1);
pane_groups.add_pane_id_to_group(PaneId::Plugin(20), screen_size, &client_id2);
let group1 = pane_groups.get_client_pane_group(&client_id1);
let group2 = pane_groups.get_client_pane_group(&client_id2);
assert!(group1.contains(&PaneId::Terminal(10)));
assert!(!group1.contains(&PaneId::Plugin(20)));
assert!(group2.contains(&PaneId::Plugin(20)));
assert!(!group2.contains(&PaneId::Terminal(10)));
}
#[test]
fn pane_id_variants_work_correctly() {
let mut pane_groups = create_test_pane_groups();
let client_id: ClientId = 1;
let screen_size = create_test_screen_size();
let terminal_pane = PaneId::Terminal(100);
let plugin_pane = PaneId::Plugin(200);
pane_groups.add_pane_id_to_group(terminal_pane, screen_size, &client_id);
pane_groups.add_pane_id_to_group(plugin_pane, screen_size, &client_id);
let result = pane_groups.get_client_pane_group(&client_id);
assert!(result.contains(&terminal_pane));
assert!(result.contains(&plugin_pane));
assert_eq!(result.len(), 2);
let another_terminal = PaneId::Terminal(200);
assert!(!result.contains(&another_terminal));
}
#[test]
fn should_launch_plugin_returns_true_when_first_pane_added() {
let pane_groups = create_test_pane_groups();
let client_id: ClientId = 1;
let previous_groups = HashMap::new();
assert!(pane_groups.should_launch_plugin(&previous_groups, &client_id));
}
#[test]
fn should_launch_plugin_returns_true_when_empty_to_non_empty() {
let mut pane_groups = create_test_pane_groups();
let client_id: ClientId = 1;
let screen_size = create_test_screen_size();
let mut previous_groups = HashMap::new();
previous_groups.insert(client_id, vec![]);
pane_groups.add_pane_id_to_group(PaneId::Terminal(10), screen_size, &client_id);
assert!(pane_groups.should_launch_plugin(&previous_groups, &client_id));
}
#[test]
fn should_launch_plugin_returns_false_when_non_empty_to_non_empty() {
let mut pane_groups = create_test_pane_groups();
let client_id: ClientId = 1;
let screen_size = create_test_screen_size();
pane_groups.add_pane_id_to_group(PaneId::Terminal(10), screen_size, &client_id);
let previous_groups = pane_groups.clone_inner();
pane_groups.add_pane_id_to_group(PaneId::Plugin(20), screen_size, &client_id);
assert!(!pane_groups.should_launch_plugin(&previous_groups, &client_id));
}
#[test]
fn should_launch_plugin_returns_false_when_non_empty_to_empty() {
let pane_groups = create_test_pane_groups();
let client_id: ClientId = 1;
let mut previous_groups = HashMap::new();
previous_groups.insert(client_id, vec![PaneId::Terminal(10)]);
assert!(!pane_groups.should_launch_plugin(&previous_groups, &client_id));
}
#[test]
fn should_launch_plugin_returns_false_when_empty_to_empty() {
let pane_groups = create_test_pane_groups();
let client_id: ClientId = 1;
let mut previous_groups = HashMap::new();
previous_groups.insert(client_id, vec![]);
assert!(!pane_groups.should_launch_plugin(&previous_groups, &client_id));
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/pty.rs | zellij-server/src/pty.rs | use crate::background_jobs::BackgroundJob;
use crate::route::NotificationEnd;
use crate::terminal_bytes::TerminalBytes;
use crate::{
panes::PaneId,
plugins::{PluginId, PluginInstruction},
screen::ScreenInstruction,
session_layout_metadata::SessionLayoutMetadata,
thread_bus::{Bus, ThreadSenders},
ClientId, ServerInstruction,
};
use async_std::{
self,
task::{self, JoinHandle},
};
use nix::unistd::Pid;
use std::sync::Arc;
use std::{collections::HashMap, os::unix::io::RawFd, path::PathBuf};
use zellij_utils::{
data::{
CommandOrPlugin, Event, FloatingPaneCoordinates, GetPanePidResponse, NewPanePlacement,
OriginatingPlugin,
},
errors::prelude::*,
errors::{ContextType, PtyContext},
input::{
command::{OpenFilePayload, RunCommand, TerminalAction},
layout::{
FloatingPaneLayout, Layout, Run, RunPluginOrAlias, SwapFloatingLayout, SwapTiledLayout,
TiledPaneLayout,
},
},
pane_size::Size,
session_serialization,
};
pub type VteBytes = Vec<u8>;
pub type TabIndex = u32;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ClientTabIndexOrPaneId {
ClientId(ClientId),
TabIndex(usize),
PaneId(PaneId),
}
/// Instructions related to PTYs (pseudoterminals).
#[derive(Clone, Debug)]
pub enum PtyInstruction {
SpawnTerminal(
Option<TerminalAction>,
Option<String>,
NewPanePlacement,
bool, // start suppressed
ClientTabIndexOrPaneId,
Option<NotificationEnd>, // completion signal
bool, // set_blocking
), // bool (if Some) is
// should_float, String is an optional pane name
OpenInPlaceEditor(
PathBuf,
Option<usize>,
ClientTabIndexOrPaneId,
Option<NotificationEnd>,
), // Option<usize> is the optional line number
UpdateActivePane(Option<PaneId>, ClientId),
GoToTab(TabIndex, ClientId),
NewTab(
Option<PathBuf>,
Option<TerminalAction>,
Option<TiledPaneLayout>,
Vec<FloatingPaneLayout>,
usize, // tab_index
HashMap<RunPluginOrAlias, Vec<u32>>, // plugin_ids
Option<Vec<CommandOrPlugin>>, // initial_panes
bool, // block_on_first_terminal
bool, // should change focus to new tab
(ClientId, bool), // bool -> is_web_client
Option<NotificationEnd>, // completion signal
), // the String is the tab name
OverrideLayout(
Option<PathBuf>, // CWD
Option<TerminalAction>, // Default Shell
TiledPaneLayout,
Vec<FloatingPaneLayout>,
Option<Vec<SwapTiledLayout>>,
Option<Vec<SwapFloatingLayout>>,
bool, // retain_existing_terminal_panes
bool, // retain_existing_plugin_panes
usize, // tab_index
HashMap<RunPluginOrAlias, Vec<u32>>, // plugin_ids
ClientId,
Option<NotificationEnd>,
),
ClosePane(PaneId, Option<NotificationEnd>),
CloseTab(Vec<PaneId>),
ReRunCommandInPane(PaneId, RunCommand, Option<NotificationEnd>),
DropToShellInPane {
pane_id: PaneId,
shell: Option<PathBuf>,
working_dir: Option<PathBuf>,
completion_tx: Option<NotificationEnd>,
},
SpawnInPlaceTerminal(
Option<TerminalAction>,
Option<String>,
bool, // close replaced pane
ClientTabIndexOrPaneId,
Option<NotificationEnd>, // completion signal
), // String is an optional pane name
DumpLayout(SessionLayoutMetadata, ClientId, Option<NotificationEnd>),
DumpLayoutToPlugin(SessionLayoutMetadata, PluginId),
LogLayoutToHd(SessionLayoutMetadata),
FillPluginCwd(
Option<bool>, // should float
bool, // should be opened in place
Option<String>, // pane title
RunPluginOrAlias,
usize, // tab index
Option<PaneId>, // pane id to replace if this is to be opened "in-place"
ClientId,
Size,
bool, // skip cache
Option<PathBuf>, // if Some, will not fill cwd but just forward the message
Option<bool>, // should focus plugin
Option<FloatingPaneCoordinates>,
Option<NotificationEnd>,
),
ListClientsMetadata(SessionLayoutMetadata, ClientId, Option<NotificationEnd>),
Reconfigure {
client_id: ClientId,
default_editor: Option<PathBuf>,
post_command_discovery_hook: Option<String>,
},
ListClientsToPlugin(SessionLayoutMetadata, PluginId, ClientId),
ReportPluginCwd(PluginId, PathBuf),
SendSigintToPaneId(PaneId),
SendSigkillToPaneId(PaneId),
GetPanePid {
pane_id: PaneId,
response_channel: crossbeam::channel::Sender<GetPanePidResponse>,
},
UpdateAndReportCwds,
Exit,
}
impl From<&PtyInstruction> for PtyContext {
fn from(pty_instruction: &PtyInstruction) -> Self {
match *pty_instruction {
PtyInstruction::SpawnTerminal(..) => PtyContext::SpawnTerminal,
PtyInstruction::OpenInPlaceEditor(..) => PtyContext::OpenInPlaceEditor,
PtyInstruction::UpdateActivePane(..) => PtyContext::UpdateActivePane,
PtyInstruction::GoToTab(..) => PtyContext::GoToTab,
PtyInstruction::ClosePane(..) => PtyContext::ClosePane,
PtyInstruction::CloseTab(_) => PtyContext::CloseTab,
PtyInstruction::NewTab(..) => PtyContext::NewTab,
PtyInstruction::OverrideLayout(..) => PtyContext::OverrideLayout,
PtyInstruction::ReRunCommandInPane(..) => PtyContext::ReRunCommandInPane,
PtyInstruction::DropToShellInPane { .. } => PtyContext::DropToShellInPane,
PtyInstruction::SpawnInPlaceTerminal(..) => PtyContext::SpawnInPlaceTerminal,
PtyInstruction::DumpLayout(..) => PtyContext::DumpLayout,
PtyInstruction::DumpLayoutToPlugin(..) => PtyContext::DumpLayoutToPlugin,
PtyInstruction::LogLayoutToHd(..) => PtyContext::LogLayoutToHd,
PtyInstruction::FillPluginCwd(..) => PtyContext::FillPluginCwd,
PtyInstruction::ListClientsMetadata(..) => PtyContext::ListClientsMetadata,
PtyInstruction::Reconfigure { .. } => PtyContext::Reconfigure,
PtyInstruction::ListClientsToPlugin(..) => PtyContext::ListClientsToPlugin,
PtyInstruction::ReportPluginCwd(..) => PtyContext::ReportPluginCwd,
PtyInstruction::SendSigintToPaneId(..) => PtyContext::SendSigintToPaneId,
PtyInstruction::SendSigkillToPaneId(..) => PtyContext::SendSigkillToPaneId,
PtyInstruction::GetPanePid { .. } => PtyContext::GetPanePid,
PtyInstruction::UpdateAndReportCwds => PtyContext::UpdateAndReportCwds,
PtyInstruction::Exit => PtyContext::Exit,
}
}
}
pub(crate) struct Pty {
pub active_panes: HashMap<ClientId, PaneId>,
pub bus: Bus<PtyInstruction>,
pub id_to_child_pid: HashMap<u32, RawFd>, // terminal_id => child raw fd
originating_plugins: HashMap<u32, OriginatingPlugin>,
debug_to_file: bool,
task_handles: HashMap<u32, JoinHandle<()>>, // terminal_id to join-handle
default_editor: Option<PathBuf>,
post_command_discovery_hook: Option<String>,
plugin_cwds: HashMap<u32, PathBuf>, // plugin_id -> cwd
terminal_cwds: HashMap<u32, PathBuf>, // terminal_id -> cwd
}
pub(crate) fn pty_thread_main(mut pty: Pty, layout: Box<Layout>) -> Result<()> {
loop {
let (event, mut err_ctx) = pty.bus.recv().expect("failed to receive event on channel");
err_ctx.add_call(ContextType::Pty((&event).into()));
match event {
PtyInstruction::SpawnTerminal(
terminal_action,
name,
new_pane_placement,
start_suppressed,
client_or_tab_index,
completion_tx,
set_blocking,
) => {
let err_context =
|| format!("failed to spawn terminal for {:?}", client_or_tab_index);
let (hold_on_close, run_command, pane_title, open_file_payload) =
match &terminal_action {
Some(TerminalAction::RunCommand(run_command)) => (
run_command.hold_on_close,
Some(run_command.clone()),
if run_command.use_terminal_title {
None
} else {
Some(name.unwrap_or_else(|| run_command.to_string()))
},
None,
),
Some(TerminalAction::OpenFile(open_file_payload)) => {
(false, None, name, Some(open_file_payload.clone()))
},
_ => (false, None, name, None),
};
let invoked_with = match &terminal_action {
Some(TerminalAction::RunCommand(run_command)) => {
Some(Run::Command(run_command.clone()))
},
Some(TerminalAction::OpenFile(payload)) => Some(Run::EditFile(
payload.path.clone(),
payload.line_number.clone(),
payload.cwd.clone(),
)),
_ => None,
};
match pty
.spawn_terminal(terminal_action, client_or_tab_index)
.with_context(err_context)
{
Ok((pid, starts_held)) => {
let hold_for_command = if starts_held {
run_command.clone()
} else {
None
};
// if this command originated in a plugin, we send the plugin back an event
// to let it know the command started and which pane_id it has
if let Some(originating_plugin) =
run_command.and_then(|r| r.originating_plugin)
{
pty.originating_plugins
.insert(pid, originating_plugin.clone());
let update_event =
Event::CommandPaneOpened(pid, originating_plugin.context.clone());
pty.bus
.senders
.send_to_plugin(PluginInstruction::Update(vec![(
Some(originating_plugin.plugin_id),
Some(originating_plugin.client_id),
update_event,
)]))
.with_context(err_context)?;
}
if let Some(originating_plugin) =
open_file_payload.and_then(|o| o.originating_plugin)
{
let update_event =
Event::EditPaneOpened(pid, originating_plugin.context.clone());
pty.bus
.senders
.send_to_plugin(PluginInstruction::Update(vec![(
Some(originating_plugin.plugin_id),
Some(originating_plugin.client_id),
update_event,
)]))
.with_context(err_context)?;
}
pty.bus
.senders
.send_to_screen(ScreenInstruction::NewPane(
PaneId::Terminal(pid),
pane_title,
hold_for_command,
invoked_with,
new_pane_placement,
start_suppressed,
client_or_tab_index,
completion_tx,
set_blocking,
))
.with_context(err_context)?;
},
Err(err) => match err.downcast_ref::<ZellijError>() {
Some(ZellijError::CommandNotFound { terminal_id, .. }) => {
if hold_on_close {
let hold_for_command = None; // we do not hold an "error" pane
pty.bus
.senders
.send_to_screen(ScreenInstruction::NewPane(
PaneId::Terminal(*terminal_id),
pane_title,
hold_for_command,
invoked_with,
new_pane_placement,
start_suppressed,
client_or_tab_index,
completion_tx,
set_blocking,
))
.with_context(err_context)?;
if let Some(run_command) = run_command {
send_command_not_found_to_screen(
pty.bus.senders.clone(),
*terminal_id,
run_command.clone(),
)
.with_context(err_context)?;
}
} else {
log::error!("Failed to spawn terminal: {:?}", err);
pty.close_pane(PaneId::Terminal(*terminal_id))
.with_context(err_context)?;
}
},
_ => Err::<(), _>(err).non_fatal(),
},
}
},
PtyInstruction::SpawnInPlaceTerminal(
terminal_action,
name,
close_replaced_pane,
client_id_tab_index_or_pane_id,
completion_tx,
) => {
let err_context = || {
format!(
"failed to spawn terminal for {:?}",
client_id_tab_index_or_pane_id
)
};
let (hold_on_close, run_command, pane_title) = match &terminal_action {
Some(TerminalAction::RunCommand(run_command)) => (
run_command.hold_on_close,
Some(run_command.clone()),
if run_command.use_terminal_title {
None
} else {
Some(name.unwrap_or_else(|| run_command.to_string()))
},
),
_ => (false, None, name),
};
let invoked_with = match &terminal_action {
Some(TerminalAction::RunCommand(run_command)) => {
Some(Run::Command(run_command.clone()))
},
Some(TerminalAction::OpenFile(payload)) => Some(Run::EditFile(
payload.path.clone(),
payload.line_number.clone(),
payload.cwd.clone(),
)),
_ => None,
};
match pty
.spawn_terminal(terminal_action, client_id_tab_index_or_pane_id)
.with_context(err_context)
{
Ok((pid, starts_held)) => {
let hold_for_command = if starts_held { run_command } else { None };
pty.bus
.senders
.send_to_screen(ScreenInstruction::ReplacePane(
PaneId::Terminal(pid),
hold_for_command,
pane_title,
invoked_with,
close_replaced_pane,
client_id_tab_index_or_pane_id,
completion_tx,
))
.with_context(err_context)?;
},
Err(err) => match err.downcast_ref::<ZellijError>() {
Some(ZellijError::CommandNotFound { terminal_id, .. }) => {
if hold_on_close {
let hold_for_command = None; // we do not hold an "error" pane
pty.bus
.senders
.send_to_screen(ScreenInstruction::ReplacePane(
PaneId::Terminal(*terminal_id),
hold_for_command,
pane_title,
invoked_with,
close_replaced_pane,
client_id_tab_index_or_pane_id,
completion_tx,
))
.with_context(err_context)?;
if let Some(run_command) = run_command {
send_command_not_found_to_screen(
pty.bus.senders.clone(),
*terminal_id,
run_command.clone(),
)
.with_context(err_context)?;
}
} else {
log::error!("Failed to spawn terminal: {:?}", err);
pty.close_pane(PaneId::Terminal(*terminal_id))
.with_context(err_context)?;
}
},
_ => Err::<(), _>(err).non_fatal(),
},
}
},
PtyInstruction::OpenInPlaceEditor(
temp_file,
line_number,
client_tab_index_or_pane_id,
_completion_tx,
) => {
let err_context = || format!("failed to open in-place editor for client");
match pty.spawn_terminal(
Some(TerminalAction::OpenFile(OpenFilePayload::new(
temp_file,
line_number,
None,
))),
client_tab_index_or_pane_id,
) {
Ok((pid, _starts_held)) => {
pty.bus
.senders
.send_to_screen(ScreenInstruction::OpenInPlaceEditor(
PaneId::Terminal(pid),
client_tab_index_or_pane_id,
))
.with_context(err_context)?;
},
Err(e) => {
Err::<(), _>(e).with_context(err_context).non_fatal();
},
}
},
PtyInstruction::UpdateActivePane(pane_id, client_id) => {
pty.set_active_pane(pane_id, client_id);
},
PtyInstruction::GoToTab(tab_index, client_id) => {
pty.bus
.senders
.send_to_screen(ScreenInstruction::GoToTab(tab_index, Some(client_id), None))
.with_context(|| {
format!("failed to move client {} to tab {}", client_id, tab_index)
})?;
},
PtyInstruction::NewTab(
cwd,
terminal_action,
tab_layout,
floating_panes_layout,
tab_index,
plugin_ids,
initial_panes,
block_on_first_terminal,
should_change_focus_to_new_tab,
client_id_and_is_web_client,
completion_tx,
) => {
let err_context = || "failed to open new tab";
let floating_panes_layout = if floating_panes_layout.is_empty() {
layout.new_tab().1
} else {
floating_panes_layout
};
pty.spawn_terminals_for_layout(
cwd,
tab_layout.unwrap_or_else(|| layout.new_tab().0),
floating_panes_layout,
terminal_action.clone(),
plugin_ids,
initial_panes,
tab_index,
block_on_first_terminal,
should_change_focus_to_new_tab,
client_id_and_is_web_client,
completion_tx,
)
.with_context(err_context)?;
},
PtyInstruction::OverrideLayout(
cwd,
default_shell,
tiled_layout,
floating_panes_layout,
swap_tiled_layouts,
swap_floating_layouts,
retain_existing_terminal_panes,
retain_existing_plugin_panes,
tab_index,
plugin_ids,
client_id,
completion_tx,
) => {
let err_context = || "failed to override layout";
pty.spawn_terminals_for_layout_override(
cwd,
tiled_layout,
floating_panes_layout,
default_shell,
plugin_ids,
tab_index,
client_id,
swap_tiled_layouts,
swap_floating_layouts,
retain_existing_terminal_panes,
retain_existing_plugin_panes,
completion_tx,
)
.with_context(err_context)?;
},
PtyInstruction::ClosePane(id, _completion_tx) => {
pty.close_pane(id)
.and_then(|_| {
pty.bus
.senders
.send_to_server(ServerInstruction::UnblockInputThread)
})
.with_context(|| format!("failed to close pane {:?}", id))?;
},
PtyInstruction::CloseTab(ids) => {
pty.close_tab(ids)
.and_then(|_| {
pty.bus
.senders
.send_to_server(ServerInstruction::UnblockInputThread)
})
.context("failed to close tabs")?;
},
PtyInstruction::ReRunCommandInPane(pane_id, run_command, _completion_tx) => {
let err_context = || format!("failed to rerun command in pane {:?}", pane_id);
match pty
.rerun_command_in_pane(pane_id, run_command.clone())
.with_context(err_context)
{
Ok(..) => {},
Err(err) => match err.downcast_ref::<ZellijError>() {
Some(ZellijError::CommandNotFound { terminal_id, .. }) => {
if run_command.hold_on_close {
pty.bus
.senders
.send_to_screen(ScreenInstruction::PtyBytes(
*terminal_id,
format!(
"Command not found: {}",
run_command.command.display()
)
.as_bytes()
.to_vec(),
))
.with_context(err_context)?;
pty.bus
.senders
.send_to_screen(ScreenInstruction::HoldPane(
PaneId::Terminal(*terminal_id),
Some(2), // exit status
run_command,
))
.with_context(err_context)?;
}
},
_ => Err::<(), _>(err).non_fatal(),
},
}
},
PtyInstruction::DropToShellInPane {
pane_id,
shell,
working_dir,
completion_tx: _completion_tx,
} => {
let err_context = || format!("failed to rerun command in pane {:?}", pane_id);
// TODO: get configured default_shell from screen/tab as an option and default to
// this otherwise (also look for a place that turns get_default_shell into a
// RunCommand, we might have done this before)
let run_command = RunCommand {
command: shell.unwrap_or_else(|| get_default_shell()),
hold_on_close: false,
hold_on_start: false,
cwd: working_dir,
..Default::default()
};
match pty
.rerun_command_in_pane(pane_id, run_command.clone())
.with_context(err_context)
{
Ok(..) => {},
Err(err) => match err.downcast_ref::<ZellijError>() {
Some(ZellijError::CommandNotFound { terminal_id, .. }) => {
if run_command.hold_on_close {
pty.bus
.senders
.send_to_screen(ScreenInstruction::PtyBytes(
*terminal_id,
format!(
"Command not found: {}",
run_command.command.display()
)
.as_bytes()
.to_vec(),
))
.with_context(err_context)?;
pty.bus
.senders
.send_to_screen(ScreenInstruction::HoldPane(
PaneId::Terminal(*terminal_id),
Some(2), // exit status
run_command,
))
.with_context(err_context)?;
}
},
_ => Err::<(), _>(err).non_fatal(),
},
}
},
PtyInstruction::DumpLayout(mut session_layout_metadata, client_id, completion_tx) => {
let err_context = || format!("Failed to dump layout");
pty.populate_session_layout_metadata(&mut session_layout_metadata);
match session_serialization::serialize_session_layout(
session_layout_metadata.into(),
) {
Ok((kdl_layout, _pane_contents)) => {
pty.bus
.senders
.send_to_server(ServerInstruction::Log(
vec![kdl_layout],
client_id,
completion_tx,
))
.with_context(err_context)
.non_fatal();
},
Err(e) => {
pty.bus
.senders
.send_to_server(ServerInstruction::Log(
vec![e.to_owned()],
client_id,
completion_tx,
))
.with_context(err_context)
.non_fatal();
},
}
},
PtyInstruction::ListClientsMetadata(
mut session_layout_metadata,
client_id,
completion_tx,
) => {
let err_context = || format!("Failed to dump layout");
pty.populate_session_layout_metadata(&mut session_layout_metadata);
pty.bus
.senders
.send_to_server(ServerInstruction::Log(
vec![format!(
"{}",
session_layout_metadata.list_clients_metadata(),
)],
client_id,
completion_tx,
))
.with_context(err_context)
.non_fatal();
},
PtyInstruction::DumpLayoutToPlugin(mut session_layout_metadata, plugin_id) => {
let err_context = || format!("Failed to dump layout");
pty.populate_session_layout_metadata(&mut session_layout_metadata);
pty.bus
.senders
.send_to_plugin(PluginInstruction::DumpLayoutToPlugin(
session_layout_metadata,
plugin_id,
))
.with_context(err_context)
.non_fatal();
},
PtyInstruction::ListClientsToPlugin(
mut session_layout_metadata,
plugin_id,
client_id,
) => {
let err_context = || format!("Failed to dump layout");
pty.populate_session_layout_metadata(&mut session_layout_metadata);
pty.bus
.senders
.send_to_plugin(PluginInstruction::ListClientsToPlugin(
session_layout_metadata,
plugin_id,
client_id,
))
.with_context(err_context)
.non_fatal();
},
PtyInstruction::ReportPluginCwd(plugin_id, cwd) => {
pty.plugin_cwds.insert(plugin_id, cwd);
},
PtyInstruction::LogLayoutToHd(mut session_layout_metadata) => {
let err_context = || format!("Failed to dump layout");
pty.populate_session_layout_metadata(&mut session_layout_metadata);
if session_layout_metadata.is_dirty() {
match session_serialization::serialize_session_layout(
session_layout_metadata.into(),
) {
Ok(kdl_layout_and_pane_contents) => {
pty.bus
.senders
.send_to_background_jobs(BackgroundJob::ReportLayoutInfo(
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/session_layout_metadata.rs | zellij-server/src/session_layout_metadata.rs | use crate::panes::PaneId;
use crate::ClientId;
use std::collections::{BTreeMap, HashMap};
use std::path::PathBuf;
use zellij_utils::common_path::common_path_all;
use zellij_utils::pane_size::PaneGeom;
use zellij_utils::{
input::command::RunCommand,
input::layout::{Layout, Run, RunPlugin, RunPluginOrAlias},
input::plugins::PluginAliases,
session_serialization::{
extract_command_and_args, extract_edit_and_line_number, extract_plugin_and_config,
GlobalLayoutManifest, PaneLayoutManifest, TabLayoutManifest,
},
};
#[derive(Default, Debug, Clone)]
pub struct SessionLayoutMetadata {
default_layout: Box<Layout>,
global_cwd: Option<PathBuf>,
pub default_shell: Option<PathBuf>,
pub default_editor: Option<PathBuf>,
tabs: Vec<TabLayoutMetadata>,
}
impl SessionLayoutMetadata {
pub fn new(default_layout: Box<Layout>) -> Self {
SessionLayoutMetadata {
default_layout,
..Default::default()
}
}
pub fn update_default_shell(&mut self, default_shell: PathBuf) {
if self.default_shell.is_none() {
self.default_shell = Some(default_shell);
}
for tab in self.tabs.iter_mut() {
for tiled_pane in tab.tiled_panes.iter_mut() {
if let Some(Run::Command(run_command)) = tiled_pane.run.as_mut() {
if Self::is_default_shell(
self.default_shell.as_ref(),
&run_command.command.display().to_string(),
&run_command.args,
) {
tiled_pane.run = None;
}
}
}
for floating_pane in tab.floating_panes.iter_mut() {
if let Some(Run::Command(run_command)) = floating_pane.run.as_mut() {
if Self::is_default_shell(
self.default_shell.as_ref(),
&run_command.command.display().to_string(),
&run_command.args,
) {
floating_pane.run = None;
}
}
}
}
}
pub fn list_clients_metadata(&self) -> String {
let mut clients_metadata: BTreeMap<ClientId, ClientMetadata> = BTreeMap::new();
for tab in &self.tabs {
let panes = if tab.hide_floating_panes {
&tab.tiled_panes
} else {
&tab.floating_panes
};
for pane in panes {
for focused_client in &pane.focused_clients {
clients_metadata.insert(
*focused_client,
ClientMetadata {
pane_id: pane.id.clone(),
command: pane.run.clone(),
},
);
}
}
}
ClientMetadata::render_many(clients_metadata, &self.default_editor)
}
pub fn all_clients_metadata(&self) -> BTreeMap<ClientId, ClientMetadata> {
let mut clients_metadata: BTreeMap<ClientId, ClientMetadata> = BTreeMap::new();
for tab in &self.tabs {
let panes = if tab.hide_floating_panes {
&tab.tiled_panes
} else {
&tab.floating_panes
};
for pane in panes {
for focused_client in &pane.focused_clients {
clients_metadata.insert(
*focused_client,
ClientMetadata {
pane_id: pane.id.clone(),
command: pane.run.clone(),
},
);
}
}
}
clients_metadata
}
pub fn is_dirty(&self) -> bool {
// here we check to see if the serialized layout would be different than the base one, and
// thus is "dirty". A layout is considered dirty if one of the following is true:
// 1. The current number of panes is different than the number of panes in the base layout
// (meaning a pane was opened or closed)
// 2. One or more terminal panes are running a command that is not the default shell
let base_layout_pane_count = self.default_layout.pane_count();
let current_pane_count = self.pane_count();
if current_pane_count != base_layout_pane_count {
return true;
}
for tab in &self.tabs {
for tiled_pane in &tab.tiled_panes {
if let Some(Run::Command(run_command)) = tiled_pane.run.as_ref() {
if !Self::is_default_shell(
self.default_shell.as_ref(),
&run_command.command.display().to_string(),
&run_command.args,
) {
return true;
}
}
}
for floating_pane in &tab.floating_panes {
if let Some(Run::Command(run_command)) = floating_pane.run.as_ref() {
if !Self::is_default_shell(
self.default_shell.as_ref(),
&run_command.command.display().to_string(),
&run_command.args,
) {
return true;
}
}
}
}
false
}
fn pane_count(&self) -> usize {
let mut pane_count = 0;
for tab in &self.tabs {
for tiled_pane in &tab.tiled_panes {
if !self.should_exclude_from_count(tiled_pane) {
pane_count += 1;
}
}
for floating_pane in &tab.floating_panes {
if !self.should_exclude_from_count(floating_pane) {
pane_count += 1;
}
}
}
pane_count
}
fn should_exclude_from_count(&self, pane: &PaneLayoutMetadata) -> bool {
if let Some(Run::Plugin(run_plugin)) = &pane.run {
let location_string = run_plugin.location_string();
if location_string == "zellij:about" {
return true;
}
if location_string == "zellij:session-manager" {
return true;
}
if location_string == "zellij:plugin-manager" {
return true;
}
if location_string == "zellij:configuration-manager" {
return true;
}
if location_string == "zellij:share" {
return true;
}
}
false
}
fn is_default_shell(
default_shell: Option<&PathBuf>,
command_name: &String,
args: &Vec<String>,
) -> bool {
default_shell
.as_ref()
.map(|c| c.display().to_string())
.as_ref()
== Some(command_name)
&& args.is_empty()
}
}
impl SessionLayoutMetadata {
pub fn add_tab(
&mut self,
name: String,
is_focused: bool,
hide_floating_panes: bool,
tiled_panes: Vec<PaneLayoutMetadata>,
floating_panes: Vec<PaneLayoutMetadata>,
) {
self.tabs.push(TabLayoutMetadata {
name: Some(name),
is_focused,
hide_floating_panes,
tiled_panes,
floating_panes,
})
}
pub fn all_terminal_ids(&self) -> Vec<u32> {
let mut terminal_ids = vec![];
for tab in &self.tabs {
for pane_layout_metadata in &tab.tiled_panes {
if let PaneId::Terminal(id) = pane_layout_metadata.id {
terminal_ids.push(id);
}
}
for pane_layout_metadata in &tab.floating_panes {
if let PaneId::Terminal(id) = pane_layout_metadata.id {
terminal_ids.push(id);
}
}
}
terminal_ids
}
pub fn all_plugin_ids(&self) -> Vec<u32> {
let mut plugin_ids = vec![];
for tab in &self.tabs {
for pane_layout_metadata in &tab.tiled_panes {
if let PaneId::Plugin(id) = pane_layout_metadata.id {
plugin_ids.push(id);
}
}
for pane_layout_metadata in &tab.floating_panes {
if let PaneId::Plugin(id) = pane_layout_metadata.id {
plugin_ids.push(id);
}
}
}
plugin_ids
}
pub fn update_terminal_commands(
&mut self,
mut terminal_ids_to_commands: HashMap<u32, Vec<String>>,
) {
let mut update_cmd_in_pane_metadata = |pane_layout_metadata: &mut PaneLayoutMetadata| {
if let PaneId::Terminal(id) = pane_layout_metadata.id {
if let Some(command) = terminal_ids_to_commands.remove(&id) {
let mut command_line = command.iter();
if let Some(command_name) = command_line.next() {
let args: Vec<String> = command_line.map(|c| c.to_owned()).collect();
if Self::is_default_shell(self.default_shell.as_ref(), &command_name, &args)
{
pane_layout_metadata.run = None;
} else {
let mut run_command = RunCommand::new(PathBuf::from(command_name));
run_command.args = args;
pane_layout_metadata.run = Some(Run::Command(run_command));
}
}
}
}
};
for tab in self.tabs.iter_mut() {
for pane_layout_metadata in tab.tiled_panes.iter_mut() {
update_cmd_in_pane_metadata(pane_layout_metadata);
}
for pane_layout_metadata in tab.floating_panes.iter_mut() {
update_cmd_in_pane_metadata(pane_layout_metadata);
}
}
}
pub fn update_terminal_cwds(&mut self, mut terminal_ids_to_cwds: HashMap<u32, PathBuf>) {
if let Some(common_path_between_cwds) =
common_path_all(terminal_ids_to_cwds.values().map(|p| p.as_path()))
{
terminal_ids_to_cwds.values_mut().for_each(|p| {
if let Ok(stripped) = p.strip_prefix(&common_path_between_cwds) {
*p = PathBuf::from(stripped)
}
});
self.global_cwd = Some(PathBuf::from(common_path_between_cwds));
}
let mut update_cwd_in_pane_metadata = |pane_layout_metadata: &mut PaneLayoutMetadata| {
if let PaneId::Terminal(id) = pane_layout_metadata.id {
if let Some(cwd) = terminal_ids_to_cwds.remove(&id) {
pane_layout_metadata.cwd = Some(cwd);
}
}
};
for tab in self.tabs.iter_mut() {
for pane_layout_metadata in tab.tiled_panes.iter_mut() {
update_cwd_in_pane_metadata(pane_layout_metadata);
}
for pane_layout_metadata in tab.floating_panes.iter_mut() {
update_cwd_in_pane_metadata(pane_layout_metadata);
}
}
}
pub fn update_plugin_cmds(&mut self, mut plugin_ids_to_run_plugins: HashMap<u32, RunPlugin>) {
let mut update_cmd_in_pane_metadata = |pane_layout_metadata: &mut PaneLayoutMetadata| {
if let PaneId::Plugin(id) = pane_layout_metadata.id {
if let Some(run_plugin) = plugin_ids_to_run_plugins.remove(&id) {
pane_layout_metadata.run =
Some(Run::Plugin(RunPluginOrAlias::RunPlugin(run_plugin)));
}
}
};
for tab in self.tabs.iter_mut() {
for pane_layout_metadata in tab.tiled_panes.iter_mut() {
update_cmd_in_pane_metadata(pane_layout_metadata);
}
for pane_layout_metadata in tab.floating_panes.iter_mut() {
update_cmd_in_pane_metadata(pane_layout_metadata);
}
}
}
pub fn update_default_editor(&mut self, default_editor: &Option<PathBuf>) {
let default_editor = default_editor.clone().unwrap_or_else(|| {
PathBuf::from(
std::env::var("EDITOR")
.unwrap_or_else(|_| std::env::var("VISUAL").unwrap_or_else(|_| "vi".into())),
)
});
self.default_editor = Some(default_editor);
}
pub fn update_plugin_aliases_in_default_layout(&mut self, plugin_aliases: &PluginAliases) {
self.default_layout
.populate_plugin_aliases_in_layout(&plugin_aliases);
}
}
impl Into<GlobalLayoutManifest> for SessionLayoutMetadata {
fn into(self) -> GlobalLayoutManifest {
GlobalLayoutManifest {
default_layout: self.default_layout,
default_shell: self.default_shell,
global_cwd: self.global_cwd,
tabs: self
.tabs
.into_iter()
.map(|t| (t.name.clone().unwrap_or_default(), t.into()))
.collect(),
}
}
}
impl Into<TabLayoutManifest> for TabLayoutMetadata {
fn into(self) -> TabLayoutManifest {
TabLayoutManifest {
tiled_panes: self.tiled_panes.into_iter().map(|t| t.into()).collect(),
floating_panes: self.floating_panes.into_iter().map(|t| t.into()).collect(),
is_focused: self.is_focused,
hide_floating_panes: self.hide_floating_panes,
}
}
}
impl Into<PaneLayoutManifest> for PaneLayoutMetadata {
fn into(self) -> PaneLayoutManifest {
PaneLayoutManifest {
geom: self.geom,
run: self.run,
cwd: self.cwd,
is_borderless: self.is_borderless,
title: self.title,
is_focused: self.is_focused,
pane_contents: self.pane_contents,
}
}
}
#[derive(Default, Debug, Clone)]
pub struct TabLayoutMetadata {
name: Option<String>,
tiled_panes: Vec<PaneLayoutMetadata>,
floating_panes: Vec<PaneLayoutMetadata>,
is_focused: bool,
hide_floating_panes: bool,
}
#[derive(Debug, Clone)]
pub struct PaneLayoutMetadata {
id: PaneId,
geom: PaneGeom,
run: Option<Run>,
cwd: Option<PathBuf>,
is_borderless: bool,
title: Option<String>,
is_focused: bool,
pane_contents: Option<String>,
focused_clients: Vec<ClientId>,
}
impl PaneLayoutMetadata {
pub fn new(
id: PaneId,
geom: PaneGeom,
is_borderless: bool,
run: Option<Run>,
title: Option<String>,
is_focused: bool,
pane_contents: Option<String>,
focused_clients: Vec<ClientId>,
) -> Self {
PaneLayoutMetadata {
id,
geom,
run,
cwd: None,
is_borderless,
title,
is_focused,
pane_contents,
focused_clients,
}
}
}
pub struct ClientMetadata {
pane_id: PaneId,
command: Option<Run>,
}
impl ClientMetadata {
pub fn stringify_pane_id(&self) -> String {
match self.pane_id {
PaneId::Terminal(terminal_id) => format!("terminal_{}", terminal_id),
PaneId::Plugin(plugin_id) => format!("plugin_{}", plugin_id),
}
}
pub fn stringify_command(&self, editor: &Option<PathBuf>) -> String {
let stringified = match &self.command {
Some(Run::Command(..)) => {
let (command, args) = extract_command_and_args(&self.command);
command.map(|c| format!("{} {}", c, args.join(" ")))
},
Some(Run::EditFile(..)) => {
let (file_to_edit, _line_number) = extract_edit_and_line_number(&self.command);
editor.as_ref().and_then(|editor| {
file_to_edit
.map(|file_to_edit| format!("{} {}", editor.display(), file_to_edit))
})
},
Some(Run::Plugin(..)) => {
let (plugin, _plugin_config) = extract_plugin_and_config(&self.command);
plugin.map(|p| format!("{}", p))
},
_ => None,
};
stringified.unwrap_or("N/A".to_owned())
}
pub fn get_pane_id(&self) -> PaneId {
self.pane_id
}
pub fn render_many(
clients_metadata: BTreeMap<ClientId, ClientMetadata>,
default_editor: &Option<PathBuf>,
) -> String {
let mut lines = vec![];
lines.push(String::from("CLIENT_ID ZELLIJ_PANE_ID RUNNING_COMMAND"));
for (client_id, client_metadata) in clients_metadata.iter() {
// 9 - CLIENT_ID, 14 - ZELLIJ_PANE_ID, 15 - RUNNING_COMMAND
lines.push(format!(
"{} {} {}",
format!("{0: <9}", client_id),
format!("{0: <14}", client_metadata.stringify_pane_id()),
format!(
"{0: <15}",
client_metadata.stringify_command(default_editor)
)
));
}
lines.join("\n")
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/terminal_bytes.rs | zellij-server/src/terminal_bytes.rs | use crate::{
os_input_output::{AsyncReader, ServerOsApi},
screen::ScreenInstruction,
thread_bus::ThreadSenders,
};
use async_std::task;
use std::{
os::unix::io::RawFd,
time::{Duration, Instant},
};
use zellij_utils::{
errors::{get_current_ctx, prelude::*, ContextType},
logging::debug_to_file,
};
pub(crate) struct TerminalBytes {
pid: RawFd,
terminal_id: u32,
senders: ThreadSenders,
async_reader: Box<dyn AsyncReader>,
debug: bool,
}
impl TerminalBytes {
pub fn new(
pid: RawFd,
senders: ThreadSenders,
os_input: Box<dyn ServerOsApi>,
debug: bool,
terminal_id: u32,
) -> Self {
TerminalBytes {
pid,
terminal_id,
senders,
debug,
async_reader: os_input.async_file_reader(pid),
}
}
pub async fn listen(&mut self) -> Result<()> {
// This function reads bytes from the pty and then sends them as
// ScreenInstruction::PtyBytes to screen to be parsed there
// We also send a separate instruction to Screen to render as ScreenInstruction::Render
//
// We endeavour to send a Render instruction to screen immediately after having send bytes
// to parse - this is so that the rendering is quick and smooth. However, this can cause
// latency if the screen is backed up. For this reason, if we detect a peak in the time it
// takes to send the render instruction, we assume the screen thread is backed up and so
// only send a render instruction sparingly, giving screen time to process bytes and render
// while still allowing the user to see an indication that things are happening (the
// sparing render instructions)
let err_context = || "failed to listen for bytes from PTY".to_string();
let mut err_ctx = get_current_ctx();
err_ctx.add_call(ContextType::AsyncTask);
let mut buf = [0u8; 65536];
loop {
match self.async_reader.read(&mut buf).await {
Ok(0) => break, // EOF
Err(err) => {
log::error!("{}", err);
break;
},
Ok(n_bytes) => {
let bytes = &buf[..n_bytes];
if self.debug {
let _ = debug_to_file(bytes, self.pid);
}
self.async_send_to_screen(ScreenInstruction::PtyBytes(
self.terminal_id,
bytes.to_vec(),
))
.await
.with_context(err_context)?;
},
}
}
// Ignore any errors that happen here.
// We only leave the loop above when the pane exits. This can happen in a lot of ways, but
// the most problematic is when quitting zellij with `Ctrl+q`. That is because the channel
// for `Screen` will have exited already, so this send *will* fail. This isn't a problem
// per-se because the application terminates anyway, but it will print a lengthy error
// message into the log for every pane that was still active when we quit the application.
// This:
//
// 1. Makes the log rather pointless, because even when the application exits "normally",
// there will be errors inside and
// 2. Leaves the impression we have a bug in the code and can't terminate properly
//
// FIXME: Ideally we detect whether the application is being quit and only ignore the error
// in that particular case?
let _ = self.async_send_to_screen(ScreenInstruction::Render).await;
Ok(())
}
async fn async_send_to_screen(
&self,
screen_instruction: ScreenInstruction,
) -> Result<Duration> {
// returns the time it blocked the thread for
let sent_at = Instant::now();
let senders = self.senders.clone();
task::spawn_blocking(move || senders.send_to_screen(screen_instruction))
.await
.context("failed to async-send to screen")?;
Ok(sent_at.elapsed())
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/route.rs | zellij-server/src/route.rs | use std::collections::{BTreeMap, HashSet, VecDeque};
use std::sync::{Arc, RwLock};
use tokio::sync::oneshot;
use crate::global_async_runtime::get_tokio_runtime;
use crate::thread_bus::ThreadSenders;
use crate::{
os_input_output::ServerOsApi,
panes::PaneId,
plugins::PluginInstruction,
pty::{ClientTabIndexOrPaneId, PtyInstruction},
screen::ScreenInstruction,
ServerInstruction, SessionMetaData, SessionState,
};
use std::thread;
use std::time::Duration;
use uuid::Uuid;
use zellij_utils::{
channels::SenderWithContext,
data::{
BareKey, ConnectToSession, Direction, Event, InputMode, KeyModifier, NewPanePlacement,
PluginCapabilities, ResizeStrategy, UnblockCondition,
},
envs,
errors::prelude::*,
input::{
actions::{Action, SearchDirection, SearchOption},
command::TerminalAction,
get_mode_info,
keybinds::Keybinds,
layout::{Layout, TiledPaneLayout},
},
ipc::{
ClientAttributes, ClientToServerMsg, ExitReason, IpcReceiverWithContext, ServerToClientMsg,
},
};
use crate::ClientId;
const ACTION_COMPLETION_TIMEOUT: Duration = Duration::from_secs(1);
#[derive(Debug, Clone)]
pub struct ActionCompletionResult {
pub exit_status: Option<i32>,
pub affected_pane_id: Option<PaneId>,
}
fn wait_for_action_completion(
receiver: oneshot::Receiver<ActionCompletionResult>,
action_name: &str,
wait_forever: bool,
) -> ActionCompletionResult {
let runtime = get_tokio_runtime();
if wait_forever {
runtime.block_on(async {
match receiver.await {
Ok(result) => result,
Err(e) => {
log::error!("Failed to wait for action {}: {}", action_name, e);
ActionCompletionResult {
exit_status: None,
affected_pane_id: None,
}
},
}
})
} else {
match runtime
.block_on(async { tokio::time::timeout(ACTION_COMPLETION_TIMEOUT, receiver).await })
{
Ok(Ok(result)) => result,
Err(_) | Ok(Err(_)) => {
log::error!(
"Action {} did not complete within {:?} timeout",
action_name,
ACTION_COMPLETION_TIMEOUT
);
ActionCompletionResult {
exit_status: None,
affected_pane_id: None,
}
},
}
}
}
// This is used to wait for actions that span multiple threads until they logically end
// dropping this struct sends a notification through the oneshot channel to the receiver, letting
// it know the action is ended and thus releasing it
//
// Note: Cloning this struct DOES NOT clone that internal receiver, it only implements Clone so
// that it can be included in various other larger structs - DO NOT RELY ON CLONING IT!
#[derive(Debug)]
pub struct NotificationEnd {
channel: Option<oneshot::Sender<ActionCompletionResult>>,
exit_status: Option<i32>,
unblock_condition: Option<UnblockCondition>,
affected_pane_id: Option<PaneId>, // optional payload of the pane id affected by this action
}
impl Clone for NotificationEnd {
fn clone(&self) -> Self {
// Always clone as None - only the original holder should signal completion
NotificationEnd {
channel: None,
exit_status: self.exit_status,
unblock_condition: self.unblock_condition,
affected_pane_id: self.affected_pane_id,
}
}
}
impl NotificationEnd {
pub fn new(sender: oneshot::Sender<ActionCompletionResult>) -> Self {
NotificationEnd {
channel: Some(sender),
exit_status: None,
unblock_condition: None,
affected_pane_id: None,
}
}
pub fn new_with_condition(
sender: oneshot::Sender<ActionCompletionResult>,
unblock_condition: UnblockCondition,
) -> Self {
NotificationEnd {
channel: Some(sender),
exit_status: None,
unblock_condition: Some(unblock_condition),
affected_pane_id: None,
}
}
pub fn set_exit_status(&mut self, exit_status: i32) {
self.exit_status = Some(exit_status);
}
pub fn set_affected_pane_id(&mut self, pane_id: PaneId) {
self.affected_pane_id = Some(pane_id);
}
pub fn unblock_condition(&self) -> Option<UnblockCondition> {
self.unblock_condition
}
}
impl Drop for NotificationEnd {
fn drop(&mut self) {
if let Some(tx) = self.channel.take() {
let result = ActionCompletionResult {
exit_status: self.exit_status,
affected_pane_id: self.affected_pane_id,
};
let _ = tx.send(result);
}
}
}
pub(crate) fn route_action(
action: Action,
client_id: ClientId,
cli_client_id: Option<ClientId>,
pane_id: Option<PaneId>,
senders: ThreadSenders,
capabilities: PluginCapabilities,
client_attributes: ClientAttributes,
default_shell: Option<TerminalAction>,
default_layout: Box<Layout>,
mut seen_cli_pipes: Option<&mut HashSet<String>>,
client_keybinds: Keybinds,
default_mode: InputMode,
os_input: Option<Box<dyn ServerOsApi>>,
) -> Result<(bool, Option<ActionCompletionResult>)> {
let mut should_break = false;
let err_context = || format!("failed to route action for client {client_id}");
let action_name = action.to_string();
if !action.is_mouse_action() {
// mouse actions should only send InputReceived to plugins
// if they do not result in text being marked, this is handled in Tab
senders
.send_to_plugin(PluginInstruction::Update(vec![(
None,
Some(client_id),
Event::InputReceived,
)]))
.with_context(err_context)?;
}
// we use this oneshot channel to wait for an action to be "logically"
// done, meaning that it traveled through all the threads it needed to travel through and the
// app has confirmed that it is complete. Once this happens, we get a signal through the
// wait_for_action_completion call below (or timeout after 1 second) and release this thread,
// allowing the client to produce another action without risking races
let (completion_tx, completion_rx) = oneshot::channel();
let mut wait_forever = false;
match action {
Action::ToggleTab => {
senders
.send_to_screen(ScreenInstruction::ToggleTab(
client_id,
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::Write {
key_with_modifier,
bytes: raw_bytes,
is_kitty_keyboard_protocol,
} => {
senders
.send_to_screen(ScreenInstruction::ClearScroll(client_id))
.with_context(err_context)?;
senders
.send_to_screen(ScreenInstruction::WriteCharacter(
key_with_modifier,
raw_bytes,
is_kitty_keyboard_protocol,
client_id,
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::WriteChars { chars } => {
senders
.send_to_screen(ScreenInstruction::ClearScroll(client_id))
.with_context(err_context)?;
let chars = chars.into_bytes();
senders
.send_to_screen(ScreenInstruction::WriteCharacter(
None,
chars,
false,
client_id,
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::SwitchToMode { input_mode } => {
let attrs = &client_attributes;
senders
.send_to_server(ServerInstruction::ChangeMode(client_id, input_mode))
.with_context(err_context)?;
senders
.send_to_screen(ScreenInstruction::ChangeMode(
get_mode_info(
input_mode,
attrs,
capabilities,
&client_keybinds,
Some(default_mode),
),
client_id,
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
senders
.send_to_screen(ScreenInstruction::Render)
.with_context(err_context)?;
},
Action::Resize { resize, direction } => {
let screen_instr = ScreenInstruction::Resize(
client_id,
ResizeStrategy::new(resize, direction),
Some(NotificationEnd::new(completion_tx)),
);
senders
.send_to_screen(screen_instr)
.with_context(err_context)?;
},
Action::SwitchFocus => {
senders
.send_to_screen(ScreenInstruction::SwitchFocus(
client_id,
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::FocusNextPane => {
senders
.send_to_screen(ScreenInstruction::FocusNextPane(
client_id,
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::FocusPreviousPane => {
senders
.send_to_screen(ScreenInstruction::FocusPreviousPane(
client_id,
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::MoveFocus { direction } => {
let notification_end = Some(NotificationEnd::new(completion_tx));
let screen_instr = match direction {
Direction::Left => ScreenInstruction::MoveFocusLeft(client_id, notification_end),
Direction::Right => ScreenInstruction::MoveFocusRight(client_id, notification_end),
Direction::Up => ScreenInstruction::MoveFocusUp(client_id, notification_end),
Direction::Down => ScreenInstruction::MoveFocusDown(client_id, notification_end),
};
senders
.send_to_screen(screen_instr)
.with_context(err_context)?;
},
Action::MoveFocusOrTab { direction } => {
let notification_end = Some(NotificationEnd::new(completion_tx));
let screen_instr = match direction {
Direction::Left => {
ScreenInstruction::MoveFocusLeftOrPreviousTab(client_id, notification_end)
},
Direction::Right => {
ScreenInstruction::MoveFocusRightOrNextTab(client_id, notification_end)
},
Direction::Up => ScreenInstruction::SwitchTabNext(client_id, notification_end),
Direction::Down => ScreenInstruction::SwitchTabPrev(client_id, notification_end),
};
senders
.send_to_screen(screen_instr)
.with_context(err_context)?;
},
Action::MovePane { direction } => {
let notification_end = Some(NotificationEnd::new(completion_tx));
let screen_instr = match direction {
Some(Direction::Left) => {
ScreenInstruction::MovePaneLeft(client_id, notification_end)
},
Some(Direction::Right) => {
ScreenInstruction::MovePaneRight(client_id, notification_end)
},
Some(Direction::Up) => ScreenInstruction::MovePaneUp(client_id, notification_end),
Some(Direction::Down) => {
ScreenInstruction::MovePaneDown(client_id, notification_end)
},
None => ScreenInstruction::MovePane(client_id, notification_end),
};
senders
.send_to_screen(screen_instr)
.with_context(err_context)?;
},
Action::MovePaneBackwards => {
senders
.send_to_screen(ScreenInstruction::MovePaneBackwards(
client_id,
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::ClearScreen => {
senders
.send_to_screen(ScreenInstruction::ClearScreen(
client_id,
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::DumpScreen {
file_path,
include_scrollback,
} => {
senders
.send_to_screen(ScreenInstruction::DumpScreen(
file_path,
client_id,
include_scrollback,
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::DumpLayout => {
let default_shell = match default_shell {
Some(TerminalAction::RunCommand(run_command)) => Some(run_command.command),
_ => None,
};
senders
.send_to_screen(ScreenInstruction::DumpLayout(
default_shell,
cli_client_id.unwrap_or(client_id), // we prefer the cli client here because
// this is a cli query and we want to print
// it there
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::EditScrollback => {
senders
.send_to_screen(ScreenInstruction::EditScrollback(
client_id,
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::ScrollUp => {
senders
.send_to_screen(ScreenInstruction::ScrollUp(
client_id,
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::ScrollUpAt { position } => {
senders
.send_to_screen(ScreenInstruction::ScrollUpAt(
position,
client_id,
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::ScrollDown => {
senders
.send_to_screen(ScreenInstruction::ScrollDown(
client_id,
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::ScrollDownAt { position } => {
senders
.send_to_screen(ScreenInstruction::ScrollDownAt(
position,
client_id,
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::ScrollToBottom => {
senders
.send_to_screen(ScreenInstruction::ScrollToBottom(
client_id,
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::ScrollToTop => {
senders
.send_to_screen(ScreenInstruction::ScrollToTop(
client_id,
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::PageScrollUp => {
senders
.send_to_screen(ScreenInstruction::PageScrollUp(
client_id,
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::PageScrollDown => {
senders
.send_to_screen(ScreenInstruction::PageScrollDown(
client_id,
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::HalfPageScrollUp => {
senders
.send_to_screen(ScreenInstruction::HalfPageScrollUp(
client_id,
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::HalfPageScrollDown => {
senders
.send_to_screen(ScreenInstruction::HalfPageScrollDown(
client_id,
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::ToggleFocusFullscreen => {
senders
.send_to_screen(ScreenInstruction::ToggleActiveTerminalFullscreen(
client_id,
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::TogglePaneFrames => {
senders
.send_to_screen(ScreenInstruction::TogglePaneFrames(Some(
NotificationEnd::new(completion_tx),
)))
.with_context(err_context)?;
},
Action::NewPane {
direction,
pane_name,
start_suppressed,
} => {
let shell = default_shell.clone();
let new_pane_placement = match direction {
Some(direction) => NewPanePlacement::Tiled(Some(direction)),
None => NewPanePlacement::NoPreference,
};
senders
.send_to_pty(PtyInstruction::SpawnTerminal(
shell,
pane_name,
new_pane_placement,
start_suppressed,
ClientTabIndexOrPaneId::ClientId(client_id),
Some(NotificationEnd::new(completion_tx)),
false, // set_blocking
))
.with_context(err_context)?;
},
Action::NewBlockingPane {
placement,
pane_name,
command,
unblock_condition,
near_current_pane,
} => {
let command = command
.map(|cmd| TerminalAction::RunCommand(cmd.into()))
.or_else(|| default_shell.clone());
let set_pane_blocking = true;
let notification_end = if let Some(condition) = unblock_condition {
Some(NotificationEnd::new_with_condition(
completion_tx,
condition,
))
} else {
Some(NotificationEnd::new(completion_tx))
};
// we prefer the pane id provided by the action explicitly over the one that originated
// it (this might be a bit misleading with "near_current_pane", but it's still the
// right behavior - in the latter case, if the originator does not wish for this
// behavior, they should not provide pane
// inside the placement, but rather have the current pane id be picked up instead)
let pane_id = match placement {
NewPanePlacement::Stacked(pane_id_to_stack_under) => {
pane_id_to_stack_under.map(|p| p.into()).or(pane_id)
},
NewPanePlacement::InPlace {
pane_id_to_replace, ..
} => pane_id_to_replace.map(|p| p.into()).or(pane_id),
_ => pane_id,
};
let client_tab_index_or_paneid = if near_current_pane && pane_id.is_some() {
ClientTabIndexOrPaneId::PaneId(pane_id.unwrap())
} else {
ClientTabIndexOrPaneId::ClientId(client_id)
};
senders
.send_to_pty(PtyInstruction::SpawnTerminal(
command,
pane_name,
placement,
false,
client_tab_index_or_paneid,
notification_end,
set_pane_blocking,
))
.with_context(err_context)?;
wait_forever = true;
},
Action::EditFile {
payload: open_file_payload,
direction: split_direction,
floating: should_float,
in_place: should_open_in_place,
start_suppressed,
coordinates: floating_pane_coordinates,
near_current_pane,
} => {
let title = format!("Editing: {}", open_file_payload.path.display());
let open_file = TerminalAction::OpenFile(open_file_payload);
let pty_instr = if should_open_in_place {
match pane_id {
Some(pane_id) if near_current_pane => PtyInstruction::SpawnInPlaceTerminal(
Some(open_file),
Some(title),
false,
ClientTabIndexOrPaneId::PaneId(pane_id),
Some(NotificationEnd::new(completion_tx)),
),
_ => PtyInstruction::SpawnInPlaceTerminal(
Some(open_file),
Some(title),
false,
ClientTabIndexOrPaneId::ClientId(client_id),
Some(NotificationEnd::new(completion_tx)),
),
}
} else {
PtyInstruction::SpawnTerminal(
Some(open_file),
Some(title),
if should_float {
NewPanePlacement::Floating(floating_pane_coordinates)
} else {
NewPanePlacement::Tiled(split_direction)
},
start_suppressed,
ClientTabIndexOrPaneId::ClientId(client_id),
Some(NotificationEnd::new(completion_tx)),
false, // set_blocking
)
};
senders.send_to_pty(pty_instr).with_context(err_context)?;
},
Action::SwitchModeForAllClients { input_mode } => {
let attrs = &client_attributes;
senders
.send_to_plugin(PluginInstruction::Update(vec![(
None,
None,
Event::ModeUpdate(get_mode_info(
input_mode,
attrs,
capabilities,
&client_keybinds,
Some(default_mode),
)),
)]))
.with_context(err_context)?;
senders
.send_to_server(ServerInstruction::ChangeModeForAllClients(input_mode))
.with_context(err_context)?;
senders
.send_to_screen(ScreenInstruction::ChangeModeForAllClients(
get_mode_info(
input_mode,
attrs,
capabilities,
&client_keybinds,
Some(default_mode),
),
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::NewFloatingPane {
command: run_command,
pane_name: name,
coordinates: floating_pane_coordinates,
near_current_pane,
} => {
let run_cmd = run_command
.map(|cmd| TerminalAction::RunCommand(cmd.into()))
.or_else(|| default_shell.clone());
let client_tab_index_or_paneid = if near_current_pane && pane_id.is_some() {
ClientTabIndexOrPaneId::PaneId(pane_id.unwrap())
} else {
ClientTabIndexOrPaneId::ClientId(client_id)
};
senders
.send_to_pty(PtyInstruction::SpawnTerminal(
run_cmd,
name,
NewPanePlacement::Floating(floating_pane_coordinates),
false,
client_tab_index_or_paneid,
Some(NotificationEnd::new(completion_tx)),
false, // set_blocking
))
.with_context(err_context)?;
},
Action::NewInPlacePane {
command: run_command,
pane_name: name,
near_current_pane,
pane_id_to_replace,
close_replace_pane,
} => {
let run_cmd = run_command
.map(|cmd| TerminalAction::RunCommand(cmd.into()))
.or_else(|| default_shell.clone());
let pane_id = match pane_id_to_replace {
Some(pane_id_to_replace) => pane_id_to_replace.try_into().ok(),
None => pane_id,
};
match pane_id {
Some(pane_id) if near_current_pane => {
senders
.send_to_pty(PtyInstruction::SpawnInPlaceTerminal(
run_cmd,
name,
close_replace_pane,
ClientTabIndexOrPaneId::PaneId(pane_id),
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
_ => {
senders
.send_to_pty(PtyInstruction::SpawnInPlaceTerminal(
run_cmd,
name,
close_replace_pane,
ClientTabIndexOrPaneId::ClientId(client_id),
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
}
},
Action::NewStackedPane {
command: run_command,
pane_name: name,
near_current_pane,
} => {
let run_cmd = run_command
.map(|cmd| TerminalAction::RunCommand(cmd.into()))
.or_else(|| default_shell.clone());
match pane_id {
Some(pane_id) if near_current_pane => {
senders
.send_to_pty(PtyInstruction::SpawnTerminal(
run_cmd,
name,
NewPanePlacement::Stacked(Some(pane_id.into())),
false,
ClientTabIndexOrPaneId::PaneId(pane_id),
Some(NotificationEnd::new(completion_tx)),
false, // set_blocking
))
.with_context(err_context)?;
},
_ => {
senders
.send_to_pty(PtyInstruction::SpawnTerminal(
run_cmd,
name,
NewPanePlacement::Stacked(None),
false,
ClientTabIndexOrPaneId::ClientId(client_id),
Some(NotificationEnd::new(completion_tx)),
false, // set_blocking
))
.with_context(err_context)?;
},
}
},
Action::NewTiledPane {
direction,
command: run_command,
pane_name: name,
near_current_pane,
} => {
let run_cmd = run_command
.map(|cmd| TerminalAction::RunCommand(cmd.into()))
.or_else(|| default_shell.clone());
let client_tab_index_or_paneid = if near_current_pane && pane_id.is_some() {
ClientTabIndexOrPaneId::PaneId(pane_id.unwrap())
} else {
ClientTabIndexOrPaneId::ClientId(client_id)
};
senders
.send_to_pty(PtyInstruction::SpawnTerminal(
run_cmd,
name,
NewPanePlacement::Tiled(direction),
false,
client_tab_index_or_paneid,
Some(NotificationEnd::new(completion_tx)),
false, // set_blocking
))
.with_context(err_context)?;
},
Action::TogglePaneEmbedOrFloating => {
senders
.send_to_screen(ScreenInstruction::TogglePaneEmbedOrFloating(
client_id,
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::ToggleFloatingPanes => {
senders
.send_to_screen(ScreenInstruction::ToggleFloatingPanes(
client_id,
default_shell.clone(),
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::PaneNameInput { input } => {
senders
.send_to_screen(ScreenInstruction::UpdatePaneName(
input,
client_id,
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::UndoRenamePane => {
senders
.send_to_screen(ScreenInstruction::UndoRenamePane(
client_id,
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::Run {
command,
near_current_pane,
} => {
let run_cmd = Some(TerminalAction::RunCommand(command.clone().into()));
let client_tab_index_or_paneid = if near_current_pane && pane_id.is_some() {
ClientTabIndexOrPaneId::PaneId(pane_id.unwrap())
} else {
ClientTabIndexOrPaneId::ClientId(client_id)
};
senders
.send_to_pty(PtyInstruction::SpawnTerminal(
run_cmd,
None,
NewPanePlacement::Tiled(command.direction),
false,
client_tab_index_or_paneid,
Some(NotificationEnd::new(completion_tx)),
false, // set_blocking
))
.with_context(err_context)?;
},
Action::CloseFocus => {
senders
.send_to_screen(ScreenInstruction::CloseFocusedPane(
client_id,
Some(NotificationEnd::new(completion_tx)),
))
.with_context(err_context)?;
},
Action::NewTab {
tiled_layout: tab_layout,
floating_layouts: floating_panes_layout,
swap_tiled_layouts,
swap_floating_layouts,
tab_name,
should_change_focus_to_new_tab,
cwd,
initial_panes,
first_pane_unblock_condition,
} => {
let shell = default_shell.clone();
let swap_tiled_layouts =
swap_tiled_layouts.unwrap_or_else(|| default_layout.swap_tiled_layouts.clone());
let swap_floating_layouts = swap_floating_layouts
.unwrap_or_else(|| default_layout.swap_floating_layouts.clone());
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/thread_bus.rs | zellij-server/src/thread_bus.rs | //! Definitions and helpers for sending and receiving messages between threads.
use crate::{
background_jobs::BackgroundJob, os_input_output::ServerOsApi, plugins::PluginInstruction,
pty::PtyInstruction, pty_writer::PtyWriteInstruction, screen::ScreenInstruction,
ServerInstruction,
};
use zellij_utils::errors::prelude::*;
use zellij_utils::{channels, channels::SenderWithContext, errors::ErrorContext};
/// A container for senders to the different threads in zellij on the server side
#[derive(Default, Clone)]
pub struct ThreadSenders {
pub to_screen: Option<SenderWithContext<ScreenInstruction>>,
pub to_pty: Option<SenderWithContext<PtyInstruction>>,
pub to_plugin: Option<SenderWithContext<PluginInstruction>>,
pub to_server: Option<SenderWithContext<ServerInstruction>>,
pub to_pty_writer: Option<SenderWithContext<PtyWriteInstruction>>,
pub to_background_jobs: Option<SenderWithContext<BackgroundJob>>,
// this is a convenience for the unit tests
// it's not advisable to set it to true in production code
pub should_silently_fail: bool,
}
impl ThreadSenders {
pub fn send_to_screen(&self, instruction: ScreenInstruction) -> Result<()> {
if self.should_silently_fail {
let _ = self
.to_screen
.as_ref()
.map(|sender| sender.send(instruction))
.unwrap_or_else(|| Ok(()));
Ok(())
} else {
self.to_screen
.as_ref()
.context("failed to get screen sender")?
.send(instruction)
.to_anyhow()
.context("failed to send message to screen")
}
}
pub fn send_to_pty(&self, instruction: PtyInstruction) -> Result<()> {
if self.should_silently_fail {
let _ = self
.to_pty
.as_ref()
.map(|sender| sender.send(instruction))
.unwrap_or_else(|| Ok(()));
Ok(())
} else {
self.to_pty
.as_ref()
.context("failed to get pty sender")?
.send(instruction)
.to_anyhow()
.context("failed to send message to pty")
}
}
pub fn send_to_plugin(&self, instruction: PluginInstruction) -> Result<()> {
if self.should_silently_fail {
let _ = self
.to_plugin
.as_ref()
.map(|sender| sender.send(instruction))
.unwrap_or_else(|| Ok(()));
Ok(())
} else {
self.to_plugin
.as_ref()
.context("failed to get plugin sender")?
.send(instruction)
.to_anyhow()
.context("failed to send message to plugin")
}
}
pub fn send_to_server(&self, instruction: ServerInstruction) -> Result<()> {
if self.should_silently_fail {
let _ = self
.to_server
.as_ref()
.map(|sender| sender.send(instruction))
.unwrap_or_else(|| Ok(()));
Ok(())
} else {
self.to_server
.as_ref()
.context("failed to get server sender")?
.send(instruction)
.to_anyhow()
.context("failed to send message to server")
}
}
pub fn send_to_pty_writer(&self, instruction: PtyWriteInstruction) -> Result<()> {
if self.should_silently_fail {
let _ = self
.to_pty_writer
.as_ref()
.map(|sender| sender.send(instruction))
.unwrap_or_else(|| Ok(()));
Ok(())
} else {
self.to_pty_writer
.as_ref()
.context("failed to get pty writer sender")?
.send(instruction)
.to_anyhow()
.context("failed to send message to pty writer")
}
}
pub fn send_to_background_jobs(&self, background_job: BackgroundJob) -> Result<()> {
if self.should_silently_fail {
let _ = self
.to_background_jobs
.as_ref()
.map(|sender| sender.send(background_job))
.unwrap_or_else(|| Ok(()));
Ok(())
} else {
self.to_background_jobs
.as_ref()
.context("failed to get background jobs sender")?
.send(background_job)
.to_anyhow()
.context("failed to send message to background jobs")
}
}
#[allow(unused)]
pub fn silently_fail_on_send(mut self) -> Self {
// this is mostly used for the tests, see struct
self.should_silently_fail = true;
self
}
#[allow(unused)]
pub fn replace_to_pty_writer(
&mut self,
new_pty_writer: SenderWithContext<PtyWriteInstruction>,
) {
// this is mostly used for the tests, see struct
self.to_pty_writer.replace(new_pty_writer);
}
#[allow(unused)]
pub fn replace_to_pty(&mut self, new_pty: SenderWithContext<PtyInstruction>) {
// this is mostly used for the tests, see struct
self.to_pty.replace(new_pty);
}
#[allow(unused)]
pub fn replace_to_plugin(&mut self, new_to_plugin: SenderWithContext<PluginInstruction>) {
// this is mostly used for the tests, see struct
self.to_plugin.replace(new_to_plugin);
}
}
/// A container for a receiver, OS input and the senders to a given thread
#[derive(Default)]
pub(crate) struct Bus<T> {
receivers: Vec<channels::Receiver<(T, ErrorContext)>>,
pub senders: ThreadSenders,
pub os_input: Option<Box<dyn ServerOsApi>>,
}
impl<T> Bus<T> {
pub fn new(
receivers: Vec<channels::Receiver<(T, ErrorContext)>>,
to_screen: Option<&SenderWithContext<ScreenInstruction>>,
to_pty: Option<&SenderWithContext<PtyInstruction>>,
to_plugin: Option<&SenderWithContext<PluginInstruction>>,
to_server: Option<&SenderWithContext<ServerInstruction>>,
to_pty_writer: Option<&SenderWithContext<PtyWriteInstruction>>,
to_background_jobs: Option<&SenderWithContext<BackgroundJob>>,
os_input: Option<Box<dyn ServerOsApi>>,
) -> Self {
Bus {
receivers,
senders: ThreadSenders {
to_screen: to_screen.cloned(),
to_pty: to_pty.cloned(),
to_plugin: to_plugin.cloned(),
to_server: to_server.cloned(),
to_pty_writer: to_pty_writer.cloned(),
to_background_jobs: to_background_jobs.cloned(),
should_silently_fail: false,
},
os_input: os_input.clone(),
}
}
#[allow(unused)]
pub fn should_silently_fail(mut self) -> Self {
// this is mostly used for the tests
self.senders.should_silently_fail = true;
self
}
#[allow(unused)]
pub fn empty() -> Self {
// this is mostly used for the tests
Bus {
receivers: vec![],
senders: ThreadSenders {
to_screen: None,
to_pty: None,
to_plugin: None,
to_server: None,
to_pty_writer: None,
to_background_jobs: None,
should_silently_fail: true,
},
os_input: None,
}
}
pub fn recv(&self) -> Result<(T, ErrorContext), channels::RecvError> {
let mut selector = channels::Select::new();
self.receivers.iter().for_each(|r| {
selector.recv(r);
});
let oper = selector.select();
let idx = oper.index();
oper.recv(&self.receivers[idx])
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/pty_writer.rs | zellij-server/src/pty_writer.rs | use zellij_utils::errors::{prelude::*, ContextType, PtyWriteContext};
use crate::thread_bus::Bus;
// we separate these instruction to a different thread because some programs get deadlocked if
// you write into their STDIN while reading from their STDOUT (I'm looking at you, vim)
// while the same has not been observed to happen with resizes, it could conceivably happen and we have this
// here anyway, so
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum PtyWriteInstruction {
Write(Vec<u8>, u32),
ResizePty(u32, u16, u16, Option<u16>, Option<u16>), // terminal_id, columns, rows, pixel width, pixel height
StartCachingResizes,
ApplyCachedResizes,
Exit,
}
impl From<&PtyWriteInstruction> for PtyWriteContext {
fn from(tty_write_instruction: &PtyWriteInstruction) -> Self {
match *tty_write_instruction {
PtyWriteInstruction::Write(..) => PtyWriteContext::Write,
PtyWriteInstruction::ResizePty(..) => PtyWriteContext::ResizePty,
PtyWriteInstruction::ApplyCachedResizes => PtyWriteContext::ApplyCachedResizes,
PtyWriteInstruction::StartCachingResizes => PtyWriteContext::StartCachingResizes,
PtyWriteInstruction::Exit => PtyWriteContext::Exit,
}
}
}
pub(crate) fn pty_writer_main(bus: Bus<PtyWriteInstruction>) -> Result<()> {
let err_context = || "failed to write to pty".to_string();
loop {
let (event, mut err_ctx) = bus.recv().with_context(err_context)?;
err_ctx.add_call(ContextType::PtyWrite((&event).into()));
let mut os_input = bus
.os_input
.clone()
.context("no OS input API found")
.with_context(err_context)?;
match event {
PtyWriteInstruction::Write(bytes, terminal_id) => {
os_input
.write_to_tty_stdin(terminal_id, &bytes)
.with_context(err_context)
.non_fatal();
os_input
.tcdrain(terminal_id)
.with_context(err_context)
.non_fatal();
},
PtyWriteInstruction::ResizePty(
terminal_id,
columns,
rows,
width_in_pixels,
height_in_pixels,
) => {
os_input
.set_terminal_size_using_terminal_id(
terminal_id,
columns,
rows,
width_in_pixels,
height_in_pixels,
)
.with_context(err_context)
.non_fatal();
},
PtyWriteInstruction::StartCachingResizes => {
// we do this because there are some logic traps inside the screen/tab/layout code
// the cause multiple resizes to be sent to the pty - while the last one is always
// the correct one, many programs and shells debounce those (I guess due to the
// trauma of dealing with GUI resizes of the controlling terminal window), and this
// then causes glitches and missing redraws
// so we do this to play nice and always only send the last resize instruction to
// each pane
// the logic for this happens in the main Screen event loop
os_input.cache_resizes();
},
PtyWriteInstruction::ApplyCachedResizes => {
os_input.apply_cached_resizes();
},
PtyWriteInstruction::Exit => {
return Ok(());
},
}
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/screen.rs | zellij-server/src/screen.rs | //! Things related to [`Screen`]s.
use std::cell::RefCell;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::net::{IpAddr, Ipv4Addr};
use std::path::PathBuf;
use std::rc::Rc;
use std::str;
use std::time::{Duration, Instant};
use crate::route::NotificationEnd;
use log::{debug, warn};
use zellij_utils::data::{
CommandOrPlugin, Direction, FloatingPaneCoordinates, KeyWithModifier, NewPanePlacement,
PaneContents, PaneManifest, PaneScrollbackResponse, PluginPermission, Resize, ResizeStrategy,
SessionInfo, Styling, WebSharing,
};
use zellij_utils::errors::prelude::*;
use zellij_utils::input::command::RunCommand;
use zellij_utils::input::config::Config;
use zellij_utils::input::keybinds::Keybinds;
use zellij_utils::input::mouse::MouseEvent;
use zellij_utils::input::options::Clipboard;
use zellij_utils::pane_size::{Size, SizeInPixels};
use zellij_utils::shared::clean_string_from_control_and_linebreak;
use zellij_utils::{
consts::{session_info_folder_for_session, ZELLIJ_SOCK_DIR},
envs::set_session_name,
input::command::TerminalAction,
input::layout::{
FloatingPaneLayout, Layout, Run, RunPluginOrAlias, SplitSize, SwapFloatingLayout,
SwapTiledLayout, TiledPaneLayout,
},
position::Position,
};
use crate::background_jobs::BackgroundJob;
use crate::os_input_output::ResizeCache;
use crate::pane_groups::PaneGroups;
use crate::panes::alacritty_functions::xparse_color;
use crate::panes::terminal_character::AnsiCode;
use crate::panes::terminal_pane::{BRACKETED_PASTE_BEGIN, BRACKETED_PASTE_END};
use crate::session_layout_metadata::{PaneLayoutMetadata, SessionLayoutMetadata};
use crate::{
output::Output,
panes::sixel::SixelImageStore,
panes::PaneId,
plugins::{PluginId, PluginInstruction, PluginRenderAsset},
pty::{get_default_shell, ClientTabIndexOrPaneId, PtyInstruction, VteBytes},
tab::{SuppressedPanes, Tab},
thread_bus::Bus,
ui::loading_indication::LoadingIndication,
ClientId, ServerInstruction,
};
use zellij_utils::{
data::{Event, InputMode, ModeInfo, Palette, PaletteColor, PluginCapabilities, Style, TabInfo},
errors::{ContextType, ScreenContext},
input::get_mode_info,
ipc::{ClientAttributes, PixelDimensions, ServerToClientMsg},
};
/// Get the active tab and call a closure on it
///
/// If no active tab can be found, an error is logged instead.
///
/// # Parameters
///
/// - screen: An instance of `Screen` to operate on
/// - client_id: The client_id, usually taken from the `ScreenInstruction` that's being processed
/// - closure: A closure satisfying `|tab: &mut Tab| -> ()` OR `|tab: &mut Tab| -> Result<T>` (see
/// '?' below)
/// - ?: A literal "?", to append a `?` to the closure when it returns a `Result` type. This
/// argument is optional and not needed when the closure returns `()`
macro_rules! active_tab {
($screen:ident, $client_id:ident, $closure:expr) => {
match $screen.get_active_tab_mut($client_id) {
Ok(active_tab) => {
// This could be made more ergonomic by declaring the type of 'active_tab' in the
// closure, known as "Type Ascription". Then we could hint the type here and forego the
// "&mut Tab" in all the closures below...
// See: https://github.com/rust-lang/rust/issues/23416
$closure(active_tab);
},
Err(err) => Err::<(), _>(err).non_fatal(),
};
};
// Same as above, but with an added `?` for when the close returns a `Result` type.
($screen:ident, $client_id:ident, $closure:expr, ?) => {
match $screen.get_active_tab_mut($client_id) {
Ok(active_tab) => {
$closure(active_tab)?;
},
Err(err) => Err::<(), _>(err).non_fatal(),
};
};
}
macro_rules! active_tab_and_connected_client_id {
($screen:ident, $client_id:ident, $closure:expr) => {
match $screen.get_active_tab_mut($client_id) {
Ok(active_tab) => {
$closure(active_tab, $client_id);
},
Err(_) => {
if let Some(client_id) = $screen.get_first_client_id() {
match $screen.get_active_tab_mut(client_id) {
Ok(active_tab) => {
$closure(active_tab, client_id);
},
Err(err) => Err::<(), _>(err).non_fatal(),
}
} else {
log::error!("No client ids in screen found");
};
},
}
};
// Same as above, but with an added `?` for when the closure returns a `Result` type.
($screen:ident, $client_id:ident, $closure:expr, ?) => {
match $screen.get_active_tab_mut($client_id) {
Ok(active_tab) => {
$closure(active_tab, $client_id).non_fatal();
},
Err(_) => {
if let Some(client_id) = $screen.get_first_client_id() {
match $screen.get_active_tab_mut(client_id) {
Ok(active_tab) => {
$closure(active_tab, client_id)?;
},
Err(err) => Err::<(), _>(err).non_fatal(),
}
} else {
log::error!("No client ids in screen found");
};
},
}
};
}
type InitialTitle = String;
type HoldForCommand = Option<RunCommand>;
/// Instructions that can be sent to the [`Screen`].
#[derive(Debug, Clone)]
pub enum ScreenInstruction {
PtyBytes(u32, VteBytes),
PluginBytes(Vec<PluginRenderAsset>),
Render,
RenderToClients,
NewPane(
PaneId,
Option<InitialTitle>,
HoldForCommand,
Option<Run>, // invoked with
NewPanePlacement,
bool, // start suppressed
ClientTabIndexOrPaneId,
Option<NotificationEnd>, // completion signal
bool, // set_blocking
),
OpenInPlaceEditor(PaneId, ClientTabIndexOrPaneId),
TogglePaneEmbedOrFloating(ClientId, Option<NotificationEnd>),
ToggleFloatingPanes(ClientId, Option<TerminalAction>, Option<NotificationEnd>),
WriteCharacter(
Option<KeyWithModifier>,
Vec<u8>,
bool,
ClientId,
Option<NotificationEnd>,
), // bool ->
// is_kitty_keyboard_protocol
Resize(ClientId, ResizeStrategy, Option<NotificationEnd>),
SwitchFocus(ClientId, Option<NotificationEnd>),
FocusNextPane(ClientId, Option<NotificationEnd>),
FocusPreviousPane(ClientId, Option<NotificationEnd>),
MoveFocusLeft(ClientId, Option<NotificationEnd>),
MoveFocusLeftOrPreviousTab(ClientId, Option<NotificationEnd>),
MoveFocusDown(ClientId, Option<NotificationEnd>),
MoveFocusUp(ClientId, Option<NotificationEnd>),
MoveFocusRight(ClientId, Option<NotificationEnd>),
MoveFocusRightOrNextTab(ClientId, Option<NotificationEnd>),
MovePane(ClientId, Option<NotificationEnd>),
MovePaneBackwards(ClientId, Option<NotificationEnd>),
MovePaneUp(ClientId, Option<NotificationEnd>),
MovePaneDown(ClientId, Option<NotificationEnd>),
MovePaneRight(ClientId, Option<NotificationEnd>),
MovePaneLeft(ClientId, Option<NotificationEnd>),
Exit,
ClearScreen(ClientId, Option<NotificationEnd>),
DumpScreen(String, ClientId, bool, Option<NotificationEnd>),
DumpLayout(Option<PathBuf>, ClientId, Option<NotificationEnd>), // PathBuf is the default configured
// shell
DumpLayoutToPlugin(PluginId),
EditScrollback(ClientId, Option<NotificationEnd>),
GetPaneScrollback {
pane_id: PaneId,
client_id: ClientId,
get_full_scrollback: bool,
response_channel: crossbeam::channel::Sender<PaneScrollbackResponse>,
},
ScrollUp(ClientId, Option<NotificationEnd>),
ScrollUpAt(Position, ClientId, Option<NotificationEnd>),
ScrollDown(ClientId, Option<NotificationEnd>),
ScrollDownAt(Position, ClientId, Option<NotificationEnd>),
ScrollToBottom(ClientId, Option<NotificationEnd>),
ScrollToTop(ClientId, Option<NotificationEnd>),
PageScrollUp(ClientId, Option<NotificationEnd>),
PageScrollDown(ClientId, Option<NotificationEnd>),
HalfPageScrollUp(ClientId, Option<NotificationEnd>),
HalfPageScrollDown(ClientId, Option<NotificationEnd>),
ClearScroll(ClientId),
CloseFocusedPane(ClientId, Option<NotificationEnd>),
ToggleActiveTerminalFullscreen(ClientId, Option<NotificationEnd>),
TogglePaneFrames(Option<NotificationEnd>),
SetSelectable(PaneId, bool),
ShowPluginCursor(u32, ClientId, Option<(usize, usize)>),
ClosePane(
PaneId,
Option<ClientId>,
Option<NotificationEnd>,
Option<i32>,
), // i32 -> optional exit
// status
HoldPane(PaneId, Option<i32>, RunCommand),
UpdatePaneName(Vec<u8>, ClientId, Option<NotificationEnd>),
UndoRenamePane(ClientId, Option<NotificationEnd>),
NewTab(
Option<PathBuf>,
Option<TerminalAction>,
Option<TiledPaneLayout>,
Vec<FloatingPaneLayout>,
Option<String>,
(Vec<SwapTiledLayout>, Vec<SwapFloatingLayout>), // swap layouts
Option<Vec<CommandOrPlugin>>, // initial_panes
bool, // block_on_first_terminal
bool, // should_change_focus_to_new_tab
(ClientId, bool), // bool -> is_web_client
Option<NotificationEnd>, // completion signal
),
ApplyLayout(
TiledPaneLayout,
Vec<FloatingPaneLayout>,
Vec<(u32, HoldForCommand)>, // new pane pids
Vec<(u32, HoldForCommand)>, // new floating pane pids
HashMap<RunPluginOrAlias, Vec<u32>>,
usize, // tab_index
bool, // should change focus to new tab
(ClientId, bool), // bool -> is_web_client
Option<NotificationEnd>, // regular completion signal
Option<(u32, NotificationEnd)>, // blocking_terminal (terminal_id, completion_tx)
),
SwitchTabNext(ClientId, Option<NotificationEnd>),
SwitchTabPrev(ClientId, Option<NotificationEnd>),
ToggleActiveSyncTab(ClientId, Option<NotificationEnd>),
CloseTab(ClientId, Option<NotificationEnd>),
GoToTab(u32, Option<ClientId>, Option<NotificationEnd>), // this Option is a hacky workaround, please do not copy this behaviour
GoToTabName(
String,
(Vec<SwapTiledLayout>, Vec<SwapFloatingLayout>), // swap layouts
Option<TerminalAction>, // default_shell
bool,
Option<ClientId>,
Option<NotificationEnd>,
),
ToggleTab(ClientId, Option<NotificationEnd>),
UpdateTabName(Vec<u8>, ClientId, Option<NotificationEnd>),
UndoRenameTab(ClientId, Option<NotificationEnd>),
MoveTabLeft(ClientId, Option<NotificationEnd>),
MoveTabRight(ClientId, Option<NotificationEnd>),
TerminalResize(Size),
TerminalPixelDimensions(PixelDimensions),
TerminalBackgroundColor(String),
TerminalForegroundColor(String),
TerminalColorRegisters(Vec<(usize, String)>),
ChangeMode(ModeInfo, ClientId, Option<NotificationEnd>),
ChangeModeForAllClients(ModeInfo, Option<NotificationEnd>),
MouseEvent(MouseEvent, ClientId, Option<NotificationEnd>),
Copy(ClientId, Option<NotificationEnd>),
AddClient(
ClientId,
bool, // is_web_client
Option<usize>, // tab position to focus
Option<(u32, bool)>, // (pane_id, is_plugin) => pane_id to focus
),
RemoveClient(ClientId),
UpdateSearch(Vec<u8>, ClientId, Option<NotificationEnd>),
SearchDown(ClientId, Option<NotificationEnd>),
SearchUp(ClientId, Option<NotificationEnd>),
SearchToggleCaseSensitivity(ClientId, Option<NotificationEnd>),
SearchToggleWholeWord(ClientId, Option<NotificationEnd>),
SearchToggleWrap(ClientId, Option<NotificationEnd>),
AddRedPaneFrameColorOverride(Vec<PaneId>, Option<String>), // Option<String> => optional error text
ClearPaneFrameColorOverride(Vec<PaneId>),
PreviousSwapLayout(ClientId, Option<NotificationEnd>),
NextSwapLayout(ClientId, Option<NotificationEnd>),
OverrideLayout(
Option<PathBuf>, // cwd
Option<TerminalAction>, // default_shell
Option<String>, // new name for tab
TiledPaneLayout,
Vec<FloatingPaneLayout>,
Option<Vec<SwapTiledLayout>>,
Option<Vec<SwapFloatingLayout>>,
bool, // retain_existing_terminal_panes
bool, // retain_existing_plugin_panes
ClientId,
Option<NotificationEnd>,
),
OverrideLayoutComplete(
TiledPaneLayout,
Vec<FloatingPaneLayout>,
Option<Vec<SwapTiledLayout>>,
Option<Vec<SwapFloatingLayout>>,
Vec<(u32, HoldForCommand)>, // new terminal pids
Vec<(u32, HoldForCommand)>, // new floating pane pids
HashMap<RunPluginOrAlias, Vec<u32>>,
bool, // retain_existing_terminal_panes
bool, // retain_existing_plugin_panes
usize, // tab_index
ClientId,
Option<NotificationEnd>,
),
QueryTabNames(ClientId, Option<NotificationEnd>),
NewTiledPluginPane(
RunPluginOrAlias,
Option<String>,
bool,
Option<PathBuf>,
ClientId,
Option<NotificationEnd>,
), // Option<String> is
// optional pane title, bool is skip cache, Option<PathBuf> is an optional cwd
NewFloatingPluginPane(
RunPluginOrAlias,
Option<String>,
bool,
Option<PathBuf>,
Option<FloatingPaneCoordinates>,
ClientId,
Option<NotificationEnd>,
), // Option<String> is an
// optional pane title, bool
// is skip cache, Option<PathBuf> is an optional cwd
NewInPlacePluginPane(
RunPluginOrAlias,
Option<String>,
PaneId,
bool,
ClientId,
Option<NotificationEnd>,
), // Option<String> is an
// optional pane title, bool is skip cache
StartOrReloadPluginPane(RunPluginOrAlias, Option<String>, Option<NotificationEnd>),
AddPlugin(
Option<bool>, // should_float
bool, // should be opened in place
RunPluginOrAlias,
Option<String>, // pane title
Option<usize>, // tab index
u32, // plugin id
Option<PaneId>,
Option<PathBuf>, // cwd
bool, // start suppressed
Option<FloatingPaneCoordinates>,
Option<bool>, // should focus plugin
Option<ClientId>,
Option<NotificationEnd>, // completion signal
),
UpdatePluginLoadingStage(u32, LoadingIndication), // u32 - plugin_id
StartPluginLoadingIndication(u32, LoadingIndication), // u32 - plugin_id
ProgressPluginLoadingOffset(u32), // u32 - plugin id
RequestStateUpdateForPlugins,
LaunchOrFocusPlugin(
RunPluginOrAlias,
bool,
bool,
bool,
Option<PaneId>,
bool,
ClientId,
Option<NotificationEnd>,
), // bools are: should_float, move_to_focused_tab, should_open_in_place, Option<PaneId> is the pane id to replace, bool following it is skip_cache
LaunchPlugin(
RunPluginOrAlias,
bool,
bool,
Option<PaneId>,
bool,
Option<PathBuf>,
ClientId,
Option<NotificationEnd>,
), // bools are: should_float, should_open_in_place Option<PaneId> is the pane id to replace, Option<PathBuf> is an optional cwd, bool after is skip_cache
SuppressPane(PaneId, ClientId),
UnsuppressPane(PaneId, bool), // bool -> should float if hidden
UnsuppressOrExpandPane(PaneId, bool), // bool -> should float if hidden
FocusPaneWithId(PaneId, bool, bool, ClientId, Option<NotificationEnd>), // bools:
// should_float_if_hidden,
// should_be_in_place_if_hidden
RenamePane(PaneId, Vec<u8>, Option<NotificationEnd>),
RenameTab(usize, Vec<u8>, Option<NotificationEnd>),
RequestPluginPermissions(
u32, // u32 - plugin_id
PluginPermission,
),
BreakPane(
Box<Layout>,
Option<TerminalAction>,
ClientId,
Option<NotificationEnd>,
),
BreakPaneRight(ClientId, Option<NotificationEnd>),
BreakPaneLeft(ClientId, Option<NotificationEnd>),
UpdateSessionInfos(
BTreeMap<String, SessionInfo>, // String is the session name
BTreeMap<String, Duration>, // resurrectable sessions - <name, created>
),
ReplacePane(
PaneId,
HoldForCommand,
Option<InitialTitle>,
Option<Run>,
bool, // close replaced pane
ClientTabIndexOrPaneId,
Option<NotificationEnd>, // completion signal
),
SerializeLayoutForResurrection,
RenameSession(String, ClientId, Option<NotificationEnd>), // String -> new name
ListClientsMetadata(Option<PathBuf>, ClientId, Option<NotificationEnd>), // Option<PathBuf> - default shell
Reconfigure {
client_id: ClientId,
keybinds: Keybinds,
default_mode: InputMode,
theme: Styling,
simplified_ui: bool,
default_shell: Option<PathBuf>,
pane_frames: bool,
copy_command: Option<String>,
copy_to_clipboard: Option<Clipboard>,
copy_on_select: bool,
auto_layout: bool,
rounded_corners: bool,
hide_session_name: bool,
stacked_resize: bool,
default_editor: Option<PathBuf>,
advanced_mouse_actions: bool,
},
RerunCommandPane(u32, Option<NotificationEnd>), // u32 - terminal pane id
ResizePaneWithId(ResizeStrategy, PaneId),
EditScrollbackForPaneWithId(PaneId, Option<NotificationEnd>),
WriteToPaneId(Vec<u8>, PaneId),
CopyTextToClipboard(String, u32), // String - text to copy, u32 - plugin_id
MovePaneWithPaneId(PaneId),
MovePaneWithPaneIdInDirection(PaneId, Direction),
ClearScreenForPaneId(PaneId),
ScrollUpInPaneId(PaneId),
ScrollDownInPaneId(PaneId),
ScrollToTopInPaneId(PaneId),
ScrollToBottomInPaneId(PaneId),
PageScrollUpInPaneId(PaneId),
PageScrollDownInPaneId(PaneId),
TogglePaneIdFullscreen(PaneId),
TogglePaneEmbedOrEjectForPaneId(PaneId),
CloseTabWithIndex(usize),
BreakPanesToNewTab {
pane_ids: Vec<PaneId>,
default_shell: Option<TerminalAction>,
should_change_focus_to_new_tab: bool,
new_tab_name: Option<String>,
client_id: ClientId,
},
BreakPanesToTabWithIndex {
pane_ids: Vec<PaneId>,
tab_index: usize,
should_change_focus_to_new_tab: bool,
client_id: ClientId,
},
ListClientsToPlugin(PluginId, ClientId),
TogglePanePinned(ClientId, Option<NotificationEnd>),
SetFloatingPanePinned(PaneId, bool),
StackPanes(Vec<PaneId>, ClientId, Option<NotificationEnd>),
ChangeFloatingPanesCoordinates(
Vec<(PaneId, FloatingPaneCoordinates)>,
Option<NotificationEnd>,
),
AddHighlightPaneFrameColorOverride(Vec<PaneId>, Option<String>), // Option<String> => optional
// message
GroupAndUngroupPanes(Vec<PaneId>, Vec<PaneId>, bool, ClientId), // panes_to_group, panes_to_ungroup, bool -> for all clients
HighlightAndUnhighlightPanes(Vec<PaneId>, Vec<PaneId>, ClientId), // panes_to_highlight, panes_to_unhighlight
FloatMultiplePanes(Vec<PaneId>, ClientId),
EmbedMultiplePanes(Vec<PaneId>, ClientId),
TogglePaneInGroup(ClientId, Option<NotificationEnd>),
ToggleGroupMarking(ClientId, Option<NotificationEnd>),
SessionSharingStatusChange(bool),
SetMouseSelectionSupport(PaneId, bool),
InterceptKeyPresses(PluginId, ClientId),
ClearKeyPressesIntercepts(ClientId),
ReplacePaneWithExistingPane(PaneId, PaneId, bool), // bool -> suppress_replaced_pane
AddWatcherClient(ClientId, Size),
RemoveWatcherClient(ClientId),
SetFollowedClient(ClientId),
WatcherTerminalResize(ClientId, Size),
}
impl From<&ScreenInstruction> for ScreenContext {
fn from(screen_instruction: &ScreenInstruction) -> Self {
match *screen_instruction {
ScreenInstruction::PtyBytes(..) => ScreenContext::HandlePtyBytes,
ScreenInstruction::PluginBytes(..) => ScreenContext::PluginBytes,
ScreenInstruction::Render => ScreenContext::Render,
ScreenInstruction::RenderToClients => ScreenContext::RenderToClients,
ScreenInstruction::NewPane(..) => ScreenContext::NewPane,
ScreenInstruction::OpenInPlaceEditor(..) => ScreenContext::OpenInPlaceEditor,
ScreenInstruction::TogglePaneEmbedOrFloating(..) => {
ScreenContext::TogglePaneEmbedOrFloating
},
ScreenInstruction::ToggleFloatingPanes(..) => ScreenContext::ToggleFloatingPanes,
ScreenInstruction::WriteCharacter(..) => ScreenContext::WriteCharacter,
ScreenInstruction::Resize(.., strategy, _) => match strategy {
ResizeStrategy {
resize: Resize::Increase,
direction,
..
} => match direction {
Some(Direction::Left) => ScreenContext::ResizeIncreaseLeft,
Some(Direction::Down) => ScreenContext::ResizeIncreaseDown,
Some(Direction::Up) => ScreenContext::ResizeIncreaseUp,
Some(Direction::Right) => ScreenContext::ResizeIncreaseRight,
None => ScreenContext::ResizeIncreaseAll,
},
ResizeStrategy {
resize: Resize::Decrease,
direction,
..
} => match direction {
Some(Direction::Left) => ScreenContext::ResizeDecreaseLeft,
Some(Direction::Down) => ScreenContext::ResizeDecreaseDown,
Some(Direction::Up) => ScreenContext::ResizeDecreaseUp,
Some(Direction::Right) => ScreenContext::ResizeDecreaseRight,
None => ScreenContext::ResizeDecreaseAll,
},
},
ScreenInstruction::SwitchFocus(..) => ScreenContext::SwitchFocus,
ScreenInstruction::FocusNextPane(..) => ScreenContext::FocusNextPane,
ScreenInstruction::FocusPreviousPane(..) => ScreenContext::FocusPreviousPane,
ScreenInstruction::MoveFocusLeft(..) => ScreenContext::MoveFocusLeft,
ScreenInstruction::MoveFocusLeftOrPreviousTab(..) => {
ScreenContext::MoveFocusLeftOrPreviousTab
},
ScreenInstruction::MoveFocusDown(..) => ScreenContext::MoveFocusDown,
ScreenInstruction::MoveFocusUp(..) => ScreenContext::MoveFocusUp,
ScreenInstruction::MoveFocusRight(..) => ScreenContext::MoveFocusRight,
ScreenInstruction::MoveFocusRightOrNextTab(..) => {
ScreenContext::MoveFocusRightOrNextTab
},
ScreenInstruction::MovePane(..) => ScreenContext::MovePane,
ScreenInstruction::MovePaneBackwards(..) => ScreenContext::MovePaneBackwards,
ScreenInstruction::MovePaneDown(..) => ScreenContext::MovePaneDown,
ScreenInstruction::MovePaneUp(..) => ScreenContext::MovePaneUp,
ScreenInstruction::MovePaneRight(..) => ScreenContext::MovePaneRight,
ScreenInstruction::MovePaneLeft(..) => ScreenContext::MovePaneLeft,
ScreenInstruction::Exit => ScreenContext::Exit,
ScreenInstruction::ClearScreen(..) => ScreenContext::ClearScreen,
ScreenInstruction::DumpScreen(..) => ScreenContext::DumpScreen,
ScreenInstruction::DumpLayout(..) => ScreenContext::DumpLayout,
ScreenInstruction::DumpLayoutToPlugin(..) => ScreenContext::DumpLayoutToPlugin,
ScreenInstruction::EditScrollback(..) => ScreenContext::EditScrollback,
ScreenInstruction::GetPaneScrollback { .. } => ScreenContext::GetPaneScrollback,
ScreenInstruction::ScrollUp(..) => ScreenContext::ScrollUp,
ScreenInstruction::ScrollDown(..) => ScreenContext::ScrollDown,
ScreenInstruction::ScrollToBottom(..) => ScreenContext::ScrollToBottom,
ScreenInstruction::ScrollToTop(..) => ScreenContext::ScrollToTop,
ScreenInstruction::PageScrollUp(..) => ScreenContext::PageScrollUp,
ScreenInstruction::PageScrollDown(..) => ScreenContext::PageScrollDown,
ScreenInstruction::HalfPageScrollUp(..) => ScreenContext::HalfPageScrollUp,
ScreenInstruction::HalfPageScrollDown(..) => ScreenContext::HalfPageScrollDown,
ScreenInstruction::ClearScroll(..) => ScreenContext::ClearScroll,
ScreenInstruction::CloseFocusedPane(..) => ScreenContext::CloseFocusedPane,
ScreenInstruction::ToggleActiveTerminalFullscreen(..) => {
ScreenContext::ToggleActiveTerminalFullscreen
},
ScreenInstruction::TogglePaneFrames(..) => ScreenContext::TogglePaneFrames,
ScreenInstruction::SetSelectable(..) => ScreenContext::SetSelectable,
ScreenInstruction::ShowPluginCursor(..) => ScreenContext::ShowPluginCursor,
ScreenInstruction::ClosePane(..) => ScreenContext::ClosePane,
ScreenInstruction::HoldPane(..) => ScreenContext::HoldPane,
ScreenInstruction::UpdatePaneName(..) => ScreenContext::UpdatePaneName,
ScreenInstruction::UndoRenamePane(..) => ScreenContext::UndoRenamePane,
ScreenInstruction::NewTab(..) => ScreenContext::NewTab,
ScreenInstruction::ApplyLayout(..) => ScreenContext::ApplyLayout,
ScreenInstruction::SwitchTabNext(..) => ScreenContext::SwitchTabNext,
ScreenInstruction::SwitchTabPrev(..) => ScreenContext::SwitchTabPrev,
ScreenInstruction::CloseTab(..) => ScreenContext::CloseTab,
ScreenInstruction::GoToTab(..) => ScreenContext::GoToTab,
ScreenInstruction::GoToTabName(..) => ScreenContext::GoToTabName,
ScreenInstruction::UpdateTabName(..) => ScreenContext::UpdateTabName,
ScreenInstruction::UndoRenameTab(..) => ScreenContext::UndoRenameTab,
ScreenInstruction::MoveTabLeft(..) => ScreenContext::MoveTabLeft,
ScreenInstruction::MoveTabRight(..) => ScreenContext::MoveTabRight,
ScreenInstruction::TerminalResize(..) => ScreenContext::TerminalResize,
ScreenInstruction::TerminalPixelDimensions(..) => {
ScreenContext::TerminalPixelDimensions
},
ScreenInstruction::TerminalBackgroundColor(..) => {
ScreenContext::TerminalBackgroundColor
},
ScreenInstruction::TerminalForegroundColor(..) => {
ScreenContext::TerminalForegroundColor
},
ScreenInstruction::TerminalColorRegisters(..) => ScreenContext::TerminalColorRegisters,
ScreenInstruction::ChangeMode(..) => ScreenContext::ChangeMode,
ScreenInstruction::ChangeModeForAllClients(..) => {
ScreenContext::ChangeModeForAllClients
},
ScreenInstruction::ToggleActiveSyncTab(..) => ScreenContext::ToggleActiveSyncTab,
ScreenInstruction::ScrollUpAt(..) => ScreenContext::ScrollUpAt,
ScreenInstruction::ScrollDownAt(..) => ScreenContext::ScrollDownAt,
ScreenInstruction::MouseEvent(..) => ScreenContext::MouseEvent,
ScreenInstruction::Copy(..) => ScreenContext::Copy,
ScreenInstruction::ToggleTab(..) => ScreenContext::ToggleTab,
ScreenInstruction::AddClient(..) => ScreenContext::AddClient,
ScreenInstruction::RemoveClient(..) => ScreenContext::RemoveClient,
ScreenInstruction::UpdateSearch(..) => ScreenContext::UpdateSearch,
ScreenInstruction::SearchDown(..) => ScreenContext::SearchDown,
ScreenInstruction::SearchUp(..) => ScreenContext::SearchUp,
ScreenInstruction::SearchToggleCaseSensitivity(..) => {
ScreenContext::SearchToggleCaseSensitivity
},
ScreenInstruction::SearchToggleWholeWord(..) => ScreenContext::SearchToggleWholeWord,
ScreenInstruction::SearchToggleWrap(..) => ScreenContext::SearchToggleWrap,
ScreenInstruction::AddRedPaneFrameColorOverride(..) => {
ScreenContext::AddRedPaneFrameColorOverride
},
ScreenInstruction::ClearPaneFrameColorOverride(..) => {
ScreenContext::ClearPaneFrameColorOverride
},
ScreenInstruction::PreviousSwapLayout(..) => ScreenContext::PreviousSwapLayout,
ScreenInstruction::NextSwapLayout(..) => ScreenContext::NextSwapLayout,
ScreenInstruction::OverrideLayout(..) => ScreenContext::OverrideLayout,
ScreenInstruction::OverrideLayoutComplete(..) => ScreenContext::OverrideLayoutComplete,
ScreenInstruction::QueryTabNames(..) => ScreenContext::QueryTabNames,
ScreenInstruction::NewTiledPluginPane(..) => ScreenContext::NewTiledPluginPane,
ScreenInstruction::NewFloatingPluginPane(..) => ScreenContext::NewFloatingPluginPane,
ScreenInstruction::StartOrReloadPluginPane(..) => {
ScreenContext::StartOrReloadPluginPane
},
ScreenInstruction::AddPlugin(..) => ScreenContext::AddPlugin,
ScreenInstruction::UpdatePluginLoadingStage(..) => {
ScreenContext::UpdatePluginLoadingStage
},
ScreenInstruction::ProgressPluginLoadingOffset(..) => {
ScreenContext::ProgressPluginLoadingOffset
},
ScreenInstruction::StartPluginLoadingIndication(..) => {
ScreenContext::StartPluginLoadingIndication
},
ScreenInstruction::RequestStateUpdateForPlugins => {
ScreenContext::RequestStateUpdateForPlugins
},
ScreenInstruction::LaunchOrFocusPlugin(..) => ScreenContext::LaunchOrFocusPlugin,
ScreenInstruction::LaunchPlugin(..) => ScreenContext::LaunchPlugin,
ScreenInstruction::SuppressPane(..) => ScreenContext::SuppressPane,
ScreenInstruction::UnsuppressPane(..) => ScreenContext::UnsuppressPane,
ScreenInstruction::UnsuppressOrExpandPane(..) => ScreenContext::UnsuppressOrExpandPane,
ScreenInstruction::FocusPaneWithId(..) => ScreenContext::FocusPaneWithId,
ScreenInstruction::RenamePane(..) => ScreenContext::RenamePane,
ScreenInstruction::RenameTab(..) => ScreenContext::RenameTab,
ScreenInstruction::RequestPluginPermissions(..) => {
ScreenContext::RequestPluginPermissions
},
ScreenInstruction::BreakPane(..) => ScreenContext::BreakPane,
ScreenInstruction::BreakPaneRight(..) => ScreenContext::BreakPaneRight,
ScreenInstruction::BreakPaneLeft(..) => ScreenContext::BreakPaneLeft,
ScreenInstruction::UpdateSessionInfos(..) => ScreenContext::UpdateSessionInfos,
ScreenInstruction::ReplacePane(..) => ScreenContext::ReplacePane,
ScreenInstruction::NewInPlacePluginPane(..) => ScreenContext::NewInPlacePluginPane,
ScreenInstruction::SerializeLayoutForResurrection => {
ScreenContext::SerializeLayoutForResurrection
},
ScreenInstruction::RenameSession(..) => ScreenContext::RenameSession,
ScreenInstruction::ListClientsMetadata(..) => ScreenContext::ListClientsMetadata,
ScreenInstruction::Reconfigure { .. } => ScreenContext::Reconfigure,
ScreenInstruction::RerunCommandPane { .. } => ScreenContext::RerunCommandPane,
ScreenInstruction::ResizePaneWithId(..) => ScreenContext::ResizePaneWithId,
ScreenInstruction::EditScrollbackForPaneWithId(..) => {
ScreenContext::EditScrollbackForPaneWithId
},
ScreenInstruction::WriteToPaneId(..) => ScreenContext::WriteToPaneId,
ScreenInstruction::CopyTextToClipboard(..) => ScreenContext::CopyTextToClipboard,
ScreenInstruction::MovePaneWithPaneId(..) => ScreenContext::MovePaneWithPaneId,
ScreenInstruction::MovePaneWithPaneIdInDirection(..) => {
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/plugins/pinned_executor.rs | zellij-server/src/plugins/pinned_executor.rs | use crate::plugins::plugin_map::PluginMap;
use crate::plugins::wasm_bridge::PluginCache;
use crate::ClientId;
use crate::ThreadSenders;
use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{channel, Sender};
use std::sync::{Arc, Mutex};
use std::thread;
use wasmi::Engine;
use zellij_utils::input::layout::Layout;
/// A dynamic thread pool that pins jobs to specific threads based on plugin_id
/// Starts with 1 thread and expands when threads are busy, shrinks when plugins unload
pub struct PinnedExecutor {
// Sparse vector - Some(thread) for active threads, None for removed threads
execution_threads: Arc<Mutex<Vec<Option<ExecutionThread>>>>,
// Maps plugin_id -> thread_index (permanent assignment)
plugin_assignments: Arc<Mutex<HashMap<u32, usize>>>,
// Maps thread_index -> set of plugin_ids assigned to it
thread_plugins: Arc<Mutex<HashMap<usize, HashSet<u32>>>>,
// Next thread index to use when spawning (monotonically increasing)
next_thread_idx: AtomicUsize,
// Maximum threads allowed
max_threads: usize,
// state to send to plugins (to be kept on execution threads)
senders: ThreadSenders,
plugin_map: Arc<Mutex<PluginMap>>,
connected_clients: Arc<Mutex<Vec<ClientId>>>,
default_layout: Box<Layout>,
plugin_cache: PluginCache,
engine: Engine,
}
struct ExecutionThread {
sender: Sender<Job>,
jobs_in_flight: Arc<AtomicUsize>, // Busy state tracking
}
enum Job {
Work(
Box<
dyn FnOnce(
ThreadSenders,
Arc<Mutex<PluginMap>>,
Arc<Mutex<Vec<ClientId>>>,
Box<Layout>,
PluginCache,
Engine,
) + Send
+ 'static,
>,
),
Shutdown, // Signal to exit the worker loop
}
impl PinnedExecutor {
/// Creates a new pinned executor with the specified maximum number of threads
/// Starts with exactly 1 thread
pub fn new(
max_threads: usize,
senders: &ThreadSenders,
plugin_map: &Arc<Mutex<PluginMap>>,
connected_clients: &Arc<Mutex<Vec<ClientId>>>,
default_layout: &Box<Layout>,
plugin_cache: &PluginCache,
engine: &Engine,
) -> Self {
let max_threads = max_threads.max(1); // At least 1
let thread_0 = Self::spawn_thread(
0,
senders.clone(),
plugin_map.clone(),
connected_clients.clone(),
default_layout.clone(),
plugin_cache.clone(),
engine.clone(),
);
PinnedExecutor {
execution_threads: Arc::new(Mutex::new(vec![Some(thread_0)])),
plugin_assignments: Arc::new(Mutex::new(HashMap::new())),
thread_plugins: Arc::new(Mutex::new(HashMap::new())),
next_thread_idx: AtomicUsize::new(1), // Next will be index 1
max_threads,
senders: senders.clone(),
plugin_map: plugin_map.clone(),
connected_clients: connected_clients.clone(),
default_layout: default_layout.clone(),
plugin_cache: plugin_cache.clone(),
engine: engine.clone(),
}
}
fn spawn_thread(
thread_idx: usize,
senders: ThreadSenders,
plugin_map: Arc<Mutex<PluginMap>>,
connected_clients: Arc<Mutex<Vec<ClientId>>>,
default_layout: Box<Layout>,
plugin_cache: PluginCache,
engine: Engine,
) -> ExecutionThread {
let (sender, receiver) = channel::<Job>();
let jobs_in_flight = Arc::new(AtomicUsize::new(0));
let jobs_in_flight_clone = jobs_in_flight.clone();
let thread_handle = thread::Builder::new()
.name(format!("plugin-exec-{}", thread_idx))
.spawn({
move || {
let senders = senders;
let plugin_map = plugin_map;
let connected_clients = connected_clients;
let default_layout = default_layout;
let plugin_cache = plugin_cache;
let engine = engine;
while let Ok(job) = receiver.recv() {
match job {
Job::Work(work) => {
work(
senders.clone(),
plugin_map.clone(),
connected_clients.clone(),
default_layout.clone(),
plugin_cache.clone(),
engine.clone(),
);
jobs_in_flight_clone.fetch_sub(1, Ordering::SeqCst);
},
Job::Shutdown => break,
}
}
}
});
if let Err(e) = thread_handle {
log::error!("Failed to spawn plugin execution thread: {}", e);
}
ExecutionThread {
sender,
jobs_in_flight,
}
}
/// Register a plugin and assign it to a thread
/// Called from wasm_bridge when loading a plugin
pub fn register_plugin(&self, plugin_id: u32) -> usize {
let mut assignments = self.plugin_assignments.lock().unwrap();
// If already assigned (shouldn't happen, but defensive)
if let Some(&thread_idx) = assignments.get(&plugin_id) {
return thread_idx;
}
let mut thread_plugins = self.thread_plugins.lock().unwrap();
let threads = self.execution_threads.lock().unwrap();
// Find a non-busy thread with assigned plugins (prefer reusing threads)
let mut best_thread: Option<(usize, usize)> = None; // (index, load)
for (idx, thread_opt) in threads.iter().enumerate() {
if let Some(thread) = thread_opt {
let is_busy = thread.jobs_in_flight.load(Ordering::SeqCst) > 0;
if !is_busy {
let load = thread_plugins.get(&idx).map(|s| s.len()).unwrap_or(0);
if best_thread.is_none() || best_thread.map(|b| load < b.1).unwrap_or(false) {
best_thread = Some((idx, load));
}
}
}
}
let thread_idx = if let Some((idx, _)) = best_thread {
// Found a non-busy thread
idx
} else {
// All threads are busy - need to expand
if threads.len() < self.max_threads {
// Spawn a new thread
let new_idx = self.next_thread_idx.fetch_add(1, Ordering::SeqCst);
drop(threads); // Release lock before spawning
self.add_thread(new_idx);
new_idx
} else {
// At max capacity, assign to least-loaded thread
threads
.iter()
.enumerate()
.filter_map(|(idx, t)| t.as_ref().map(|_| idx))
.min_by_key(|&idx| thread_plugins.get(&idx).map(|s| s.len()).unwrap_or(0))
.unwrap_or_else(|| {
log::error!("Failed to find free thread to run the plugin!");
0 // this is a misconfiguration, but we don't want to crash the app
// if it happens
})
}
};
// Update mappings
assignments.insert(plugin_id, thread_idx);
thread_plugins
.entry(thread_idx)
.or_insert_with(HashSet::new)
.insert(plugin_id);
thread_idx
}
fn add_thread(&self, thread_idx: usize) {
let mut threads = self.execution_threads.lock().unwrap();
let new_thread = Self::spawn_thread(
thread_idx,
self.senders.clone(),
self.plugin_map.clone(),
self.connected_clients.clone(),
self.default_layout.clone(),
self.plugin_cache.clone(),
self.engine.clone(),
);
// Extend vector if needed
while threads.len() <= thread_idx {
threads.push(None);
}
threads[thread_idx] = Some(new_thread);
}
/// Execute job pinned to plugin's assigned thread
pub fn execute_for_plugin<F>(&self, plugin_id: u32, f: F)
where
F: FnOnce(
ThreadSenders,
Arc<Mutex<PluginMap>>,
Arc<Mutex<Vec<ClientId>>>,
Box<Layout>,
PluginCache,
Engine,
) + Send
+ 'static,
{
// Look up assigned thread
let thread_idx = {
let assignments = self.plugin_assignments.lock().unwrap();
assignments.get(&plugin_id).copied()
};
let Some(thread_idx) = thread_idx else {
log::error!("Failed to find thread for plugin with id: {}", plugin_id);
return;
};
// Get thread and mark as busy
let threads = self.execution_threads.lock().unwrap();
let thread = threads[thread_idx].as_ref();
let Some(thread) = thread else {
log::error!("Failed to find thread for plugin with id: {}", plugin_id);
return;
};
// Increment busy counter BEFORE sending work
thread.jobs_in_flight.fetch_add(1, Ordering::SeqCst);
// Send work
let job = Job::Work(Box::new(f));
if let Err(_) = thread.sender.send(job) {
// Thread died unexpectedly - this is a critical error
thread.jobs_in_flight.fetch_sub(1, Ordering::SeqCst);
log::error!("Plugin executor thread {} has died", thread_idx);
}
}
/// Load a plugin: register it and execute the load work on its assigned thread
/// This combines registration + execution for plugin loading
pub fn execute_plugin_load<F>(&self, plugin_id: u32, f: F)
where
F: FnOnce(
ThreadSenders,
Arc<Mutex<PluginMap>>,
Arc<Mutex<Vec<ClientId>>>,
Box<Layout>,
PluginCache,
Engine,
) + Send
+ 'static,
{
// Register plugin and assign to a thread
self.register_plugin(plugin_id);
// Execute the load work on the assigned thread
self.execute_for_plugin(plugin_id, f);
}
/// Unload a plugin: execute cleanup work, then unregister and potentially shrink pool
/// This combines cleanup execution + unregistration for plugin unloading
/// Requires Arc<Self> so we can clone it into the closure for unregistration
pub fn execute_plugin_unload(
self: &Arc<Self>,
plugin_id: u32,
f: impl FnOnce(
ThreadSenders,
Arc<Mutex<PluginMap>>,
Arc<Mutex<Vec<ClientId>>>,
Box<Layout>,
PluginCache,
Engine,
) + Send
+ 'static,
) {
let executor = self.clone();
self.execute_for_plugin(
plugin_id,
move |senders, plugin_map, connected_clients, default_layout, plugin_cache, engine| {
// Execute the cleanup work
f(
senders,
plugin_map,
connected_clients,
default_layout,
plugin_cache,
engine,
);
// Unregister plugin and potentially shrink the pool
executor.unregister_plugin(plugin_id);
},
);
}
/// Unregister a plugin and potentially shrink the pool
/// Called from wasm_bridge after plugin cleanup is complete
pub fn unregister_plugin(&self, plugin_id: u32) {
let mut assignments = self.plugin_assignments.lock().unwrap();
let mut thread_plugins = self.thread_plugins.lock().unwrap();
if let Some(thread_idx) = assignments.remove(&plugin_id) {
if let Some(plugins) = thread_plugins.get_mut(&thread_idx) {
plugins.remove(&plugin_id);
}
}
drop(assignments);
drop(thread_plugins);
// Try to shrink the pool
self.try_shrink_pool();
}
fn try_shrink_pool(&self) {
let mut threads = self.execution_threads.lock().unwrap();
let thread_plugins = self.thread_plugins.lock().unwrap();
// Find threads with no assigned plugins (except thread 0, always keep it)
let threads_to_remove: Vec<usize> = threads
.iter()
.enumerate()
.skip(1) // Never remove thread 0
.filter_map(|(idx, thread_opt)| {
if thread_opt.is_some() {
let has_plugins = thread_plugins
.get(&idx)
.map(|s| !s.is_empty())
.unwrap_or(false);
if !has_plugins {
Some(idx)
} else {
None
}
} else {
None
}
})
.collect();
// Shutdown and remove idle threads
for idx in threads_to_remove {
if let Some(thread) = threads[idx].take() {
let _ = thread.sender.send(Job::Shutdown);
}
}
}
#[cfg(test)]
pub fn thread_count(&self) -> usize {
self.execution_threads
.lock()
.unwrap()
.iter()
.filter(|t| t.is_some())
.count()
}
}
impl Drop for PinnedExecutor {
fn drop(&mut self) {
let mut threads = self.execution_threads.lock().unwrap();
// Send shutdown to all threads
for thread_opt in threads.iter_mut() {
if let Some(thread) = thread_opt {
let _ = thread.sender.send(Job::Shutdown);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{channel, Sender};
use std::sync::{Arc, Barrier, Mutex};
use std::thread;
use std::time::Duration;
// Test fixtures
fn create_test_dependencies() -> (
ThreadSenders,
Arc<Mutex<PluginMap>>,
Arc<Mutex<Vec<ClientId>>>,
Box<Layout>,
PluginCache,
Engine,
) {
use std::path::PathBuf;
use wasmi::Module;
use zellij_utils::channels::{self, SenderWithContext};
let (send_to_pty, _receive_pty) = channels::bounded(1);
let (send_to_screen, _receive_screen) = channels::bounded(1);
let (send_to_plugin, _receive_plugin) = channels::bounded(1);
let (send_to_server, _receive_server) = channels::bounded(1);
let (send_to_pty_writer, _receive_pty_writer) = channels::bounded(1);
let (send_to_background_jobs, _receive_background_jobs) = channels::bounded(1);
let to_pty = SenderWithContext::new(send_to_pty);
let to_screen = SenderWithContext::new(send_to_screen);
let to_plugin = SenderWithContext::new(send_to_plugin);
let to_server = SenderWithContext::new(send_to_server);
let to_pty_writer = SenderWithContext::new(send_to_pty_writer);
let to_background_jobs = SenderWithContext::new(send_to_background_jobs);
let senders = ThreadSenders {
to_pty: Some(to_pty),
to_screen: Some(to_screen),
to_plugin: Some(to_plugin),
to_server: Some(to_server),
to_pty_writer: Some(to_pty_writer),
to_background_jobs: Some(to_background_jobs),
should_silently_fail: false,
};
let plugin_map = Arc::new(Mutex::new(PluginMap::default()));
let connected_clients = Arc::new(Mutex::new(vec![]));
let layout = Box::new(Layout::default());
let plugin_cache = Arc::new(Mutex::new(
std::collections::HashMap::<PathBuf, Module>::new(),
));
let engine = Engine::default();
(
senders,
plugin_map,
connected_clients,
layout,
plugin_cache,
engine,
)
}
fn create_test_executor(max_threads: usize) -> Arc<PinnedExecutor> {
let (senders, plugin_map, clients, layout, cache, engine) = create_test_dependencies();
Arc::new(PinnedExecutor::new(
max_threads,
&senders,
&plugin_map,
&clients,
&layout,
&cache,
&engine,
))
}
// Helper to create a job that signals completion via channel
fn make_signaling_job(
tx: Sender<()>,
) -> impl FnOnce(
ThreadSenders,
Arc<Mutex<PluginMap>>,
Arc<Mutex<Vec<ClientId>>>,
Box<Layout>,
PluginCache,
Engine,
) + Send
+ 'static {
move |_senders, _plugin_map, _clients, _layout, _cache, _engine| {
tx.send(()).unwrap();
}
}
// Helper to verify thread assignment by capturing thread name in job
fn get_thread_name_for_plugin(executor: &Arc<PinnedExecutor>, plugin_id: u32) -> String {
let (tx, rx) = channel();
executor.execute_for_plugin(plugin_id, move |_s, _p, _c, _l, _ca, _e| {
let name = thread::current().name().unwrap().to_string();
tx.send(name).unwrap();
});
rx.recv_timeout(Duration::from_secs(5))
.expect("Thread name should be received")
}
#[test]
fn test_new_creates_one_thread() {
let executor = create_test_executor(4);
assert_eq!(executor.thread_count(), 1);
}
#[test]
fn test_new_respects_min_threads() {
let executor = create_test_executor(0);
assert_eq!(
executor.thread_count(),
1,
"Executor should enforce minimum of 1 thread"
);
}
#[test]
fn test_first_plugin_assigned_to_thread_zero() {
let executor = create_test_executor(4);
let thread_idx = executor.register_plugin(1);
assert_eq!(thread_idx, 0);
}
#[test]
fn test_multiple_plugins_share_thread_when_idle() {
let executor = create_test_executor(4);
let thread_idx1 = executor.register_plugin(1);
let thread_idx2 = executor.register_plugin(2);
assert_eq!(thread_idx1, 0);
assert_eq!(
thread_idx2, 0,
"Second plugin should share thread 0 when idle"
);
}
#[test]
fn test_new_thread_spawns_when_all_busy() {
let executor = create_test_executor(3);
// Register plugin 1, gets thread 0
let thread_idx1 = executor.register_plugin(1);
assert_eq!(thread_idx1, 0);
// Make thread 0 busy with a barrier
let barrier = Arc::new(Barrier::new(2));
let barrier_clone = barrier.clone();
executor.execute_for_plugin(1, move |_s, _p, _c, _l, _ca, _e| {
barrier_clone.wait();
});
// Give the job a moment to start executing and block
thread::sleep(Duration::from_millis(50));
// Register plugin 2 while thread 0 is busy
let thread_idx2 = executor.register_plugin(2);
assert_eq!(
thread_idx2, 1,
"Plugin 2 should get new thread 1 when thread 0 is busy"
);
// Verify thread count
assert_eq!(executor.thread_count(), 2);
// Release barrier
barrier.wait();
}
#[test]
fn test_respects_max_threads_limit() {
let executor = create_test_executor(2);
// Register plugin 1, gets thread 0
executor.register_plugin(1);
// Make thread 0 busy
let barrier1 = Arc::new(Barrier::new(2));
let barrier1_clone = barrier1.clone();
executor.execute_for_plugin(1, move |_s, _p, _c, _l, _ca, _e| {
barrier1_clone.wait();
});
thread::sleep(Duration::from_millis(50));
// Register plugin 2, gets thread 1
executor.register_plugin(2);
// Make thread 1 busy
let barrier2 = Arc::new(Barrier::new(2));
let barrier2_clone = barrier2.clone();
executor.execute_for_plugin(2, move |_s, _p, _c, _l, _ca, _e| {
barrier2_clone.wait();
});
thread::sleep(Duration::from_millis(50));
// Register plugin 3 when all threads busy
let thread_idx3 = executor.register_plugin(3);
assert!(
thread_idx3 == 0 || thread_idx3 == 1,
"Plugin 3 should be assigned to existing thread"
);
assert_eq!(executor.thread_count(), 2, "Should not exceed max_threads");
// Release barriers
barrier1.wait();
barrier2.wait();
}
#[test]
fn test_duplicate_registration_returns_same_thread() {
let executor = create_test_executor(4);
let thread_idx1 = executor.register_plugin(1);
let thread_idx2 = executor.register_plugin(1);
assert_eq!(
thread_idx1, thread_idx2,
"Duplicate registration should return same thread"
);
}
#[test]
fn test_load_balancing_prefers_least_loaded() {
let executor = create_test_executor(3);
// Register plugins 1, 2, 3 to thread 0 (when idle)
executor.register_plugin(1);
executor.register_plugin(2);
executor.register_plugin(3);
// Make thread 0 busy
let barrier = Arc::new(Barrier::new(2));
let barrier_clone = barrier.clone();
executor.execute_for_plugin(1, move |_s, _p, _c, _l, _ca, _e| {
barrier_clone.wait();
});
thread::sleep(Duration::from_millis(50));
// Register plugin 4 while thread 0 is busy (spawns thread 1)
let thread_idx4 = executor.register_plugin(4);
assert_eq!(thread_idx4, 1);
// Release barrier
barrier.wait();
thread::sleep(Duration::from_millis(50));
// Register plugin 5 when both threads idle
// Thread 0 has 3 plugins, thread 1 has 1 plugin
let thread_idx5 = executor.register_plugin(5);
assert_eq!(
thread_idx5, 1,
"Plugin 5 should be assigned to less loaded thread 1"
);
}
#[test]
fn test_execute_for_plugin_runs_on_correct_thread() {
let executor = create_test_executor(3);
// Register plugin 1 to thread 0
executor.register_plugin(1);
// Make thread 0 busy to force plugin 2 to thread 1
let barrier = Arc::new(Barrier::new(2));
let barrier_clone = barrier.clone();
executor.execute_for_plugin(1, move |_s, _p, _c, _l, _ca, _e| {
barrier_clone.wait();
});
thread::sleep(Duration::from_millis(50));
// Register plugin 2 to thread 1
executor.register_plugin(2);
// Release barrier
barrier.wait();
thread::sleep(Duration::from_millis(50));
// Get thread names for both plugins
let thread_name1 = get_thread_name_for_plugin(&executor, 1);
let thread_name2 = get_thread_name_for_plugin(&executor, 2);
assert_eq!(thread_name1, "plugin-exec-0");
assert_eq!(thread_name2, "plugin-exec-1");
}
#[test]
fn test_execute_for_plugin_unregistered() {
let executor = create_test_executor(4);
let (tx, rx) = channel();
// Execute job for unregistered plugin
executor.execute_for_plugin(999, make_signaling_job(tx));
// Try to receive with timeout - should timeout
let result = rx.recv_timeout(Duration::from_millis(100));
assert!(
result.is_err(),
"Job for unregistered plugin should not execute"
);
}
#[test]
fn test_job_execution_order_per_thread() {
let executor = create_test_executor(4);
executor.register_plugin(1);
let order = Arc::new(Mutex::new(Vec::new()));
let (tx, rx) = channel();
// Execute 3 jobs for plugin 1
for i in 1..=3 {
let order_clone = order.clone();
let tx_clone = tx.clone();
executor.execute_for_plugin(1, move |_s, _p, _c, _l, _ca, _e| {
order_clone.lock().unwrap().push(i);
tx_clone.send(()).unwrap();
});
}
// Wait for all 3 jobs to complete
for _ in 0..3 {
rx.recv_timeout(Duration::from_secs(5))
.expect("Job should complete");
}
assert_eq!(
*order.lock().unwrap(),
vec![1, 2, 3],
"Jobs should execute in order"
);
}
#[test]
fn test_jobs_complete_successfully() {
let executor = create_test_executor(4);
executor.register_plugin(1);
let (tx, rx) = channel();
executor.execute_for_plugin(1, make_signaling_job(tx));
let result = rx.recv_timeout(Duration::from_secs(5));
assert!(result.is_ok(), "Job should complete successfully");
}
#[test]
fn test_concurrent_jobs_on_different_threads() {
let executor = create_test_executor(3);
// Register plugin 1 to thread 0
executor.register_plugin(1);
// Make thread 0 busy to force plugin 2 to thread 1
let barrier = Arc::new(Barrier::new(2));
let barrier_clone = barrier.clone();
executor.execute_for_plugin(1, move |_s, _p, _c, _l, _ca, _e| {
barrier_clone.wait();
});
thread::sleep(Duration::from_millis(50));
// Register plugin 2 to thread 1
executor.register_plugin(2);
// Release barrier
barrier.wait();
thread::sleep(Duration::from_millis(50));
// Execute jobs on both threads concurrently
let sync_barrier = Arc::new(Barrier::new(3)); // 2 jobs + test thread
let (tx1, rx1) = channel();
let (tx2, rx2) = channel();
let barrier1 = sync_barrier.clone();
executor.execute_for_plugin(1, move |_s, _p, _c, _l, _ca, _e| {
barrier1.wait();
tx1.send(()).unwrap();
});
let barrier2 = sync_barrier.clone();
executor.execute_for_plugin(2, move |_s, _p, _c, _l, _ca, _e| {
barrier2.wait();
tx2.send(()).unwrap();
});
// Release both jobs simultaneously
sync_barrier.wait();
// Both should complete
assert!(rx1.recv_timeout(Duration::from_secs(5)).is_ok());
assert!(rx2.recv_timeout(Duration::from_secs(5)).is_ok());
}
#[test]
fn test_execute_plugin_load_registers_and_executes() {
let executor = create_test_executor(4);
let (tx, rx) = channel();
executor.execute_plugin_load(1, make_signaling_job(tx));
// Wait for load to complete
rx.recv_timeout(Duration::from_secs(5))
.expect("Load should complete");
// Verify plugin is registered
let thread_idx = executor.register_plugin(1);
assert_eq!(thread_idx, 0, "Plugin should already be registered");
}
#[test]
fn test_execute_plugin_unload_runs_cleanup_before_unregister() {
let executor = create_test_executor(4);
// Load plugin
let (tx_load, rx_load) = channel();
executor.execute_plugin_load(1, make_signaling_job(tx_load));
rx_load
.recv_timeout(Duration::from_secs(5))
.expect("Load should complete");
// Unload plugin with cleanup
let counter = Arc::new(AtomicUsize::new(0));
let counter_clone = counter.clone();
let (tx_unload, rx_unload) = channel();
executor.execute_plugin_unload(1, move |_s, _p, _c, _l, _ca, _e| {
counter_clone.fetch_add(1, Ordering::SeqCst);
tx_unload.send(()).unwrap();
});
// Wait for unload to complete
rx_unload
.recv_timeout(Duration::from_secs(5))
.expect("Unload should complete");
// Verify cleanup ran
assert_eq!(counter.load(Ordering::SeqCst), 1, "Cleanup should have run");
// Give unregister a moment to complete
thread::sleep(Duration::from_millis(100));
// Plugin should be unregistered - registering again should assign new thread
let thread_idx = executor.register_plugin(1);
assert_eq!(thread_idx, 0, "Plugin should be re-registered to thread 0");
}
#[test]
fn test_unload_sequence_is_correct() {
let executor = create_test_executor(4);
// Load plugin
let (tx_load, rx_load) = channel();
executor.execute_plugin_load(1, make_signaling_job(tx_load));
rx_load
.recv_timeout(Duration::from_secs(5))
.expect("Load should complete");
// Unload with sequence tracking
let sequence = Arc::new(Mutex::new(Vec::new()));
let sequence_clone = sequence.clone();
let (tx_unload, rx_unload) = channel();
executor.execute_plugin_unload(1, move |_s, _p, _c, _l, _ca, _e| {
sequence_clone.lock().unwrap().push("cleanup");
tx_unload.send(()).unwrap();
});
// Wait for unload to complete
rx_unload
.recv_timeout(Duration::from_secs(5))
.expect("Unload should complete");
sequence.lock().unwrap().push("after");
assert_eq!(*sequence.lock().unwrap(), vec!["cleanup", "after"]);
}
#[test]
fn test_shrink_removes_idle_threads() {
let executor = create_test_executor(4);
// Load plugin 1 to thread 0
let (tx1, rx1) = channel();
executor.execute_plugin_load(1, make_signaling_job(tx1));
rx1.recv_timeout(Duration::from_secs(5))
.expect("Load should complete");
// Make thread 0 busy to force plugin 2 to thread 1
let barrier = Arc::new(Barrier::new(2));
let barrier_clone = barrier.clone();
executor.execute_for_plugin(1, move |_s, _p, _c, _l, _ca, _e| {
barrier_clone.wait();
});
thread::sleep(Duration::from_millis(50));
// Load plugin 2 to thread 1
let (tx2, rx2) = channel();
executor.execute_plugin_load(2, make_signaling_job(tx2));
rx2.recv_timeout(Duration::from_secs(5))
.expect("Load should complete");
// Release barrier
barrier.wait();
thread::sleep(Duration::from_millis(50));
let thread_count_before = executor.thread_count();
assert!(thread_count_before >= 2, "Should have at least 2 threads");
// Unload plugin 2
let (tx_unload2, rx_unload2) = channel();
executor.execute_plugin_unload(2, make_signaling_job(tx_unload2));
rx_unload2
.recv_timeout(Duration::from_secs(5))
.expect("Unload should complete");
// Give shrinking a moment to complete
thread::sleep(Duration::from_millis(100));
// Thread count should decrease after unloading
let thread_count_after = executor.thread_count();
assert!(
thread_count_after < thread_count_before,
"Idle threads should be removed"
);
assert!(thread_count_after >= 1, "Thread 0 should remain");
}
#[test]
fn test_thread_zero_never_removed() {
let executor = create_test_executor(4);
// Load a plugin and then unload it
let (tx_load, rx_load) = channel();
executor.execute_plugin_load(1, make_signaling_job(tx_load));
rx_load
.recv_timeout(Duration::from_secs(5))
.expect("Load should complete");
let (tx_unload, rx_unload) = channel();
executor.execute_plugin_unload(1, make_signaling_job(tx_unload));
rx_unload
.recv_timeout(Duration::from_secs(5))
.expect("Unload should complete");
// Give shrinking a moment
thread::sleep(Duration::from_millis(100));
// Thread 0 should remain
assert!(
executor.thread_count() >= 1,
"Thread 0 should never be removed"
);
}
#[test]
fn test_active_threads_not_removed() {
let executor = create_test_executor(4);
// Load plugin 1 to thread 0
let (tx1, rx1) = channel();
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/plugins/plugin_worker.rs | zellij-server/src/plugins/plugin_worker.rs | use crate::plugins::plugin_map::PluginEnv;
use crate::plugins::zellij_exports::wasi_write_object;
use wasmi::{Instance, Store};
use async_channel::{unbounded, Receiver, Sender};
use async_std::task;
use prost::Message;
use zellij_utils::errors::prelude::*;
use zellij_utils::plugin_api::message::ProtobufMessage;
pub struct RunningWorker {
pub instance: Instance,
pub name: String,
pub store: Store<PluginEnv>,
}
impl RunningWorker {
pub fn new(store: Store<PluginEnv>, instance: Instance, name: &str) -> Self {
RunningWorker {
store,
instance,
name: name.into(),
}
}
pub fn send_message(&mut self, message: String, payload: String) -> Result<()> {
let err_context = || format!("Failed to send message to worker");
let protobuf_message = ProtobufMessage {
name: message,
payload,
..Default::default()
};
let protobuf_bytes = protobuf_message.encode_to_vec();
let work_function = self
.instance
.get_typed_func::<(), ()>(&mut self.store, &self.name)
.with_context(err_context)?;
wasi_write_object(self.store.data(), &protobuf_bytes).with_context(err_context)?;
work_function
.call(&mut self.store, ())
.with_context(err_context)?;
Ok(())
}
}
pub enum MessageToWorker {
Message(String, String), // message, payload
Exit,
}
pub fn plugin_worker(mut worker: RunningWorker) -> Sender<MessageToWorker> {
let (sender, receiver): (Sender<MessageToWorker>, Receiver<MessageToWorker>) = unbounded();
task::spawn({
async move {
loop {
match receiver.recv().await {
Ok(MessageToWorker::Message(message, payload)) => {
if let Err(e) = worker.send_message(message, payload) {
log::error!("Failed to send message to worker: {:?}", e);
}
},
Ok(MessageToWorker::Exit) => {
break;
},
Err(e) => {
log::error!("Failed to receive worker message on channel: {:?}", e);
break;
},
}
}
}
});
sender
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/plugins/plugin_loader.rs | zellij-server/src/plugins/plugin_loader.rs | use crate::plugins::plugin_map::{
PluginEnv, PluginMap, RunningPlugin, VecDequeInputStream, WriteOutputStream,
};
use crate::plugins::plugin_worker::{plugin_worker, RunningWorker};
use crate::plugins::wasm_bridge::{LoadingContext, PluginCache};
use crate::plugins::zellij_exports::{wasi_write_object, zellij_exports};
use crate::plugins::PluginId;
use prost::Message;
use std::{
collections::{HashMap, HashSet, VecDeque},
fs,
path::PathBuf,
sync::{Arc, Mutex},
};
use wasmi::{Engine, Instance, Linker, Module, Store, StoreLimits};
use wasmi_wasi::sync::WasiCtxBuilder;
use wasmi_wasi::wasi_common::pipe::{ReadPipe, WritePipe};
use wasmi_wasi::Dir;
use wasmi_wasi::WasiCtx;
use crate::{
logging_pipe::LoggingPipe, thread_bus::ThreadSenders,
ui::loading_indication::LoadingIndication, ClientId,
};
use zellij_utils::plugin_api::action::ProtobufPluginConfiguration;
use zellij_utils::{
consts::ZELLIJ_TMP_DIR,
data::{InputMode, PluginCapabilities},
errors::prelude::*,
input::command::TerminalAction,
input::keybinds::Keybinds,
input::layout::Layout,
input::plugins::PluginConfig,
ipc::ClientAttributes,
pane_size::Size,
};
fn create_plugin_fs_entries(plugin_own_data_dir: &PathBuf, plugin_own_cache_dir: &PathBuf) {
// Create filesystem entries mounted into WASM.
// We create them here to get expressive error messages in case they fail.
if let Err(e) = fs::create_dir_all(&plugin_own_data_dir) {
log::error!("Failed to create plugin data dir: {}", e);
};
if let Err(e) = fs::create_dir_all(&plugin_own_cache_dir) {
log::error!("Failed to create plugin cache dir: {}", e);
}
if let Err(e) = fs::create_dir_all(ZELLIJ_TMP_DIR.as_path()) {
log::error!("Failed to create plugin tmp dir: {}", e);
}
}
pub struct PluginLoader<'a> {
skip_cache: bool,
plugin_id: PluginId,
client_id: ClientId,
plugin_cwd: PathBuf,
plugin_own_data_dir: PathBuf,
plugin_own_cache_dir: PathBuf,
plugin_config: PluginConfig,
tab_index: Option<usize>,
path_to_default_shell: PathBuf,
capabilities: PluginCapabilities,
client_attributes: ClientAttributes,
default_shell: Option<TerminalAction>,
layout_dir: Option<PathBuf>,
default_mode: InputMode,
keybinds: Keybinds,
plugin_dir: PathBuf,
size: Size,
loading_indication: LoadingIndication,
senders: ThreadSenders,
engine: Engine,
default_layout: Box<Layout>,
plugin_cache: PluginCache,
plugin_map: &'a mut PluginMap, // we receive a mutable reference rather than the Arc so that it
// will be held for the lifetime of this struct and thus loading
// plugins for all connected clients will be one transaction
connected_clients: Option<Arc<Mutex<Vec<ClientId>>>>,
}
impl<'a> PluginLoader<'a> {
pub fn new(
skip_cache: bool,
loading_context: LoadingContext,
senders: ThreadSenders,
engine: Engine,
default_layout: Box<Layout>,
plugin_cache: PluginCache,
plugin_map: &'a mut PluginMap,
connected_clients: Arc<Mutex<Vec<ClientId>>>,
) -> Self {
let loading_indication = LoadingIndication::new("".into());
create_plugin_fs_entries(
&loading_context.plugin_own_data_dir,
&loading_context.plugin_own_cache_dir,
);
Self {
plugin_id: loading_context.plugin_id,
client_id: loading_context.client_id,
plugin_cwd: loading_context.plugin_cwd,
plugin_own_data_dir: loading_context.plugin_own_data_dir,
plugin_own_cache_dir: loading_context.plugin_own_cache_dir,
plugin_config: loading_context.plugin_config,
tab_index: loading_context.tab_index,
path_to_default_shell: loading_context.path_to_default_shell,
capabilities: loading_context.capabilities,
client_attributes: loading_context.client_attributes,
default_shell: loading_context.default_shell,
layout_dir: loading_context.layout_dir,
default_mode: loading_context.default_mode,
keybinds: loading_context.keybinds,
plugin_dir: loading_context.plugin_dir,
size: loading_context.size,
skip_cache,
senders,
engine,
default_layout,
plugin_cache,
plugin_map,
connected_clients: Some(connected_clients),
loading_indication,
}
}
pub fn without_connected_clients(mut self) -> Self {
self.connected_clients = None;
self
}
pub fn start_plugin(&mut self) -> Result<()> {
let module = if self.skip_cache {
self.interpret_module()?
} else {
self.load_module_from_memory()
.or_else(|_e| self.interpret_module())?
};
let (store, instance) = self.create_plugin_environment(module)?;
self.load_plugin_instance(store, &instance)?;
self.clone_instance_for_other_clients()?;
Ok(())
}
fn interpret_module(&mut self) -> Result<Module> {
self.loading_indication.override_previous_error();
let wasm_bytes = self.plugin_config.resolve_wasm_bytes(&self.plugin_dir)?;
let timer = std::time::Instant::now();
let module = Module::new(&self.engine, &wasm_bytes)?;
log::info!(
"Loaded plugin '{}' in {:?}",
self.plugin_config.path.display(),
timer.elapsed()
);
Ok(module)
}
fn load_module_from_memory(&mut self) -> Result<Module> {
let module = self
.plugin_cache
.lock()
.unwrap()
.remove(&self.plugin_config.path) // TODO: do we still bring it back later?
// maybe we can forgo this dance?
.ok_or(anyhow!("Plugin is not stored in memory"))?;
Ok(module)
}
fn load_plugin_instance(
&mut self,
mut store: Store<PluginEnv>,
instance: &Instance,
) -> Result<()> {
let err_context = || format!("failed to load plugin from instance {instance:#?}");
let main_user_instance = instance.clone();
let start_function = instance
.get_typed_func::<(), ()>(&mut store, "_start")
.with_context(err_context)?;
let load_function = instance
.get_typed_func::<(), ()>(&mut store, "load")
.with_context(err_context)?;
let mut workers = HashMap::new();
for function_name in instance
.exports(&mut store)
.filter_map(|export| export.clone().into_func().map(|_| export.name()))
{
if function_name.ends_with("_worker") {
let (mut store, instance) =
self.create_plugin_instance_and_wasi_env_for_worker()?;
let start_function_for_worker = instance
.get_typed_func::<(), ()>(&mut store, "_start")
.with_context(err_context)?;
start_function_for_worker
.call(&mut store, ())
.with_context(err_context)?;
let worker = RunningWorker::new(store, instance, &function_name);
let worker_sender = plugin_worker(worker);
workers.insert(function_name.into(), worker_sender);
}
}
let subscriptions = store.data().subscriptions.clone();
let plugin = Arc::new(Mutex::new(RunningPlugin::new(
store,
main_user_instance,
self.size.rows,
self.size.cols,
)));
self.plugin_map.insert(
self.plugin_id,
self.client_id,
plugin.clone(),
subscriptions,
workers,
);
start_function
.call(&mut plugin.lock().unwrap().store, ())
.with_context(err_context)?;
let protobuf_plugin_configuration: ProtobufPluginConfiguration = self
.plugin_config
.userspace_configuration
.clone()
.try_into()
.map_err(|e| anyhow!("Failed to serialize user configuration: {:?}", e))?;
let protobuf_bytes = protobuf_plugin_configuration.encode_to_vec();
wasi_write_object(plugin.lock().unwrap().store.data(), &protobuf_bytes)
.with_context(err_context)?;
load_function
.call(&mut plugin.lock().unwrap().store, ())
.with_context(err_context)?;
Ok(())
}
pub fn create_plugin_environment(
&self,
module: Module,
) -> Result<(Store<PluginEnv>, Instance)> {
let err_context = || {
format!(
"Failed to create instance, plugin env and subscriptions for plugin {}",
self.plugin_id
)
};
let stdin_pipe = Arc::new(Mutex::new(VecDeque::new()));
let stdout_pipe = Arc::new(Mutex::new(VecDeque::new()));
let wasi_ctx = PluginLoader::create_wasi_ctx(
&self.plugin_cwd,
&self.plugin_own_data_dir,
&self.plugin_own_cache_dir,
&ZELLIJ_TMP_DIR,
&self.plugin_config.location.to_string(),
self.plugin_id,
stdin_pipe.clone(),
stdout_pipe.clone(),
)?;
let plugin_path = self.plugin_config.path.clone();
let plugin_env = PluginEnv {
plugin_id: self.plugin_id,
client_id: self.client_id,
plugin: self.plugin_config.clone(), // TODO: change field name in PluginEnv to plugin_config
permissions: Arc::new(Mutex::new(None)),
senders: self.senders.clone(),
wasi_ctx,
plugin_own_data_dir: self.plugin_own_data_dir.clone(),
plugin_own_cache_dir: self.plugin_own_cache_dir.clone(),
tab_index: self.tab_index,
path_to_default_shell: self.path_to_default_shell.clone(),
capabilities: self.capabilities.clone(),
client_attributes: self.client_attributes.clone(),
default_shell: self.default_shell.clone(),
default_layout: self.default_layout.clone(),
plugin_cwd: self.plugin_cwd.clone(),
input_pipes_to_unblock: Arc::new(Mutex::new(HashSet::new())),
input_pipes_to_block: Arc::new(Mutex::new(HashSet::new())),
layout_dir: self.layout_dir.clone(),
default_mode: self.default_mode.clone(),
subscriptions: Arc::new(Mutex::new(HashSet::new())),
keybinds: self.keybinds.clone(),
intercepting_key_presses: false,
stdin_pipe,
stdout_pipe,
store_limits: create_optimized_store_limits(),
};
let mut store = Store::new(&self.engine, plugin_env);
// Apply optimized resource limits for memory efficiency
store.limiter(|plugin_env| &mut plugin_env.store_limits);
let mut linker = Linker::new(&self.engine);
wasmi_wasi::add_to_linker(&mut linker, |plugin_env: &mut PluginEnv| {
&mut plugin_env.wasi_ctx
})?;
zellij_exports(&mut linker);
let instance = linker
.instantiate_and_start(&mut store, &module)
.with_context(err_context)?;
if let Some(func) = instance.get_func(&mut store, "_initialize") {
if let Ok(typed_func) = func.typed::<(), ()>(&store) {
let _ = typed_func.call(&mut store, ());
}
}
self.plugin_cache
.lock()
.unwrap()
.insert(plugin_path.clone(), module);
Ok((store, instance))
}
pub fn clone_instance_for_other_clients(&mut self) -> Result<()> {
let Some(connected_clients) = self.connected_clients.as_ref() else {
return Ok(());
};
let connected_clients: Vec<ClientId> =
connected_clients.lock().unwrap().iter().copied().collect();
if !connected_clients.is_empty() {
self.connected_clients = None; // so we don't have infinite loops
for client_id in connected_clients {
if client_id == self.client_id {
// don't reload the plugin once more for ourselves
continue;
}
self.client_id = client_id;
self.start_plugin()?;
}
}
Ok(())
}
pub fn create_plugin_instance_and_wasi_env_for_worker(
&self,
) -> Result<(Store<PluginEnv>, Instance)> {
let plugin_id = self.plugin_id;
let err_context = || {
format!(
"Failed to create instance and plugin env for worker {}",
plugin_id
)
};
let module = self
.plugin_cache
.lock()
.unwrap()
.get(&self.plugin_config.path)
.with_context(err_context)?
.clone();
let (store, instance) = self.create_plugin_instance_env(&module)?;
Ok((store, instance))
}
fn create_plugin_instance_env(&self, module: &Module) -> Result<(Store<PluginEnv>, Instance)> {
let err_context = || {
format!(
"Failed to create instance, plugin env and subscriptions for plugin {}",
self.plugin_id
)
};
let stdin_pipe = Arc::new(Mutex::new(VecDeque::new()));
let stdout_pipe = Arc::new(Mutex::new(VecDeque::new()));
let wasi_ctx = PluginLoader::create_wasi_ctx(
&self.plugin_cwd,
&self.plugin_own_data_dir,
&self.plugin_own_cache_dir,
&ZELLIJ_TMP_DIR,
&self.plugin_config.location.to_string(),
self.plugin_id,
stdin_pipe.clone(),
stdout_pipe.clone(),
)?;
let plugin_config = self.plugin_config.clone();
let plugin_env = PluginEnv {
plugin_id: self.plugin_id,
client_id: self.client_id,
plugin: plugin_config,
permissions: Arc::new(Mutex::new(None)),
senders: self.senders.clone(),
wasi_ctx,
plugin_own_data_dir: self.plugin_own_data_dir.clone(),
plugin_own_cache_dir: self.plugin_own_cache_dir.clone(),
tab_index: self.tab_index,
path_to_default_shell: self.path_to_default_shell.clone(),
capabilities: self.capabilities.clone(),
client_attributes: self.client_attributes.clone(),
default_shell: self.default_shell.clone(),
default_layout: self.default_layout.clone(),
plugin_cwd: self.plugin_cwd.clone(),
input_pipes_to_unblock: Arc::new(Mutex::new(HashSet::new())),
input_pipes_to_block: Arc::new(Mutex::new(HashSet::new())),
layout_dir: self.layout_dir.clone(),
default_mode: self.default_mode.clone(),
subscriptions: Arc::new(Mutex::new(HashSet::new())),
keybinds: self.keybinds.clone(),
intercepting_key_presses: false,
stdin_pipe,
stdout_pipe,
store_limits: create_optimized_store_limits(),
};
let mut store = Store::new(&self.engine, plugin_env);
// Apply optimized resource limits for memory efficiency
store.limiter(|plugin_env| &mut plugin_env.store_limits);
let mut linker = Linker::new(&self.engine);
wasmi_wasi::add_to_linker(&mut linker, |plugin_env: &mut PluginEnv| {
&mut plugin_env.wasi_ctx
})?;
zellij_exports(&mut linker);
let instance = linker
.instantiate_and_start(&mut store, module)
.with_context(err_context)?;
if let Some(func) = instance.get_func(&mut store, "_initialize") {
if let Ok(typed_func) = func.typed::<(), ()>(&store) {
let _ = typed_func.call(&mut store, ());
}
}
Ok((store, instance))
}
pub fn create_wasi_ctx(
host_dir: &PathBuf,
data_dir: &PathBuf,
cache_dir: &PathBuf,
tmp_dir: &PathBuf,
plugin_url: &String,
plugin_id: PluginId,
stdin_pipe: Arc<Mutex<VecDeque<u8>>>,
stdout_pipe: Arc<Mutex<VecDeque<u8>>>,
) -> Result<WasiCtx> {
let _err_context = || format!("Failed to create wasi_ctx");
let dirs = vec![
("/host".to_owned(), host_dir.clone()),
("/data".to_owned(), data_dir.clone()),
("/cache".to_owned(), cache_dir.clone()),
("/tmp".to_owned(), tmp_dir.clone()),
];
let dirs = dirs.into_iter().filter(|(_dir_name, dir)| {
// note that this does not protect against TOCTOU errors
// eg. if one or more of these folders existed at the time of check but was deleted
// before we mounted in in the wasi environment, we'll crash
// when we move to a new wasi environment, we should address this with locking if
// there's no built-in solution
dir.try_exists().ok().unwrap_or(false)
});
let mut builder = WasiCtxBuilder::new();
builder.inherit_env()?;
// Mount directories using the builder
for (guest_path, host_path) in dirs {
match std::fs::File::open(&host_path) {
Ok(dir_file) => {
let dir = Dir::from_std_file(dir_file);
builder.preopened_dir(dir, guest_path)?;
},
Err(e) => {
log::warn!("Failed to mount directory {:?}: {}", host_path, e);
},
}
}
let ctx = builder.build();
// Set up custom stdin/stdout/stderr
ctx.set_stdin(Box::new(ReadPipe::new(VecDequeInputStream(
stdin_pipe.clone(),
))));
ctx.set_stdout(Box::new(WritePipe::new(WriteOutputStream(
stdout_pipe.clone(),
))));
ctx.set_stderr(Box::new(WritePipe::new(WriteOutputStream(Arc::new(
Mutex::new(LoggingPipe::new(plugin_url, plugin_id)),
)))));
Ok(ctx)
}
}
fn create_optimized_store_limits() -> StoreLimits {
use wasmi::StoreLimitsBuilder;
StoreLimitsBuilder::new()
.instances(1) // One instance per plugin
.memories(4) // Max 4 linear memories per plugin
.memory_size(16 * 1024 * 1024) // 16MB per memory maximum
.tables(16) // Small table element limit
.trap_on_grow_failure(true) // Fail fast on resource exhaustion
.build()
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/plugins/zellij_exports.rs | zellij-server/src/plugins/zellij_exports.rs | use super::PluginInstruction;
use crate::background_jobs::BackgroundJob;
use crate::global_async_runtime::get_tokio_runtime;
use crate::plugins::plugin_map::PluginEnv;
use crate::plugins::wasm_bridge::handle_plugin_crash;
use crate::pty::{ClientTabIndexOrPaneId, PtyInstruction};
use crate::route::route_action;
use crate::ServerInstruction;
use interprocess::local_socket::LocalSocketStream;
use log::warn;
use serde::Serialize;
use std::{
collections::{BTreeMap, HashSet},
io::{Read, Write},
path::PathBuf,
process,
str::FromStr,
thread,
time::{Duration, Instant},
};
use wasmi::{Caller, Linker};
use zellij_utils::data::{
CommandType, ConnectToSession, Event, FloatingPaneCoordinates, GetPanePidResponse, HttpVerb,
KeyWithModifier, LayoutInfo, MessageToPlugin, NewPanePlacement, OriginatingPlugin,
PaneScrollbackResponse, PermissionStatus, PermissionType, PluginPermission,
};
use zellij_utils::input::permission::PermissionCache;
use zellij_utils::ipc::{ClientToServerMsg, IpcSenderWithContext};
#[cfg(feature = "web_server_capability")]
use zellij_utils::web_authentication_tokens::{
create_token, list_tokens, rename_token, revoke_all_tokens, revoke_token,
};
#[cfg(feature = "web_server_capability")]
use zellij_utils::web_server_commands::shutdown_all_webserver_instances;
use crate::{panes::PaneId, screen::ScreenInstruction};
use prost::Message;
use zellij_utils::{
consts::{VERSION, ZELLIJ_SESSION_INFO_CACHE_DIR, ZELLIJ_SOCK_DIR},
data::{
CommandToRun, Direction, EventType, FileToOpen, InputMode, PluginCommand, PluginIds,
PluginMessage, Resize, ResizeStrategy,
},
errors::prelude::*,
input::{
actions::Action,
command::{OpenFilePayload, RunCommand, RunCommandAction, TerminalAction},
layout::{Layout, RunPluginOrAlias},
},
plugin_api::{
event::ProtobufPaneScrollbackResponse,
plugin_command::{ProtobufGetPanePidResponse, ProtobufPluginCommand},
plugin_ids::{ProtobufPluginIds, ProtobufZellijVersion},
},
};
#[cfg(feature = "web_server_capability")]
use zellij_utils::plugin_api::plugin_command::{
CreateTokenResponse, ListTokensResponse, RenameWebTokenResponse, RevokeAllWebTokensResponse,
RevokeTokenResponse,
};
macro_rules! apply_action {
($action:ident, $error_message:ident, $env: ident) => {
if let Err(e) = route_action(
$action,
$env.client_id,
None,
Some(PaneId::Plugin($env.plugin_id)),
$env.senders.clone(),
$env.capabilities.clone(),
$env.client_attributes.clone(),
$env.default_shell.clone(),
$env.default_layout.clone(),
None,
$env.keybinds.clone(),
$env.default_mode.clone(),
None,
) {
log::error!("{}: {:?}", $error_message(), e);
}
};
}
pub fn zellij_exports(linker: &mut Linker<PluginEnv>) {
linker
.func_wrap("zellij", "host_run_plugin_command", host_run_plugin_command)
.unwrap();
}
fn host_run_plugin_command(mut caller: Caller<'_, PluginEnv>) {
let mut env = caller.data_mut();
let plugin_command = env.name();
let err_context = || format!("failed to run plugin command {}", plugin_command);
wasi_read_bytes(env)
.and_then(|bytes| {
let command: ProtobufPluginCommand = ProtobufPluginCommand::decode(bytes.as_slice())?;
let command: PluginCommand = command
.try_into()
.map_err(|e| anyhow!("failed to convert serialized command: {}", e))?;
match check_command_permission(&env, &command) {
(PermissionStatus::Granted, _) => match command {
PluginCommand::Subscribe(event_list) => subscribe(env, event_list)?,
PluginCommand::Unsubscribe(event_list) => unsubscribe(env, event_list)?,
PluginCommand::SetSelectable(selectable) => set_selectable(env, selectable),
PluginCommand::ShowCursor(cursor_position) => show_cursor(env, cursor_position),
PluginCommand::GetPluginIds => get_plugin_ids(env),
PluginCommand::GetZellijVersion => get_zellij_version(env),
PluginCommand::OpenFile(file_to_open, context) => {
open_file(env, file_to_open, context)
},
PluginCommand::OpenFileFloating(
file_to_open,
floating_pane_coordinates,
context,
) => open_file_floating(env, file_to_open, floating_pane_coordinates, context),
PluginCommand::OpenTerminal(cwd) => open_terminal(env, cwd.path.try_into()?),
PluginCommand::OpenTerminalNearPlugin(cwd) => {
open_terminal_near_plugin(env, cwd.path.try_into()?)
},
PluginCommand::OpenTerminalFloating(cwd, floating_pane_coordinates) => {
open_terminal_floating(env, cwd.path.try_into()?, floating_pane_coordinates)
},
PluginCommand::OpenTerminalFloatingNearPlugin(
cwd,
floating_pane_coordinates,
) => open_terminal_floating_near_plugin(
env,
cwd.path.try_into()?,
floating_pane_coordinates,
),
PluginCommand::OpenCommandPane(command_to_run, context) => {
open_command_pane(env, command_to_run, context)
},
PluginCommand::OpenCommandPaneNearPlugin(command_to_run, context) => {
open_command_pane_near_plugin(env, command_to_run, context)
},
PluginCommand::OpenCommandPaneFloating(
command_to_run,
floating_pane_coordinates,
context,
) => open_command_pane_floating(
env,
command_to_run,
floating_pane_coordinates,
context,
),
PluginCommand::OpenCommandPaneFloatingNearPlugin(
command_to_run,
floating_pane_coordinates,
context,
) => open_command_pane_floating_near_plugin(
env,
command_to_run,
floating_pane_coordinates,
context,
),
PluginCommand::SwitchTabTo(tab_index) => switch_tab_to(env, tab_index),
PluginCommand::SetTimeout(seconds) => set_timeout(env, seconds),
PluginCommand::ExecCmd(command_line) => exec_cmd(env, command_line),
PluginCommand::RunCommand(command_line, env_variables, cwd, context) => {
run_command(env, command_line, env_variables, cwd, context)
},
PluginCommand::WebRequest(url, verb, headers, body, context) => {
web_request(env, url, verb, headers, body, context)
},
PluginCommand::PostMessageTo(plugin_message) => {
post_message_to(env, plugin_message)?
},
PluginCommand::PostMessageToPlugin(plugin_message) => {
post_message_to_plugin(env, plugin_message)?
},
PluginCommand::HideSelf => hide_self(env)?,
PluginCommand::ShowSelf(should_float_if_hidden) => {
show_self(env, should_float_if_hidden)
},
PluginCommand::SwitchToMode(input_mode) => {
switch_to_mode(env, input_mode.try_into()?)
},
PluginCommand::NewTabsWithLayout(raw_layout) => {
new_tabs_with_layout(env, &raw_layout)?
},
PluginCommand::NewTabsWithLayoutInfo(layout_info) => {
new_tabs_with_layout_info(env, layout_info)?
},
PluginCommand::NewTab { name, cwd } => new_tab(env, name, cwd),
PluginCommand::GoToNextTab => go_to_next_tab(env),
PluginCommand::GoToPreviousTab => go_to_previous_tab(env),
PluginCommand::Resize(resize_payload) => resize(env, resize_payload),
PluginCommand::ResizeWithDirection(resize_strategy) => {
resize_with_direction(env, resize_strategy)
},
PluginCommand::FocusNextPane => focus_next_pane(env),
PluginCommand::FocusPreviousPane => focus_previous_pane(env),
PluginCommand::MoveFocus(direction) => move_focus(env, direction),
PluginCommand::MoveFocusOrTab(direction) => move_focus_or_tab(env, direction),
PluginCommand::Detach => detach(env),
PluginCommand::EditScrollback => edit_scrollback(env),
PluginCommand::Write(bytes) => write(env, bytes),
PluginCommand::WriteChars(chars) => write_chars(env, chars),
PluginCommand::CopyToClipboard(text) => copy_to_clipboard(env, text)?,
PluginCommand::ToggleTab => toggle_tab(env),
PluginCommand::MovePane => move_pane(env),
PluginCommand::MovePaneWithDirection(direction) => {
move_pane_with_direction(env, direction)
},
PluginCommand::ClearScreen => clear_screen(env),
PluginCommand::ScrollUp => scroll_up(env),
PluginCommand::ScrollDown => scroll_down(env),
PluginCommand::ScrollToTop => scroll_to_top(env),
PluginCommand::ScrollToBottom => scroll_to_bottom(env),
PluginCommand::PageScrollUp => page_scroll_up(env),
PluginCommand::PageScrollDown => page_scroll_down(env),
PluginCommand::ToggleFocusFullscreen => toggle_focus_fullscreen(env),
PluginCommand::TogglePaneFrames => toggle_pane_frames(env),
PluginCommand::TogglePaneEmbedOrEject => toggle_pane_embed_or_eject(env),
PluginCommand::UndoRenamePane => undo_rename_pane(env),
PluginCommand::CloseFocus => close_focus(env),
PluginCommand::ToggleActiveTabSync => toggle_active_tab_sync(env),
PluginCommand::CloseFocusedTab => close_focused_tab(env),
PluginCommand::UndoRenameTab => undo_rename_tab(env),
PluginCommand::QuitZellij => quit_zellij(env),
PluginCommand::PreviousSwapLayout => previous_swap_layout(env),
PluginCommand::NextSwapLayout => next_swap_layout(env),
PluginCommand::GoToTabName(tab_name) => go_to_tab_name(env, tab_name),
PluginCommand::FocusOrCreateTab(tab_name) => focus_or_create_tab(env, tab_name),
PluginCommand::GoToTab(tab_index) => go_to_tab(env, tab_index),
PluginCommand::StartOrReloadPlugin(plugin_url) => {
start_or_reload_plugin(env, &plugin_url)?
},
PluginCommand::CloseTerminalPane(terminal_pane_id) => {
close_terminal_pane(env, terminal_pane_id)
},
PluginCommand::ClosePluginPane(plugin_pane_id) => {
close_plugin_pane(env, plugin_pane_id)
},
PluginCommand::FocusTerminalPane(
terminal_pane_id,
should_float_if_hidden,
should_be_in_place_if_hidden,
) => focus_terminal_pane(
env,
terminal_pane_id,
should_float_if_hidden,
should_be_in_place_if_hidden,
),
PluginCommand::FocusPluginPane(
plugin_pane_id,
should_float_if_hidden,
should_be_in_place_if_hidden,
) => focus_plugin_pane(
env,
plugin_pane_id,
should_float_if_hidden,
should_be_in_place_if_hidden,
),
PluginCommand::RenameTerminalPane(terminal_pane_id, new_name) => {
rename_terminal_pane(env, terminal_pane_id, &new_name)
},
PluginCommand::RenamePluginPane(plugin_pane_id, new_name) => {
rename_plugin_pane(env, plugin_pane_id, &new_name)
},
PluginCommand::RenameTab(tab_index, new_name) => {
rename_tab(env, tab_index, &new_name)
},
PluginCommand::ReportPanic(crash_payload) => report_panic(env, &crash_payload),
PluginCommand::RequestPluginPermissions(permissions) => {
request_permission(env, permissions)?
},
PluginCommand::SwitchSession(connect_to_session) => switch_session(
env,
connect_to_session.name,
connect_to_session.tab_position,
connect_to_session.pane_id,
connect_to_session.layout,
connect_to_session.cwd,
)?,
PluginCommand::DeleteDeadSession(session_name) => {
delete_dead_session(session_name)?
},
PluginCommand::DeleteAllDeadSessions => delete_all_dead_sessions()?,
PluginCommand::OpenFileInPlace(file_to_open, context) => {
open_file_in_place(env, file_to_open, context)
},
PluginCommand::OpenTerminalInPlace(cwd) => {
open_terminal_in_place(env, cwd.path.try_into()?)
},
PluginCommand::OpenTerminalInPlaceOfPlugin(cwd, close_plugin_after_replace) => {
open_terminal_in_place_of_plugin(
env,
cwd.path.try_into()?,
close_plugin_after_replace,
)
},
PluginCommand::OpenCommandPaneInPlace(command_to_run, context) => {
open_command_pane_in_place(env, command_to_run, context)
},
PluginCommand::OpenCommandPaneInPlaceOfPlugin(
command_to_run,
close_plugin_after_replace,
context,
) => open_command_pane_in_place_of_plugin(
env,
command_to_run,
close_plugin_after_replace,
context,
),
PluginCommand::RenameSession(new_session_name) => {
rename_session(env, new_session_name)
},
PluginCommand::UnblockCliPipeInput(pipe_name) => {
unblock_cli_pipe_input(env, pipe_name)
},
PluginCommand::BlockCliPipeInput(pipe_name) => {
block_cli_pipe_input(env, pipe_name)
},
PluginCommand::CliPipeOutput(pipe_name, output) => {
cli_pipe_output(env, pipe_name, output)?
},
PluginCommand::MessageToPlugin(message) => message_to_plugin(env, message)?,
PluginCommand::DisconnectOtherClients => disconnect_other_clients(env),
PluginCommand::KillSessions(session_list) => kill_sessions(session_list),
PluginCommand::ScanHostFolder(folder_to_scan) => {
scan_host_folder(env, folder_to_scan)
},
PluginCommand::WatchFilesystem => watch_filesystem(env),
PluginCommand::DumpSessionLayout => dump_session_layout(env),
PluginCommand::CloseSelf => close_self(env),
PluginCommand::Reconfigure(new_config, write_config_to_disk) => {
reconfigure(env, new_config, write_config_to_disk)?
},
PluginCommand::HidePaneWithId(pane_id) => {
hide_pane_with_id(env, pane_id.into())?
},
PluginCommand::ShowPaneWithId(
pane_id,
should_float_if_hidden,
should_focus_pane,
) => show_pane_with_id(
env,
pane_id.into(),
should_float_if_hidden,
should_focus_pane,
),
PluginCommand::OpenCommandPaneBackground(command_to_run, context) => {
open_command_pane_background(env, command_to_run, context)
},
PluginCommand::RerunCommandPane(terminal_pane_id) => {
rerun_command_pane(env, terminal_pane_id)
},
PluginCommand::ResizePaneIdWithDirection(resize, pane_id) => {
resize_pane_with_id(env, resize, pane_id.into())
},
PluginCommand::EditScrollbackForPaneWithId(pane_id) => {
edit_scrollback_for_pane_with_id(env, pane_id.into())
},
PluginCommand::GetPaneScrollback {
pane_id,
get_full_scrollback,
} => get_pane_scrollback(env, pane_id.into(), get_full_scrollback),
PluginCommand::WriteToPaneId(bytes, pane_id) => {
write_to_pane_id(env, bytes, pane_id.into())
},
PluginCommand::WriteCharsToPaneId(chars, pane_id) => {
write_chars_to_pane_id(env, chars, pane_id.into())
},
PluginCommand::SendSigintToPaneId(pane_id) => {
send_sigint_to_pane_id(env, pane_id.into())
},
PluginCommand::SendSigkillToPaneId(pane_id) => {
send_sigkill_to_pane_id(env, pane_id.into())
},
PluginCommand::GetPanePid { pane_id } => get_pane_pid(env, pane_id.into()),
PluginCommand::MovePaneWithPaneId(pane_id) => {
move_pane_with_pane_id(env, pane_id.into())
},
PluginCommand::MovePaneWithPaneIdInDirection(pane_id, direction) => {
move_pane_with_pane_id_in_direction(env, pane_id.into(), direction)
},
PluginCommand::ClearScreenForPaneId(pane_id) => {
clear_screen_for_pane_id(env, pane_id.into())
},
PluginCommand::ScrollUpInPaneId(pane_id) => {
scroll_up_in_pane_id(env, pane_id.into())
},
PluginCommand::ScrollDownInPaneId(pane_id) => {
scroll_down_in_pane_id(env, pane_id.into())
},
PluginCommand::ScrollToTopInPaneId(pane_id) => {
scroll_to_top_in_pane_id(env, pane_id.into())
},
PluginCommand::ScrollToBottomInPaneId(pane_id) => {
scroll_to_bottom_in_pane_id(env, pane_id.into())
},
PluginCommand::PageScrollUpInPaneId(pane_id) => {
page_scroll_up_in_pane_id(env, pane_id.into())
},
PluginCommand::PageScrollDownInPaneId(pane_id) => {
page_scroll_down_in_pane_id(env, pane_id.into())
},
PluginCommand::TogglePaneIdFullscreen(pane_id) => {
toggle_pane_id_fullscreen(env, pane_id.into())
},
PluginCommand::TogglePaneEmbedOrEjectForPaneId(pane_id) => {
toggle_pane_embed_or_eject_for_pane_id(env, pane_id.into())
},
PluginCommand::CloseTabWithIndex(tab_index) => {
close_tab_with_index(env, tab_index)
},
PluginCommand::BreakPanesToNewTab(
pane_ids,
new_tab_name,
should_change_focus_to_new_tab,
) => break_panes_to_new_tab(
env,
pane_ids.into_iter().map(|p_id| p_id.into()).collect(),
new_tab_name,
should_change_focus_to_new_tab,
),
PluginCommand::BreakPanesToTabWithIndex(
pane_ids,
should_change_focus_to_new_tab,
tab_index,
) => break_panes_to_tab_with_index(
env,
pane_ids.into_iter().map(|p_id| p_id.into()).collect(),
tab_index,
should_change_focus_to_new_tab,
),
PluginCommand::ReloadPlugin(plugin_id) => reload_plugin(env, plugin_id),
PluginCommand::LoadNewPlugin {
url,
config,
load_in_background,
skip_plugin_cache,
} => load_new_plugin(env, url, config, load_in_background, skip_plugin_cache),
PluginCommand::RebindKeys {
keys_to_rebind,
keys_to_unbind,
write_config_to_disk,
} => rebind_keys(env, keys_to_rebind, keys_to_unbind, write_config_to_disk)?,
PluginCommand::ListClients => list_clients(env),
PluginCommand::ChangeHostFolder(new_host_folder) => {
change_host_folder(env, new_host_folder)
},
PluginCommand::SetFloatingPanePinned(pane_id, should_be_pinned) => {
set_floating_pane_pinned(env, pane_id.into(), should_be_pinned)
},
PluginCommand::StackPanes(pane_ids) => {
stack_panes(env, pane_ids.into_iter().map(|p_id| p_id.into()).collect())
},
PluginCommand::ChangeFloatingPanesCoordinates(pane_ids_and_coordinates) => {
change_floating_panes_coordinates(
env,
pane_ids_and_coordinates
.into_iter()
.map(|(p_id, coordinates)| (p_id.into(), coordinates))
.collect(),
)
},
PluginCommand::OpenFileNearPlugin(file_to_open, context) => {
open_file_near_plugin(env, file_to_open, context)
},
PluginCommand::OpenFileFloatingNearPlugin(
file_to_open,
floating_pane_coordinates,
context,
) => open_file_floating_near_plugin(
env,
file_to_open,
floating_pane_coordinates,
context,
),
PluginCommand::OpenFileInPlaceOfPlugin(
file_to_open,
close_plugin_after_replace,
context,
) => open_file_in_place_of_plugin(
env,
file_to_open,
close_plugin_after_replace,
context,
),
PluginCommand::GroupAndUngroupPanes(
panes_to_group,
panes_to_ungroup,
for_all_clients,
) => group_and_ungroup_panes(
env,
panes_to_group.into_iter().map(|p| p.into()).collect(),
panes_to_ungroup.into_iter().map(|p| p.into()).collect(),
for_all_clients,
),
PluginCommand::HighlightAndUnhighlightPanes(
panes_to_highlight,
panes_to_unhighlight,
) => highlight_and_unhighlight_panes(
env,
panes_to_highlight.into_iter().map(|p| p.into()).collect(),
panes_to_unhighlight.into_iter().map(|p| p.into()).collect(),
),
PluginCommand::CloseMultiplePanes(pane_ids) => {
close_multiple_panes(env, pane_ids.into_iter().map(|p| p.into()).collect())
},
PluginCommand::FloatMultiplePanes(pane_ids) => {
float_multiple_panes(env, pane_ids.into_iter().map(|p| p.into()).collect())
},
PluginCommand::EmbedMultiplePanes(pane_ids) => {
embed_multiple_panes(env, pane_ids.into_iter().map(|p| p.into()).collect())
},
PluginCommand::StartWebServer => start_web_server(env),
PluginCommand::StopWebServer => stop_web_server(env),
PluginCommand::QueryWebServerStatus => query_web_server_status(env),
PluginCommand::ShareCurrentSession => share_current_session(env),
PluginCommand::StopSharingCurrentSession => stop_sharing_current_session(env),
PluginCommand::SetSelfMouseSelectionSupport(selection_support) => {
set_self_mouse_selection_support(env, selection_support);
},
PluginCommand::GenerateWebLoginToken(token_label, read_only) => {
generate_web_login_token(env, token_label, read_only);
},
PluginCommand::RevokeWebLoginToken(label) => {
revoke_web_login_token(env, label);
},
PluginCommand::ListWebLoginTokens => {
list_web_login_tokens(env);
},
PluginCommand::RevokeAllWebLoginTokens => {
revoke_all_web_login_tokens(env);
},
PluginCommand::RenameWebLoginToken(old_name, new_name) => {
rename_web_login_token(env, old_name, new_name);
},
PluginCommand::InterceptKeyPresses => intercept_key_presses(&mut env),
PluginCommand::ClearKeyPressesIntercepts => {
clear_key_presses_intercepts(&mut env)
},
PluginCommand::ReplacePaneWithExistingPane(
pane_id_to_replace,
existing_pane_id,
suppress_replaced_pane,
) => replace_pane_with_existing_pane(
&mut env,
pane_id_to_replace.into(),
existing_pane_id.into(),
suppress_replaced_pane,
),
PluginCommand::RunAction(action, context) => run_action(&env, action, context),
},
(PermissionStatus::Denied, permission) => {
log::error!(
"Plugin '{}' permission '{}' denied - Command '{:?}' denied",
env.name(),
permission
.map(|p| p.to_string())
.unwrap_or("UNKNOWN".to_owned()),
CommandType::from_str(&command.to_string()).with_context(err_context)?
);
},
};
Ok(())
})
.with_context(|| format!("failed to run plugin command {}", env.name()))
.non_fatal();
}
fn subscribe(env: &PluginEnv, event_list: HashSet<EventType>) -> Result<()> {
env.subscriptions
.lock()
.to_anyhow()?
.extend(event_list.clone());
env.senders
.send_to_plugin(PluginInstruction::PluginSubscribedToEvents(
env.plugin_id,
env.client_id,
event_list,
))
}
fn unblock_cli_pipe_input(env: &PluginEnv, pipe_name: String) {
env.input_pipes_to_unblock.lock().unwrap().insert(pipe_name);
}
fn block_cli_pipe_input(env: &PluginEnv, pipe_name: String) {
env.input_pipes_to_block.lock().unwrap().insert(pipe_name);
}
fn cli_pipe_output(env: &PluginEnv, pipe_name: String, output: String) -> Result<()> {
env.senders
.send_to_server(ServerInstruction::CliPipeOutput(pipe_name, output))
.context("failed to send pipe output")
}
fn message_to_plugin(env: &PluginEnv, mut message_to_plugin: MessageToPlugin) -> Result<()> {
if message_to_plugin.plugin_url.as_ref().map(|s| s.as_str()) == Some("zellij:OWN_URL") {
message_to_plugin.plugin_url = Some(env.plugin.location.display());
}
env.senders
.send_to_plugin(PluginInstruction::MessageFromPlugin {
source_plugin_id: env.plugin_id,
message: message_to_plugin,
})
.context("failed to send message to plugin")
}
fn unsubscribe(env: &PluginEnv, event_list: HashSet<EventType>) -> Result<()> {
env.subscriptions
.lock()
.to_anyhow()?
.retain(|k| !event_list.contains(k));
Ok(())
}
fn set_selectable(env: &PluginEnv, selectable: bool) {
env.senders
.send_to_screen(ScreenInstruction::SetSelectable(
PaneId::Plugin(env.plugin_id),
selectable,
))
.with_context(|| {
format!(
"failed to set plugin {} selectable from plugin {}",
selectable,
env.name()
)
})
.non_fatal();
}
fn show_cursor(env: &PluginEnv, cursor_position: Option<(usize, usize)>) {
env.senders
.send_to_screen(ScreenInstruction::ShowPluginCursor(
env.plugin_id,
env.client_id,
cursor_position,
))
.with_context(|| {
format!(
"failed to {} plugin cursor from plugin {}",
if cursor_position.is_some() {
"show"
} else {
"hide"
},
env.name()
)
})
.non_fatal();
}
fn request_permission(env: &PluginEnv, permissions: Vec<PermissionType>) -> Result<()> {
if PermissionCache::from_path_or_default(None)
.check_permissions(env.plugin.location.to_string(), &permissions)
{
return env
.senders
.send_to_plugin(PluginInstruction::PermissionRequestResult(
env.plugin_id,
Some(env.client_id),
permissions.to_vec(),
PermissionStatus::Granted,
None,
));
}
// we do this so that messages that have arrived while the user is seeing the permission screen
// will be cached and reapplied once the permission is granted
let _ = env
.senders
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/plugins/pipes.rs | zellij-server/src/plugins/pipes.rs | use super::{PluginId, PluginInstruction};
use crate::plugins::plugin_map::RunningPlugin;
use crate::plugins::wasm_bridge::PluginRenderAsset;
use crate::plugins::zellij_exports::{wasi_read_string, wasi_write_object};
use std::collections::{HashMap, HashSet};
use zellij_utils::data::{PipeMessage, PipeSource};
use zellij_utils::plugin_api::pipe_message::ProtobufPipeMessage;
use prost::Message;
use zellij_utils::errors::prelude::*;
use crate::{thread_bus::ThreadSenders, ClientId};
#[derive(Debug, Clone)]
pub enum PipeStateChange {
NoChange,
Block,
Unblock,
}
#[derive(Debug, Clone, Default)]
pub struct PendingPipes {
pipes: HashMap<String, PendingPipeInfo>,
}
impl PendingPipes {
pub fn mark_being_processed(
&mut self,
pipe_id: &str,
plugin_id: &PluginId,
client_id: &ClientId,
) {
if self.pipes.contains_key(pipe_id) {
self.pipes.get_mut(pipe_id).map(|pending_pipe_info| {
pending_pipe_info.add_processing_plugin(plugin_id, client_id)
});
} else {
self.pipes.insert(
pipe_id.to_owned(),
PendingPipeInfo::new(plugin_id, client_id),
);
}
}
// returns a list of pipes that are no longer pending and should be unblocked
pub fn update_pipe_state_change(
&mut self,
cli_pipe_name: &str,
pipe_state_change: PipeStateChange,
plugin_id: &PluginId,
client_id: &ClientId,
) -> Vec<String> {
let mut pipe_names_to_unblock = vec![];
match self.pipes.get_mut(cli_pipe_name) {
Some(pending_pipe_info) => {
let should_unblock_this_pipe =
pending_pipe_info.update_state_change(pipe_state_change, plugin_id, client_id);
if should_unblock_this_pipe {
pipe_names_to_unblock.push(cli_pipe_name.to_owned());
}
},
None => {
// state somehow corrupted, let's recover...
pipe_names_to_unblock.push(cli_pipe_name.to_owned());
},
}
for pipe_name in &pipe_names_to_unblock {
self.pipes.remove(pipe_name);
}
pipe_names_to_unblock
}
// returns a list of pipes that are no longer pending and should be unblocked
pub fn unload_plugin(&mut self, plugin_id: &PluginId) -> Vec<String> {
let mut pipe_names_to_unblock = vec![];
for (pipe_name, pending_pipe_info) in self.pipes.iter_mut() {
let should_unblock_this_pipe = pending_pipe_info.unload_plugin(plugin_id);
if should_unblock_this_pipe {
pipe_names_to_unblock.push(pipe_name.to_owned());
}
}
for pipe_name in &pipe_names_to_unblock {
self.pipes.remove(pipe_name);
}
pipe_names_to_unblock
}
}
#[derive(Debug, Clone, Default)]
pub struct PendingPipeInfo {
is_explicitly_blocked: bool,
currently_being_processed_by: HashSet<(PluginId, ClientId)>,
}
impl PendingPipeInfo {
pub fn new(plugin_id: &PluginId, client_id: &ClientId) -> Self {
let mut currently_being_processed_by = HashSet::new();
currently_being_processed_by.insert((*plugin_id, *client_id));
PendingPipeInfo {
currently_being_processed_by,
..Default::default()
}
}
pub fn add_processing_plugin(&mut self, plugin_id: &PluginId, client_id: &ClientId) {
self.currently_being_processed_by
.insert((*plugin_id, *client_id));
}
// returns true if this pipe should be unblocked
pub fn update_state_change(
&mut self,
pipe_state_change: PipeStateChange,
plugin_id: &PluginId,
client_id: &ClientId,
) -> bool {
match pipe_state_change {
PipeStateChange::Block => {
self.is_explicitly_blocked = true;
},
PipeStateChange::Unblock => {
self.is_explicitly_blocked = false;
},
_ => {},
};
self.currently_being_processed_by
.remove(&(*plugin_id, *client_id));
let pipe_should_be_unblocked =
self.currently_being_processed_by.is_empty() && !self.is_explicitly_blocked;
pipe_should_be_unblocked
}
// returns true if this pipe should be unblocked
pub fn unload_plugin(&mut self, plugin_id_to_unload: &PluginId) -> bool {
self.currently_being_processed_by
.retain(|(plugin_id, _)| plugin_id != plugin_id_to_unload);
if self.currently_being_processed_by.is_empty() && !self.is_explicitly_blocked {
true
} else {
false
}
}
}
pub fn apply_pipe_message_to_plugin(
plugin_id: PluginId,
client_id: ClientId,
running_plugin: &mut RunningPlugin,
pipe_message: &PipeMessage,
plugin_render_assets: &mut Vec<PluginRenderAsset>,
senders: &ThreadSenders,
) -> Result<()> {
let instance = &running_plugin.instance;
let rows = running_plugin.rows;
let columns = running_plugin.columns;
let err_context = || format!("Failed to apply event to plugin {plugin_id}");
let protobuf_pipe_message: ProtobufPipeMessage = pipe_message
.clone()
.try_into()
.map_err(|e| anyhow!("Failed to convert to protobuf: {:?}", e))?;
match instance.get_typed_func::<(), i32>(&mut running_plugin.store, "pipe") {
Ok(pipe) => {
wasi_write_object(
running_plugin.store.data(),
&protobuf_pipe_message.encode_to_vec(),
)
.with_context(err_context)?;
let should_render = pipe
.call(&mut running_plugin.store, ())
.with_context(err_context)?;
let should_render = should_render == 1;
if rows > 0 && columns > 0 && should_render {
let rendered_bytes = instance
.get_typed_func::<(i32, i32), ()>(&mut running_plugin.store, "render")
.and_then(|render| {
render.call(&mut running_plugin.store, (rows as i32, columns as i32))
})
.map_err(|e| anyhow!(e))
.and_then(|_| {
wasi_read_string(running_plugin.store.data()).map_err(|e| anyhow!(e))
})
.with_context(err_context)?;
let pipes_to_block_or_unblock =
pipes_to_block_or_unblock(running_plugin, Some(&pipe_message.source));
let plugin_render_asset = PluginRenderAsset::new(
plugin_id,
client_id,
rendered_bytes.as_bytes().to_vec(),
)
.with_pipes(pipes_to_block_or_unblock);
plugin_render_assets.push(plugin_render_asset);
} else {
let pipes_to_block_or_unblock =
pipes_to_block_or_unblock(running_plugin, Some(&pipe_message.source));
let plugin_render_asset = PluginRenderAsset::new(plugin_id, client_id, vec![])
.with_pipes(pipes_to_block_or_unblock);
let _ = senders
.send_to_plugin(PluginInstruction::UnblockCliPipes(vec![
plugin_render_asset,
]))
.context("failed to unblock input pipe");
}
},
Err(_e) => {
// no-op, this is probably an old plugin that does not have this interface
// we don't log this error because if we do the logs will be super crowded
let pipes_to_block_or_unblock =
pipes_to_block_or_unblock(running_plugin, Some(&pipe_message.source));
let plugin_render_asset = PluginRenderAsset::new(
plugin_id,
client_id,
vec![], // nothing to render
)
.with_pipes(pipes_to_block_or_unblock);
let _ = senders
.send_to_plugin(PluginInstruction::UnblockCliPipes(vec![
plugin_render_asset,
]))
.context("failed to unblock input pipe");
},
}
Ok(())
}
pub fn pipes_to_block_or_unblock(
running_plugin: &mut RunningPlugin,
current_pipe: Option<&PipeSource>,
) -> HashMap<String, PipeStateChange> {
let mut pipe_state_changes = HashMap::new();
let mut input_pipes_to_unblock: HashSet<String> = running_plugin
.store
.data()
.input_pipes_to_unblock
.lock()
.unwrap()
.drain()
.collect();
let mut input_pipes_to_block: HashSet<String> = running_plugin
.store
.data()
.input_pipes_to_block
.lock()
.unwrap()
.drain()
.collect();
if let Some(PipeSource::Cli(current_pipe)) = current_pipe {
pipe_state_changes.insert(current_pipe.to_owned(), PipeStateChange::NoChange);
}
for pipe in input_pipes_to_block.drain() {
pipe_state_changes.insert(pipe, PipeStateChange::Block);
}
for pipe in input_pipes_to_unblock.drain() {
// unblock has priority over block if they happened simultaneously
pipe_state_changes.insert(pipe, PipeStateChange::Unblock);
}
pipe_state_changes
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/plugins/mod.rs | zellij-server/src/plugins/mod.rs | mod pinned_executor;
mod pipes;
mod plugin_loader;
mod plugin_map;
mod plugin_worker;
mod wasm_bridge;
mod watch_filesystem;
mod zellij_exports;
use log::info;
pub use pinned_executor::PinnedExecutor;
use std::{
collections::{BTreeMap, HashMap, HashSet},
fs,
path::PathBuf,
time::Duration,
};
use wasmi::Engine;
use crate::panes::PaneId;
use crate::route::NotificationEnd;
use crate::screen::ScreenInstruction;
use crate::session_layout_metadata::SessionLayoutMetadata;
use crate::{pty::PtyInstruction, thread_bus::Bus, ClientId, ServerInstruction};
use zellij_utils::data::PaneRenderReport;
pub use wasm_bridge::PluginRenderAsset;
use wasm_bridge::WasmBridge;
use async_std::{channel, future::timeout, task};
use zellij_utils::{
data::{
ClientInfo, CommandOrPlugin, Event, EventType, FloatingPaneCoordinates, InputMode,
MessageToPlugin, PermissionStatus, PermissionType, PipeMessage, PipeSource,
PluginCapabilities, WebServerStatus,
},
errors::{prelude::*, ContextType, PluginContext},
input::{
actions::Action,
command::TerminalAction,
keybinds::Keybinds,
layout::{
FloatingPaneLayout, Layout, Run, RunPlugin, RunPluginOrAlias, SwapFloatingLayout,
SwapTiledLayout, TiledPaneLayout,
},
plugins::PluginAliases,
},
ipc::ClientAttributes,
pane_size::Size,
session_serialization,
};
pub type PluginId = u32;
#[derive(Clone, Debug)]
pub enum PluginInstruction {
Load(
Option<bool>, // should float
bool, // should be opened in place
Option<String>, // pane title
RunPluginOrAlias,
Option<usize>, // tab index
Option<PaneId>, // pane id to replace if this is to be opened "in-place"
ClientId,
Size,
Option<PathBuf>, // cwd
Option<PluginId>, // the focused plugin id if relevant
bool, // skip cache
Option<bool>, // should focus plugin
Option<FloatingPaneCoordinates>,
Option<NotificationEnd>, // completion signal
),
LoadBackgroundPlugin(RunPluginOrAlias, ClientId),
Update(Vec<(Option<PluginId>, Option<ClientId>, Event)>), // Focused plugin / broadcast, client_id, event data
Unload(PluginId), // plugin_id
Reload(
Option<bool>, // should float
Option<String>, // pane title
RunPluginOrAlias,
usize, // tab index
Size,
Option<NotificationEnd>,
),
ReloadPluginWithId(u32),
Resize(PluginId, usize, usize), // plugin_id, columns, rows
AddClient(ClientId),
RemoveClient(ClientId),
NewTab(
Option<PathBuf>,
Option<TerminalAction>,
Option<TiledPaneLayout>,
Vec<FloatingPaneLayout>,
usize, // tab_index
Option<Vec<CommandOrPlugin>>, // initial_panes
bool, // block_on_first_terminal
bool, // should change focus to new tab
(ClientId, bool), // bool -> is_web_client
Option<NotificationEnd>, // completion signal
),
OverrideLayout(
Option<PathBuf>, // cwd
Option<TerminalAction>, // default_shell
TiledPaneLayout,
Vec<FloatingPaneLayout>,
Option<Vec<SwapTiledLayout>>,
Option<Vec<SwapFloatingLayout>>,
bool, // retain_existing_terminal_panes
bool, // retain_existing_plugin_panes
usize, // tab_index
ClientId,
Option<NotificationEnd>,
),
ApplyCachedEvents {
plugin_ids: Vec<PluginId>,
done_receiving_permissions: bool,
},
ApplyCachedWorkerMessages(PluginId),
PostMessagesToPluginWorker(
PluginId,
ClientId,
String, // worker name
Vec<(
String, // serialized message name
String, // serialized payload
)>,
),
PostMessageToPlugin(
PluginId,
ClientId,
String, // serialized message
String, // serialized payload
),
PluginSubscribedToEvents(PluginId, ClientId, HashSet<EventType>),
PermissionRequestResult(
PluginId,
Option<ClientId>,
Vec<PermissionType>,
PermissionStatus,
Option<PathBuf>,
),
DumpLayout(SessionLayoutMetadata, ClientId, Option<NotificationEnd>),
ListClientsMetadata(SessionLayoutMetadata, ClientId, Option<NotificationEnd>),
DumpLayoutToPlugin(SessionLayoutMetadata, PluginId),
LogLayoutToHd(SessionLayoutMetadata),
CliPipe {
pipe_id: String,
name: String,
payload: Option<String>,
plugin: Option<String>,
args: Option<BTreeMap<String, String>>,
configuration: Option<BTreeMap<String, String>>,
floating: Option<bool>,
pane_id_to_replace: Option<PaneId>,
pane_title: Option<String>,
cwd: Option<PathBuf>,
skip_cache: bool,
cli_client_id: ClientId,
},
KeybindPipe {
name: String,
payload: Option<String>,
plugin: Option<String>,
args: Option<BTreeMap<String, String>>,
configuration: Option<BTreeMap<String, String>>,
floating: Option<bool>,
pane_id_to_replace: Option<PaneId>,
pane_title: Option<String>,
cwd: Option<PathBuf>,
skip_cache: bool,
cli_client_id: ClientId,
plugin_and_client_id: Option<(u32, ClientId)>,
},
CachePluginEvents {
plugin_id: PluginId,
},
MessageFromPlugin {
source_plugin_id: u32,
message: MessageToPlugin,
},
UnblockCliPipes(Vec<PluginRenderAsset>),
Reconfigure {
client_id: ClientId,
keybinds: Option<Keybinds>,
default_mode: Option<InputMode>,
default_shell: Option<TerminalAction>,
was_written_to_disk: bool,
},
FailedToWriteConfigToDisk {
file_path: Option<PathBuf>,
},
WatchFilesystem,
ListClientsToPlugin(SessionLayoutMetadata, PluginId, ClientId),
ChangePluginHostDir(PathBuf, PluginId, ClientId),
WebServerStarted(String), // String -> the base url of the web server
FailedToStartWebServer(String),
PaneRenderReport(PaneRenderReport),
UserInput {
client_id: ClientId,
action: Action,
terminal_id: Option<u32>,
cli_client_id: Option<ClientId>,
},
Exit,
}
impl From<&PluginInstruction> for PluginContext {
fn from(plugin_instruction: &PluginInstruction) -> Self {
match *plugin_instruction {
PluginInstruction::Load(..) => PluginContext::Load,
PluginInstruction::LoadBackgroundPlugin(..) => PluginContext::LoadBackgroundPlugin,
PluginInstruction::Update(..) => PluginContext::Update,
PluginInstruction::Unload(..) => PluginContext::Unload,
PluginInstruction::Reload(..) => PluginContext::Reload,
PluginInstruction::ReloadPluginWithId(..) => PluginContext::ReloadPluginWithId,
PluginInstruction::Resize(..) => PluginContext::Resize,
PluginInstruction::Exit => PluginContext::Exit,
PluginInstruction::AddClient(_) => PluginContext::AddClient,
PluginInstruction::RemoveClient(_) => PluginContext::RemoveClient,
PluginInstruction::NewTab(..) => PluginContext::NewTab,
PluginInstruction::OverrideLayout(..) => PluginContext::OverrideLayout,
PluginInstruction::ApplyCachedEvents { .. } => PluginContext::ApplyCachedEvents,
PluginInstruction::ApplyCachedWorkerMessages(..) => {
PluginContext::ApplyCachedWorkerMessages
},
PluginInstruction::PostMessagesToPluginWorker(..) => {
PluginContext::PostMessageToPluginWorker
},
PluginInstruction::PostMessageToPlugin(..) => PluginContext::PostMessageToPlugin,
PluginInstruction::PluginSubscribedToEvents(..) => {
PluginContext::PluginSubscribedToEvents
},
PluginInstruction::PermissionRequestResult(..) => {
PluginContext::PermissionRequestResult
},
PluginInstruction::DumpLayout(..) => PluginContext::DumpLayout,
PluginInstruction::ListClientsMetadata(..) => PluginContext::ListClientsMetadata,
PluginInstruction::LogLayoutToHd(..) => PluginContext::LogLayoutToHd,
PluginInstruction::CliPipe { .. } => PluginContext::CliPipe,
PluginInstruction::CachePluginEvents { .. } => PluginContext::CachePluginEvents,
PluginInstruction::MessageFromPlugin { .. } => PluginContext::MessageFromPlugin,
PluginInstruction::UnblockCliPipes { .. } => PluginContext::UnblockCliPipes,
PluginInstruction::WatchFilesystem => PluginContext::WatchFilesystem,
PluginInstruction::KeybindPipe { .. } => PluginContext::KeybindPipe,
PluginInstruction::DumpLayoutToPlugin(..) => PluginContext::DumpLayoutToPlugin,
PluginInstruction::Reconfigure { .. } => PluginContext::Reconfigure,
PluginInstruction::FailedToWriteConfigToDisk { .. } => {
PluginContext::FailedToWriteConfigToDisk
},
PluginInstruction::ListClientsToPlugin(..) => PluginContext::ListClientsToPlugin,
PluginInstruction::ChangePluginHostDir(..) => PluginContext::ChangePluginHostDir,
PluginInstruction::WebServerStarted(..) => PluginContext::WebServerStarted,
PluginInstruction::FailedToStartWebServer(..) => PluginContext::FailedToStartWebServer,
PluginInstruction::PaneRenderReport(..) => PluginContext::PaneRenderReport,
PluginInstruction::UserInput { .. } => PluginContext::UserInput,
}
}
}
pub(crate) fn plugin_thread_main(
bus: Bus<PluginInstruction>,
engine: Engine,
data_dir: PathBuf,
mut layout: Box<Layout>,
layout_dir: Option<PathBuf>,
path_to_default_shell: PathBuf,
zellij_cwd: PathBuf,
capabilities: PluginCapabilities,
client_attributes: ClientAttributes,
default_shell: Option<TerminalAction>,
plugin_aliases: PluginAliases,
default_mode: InputMode,
default_keybinds: Keybinds,
background_plugins: HashSet<RunPluginOrAlias>,
// the client id that started the session,
// we need it here because the thread's own list of connected clients might not yet be updated
// on session start when we need to load the background plugins, and so we must have an
// explicit client_id that has started the session
initiating_client_id: ClientId,
) -> Result<()> {
info!("Wasm main thread starts");
let plugin_dir = data_dir.join("plugins/");
let plugin_global_data_dir = plugin_dir.join("data");
layout.populate_plugin_aliases_in_layout(&plugin_aliases);
// use this channel to ensure that tasks spawned from this thread terminate before exiting
// https://tokio.rs/tokio/topics/shutdown#waiting-for-things-to-finish-shutting-down
let (shutdown_send, shutdown_receive) = channel::bounded::<()>(1);
let mut wasm_bridge = WasmBridge::new(
bus.senders.clone(),
engine,
plugin_dir,
path_to_default_shell,
zellij_cwd.clone(),
capabilities,
client_attributes,
default_shell,
layout.clone(),
layout_dir,
default_mode,
default_keybinds,
);
for run_plugin_or_alias in background_plugins {
load_background_plugin(
run_plugin_or_alias,
&mut wasm_bridge,
&bus,
&plugin_aliases,
initiating_client_id,
);
}
loop {
let (event, mut err_ctx) = bus.recv().expect("failed to receive event on channel");
err_ctx.add_call(ContextType::Plugin((&event).into()));
match event {
PluginInstruction::Load(
should_float,
should_be_open_in_place,
pane_title,
mut run_plugin_or_alias,
tab_index,
pane_id_to_replace,
client_id,
size,
cwd,
focused_plugin_id,
skip_cache,
should_focus_plugin,
floating_pane_coordinates,
completion_tx,
) => {
run_plugin_or_alias.populate_run_plugin_if_needed(&plugin_aliases);
let cwd = run_plugin_or_alias.get_initial_cwd().or(cwd).or_else(|| {
if let Some(plugin_id) = focused_plugin_id {
wasm_bridge.get_plugin_cwd(plugin_id, client_id)
} else {
None
}
});
let run_plugin = run_plugin_or_alias.get_run_plugin();
let start_suppressed = false;
match wasm_bridge.load_plugin(
&run_plugin,
tab_index,
size,
cwd.clone(),
skip_cache,
Some(client_id),
) {
Ok((plugin_id, client_id)) => {
drop(bus.senders.send_to_screen(ScreenInstruction::AddPlugin(
should_float,
should_be_open_in_place,
run_plugin_or_alias,
pane_title,
tab_index,
plugin_id,
pane_id_to_replace,
cwd.clone(),
start_suppressed,
floating_pane_coordinates,
should_focus_plugin,
Some(client_id),
completion_tx,
)));
drop(bus.senders.send_to_pty(PtyInstruction::ReportPluginCwd(
plugin_id,
cwd.unwrap_or_else(|| zellij_cwd.clone()),
)));
},
Err(e) => {
log::error!("Failed to load plugin: {e}");
},
}
},
PluginInstruction::LoadBackgroundPlugin(run_plugin_or_alias, client_id) => {
load_background_plugin(
run_plugin_or_alias,
&mut wasm_bridge,
&bus,
&plugin_aliases,
client_id,
);
},
PluginInstruction::Update(updates) => {
wasm_bridge.update_plugins(updates, shutdown_send.clone())?;
},
PluginInstruction::Unload(pid) => {
wasm_bridge.unload_plugin(pid)?;
},
PluginInstruction::Reload(
should_float,
pane_title,
mut run_plugin_or_alias,
tab_index,
size,
completion_tx,
) => {
run_plugin_or_alias.populate_run_plugin_if_needed(&plugin_aliases);
match run_plugin_or_alias.get_run_plugin() {
Some(run_plugin) => {
match wasm_bridge.reload_plugin(&run_plugin) {
Ok(_) => {
let _ = bus
.senders
.send_to_server(ServerInstruction::UnblockInputThread);
},
Err(err) => match err.downcast_ref::<ZellijError>() {
Some(ZellijError::PluginDoesNotExist) => {
log::warn!(
"Plugin {} not found, starting it instead",
run_plugin.location
);
// we intentionally do not provide the client_id here because it belongs to
// the cli who spawned the command and is not an existing client_id
let skip_cache = true; // when reloading we always skip cache
let start_suppressed = false;
match wasm_bridge.load_plugin(
&Some(run_plugin),
Some(tab_index),
size,
None,
skip_cache,
None,
) {
Ok((plugin_id, _client_id)) => {
let should_be_open_in_place = false;
drop(bus.senders.send_to_screen(
ScreenInstruction::AddPlugin(
should_float,
should_be_open_in_place,
run_plugin_or_alias,
pane_title,
Some(tab_index),
plugin_id,
None,
None,
start_suppressed,
None,
None,
None,
completion_tx,
),
));
},
Err(e) => {
log::error!("Failed to load plugin: {e}");
},
};
},
_ => {
return Err(err);
},
},
}
},
None => {
log::error!("Failed to find plugin info for: {:?}", run_plugin_or_alias);
},
}
},
PluginInstruction::ReloadPluginWithId(plugin_id) => {
wasm_bridge.reload_plugin_with_id(plugin_id).non_fatal();
},
PluginInstruction::Resize(pid, new_columns, new_rows) => {
wasm_bridge.resize_plugin(pid, new_columns, new_rows, shutdown_send.clone())?;
},
PluginInstruction::AddClient(client_id) => {
wasm_bridge.add_client(client_id)?;
},
PluginInstruction::RemoveClient(client_id) => {
wasm_bridge.remove_client(client_id);
},
PluginInstruction::NewTab(
cwd,
terminal_action,
mut tab_layout,
mut floating_panes_layout,
tab_index,
initial_panes,
block_on_first_terminal,
should_change_focus_to_new_tab,
(client_id, is_web_client),
completion_tx,
) => {
// prefer connected clients so as to avoid opening plugins in the background for
// CLI clients unless no-one else is connected
let client_id = if wasm_bridge.client_is_connected(&client_id) {
client_id
} else if let Some(first_client_id) = wasm_bridge.get_first_client_id() {
first_client_id
} else {
client_id
};
let mut plugin_ids: HashMap<RunPluginOrAlias, Vec<PluginId>> = HashMap::new();
tab_layout = tab_layout.or_else(|| Some(layout.new_tab().0));
// Match initial_panes plugins to empty slots in the layout
if let Some(ref initial_panes_vec) = initial_panes {
if let Some(ref mut tiled_layout) = tab_layout {
for initial_pane in initial_panes_vec.iter() {
if let CommandOrPlugin::Plugin(run_plugin_or_alias) = initial_pane {
if !tiled_layout.replace_next_empty_slot_with_run(Run::Plugin(
run_plugin_or_alias.clone(),
)) {
log::warn!(
"More initial_panes provided than empty slots available"
);
break;
}
}
// Skip CommandOrPlugin::Command entries (handled by pty thread)
}
}
}
tab_layout.as_mut().map(|t| {
t.populate_plugin_aliases_in_layout(&plugin_aliases);
if let Some(cwd) = cwd.as_ref() {
t.add_cwd_to_layout(cwd);
}
t
});
floating_panes_layout.iter_mut().for_each(|f| {
f.run
.as_mut()
.map(|f| f.populate_run_plugin_if_needed(&plugin_aliases));
});
let extracted_run_instructions = tab_layout
.clone()
.unwrap_or_else(|| layout.new_tab().0)
.extract_run_instructions();
let size = Size::default();
let floating_panes_layout = if floating_panes_layout.is_empty() {
layout.new_tab().1
} else {
floating_panes_layout
};
let mut extracted_floating_plugins: Vec<Option<Run>> = floating_panes_layout
.iter()
.filter(|f| !f.already_running)
.map(|f| f.run.clone())
.collect();
let mut all_run_instructions = extracted_run_instructions;
all_run_instructions.append(&mut extracted_floating_plugins);
for run_instruction in all_run_instructions {
if let Some(Run::Plugin(run_plugin_or_alias)) = run_instruction {
let run_plugin = run_plugin_or_alias.get_run_plugin();
let cwd = run_plugin_or_alias
.get_initial_cwd()
.or_else(|| cwd.clone());
let skip_cache = false;
match wasm_bridge.load_plugin(
&run_plugin,
Some(tab_index),
size,
cwd,
skip_cache,
Some(client_id),
) {
Ok((plugin_id, _client_id)) => {
plugin_ids
.entry(run_plugin_or_alias.clone())
.or_default()
.push(plugin_id);
},
Err(e) => {
log::error!("Failed to load plugin: {}", e);
},
}
}
}
drop(bus.senders.send_to_pty(PtyInstruction::NewTab(
cwd,
terminal_action,
tab_layout,
floating_panes_layout,
tab_index,
plugin_ids,
initial_panes,
block_on_first_terminal,
should_change_focus_to_new_tab,
(client_id, is_web_client),
completion_tx,
)));
},
PluginInstruction::OverrideLayout(
cwd,
default_shell,
mut tiled_layout,
mut floating_layouts,
swap_tiled_layouts,
swap_floating_layouts,
retain_existing_terminal_panes,
retain_existing_plugin_panes,
tab_index,
client_id,
completion_tx,
) => {
// Prefer connected clients to avoid opening plugins in background for CLI clients
let client_id = if wasm_bridge.client_is_connected(&client_id) {
client_id
} else if let Some(first_client_id) = wasm_bridge.get_first_client_id() {
first_client_id
} else {
client_id
};
let mut plugin_ids: HashMap<RunPluginOrAlias, Vec<PluginId>> = HashMap::new();
// Populate plugin aliases in layouts
tiled_layout.populate_plugin_aliases_in_layout(&plugin_aliases);
floating_layouts.iter_mut().for_each(|f| {
f.run
.as_mut()
.map(|f| f.populate_run_plugin_if_needed(&plugin_aliases));
});
// Extract run instructions from tiled layout
let extracted_run_instructions = tiled_layout.extract_run_instructions();
// Extract run instructions from floating layouts (excluding already_running)
let extracted_floating_plugins: Vec<Option<Run>> = floating_layouts
.iter()
.filter(|f| !f.already_running)
.map(|f| f.run.clone())
.collect();
// Combine all run instructions
let mut all_run_instructions = extracted_run_instructions;
all_run_instructions.extend(extracted_floating_plugins);
// Load plugins for all Run::Plugin instructions
let size = Size::default();
for run_instruction in all_run_instructions {
if let Some(Run::Plugin(run_plugin_or_alias)) = run_instruction {
let run_plugin = run_plugin_or_alias.get_run_plugin();
let cwd = run_plugin_or_alias.get_initial_cwd();
let skip_cache = false;
match wasm_bridge.load_plugin(
&run_plugin,
Some(tab_index),
size,
cwd,
skip_cache,
Some(client_id),
) {
Ok((plugin_id, _client_id)) => {
plugin_ids
.entry(run_plugin_or_alias.clone())
.or_default()
.push(plugin_id);
},
Err(e) => {
log::error!("Failed to load plugin: {}", e);
},
}
}
}
// Send to pty thread
drop(bus.senders.send_to_pty(PtyInstruction::OverrideLayout(
cwd,
default_shell,
tiled_layout,
floating_layouts,
swap_tiled_layouts,
swap_floating_layouts,
retain_existing_terminal_panes,
retain_existing_plugin_panes,
tab_index,
plugin_ids,
client_id,
completion_tx,
)));
},
PluginInstruction::ApplyCachedEvents {
plugin_ids,
done_receiving_permissions,
} => {
wasm_bridge.apply_cached_events(
plugin_ids,
done_receiving_permissions,
shutdown_send.clone(),
)?;
},
PluginInstruction::ApplyCachedWorkerMessages(plugin_id) => {
wasm_bridge.apply_cached_worker_messages(plugin_id)?;
},
PluginInstruction::PostMessagesToPluginWorker(
plugin_id,
client_id,
worker_name,
messages,
) => {
wasm_bridge.post_messages_to_plugin_worker(
plugin_id,
client_id,
worker_name,
messages,
)?;
},
PluginInstruction::PostMessageToPlugin(plugin_id, client_id, message, payload) => {
let updates = vec![(
Some(plugin_id),
Some(client_id),
Event::CustomMessage(message, payload),
)];
wasm_bridge.update_plugins(updates, shutdown_send.clone())?;
},
PluginInstruction::PluginSubscribedToEvents(_plugin_id, _client_id, _events) => {
// no-op, there used to be stuff we did here - now there isn't, but we might want
// to add stuff here in the future
},
PluginInstruction::PermissionRequestResult(
plugin_id,
client_id,
permissions,
status,
cache_path,
) => {
if let Err(e) = wasm_bridge.cache_plugin_permissions(
plugin_id,
client_id,
permissions,
status,
cache_path,
) {
log::error!("{}", e);
}
let updates = vec![(
Some(plugin_id),
client_id,
Event::PermissionRequestResult(status),
)];
wasm_bridge.update_plugins(updates, shutdown_send.clone())?;
let done_receiving_permissions = true;
wasm_bridge.apply_cached_events(
vec![plugin_id],
done_receiving_permissions,
shutdown_send.clone(),
)?;
},
PluginInstruction::DumpLayout(
mut session_layout_metadata,
client_id,
completion_tx,
) => {
populate_session_layout_metadata(
&mut session_layout_metadata,
&wasm_bridge,
&plugin_aliases,
);
drop(bus.senders.send_to_pty(PtyInstruction::DumpLayout(
session_layout_metadata,
client_id,
completion_tx,
)));
},
PluginInstruction::ListClientsMetadata(
mut session_layout_metadata,
client_id,
completion_tx,
) => {
populate_session_layout_metadata(
&mut session_layout_metadata,
&wasm_bridge,
&plugin_aliases,
);
drop(bus.senders.send_to_pty(PtyInstruction::ListClientsMetadata(
session_layout_metadata,
client_id,
completion_tx,
)));
},
PluginInstruction::DumpLayoutToPlugin(mut session_layout_metadata, plugin_id) => {
populate_session_layout_metadata(
&mut session_layout_metadata,
&wasm_bridge,
&plugin_aliases,
);
match session_serialization::serialize_session_layout(
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/plugins/watch_filesystem.rs | zellij-server/src/plugins/watch_filesystem.rs | use super::PluginInstruction;
use std::path::PathBuf;
use crate::thread_bus::ThreadSenders;
use std::path::Path;
use std::time::Duration;
use notify_debouncer_full::{
new_debouncer,
notify::{EventKind, RecommendedWatcher, RecursiveMode, Watcher},
DebounceEventResult, Debouncer, FileIdMap,
};
use zellij_utils::{data::Event, errors::prelude::Result};
const DEBOUNCE_DURATION_MS: u64 = 400;
pub fn watch_filesystem(
senders: ThreadSenders,
zellij_cwd: &Path,
) -> Result<Debouncer<RecommendedWatcher, FileIdMap>> {
let path_prefix_in_plugins = PathBuf::from("/host");
let current_dir = PathBuf::from(zellij_cwd);
let mut debouncer = new_debouncer(
Duration::from_millis(DEBOUNCE_DURATION_MS),
None,
move |result: DebounceEventResult| match result {
Ok(events) => {
let mut create_events = vec![];
let mut read_events = vec![];
let mut update_events = vec![];
let mut delete_events = vec![];
for event in events {
match event.kind {
EventKind::Access(_) => read_events.push(event),
EventKind::Create(_) => create_events.push(event),
EventKind::Modify(_) => update_events.push(event),
EventKind::Remove(_) => delete_events.push(event),
_ => {},
}
}
let create_paths: Vec<PathBuf> = create_events
.drain(..)
.map(|e| {
e.paths
.iter()
.map(|p| {
let stripped_prefix_path =
p.strip_prefix(¤t_dir).unwrap_or_else(|_| p);
path_prefix_in_plugins.join(stripped_prefix_path)
})
.collect()
})
.collect();
let read_paths: Vec<PathBuf> = read_events
.drain(..)
.map(|e| {
e.paths
.iter()
.map(|p| {
let stripped_prefix_path =
p.strip_prefix(¤t_dir).unwrap_or_else(|_| p);
path_prefix_in_plugins.join(stripped_prefix_path)
})
.collect()
})
.collect();
let update_paths: Vec<PathBuf> = update_events
.drain(..)
.map(|e| {
e.paths
.iter()
.map(|p| {
let stripped_prefix_path =
p.strip_prefix(¤t_dir).unwrap_or_else(|_| p);
path_prefix_in_plugins.join(stripped_prefix_path)
})
.collect()
})
.collect();
let delete_paths: Vec<PathBuf> = delete_events
.drain(..)
.map(|e| {
e.paths
.iter()
.map(|p| {
let stripped_prefix_path =
p.strip_prefix(¤t_dir).unwrap_or_else(|_| p);
path_prefix_in_plugins.join(stripped_prefix_path)
})
.collect()
})
.collect();
// TODO: at some point we might want to add FileMetadata to these, but right now
// the API is a bit unstable, so let's not rock the boat too much by adding another
// expensive syscall
let _ = senders.send_to_plugin(PluginInstruction::Update(vec![
(
None,
None,
Event::FileSystemRead(read_paths.into_iter().map(|p| (p, None)).collect()),
),
(
None,
None,
Event::FileSystemCreate(
create_paths.into_iter().map(|p| (p, None)).collect(),
),
),
(
None,
None,
Event::FileSystemUpdate(
update_paths.into_iter().map(|p| (p, None)).collect(),
),
),
(
None,
None,
Event::FileSystemDelete(
delete_paths.into_iter().map(|p| (p, None)).collect(),
),
),
]));
},
Err(errors) => errors
.iter()
.for_each(|error| log::error!("watch error: {error:?}")),
},
)?;
debouncer
.watcher()
.watch(zellij_cwd, RecursiveMode::Recursive)?;
Ok(debouncer)
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/plugins/wasm_bridge.rs | zellij-server/src/plugins/wasm_bridge.rs | use super::{PinnedExecutor, PluginId, PluginInstruction};
use crate::global_async_runtime::get_tokio_runtime;
use crate::plugins::pipes::{
apply_pipe_message_to_plugin, pipes_to_block_or_unblock, PendingPipes, PipeStateChange,
};
use crate::plugins::plugin_loader::PluginLoader;
use crate::plugins::plugin_map::{AtomicEvent, PluginEnv, PluginMap, RunningPlugin, Subscriptions};
use crate::plugins::plugin_worker::MessageToWorker;
use crate::plugins::watch_filesystem::watch_filesystem;
use crate::plugins::zellij_exports::{wasi_read_string, wasi_write_object};
use async_channel::Sender;
use highway::{HighwayHash, PortableHash};
use log::info;
use notify_debouncer_full::{notify::RecommendedWatcher, Debouncer, FileIdMap};
use std::{
collections::{BTreeMap, HashMap, HashSet},
path::PathBuf,
str::FromStr,
sync::{Arc, Mutex},
};
use url::Url;
use wasmi::{Engine, Module};
use zellij_utils::consts::{ZELLIJ_CACHE_DIR, ZELLIJ_SESSION_CACHE_DIR, ZELLIJ_TMP_DIR};
use zellij_utils::data::{
FloatingPaneCoordinates, InputMode, PaneContents, PaneRenderReport, PermissionStatus,
PermissionType, PipeMessage, PipeSource,
};
use zellij_utils::downloader::Downloader;
use zellij_utils::input::keybinds::Keybinds;
use zellij_utils::input::permission::PermissionCache;
use zellij_utils::plugin_api::event::ProtobufEvent;
use prost::Message;
use crate::panes::PaneId;
use crate::{
background_jobs::BackgroundJob, screen::ScreenInstruction, thread_bus::ThreadSenders,
ui::loading_indication::LoadingIndication, ClientId, ServerInstruction,
};
use zellij_utils::{
data::{Event, EventType, PluginCapabilities},
errors::prelude::*,
input::{
command::TerminalAction,
layout::{Layout, PluginUserConfiguration, RunPlugin, RunPluginLocation, RunPluginOrAlias},
plugins::PluginConfig,
},
ipc::ClientAttributes,
pane_size::Size,
};
#[derive(Debug, Clone)]
pub enum EventOrPipeMessage {
Event(Event),
PipeMessage(PipeMessage),
}
#[derive(Debug, Clone, Default)]
pub struct PluginRenderAsset {
// TODO: naming
pub client_id: ClientId,
pub plugin_id: PluginId,
pub bytes: Vec<u8>,
pub cli_pipes: HashMap<String, PipeStateChange>,
}
impl PluginRenderAsset {
pub fn new(plugin_id: PluginId, client_id: ClientId, bytes: Vec<u8>) -> Self {
PluginRenderAsset {
client_id,
plugin_id,
bytes,
..Default::default()
}
}
pub fn with_pipes(mut self, cli_pipes: HashMap<String, PipeStateChange>) -> Self {
self.cli_pipes = cli_pipes;
self
}
}
#[derive(Debug, Clone)]
pub struct LoadingContext {
pub plugin_id: PluginId,
pub client_id: ClientId,
pub plugin_cwd: PathBuf,
pub plugin_own_data_dir: PathBuf,
pub plugin_own_cache_dir: PathBuf,
pub plugin_config: PluginConfig,
pub tab_index: Option<usize>,
pub path_to_default_shell: PathBuf,
pub capabilities: PluginCapabilities,
pub client_attributes: ClientAttributes,
pub default_shell: Option<TerminalAction>,
pub layout_dir: Option<PathBuf>,
pub default_mode: InputMode,
pub keybinds: Keybinds,
pub plugin_dir: PathBuf,
pub size: Size,
}
impl LoadingContext {
pub fn new(
wasm_bridge: &WasmBridge,
cwd: Option<PathBuf>,
plugin_config: PluginConfig,
plugin_id: PluginId,
client_id: ClientId,
tab_index: Option<usize>,
size: Size,
) -> Self {
let plugin_own_data_dir = ZELLIJ_SESSION_CACHE_DIR
.join(Url::from(&plugin_config.location).to_string())
.join(format!("{}-{}", plugin_id, client_id));
let plugin_own_cache_dir = ZELLIJ_CACHE_DIR
.join(Url::from(&plugin_config.location).to_string())
.join(format!("plugin_cache"));
let default_mode = wasm_bridge
.base_modes
.get(&client_id)
.copied()
.unwrap_or(wasm_bridge.default_mode);
let keybinds = wasm_bridge
.keybinds
.get(&client_id)
.cloned()
.unwrap_or_else(|| wasm_bridge.default_keybinds.clone());
LoadingContext {
client_id,
plugin_id,
path_to_default_shell: wasm_bridge.path_to_default_shell.clone(),
plugin_cwd: cwd.unwrap_or_else(|| wasm_bridge.zellij_cwd.clone()),
capabilities: wasm_bridge.capabilities.clone(),
client_attributes: wasm_bridge.client_attributes.clone(),
default_shell: wasm_bridge.default_shell.clone(),
layout_dir: wasm_bridge.layout_dir.clone(),
keybinds,
default_mode,
plugin_own_data_dir,
plugin_own_cache_dir,
plugin_config,
tab_index,
plugin_dir: wasm_bridge.plugin_dir.clone(),
size,
}
}
pub fn update_plugin_path(&mut self, new_path: PathBuf) {
self.plugin_config.path = new_path;
}
}
pub type PluginCache = Arc<Mutex<HashMap<PathBuf, Module>>>;
pub struct WasmBridge {
connected_clients: Arc<Mutex<Vec<ClientId>>>,
senders: ThreadSenders,
plugin_dir: PathBuf,
plugin_map: Arc<Mutex<PluginMap>>,
plugin_executor: Arc<PinnedExecutor>,
next_plugin_id: PluginId,
plugin_ids_waiting_for_permission_request: HashSet<PluginId>,
cached_events_for_pending_plugins: HashMap<PluginId, Vec<EventOrPipeMessage>>,
cached_resizes_for_pending_plugins: HashMap<PluginId, (usize, usize)>, // (rows, columns)
cached_worker_messages: HashMap<PluginId, Vec<(ClientId, String, String, String)>>, // Vec<clientid,
// worker_name,
// message,
// payload>
loading_plugins: HashSet<(PluginId, RunPlugin)>, // tracks loading plugins without handles
pending_plugin_reloads: HashSet<RunPlugin>,
path_to_default_shell: PathBuf,
watcher: Option<Debouncer<RecommendedWatcher, FileIdMap>>,
zellij_cwd: PathBuf,
capabilities: PluginCapabilities,
client_attributes: ClientAttributes,
default_shell: Option<TerminalAction>,
cached_plugin_map:
HashMap<RunPluginLocation, HashMap<PluginUserConfiguration, Vec<(PluginId, ClientId)>>>,
pending_pipes: PendingPipes,
layout_dir: Option<PathBuf>,
default_mode: InputMode,
default_keybinds: Keybinds,
keybinds: HashMap<ClientId, Keybinds>,
base_modes: HashMap<ClientId, InputMode>,
downloader: Downloader,
previous_pane_render_report: Option<PaneRenderReport>,
}
impl WasmBridge {
pub fn new(
senders: ThreadSenders,
engine: Engine,
plugin_dir: PathBuf,
path_to_default_shell: PathBuf,
zellij_cwd: PathBuf,
capabilities: PluginCapabilities,
client_attributes: ClientAttributes,
default_shell: Option<TerminalAction>,
default_layout: Box<Layout>,
layout_dir: Option<PathBuf>,
default_mode: InputMode,
default_keybinds: Keybinds,
) -> Self {
let plugin_map = Arc::new(Mutex::new(PluginMap::default()));
let connected_clients: Arc<Mutex<Vec<ClientId>>> = Arc::new(Mutex::new(vec![]));
let plugin_cache: Arc<Mutex<HashMap<PathBuf, Module>>> =
Arc::new(Mutex::new(HashMap::new()));
let watcher = None;
let downloader = Downloader::new(ZELLIJ_CACHE_DIR.to_path_buf());
let max_threads = num_cpus::get().max(4).min(16);
let plugin_executor = Arc::new(PinnedExecutor::new(
max_threads,
&senders,
&plugin_map,
&connected_clients,
&default_layout,
&plugin_cache,
&engine,
));
WasmBridge {
connected_clients,
senders,
plugin_dir,
plugin_map,
plugin_executor,
path_to_default_shell,
watcher,
next_plugin_id: 0,
cached_events_for_pending_plugins: HashMap::new(),
plugin_ids_waiting_for_permission_request: HashSet::new(),
cached_resizes_for_pending_plugins: HashMap::new(),
cached_worker_messages: HashMap::new(),
loading_plugins: HashSet::new(),
pending_plugin_reloads: HashSet::new(),
zellij_cwd,
capabilities,
client_attributes,
default_shell,
cached_plugin_map: HashMap::new(),
pending_pipes: Default::default(),
layout_dir,
default_mode,
default_keybinds,
keybinds: HashMap::new(),
base_modes: HashMap::new(),
downloader,
previous_pane_render_report: None,
}
}
pub fn load_plugin(
&mut self,
run: &Option<RunPlugin>,
tab_index: Option<usize>,
size: Size,
cwd: Option<PathBuf>,
skip_cache: bool,
client_id: Option<ClientId>,
) -> Result<(PluginId, ClientId)> {
let err_context = move || format!("failed to load plugin");
let client_id = client_id
.and_then(|client_id| {
// first attempt to use a connected client (because this might be a cli_client that
// should not get plugins) and only if none is connected, load a "dummy" plugin for
// the cli client
let connected_clients = self.connected_clients.lock().unwrap();
if connected_clients.contains(&client_id) {
Some(client_id)
} else {
None
}
})
.or_else(|| {
// if no client id was provided, try to use the first connected client
self.connected_clients
.lock()
.unwrap()
.iter()
.next()
.copied()
})
.or(client_id) // if we got here, this is likely a cli client with no other clients
// connected, or loading a background plugin on app start, we use the provided client id as a dummy to load the
// plugin anyway
.with_context(|| {
"Plugins must have a client id, none was provided and none are connected"
})?;
let plugin_id = self.next_plugin_id;
match run {
Some(run) => {
let plugin = PluginConfig::from_run_plugin(run)
.with_context(|| format!("failed to resolve plugin {run:?}"))
.with_context(err_context)?;
let plugin_name = run.location.to_string();
self.cached_events_for_pending_plugins
.insert(plugin_id, vec![]);
self.cached_resizes_for_pending_plugins
.insert(plugin_id, (size.rows, size.cols));
self.loading_plugins.insert((plugin_id, run.clone()));
// Clone for threaded contexts
let plugin_executor = self.plugin_executor.clone();
let senders = self.senders.clone();
let zellij_cwd = cwd.unwrap_or_else(|| self.zellij_cwd.clone());
// Check if we need to download (async I/O required)
let needs_download = matches!(plugin.location, RunPluginLocation::Remote(_));
let mut loading_context = LoadingContext::new(
&self,
Some(zellij_cwd.clone()),
plugin.clone(), // TODO: rename to plugin_config
plugin_id,
client_id,
tab_index,
size,
);
if needs_download {
let downloader = self.downloader.clone();
get_tokio_runtime().spawn(async move {
let _ = senders.send_to_background_jobs(
BackgroundJob::AnimatePluginLoading(plugin_id),
);
let mut loading_indication = LoadingIndication::new(plugin_name.clone());
if let RunPluginLocation::Remote(url) = &plugin.location {
let file_name: String = PortableHash::default()
.hash128(url.as_bytes())
.iter()
.map(ToString::to_string)
.collect();
match downloader.download(url, Some(&file_name)).await {
Ok(_) => loading_context
.update_plugin_path(ZELLIJ_CACHE_DIR.join(&file_name)),
Err(e) => {
handle_plugin_loading_failure(
&senders,
plugin_id,
&mut loading_indication,
e,
Some(client_id),
);
return;
},
}
}
plugin_executor.execute_plugin_load(
plugin_id,
move |senders: ThreadSenders,
plugin_map: Arc<Mutex<PluginMap>>,
connected_clients: Arc<Mutex<Vec<ClientId>>>,
default_layout: Box<Layout>,
plugin_cache: PluginCache,
engine| {
let mut plugin_map = plugin_map.lock().unwrap();
match PluginLoader::new(
skip_cache,
loading_context,
senders.clone(),
engine.clone(),
default_layout.clone(),
plugin_cache.clone(),
&mut plugin_map,
connected_clients.clone(),
)
.start_plugin()
{
Ok(_) => {
let plugin_list = plugin_map.list_plugins();
handle_plugin_successful_loading(
&senders,
plugin_id,
plugin_list,
);
},
Err(e) => handle_plugin_loading_failure(
&senders,
plugin_id,
&mut loading_indication,
e,
Some(client_id),
),
}
let _ =
senders.send_to_plugin(PluginInstruction::ApplyCachedEvents {
plugin_ids: vec![plugin_id],
done_receiving_permissions: false,
});
},
);
});
} else {
let _ = senders
.send_to_background_jobs(BackgroundJob::AnimatePluginLoading(plugin_id));
let mut loading_indication = LoadingIndication::new(plugin_name.clone());
self.plugin_executor.execute_plugin_load(
plugin_id,
move |senders,
plugin_map,
connected_clients,
default_layout,
plugin_cache: PluginCache,
engine: Engine| {
let mut plugin_map = plugin_map.lock().unwrap();
match PluginLoader::new(
skip_cache,
loading_context,
senders.clone(),
engine.clone(),
default_layout.clone(),
plugin_cache.clone(),
&mut plugin_map,
connected_clients.clone(),
)
.start_plugin()
{
Ok(_) => {
let plugin_list = plugin_map.list_plugins();
handle_plugin_successful_loading(
&senders,
plugin_id,
plugin_list,
);
},
Err(e) => handle_plugin_loading_failure(
&senders,
plugin_id,
&mut loading_indication,
e,
Some(client_id),
),
}
let _ = senders.send_to_plugin(PluginInstruction::ApplyCachedEvents {
plugin_ids: vec![plugin_id],
done_receiving_permissions: false,
});
},
);
}
self.next_plugin_id += 1;
},
None => {
self.next_plugin_id += 1;
let mut loading_indication = LoadingIndication::new(format!("{}", plugin_id));
handle_plugin_loading_failure(
&self.senders,
plugin_id,
&mut loading_indication,
"Failed to resolve plugin alias",
None,
);
},
}
Ok((plugin_id, client_id))
}
pub fn unload_plugin(&mut self, pid: PluginId) -> Result<()> {
info!("Bye from plugin {}", &pid);
// Remove from plugin_map on main thread
let plugins_to_cleanup: Vec<_> = {
let mut plugin_map = self.plugin_map.lock().unwrap();
plugin_map.remove_plugins(pid).into_iter().collect()
};
// Schedule cleanup on each plugin's pinned thread
for ((plugin_id, client_id), (running_plugin, subscriptions, workers)) in plugins_to_cleanup
{
// Clear key intercepts if needed (on main thread is OK)
if running_plugin.lock().unwrap().intercepting_key_presses() {
let _ = self
.senders
.send_to_screen(ScreenInstruction::ClearKeyPressesIntercepts(client_id));
}
// Send worker exit messages
for (_worker_name, worker_sender) in workers {
drop(worker_sender.send(MessageToWorker::Exit));
}
self.plugin_executor.execute_plugin_unload(
plugin_id,
move |senders,
_plugin_map,
_connected_clients,
_default_layout,
_plugin_cache,
_engine| {
let subscriptions_guard = subscriptions.lock().unwrap();
let needs_before_close = subscriptions_guard.contains(&EventType::BeforeClose);
drop(subscriptions_guard); // Release lock before calling plugin
if needs_before_close {
let mut rp = running_plugin.lock().unwrap();
match apply_before_close_event_to_plugin(
plugin_id,
client_id,
&mut rp,
senders.clone(),
) {
Ok(()) => {},
Err(e) => {
log::error!("{:?}", e);
let stringified_error = format!("{:?}", e).replace("\n", "\n\r");
handle_plugin_crash(plugin_id, stringified_error, senders.clone());
},
}
let cache_dir = rp.store.data().plugin_own_data_dir.clone();
drop(rp); // Release lock before filesystem operation
if let Err(e) = std::fs::remove_dir_all(&cache_dir) {
log::error!("Failed to remove cache dir for plugin: {:?}", e);
}
} else {
let cache_dir = running_plugin
.lock()
.unwrap()
.store
.data()
.plugin_own_data_dir
.clone();
if let Err(e) = std::fs::remove_dir_all(&cache_dir) {
log::error!("Failed to remove cache dir for plugin: {:?}", e);
}
}
drop(running_plugin);
drop(subscriptions);
},
);
}
// Main thread cleanup
self.cached_plugin_map.clear();
let mut pipes_to_unblock = self.pending_pipes.unload_plugin(&pid);
for pipe_name in pipes_to_unblock.drain(..) {
let _ = self
.senders
.send_to_server(ServerInstruction::UnblockCliPipeInput(pipe_name))
.context("failed to unblock input pipe");
}
let plugin_list = self.plugin_map.lock().unwrap().list_plugins();
let _ = self
.senders
.send_to_background_jobs(BackgroundJob::ReportPluginList(plugin_list));
Ok(())
}
pub fn reload_plugin_with_id(&mut self, plugin_id: u32) -> Result<()> {
let Some(run_plugin) = self.run_plugin_of_plugin_id(plugin_id).map(|r| r.clone()) else {
log::error!("Failed to find plugin with id: {}", plugin_id);
return Ok(());
};
let (rows, columns) = self.size_of_plugin_id(plugin_id).unwrap_or((0, 0));
self.cached_events_for_pending_plugins
.insert(plugin_id, vec![]);
self.cached_resizes_for_pending_plugins
.insert(plugin_id, (rows, columns));
let mut loading_indication = LoadingIndication::new(run_plugin.location.to_string());
self.start_plugin_loading_indication(&[plugin_id], &loading_indication);
self.loading_plugins.insert((plugin_id, run_plugin.clone()));
let plugin_executor = self.plugin_executor.clone();
let Some(first_client_id) = self.get_first_client_id() else {
log::error!("No connected clients, cannot reload plugin.");
return Ok(());
};
let Some(plugin_config) = self.plugin_config_of_plugin_id(plugin_id) else {
log::error!("Could not find running plugin with id: {}", plugin_id);
return Ok(());
};
let tab_index = self.tab_index_of_plugin_id(plugin_id);
let Some(size) = self.size_of_plugin_id(plugin_id) else {
log::error!(
"Could not find size of running plugin with id: {}",
plugin_id
);
return Ok(());
};
let size = Size {
rows: size.0,
cols: size.1,
};
let cwd = self.cwd_of_plugin_id(plugin_id);
let loading_context = LoadingContext::new(
&self,
cwd,
plugin_config,
plugin_id,
first_client_id,
tab_index,
size,
);
plugin_executor.execute_for_plugin(
plugin_id,
move |senders, plugin_map, connected_clients, default_layout, plugin_cache, engine| {
let skip_cache = true; // we want to explicitly reload the plugin
let mut plugin_map = plugin_map.lock().unwrap();
match PluginLoader::new(
skip_cache,
loading_context,
senders.clone(),
engine.clone(),
default_layout.clone(),
plugin_cache.clone(),
&mut plugin_map,
connected_clients.clone(),
)
.start_plugin()
{
Ok(_) => {
let plugin_list = plugin_map.list_plugins();
handle_plugin_successful_loading(&senders, plugin_id, plugin_list);
},
Err(e) => handle_plugin_loading_failure(
&senders,
plugin_id,
&mut loading_indication,
e,
Some(first_client_id),
),
}
let _ = senders.send_to_plugin(PluginInstruction::ApplyCachedEvents {
plugin_ids: vec![plugin_id],
done_receiving_permissions: false,
});
},
);
Ok(())
}
pub fn reload_plugin(&mut self, run_plugin: &RunPlugin) -> Result<()> {
if self.plugin_is_currently_being_loaded(&run_plugin.location) {
self.pending_plugin_reloads.insert(run_plugin.clone());
return Ok(());
}
let plugin_ids = self
.all_plugin_ids_for_plugin_location(&run_plugin.location, &run_plugin.configuration)?;
for plugin_id in &plugin_ids {
self.reload_plugin_with_id(*plugin_id)?;
}
Ok(())
}
pub fn add_client(&mut self, client_id: ClientId) -> Result<()> {
if self.client_is_connected(&client_id) {
return Ok(());
}
let mut new_plugins = HashSet::new();
for plugin_id in self.plugin_map.lock().unwrap().plugin_ids() {
new_plugins.insert(plugin_id);
}
for plugin_id in new_plugins {
let Some(run_plugin) = self.run_plugin_of_plugin_id(plugin_id).map(|r| r.clone())
else {
log::error!("Failed to find plugin with id: {}", plugin_id);
return Ok(());
};
let (rows, columns) = self.size_of_plugin_id(plugin_id).unwrap_or((0, 0));
self.cached_events_for_pending_plugins
.insert(plugin_id, vec![]);
self.cached_resizes_for_pending_plugins
.insert(plugin_id, (rows, columns));
let loading_indication = LoadingIndication::new(run_plugin.location.to_string());
self.start_plugin_loading_indication(&[plugin_id], &loading_indication);
self.loading_plugins.insert((plugin_id, run_plugin.clone()));
let plugin_executor = self.plugin_executor.clone();
let Some(plugin_config) = self.plugin_config_of_plugin_id(plugin_id) else {
log::error!("Could not find running plugin with id: {}", plugin_id);
return Ok(());
};
let tab_index = self.tab_index_of_plugin_id(plugin_id);
let Some(size) = self.size_of_plugin_id(plugin_id) else {
log::error!(
"Could not find size of running plugin with id: {}",
plugin_id
);
return Ok(());
};
let size = Size {
rows: size.0,
cols: size.1,
};
let cwd = self.cwd_of_plugin_id(plugin_id);
let loading_context = LoadingContext::new(
&self,
cwd,
plugin_config,
plugin_id,
client_id,
tab_index,
size,
);
plugin_executor.execute_for_plugin(
plugin_id,
move |senders,
plugin_map,
connected_clients,
default_layout,
plugin_cache,
engine| {
let skip_cache = false;
let mut plugin_map = plugin_map.lock().unwrap();
match PluginLoader::new(
skip_cache,
loading_context,
senders.clone(),
engine.clone(),
default_layout.clone(),
plugin_cache.clone(),
&mut plugin_map,
connected_clients.clone(),
)
.without_connected_clients()
.start_plugin()
{
Ok(_) => {
let _ = senders
.send_to_screen(ScreenInstruction::RequestStateUpdateForPlugins);
let _ = senders.send_to_background_jobs(
BackgroundJob::StopPluginLoadingAnimation(plugin_id),
);
let _ = senders.send_to_plugin(PluginInstruction::ApplyCachedEvents {
plugin_ids: vec![plugin_id],
done_receiving_permissions: false,
});
},
Err(e) => {
log::error!("Failed to load plugin for new client: {}", e);
},
}
},
)
}
self.connected_clients.lock().unwrap().push(client_id);
Ok(())
}
pub fn resize_plugin(
&mut self,
pid: PluginId,
new_columns: usize,
new_rows: usize,
shutdown_sender: Sender<()>,
) -> Result<()> {
let err_context = move || format!("failed to resize plugin {pid}");
let plugins_to_resize: Vec<(PluginId, ClientId, Arc<Mutex<RunningPlugin>>)> = self
.plugin_map
.lock()
.unwrap()
.running_plugins()
.iter()
.cloned()
.filter(|(plugin_id, _client_id, _running_plugin)| {
!self
.cached_resizes_for_pending_plugins
.contains_key(&plugin_id)
})
.collect();
for (plugin_id, client_id, running_plugin) in plugins_to_resize {
if plugin_id == pid {
let event_id = running_plugin
.lock()
.unwrap()
.next_event_id(AtomicEvent::Resize);
// Execute directly on pinned thread (no async I/O needed for resize/render)
self.plugin_executor.execute_for_plugin(plugin_id, {
// let senders = self.senders.clone();
let running_plugin = running_plugin.clone();
let _s = shutdown_sender.clone();
move |senders,
_plugin_map,
_connected_clients,
_default_layout,
_plugin_cache,
_engine| {
let mut running_plugin = running_plugin.lock().unwrap();
let _s = _s; // guard to allow the task to complete before cleanup/shutdown
if running_plugin.apply_event_id(AtomicEvent::Resize, event_id) {
let old_rows = running_plugin.rows;
let old_columns = running_plugin.columns;
running_plugin.rows = new_rows;
running_plugin.columns = new_columns;
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/plugins/plugin_map.rs | zellij-server/src/plugins/plugin_map.rs | use crate::plugins::plugin_worker::MessageToWorker;
use crate::plugins::PluginId;
use std::io::Write;
use std::{
collections::{BTreeMap, HashMap, HashSet, VecDeque},
path::PathBuf,
sync::{Arc, Mutex},
};
use wasmi::{Instance, Store, StoreLimits};
use wasmi_wasi::WasiCtx;
use crate::{thread_bus::ThreadSenders, ClientId};
use async_channel::Sender;
use zellij_utils::{
data::EventType,
data::InputMode,
data::PluginCapabilities,
input::command::TerminalAction,
input::keybinds::Keybinds,
input::layout::{Layout, PluginUserConfiguration, RunPlugin, RunPluginLocation},
input::plugins::PluginConfig,
ipc::ClientAttributes,
};
use zellij_utils::{data::PermissionType, errors::prelude::*};
// the idea here is to provide atomicity when adding/removing plugins from the map (eg. when a new
// client connects) but to also allow updates/renders not to block each other
// so when adding/removing from the map - everything is halted, that's life
// but when cloning the internal RunningPlugin and Subscriptions atomics, we can call methods on
// them without blocking other instances
#[derive(Default)]
pub struct PluginMap {
plugin_assets: HashMap<
(PluginId, ClientId),
(
Arc<Mutex<RunningPlugin>>,
Arc<Mutex<Subscriptions>>,
HashMap<String, Sender<MessageToWorker>>,
),
>,
}
impl PluginMap {
pub fn remove_plugins(
&mut self,
pid: PluginId,
) -> HashMap<
(PluginId, ClientId),
(
Arc<Mutex<RunningPlugin>>,
Arc<Mutex<Subscriptions>>,
HashMap<String, Sender<MessageToWorker>>,
),
> {
let mut removed = HashMap::new();
let ids_in_plugin_map: Vec<(PluginId, ClientId)> =
self.plugin_assets.keys().copied().collect();
for (plugin_id, client_id) in ids_in_plugin_map {
if pid == plugin_id {
if let Some(plugin_asset) = self.plugin_assets.remove(&(plugin_id, client_id)) {
removed.insert((plugin_id, client_id), plugin_asset);
}
}
}
removed
}
pub fn plugin_ids(&self) -> Vec<PluginId> {
let mut unique_plugins: HashSet<PluginId> = self
.plugin_assets
.keys()
.map(|(plugin_id, _client_id)| *plugin_id)
.collect();
unique_plugins.drain().into_iter().collect()
}
pub fn running_plugins(&mut self) -> Vec<(PluginId, ClientId, Arc<Mutex<RunningPlugin>>)> {
self.plugin_assets
.iter()
.map(|((plugin_id, client_id), (running_plugin, _, _))| {
(*plugin_id, *client_id, running_plugin.clone())
})
.collect()
}
pub fn running_plugins_and_subscriptions(
&mut self,
) -> Vec<(
PluginId,
ClientId,
Arc<Mutex<RunningPlugin>>,
Arc<Mutex<Subscriptions>>,
)> {
self.plugin_assets
.iter()
.map(
|((plugin_id, client_id), (running_plugin, subscriptions, _))| {
(
*plugin_id,
*client_id,
running_plugin.clone(),
subscriptions.clone(),
)
},
)
.collect()
}
pub fn get_running_plugin_and_subscriptions(
&self,
plugin_id: PluginId,
client_id: ClientId,
) -> Option<(Arc<Mutex<RunningPlugin>>, Arc<Mutex<Subscriptions>>)> {
self.plugin_assets.get(&(plugin_id, client_id)).and_then(
|(running_plugin, subscriptions, _)| {
Some((running_plugin.clone(), subscriptions.clone()))
},
)
}
pub fn get_running_plugin(
&self,
plugin_id: PluginId,
client_id: Option<ClientId>,
) -> Option<Arc<Mutex<RunningPlugin>>> {
match client_id {
Some(client_id) => self
.plugin_assets
.get(&(plugin_id, client_id))
.and_then(|(running_plugin, _, _)| Some(running_plugin.clone())),
None => self
.plugin_assets
.iter()
.find(|((p_id, _), _)| *p_id == plugin_id)
.and_then(|(_, (running_plugin, _, _))| Some(running_plugin.clone())),
}
}
pub fn worker_sender(
&self,
plugin_id: PluginId,
client_id: ClientId,
worker_name: &str,
) -> Option<Sender<MessageToWorker>> {
self.plugin_assets
.iter()
.find(|((p_id, c_id), _)| p_id == &plugin_id && c_id == &client_id)
.and_then(|(_, (_running_plugin, _subscriptions, workers))| {
if let Some(worker) = workers.get(&format!("{}_worker", worker_name)) {
Some(worker.clone())
} else {
None
}
})
.clone()
}
pub fn all_plugin_ids_for_plugin_location(
&self,
plugin_location: &RunPluginLocation,
plugin_configuration: &PluginUserConfiguration,
) -> Result<Vec<PluginId>> {
let err_context = || format!("Failed to get plugin ids for location {plugin_location}");
let plugin_ids: Vec<PluginId> = self
.plugin_assets
.iter()
.filter(|(_, (running_plugin, _subscriptions, _workers))| {
let running_plugin = running_plugin.lock().unwrap();
let plugin_config = &running_plugin.store.data().plugin;
let running_plugin_location = &plugin_config.location;
let running_plugin_configuration = &plugin_config.userspace_configuration;
running_plugin_location == plugin_location
&& running_plugin_configuration == plugin_configuration
})
.map(|((plugin_id, _client_id), _)| *plugin_id)
.collect();
if plugin_ids.is_empty() {
return Err(ZellijError::PluginDoesNotExist).with_context(err_context);
}
Ok(plugin_ids)
}
pub fn clone_plugin_assets(
&self,
) -> HashMap<RunPluginLocation, HashMap<PluginUserConfiguration, Vec<(PluginId, ClientId)>>>
{
let mut cloned_plugin_assets: HashMap<
RunPluginLocation,
HashMap<PluginUserConfiguration, Vec<(PluginId, ClientId)>>,
> = HashMap::new();
for ((plugin_id, client_id), (running_plugin, _, _)) in self.plugin_assets.iter() {
let running_plugin = running_plugin.lock().unwrap();
let plugin_config = &running_plugin.store.data().plugin;
let running_plugin_location = &plugin_config.location;
let running_plugin_configuration = &plugin_config.userspace_configuration;
match cloned_plugin_assets.get_mut(running_plugin_location) {
Some(location_map) => match location_map.get_mut(running_plugin_configuration) {
Some(plugin_instances_info) => {
plugin_instances_info.push((*plugin_id, *client_id));
},
None => {
location_map.insert(
running_plugin_configuration.clone(),
vec![(*plugin_id, *client_id)],
);
},
},
None => {
let mut location_map = HashMap::new();
location_map.insert(
running_plugin_configuration.clone(),
vec![(*plugin_id, *client_id)],
);
cloned_plugin_assets.insert(running_plugin_location.clone(), location_map);
},
}
}
cloned_plugin_assets
}
pub fn all_plugin_ids(&self) -> Vec<(PluginId, ClientId)> {
self.plugin_assets
.iter()
.map(|((plugin_id, client_id), _)| (*plugin_id, *client_id))
.collect()
}
pub fn insert(
&mut self,
plugin_id: PluginId,
client_id: ClientId,
running_plugin: Arc<Mutex<RunningPlugin>>,
subscriptions: Arc<Mutex<Subscriptions>>,
running_workers: HashMap<String, Sender<MessageToWorker>>,
) {
self.plugin_assets.insert(
(plugin_id, client_id),
(running_plugin, subscriptions, running_workers),
);
}
pub fn run_plugin_of_plugin_id(&self, plugin_id: PluginId) -> Option<RunPlugin> {
self.plugin_assets
.iter()
.find_map(|((p_id, _), (running_plugin, _, _))| {
if *p_id == plugin_id {
let running_plugin = running_plugin.lock().unwrap();
let plugin_config = &running_plugin.store.data().plugin;
let run_plugin_location = plugin_config.location.clone();
let run_plugin_configuration = plugin_config.userspace_configuration.clone();
let initial_cwd = plugin_config.initial_cwd.clone();
Some(RunPlugin {
_allow_exec_host_cmd: false,
location: run_plugin_location,
configuration: run_plugin_configuration,
initial_cwd,
})
} else {
None
}
})
}
pub fn list_plugins(&self) -> BTreeMap<PluginId, RunPlugin> {
let all_plugin_ids: HashSet<PluginId> = self
.all_plugin_ids()
.into_iter()
.map(|(plugin_id, _client_id)| plugin_id)
.collect();
let mut plugin_ids_to_cmds: BTreeMap<u32, RunPlugin> = BTreeMap::new();
for plugin_id in all_plugin_ids {
let plugin_cmd = self.run_plugin_of_plugin_id(plugin_id);
match plugin_cmd {
Some(plugin_cmd) => {
plugin_ids_to_cmds.insert(plugin_id, plugin_cmd.clone());
},
None => log::error!("Plugin with id: {plugin_id} not found"),
}
}
plugin_ids_to_cmds
}
}
pub type Subscriptions = HashSet<EventType>;
pub struct PluginEnv {
pub plugin_id: PluginId,
pub plugin: PluginConfig,
pub permissions: Arc<Mutex<Option<HashSet<PermissionType>>>>,
pub senders: ThreadSenders,
pub wasi_ctx: WasiCtx,
pub tab_index: Option<usize>,
pub client_id: ClientId,
#[allow(dead_code)]
pub plugin_own_data_dir: PathBuf,
pub plugin_own_cache_dir: PathBuf,
pub path_to_default_shell: PathBuf,
pub capabilities: PluginCapabilities,
pub client_attributes: ClientAttributes,
pub default_shell: Option<TerminalAction>,
pub default_layout: Box<Layout>,
pub layout_dir: Option<PathBuf>,
pub plugin_cwd: PathBuf,
pub input_pipes_to_unblock: Arc<Mutex<HashSet<String>>>,
pub input_pipes_to_block: Arc<Mutex<HashSet<String>>>,
pub default_mode: InputMode,
pub subscriptions: Arc<Mutex<Subscriptions>>,
pub stdin_pipe: Arc<Mutex<VecDeque<u8>>>,
pub stdout_pipe: Arc<Mutex<VecDeque<u8>>>,
pub keybinds: Keybinds,
pub intercepting_key_presses: bool,
pub store_limits: StoreLimits,
}
#[derive(Clone)]
pub struct VecDequeInputStream(pub Arc<Mutex<VecDeque<u8>>>);
impl std::io::Read for VecDequeInputStream {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let mut inner = self.0.lock().unwrap();
let len = std::cmp::min(buf.len(), inner.len());
for (i, byte) in inner.drain(0..len).enumerate() {
buf[i] = byte;
}
Ok(len)
}
}
pub struct WriteOutputStream<T>(pub Arc<Mutex<T>>);
impl<T> Clone for WriteOutputStream<T> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<T: Write + Send + 'static> std::io::Write for WriteOutputStream<T> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let mut inner = self.0.lock().unwrap();
inner.write(buf)
}
fn flush(&mut self) -> std::io::Result<()> {
let mut inner = self.0.lock().unwrap();
inner.flush()
}
}
impl PluginEnv {
// Get the name (path) of the containing plugin
pub fn name(&self) -> String {
format!(
"{} (ID {})",
self.plugin.path.display().to_string(),
self.plugin_id
)
}
pub fn set_permissions(&mut self, permissions: HashSet<PermissionType>) {
self.permissions.lock().unwrap().replace(permissions);
}
}
#[derive(Eq, PartialEq, Hash)]
pub enum AtomicEvent {
Resize,
}
pub struct RunningPlugin {
pub store: Store<PluginEnv>,
pub instance: Instance,
pub rows: usize,
pub columns: usize,
next_event_ids: HashMap<AtomicEvent, usize>,
last_applied_event_ids: HashMap<AtomicEvent, usize>,
}
impl RunningPlugin {
pub fn new(store: Store<PluginEnv>, instance: Instance, rows: usize, columns: usize) -> Self {
RunningPlugin {
store,
instance,
rows,
columns,
next_event_ids: HashMap::new(),
last_applied_event_ids: HashMap::new(),
}
}
pub fn next_event_id(&mut self, atomic_event: AtomicEvent) -> usize {
let current_event_id = *self.next_event_ids.get(&atomic_event).unwrap_or(&0);
if current_event_id < usize::MAX {
let next_event_id = current_event_id + 1;
self.next_event_ids.insert(atomic_event, next_event_id);
current_event_id
} else {
let current_event_id = 0;
let next_event_id = 1;
self.last_applied_event_ids.remove(&atomic_event);
self.next_event_ids.insert(atomic_event, next_event_id);
current_event_id
}
}
pub fn apply_event_id(&mut self, atomic_event: AtomicEvent, event_id: usize) -> bool {
if &event_id >= self.last_applied_event_ids.get(&atomic_event).unwrap_or(&0) {
self.last_applied_event_ids.insert(atomic_event, event_id);
true
} else {
false
}
}
pub fn update_keybinds(&mut self, keybinds: Keybinds) {
self.store.data_mut().keybinds = keybinds;
}
pub fn update_default_mode(&mut self, default_mode: InputMode) {
self.store.data_mut().default_mode = default_mode;
}
pub fn update_default_shell(&mut self, default_shell: Option<TerminalAction>) {
self.store.data_mut().default_shell = default_shell;
}
pub fn intercepting_key_presses(&self) -> bool {
self.store.data().intercepting_key_presses
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/plugins/unit/plugin_tests.rs | zellij-server/src/plugins/unit/plugin_tests.rs | use super::plugin_thread_main;
use crate::screen::ScreenInstruction;
use crate::{channels::SenderWithContext, thread_bus::Bus, ServerInstruction};
use insta::assert_snapshot;
use lazy_static::lazy_static;
use std::collections::BTreeMap;
use std::path::PathBuf;
use tempfile::tempdir;
use wasmi::Engine;
use zellij_utils::data::{
BareKey, Event, InputMode, KeyWithModifier, PermissionStatus, PermissionType,
PluginCapabilities,
};
use zellij_utils::errors::ErrorContext;
use zellij_utils::input::keybinds::Keybinds;
use zellij_utils::input::layout::{
Layout, PluginAlias, PluginUserConfiguration, RunPlugin, RunPluginLocation, RunPluginOrAlias,
};
use zellij_utils::input::permission::PermissionCache;
use zellij_utils::input::plugins::PluginAliases;
use zellij_utils::ipc::ClientAttributes;
use zellij_utils::pane_size::Size;
use crate::background_jobs::BackgroundJob;
use crate::pty_writer::PtyWriteInstruction;
use std::env::set_var;
use std::sync::{Arc, Mutex};
use crate::{plugins::PluginInstruction, pty::PtyInstruction};
use zellij_utils::channels::{self, ChannelWithContext, Receiver};
macro_rules! log_actions_in_thread {
( $arc_mutex_log:expr, $exit_event:path, $receiver:expr, $exit_after_count:expr ) => {
std::thread::Builder::new()
.name("logger thread".to_string())
.spawn({
let log = $arc_mutex_log.clone();
let mut exit_event_count = 0;
move || loop {
let (event, _err_ctx) = $receiver
.recv()
.expect("failed to receive event on channel");
match event {
$exit_event(..) => {
exit_event_count += 1;
log.lock().unwrap().push(event);
if exit_event_count == $exit_after_count {
break;
}
},
_ => {
log.lock().unwrap().push(event);
},
}
}
})
.unwrap()
};
}
macro_rules! log_actions_in_thread_struct {
( $arc_mutex_log:expr, $exit_event:path, $receiver:expr, $exit_after_count:expr ) => {
std::thread::Builder::new()
.name("logger thread".to_string())
.spawn({
let log = $arc_mutex_log.clone();
let mut exit_event_count = 0;
move || loop {
let (event, _err_ctx) = $receiver
.recv()
.expect("failed to receive event on channel");
match event {
$exit_event { .. } => {
exit_event_count += 1;
log.lock().unwrap().push(event);
if exit_event_count == $exit_after_count {
break;
}
},
_ => {
log.lock().unwrap().push(event);
},
}
}
})
.unwrap()
};
}
macro_rules! grant_permissions_and_log_actions_in_thread {
( $arc_mutex_log:expr, $exit_event:path, $receiver:expr, $exit_after_count:expr, $permission_type:expr, $cache_path:expr, $plugin_thread_sender:expr, $client_id:expr ) => {
std::thread::Builder::new()
.name("fake_screen_thread".to_string())
.spawn({
let log = $arc_mutex_log.clone();
let mut exit_event_count = 0;
let cache_path = $cache_path.clone();
let plugin_thread_sender = $plugin_thread_sender.clone();
move || loop {
let (event, _err_ctx) = $receiver
.recv()
.expect("failed to receive event on channel");
match event {
$exit_event(..) => {
exit_event_count += 1;
log.lock().unwrap().push(event);
if exit_event_count == $exit_after_count {
break;
}
},
ScreenInstruction::RequestPluginPermissions(_, plugin_permission) => {
if plugin_permission.permissions.contains($permission_type) {
let _ = plugin_thread_sender.send(
PluginInstruction::PermissionRequestResult(
0,
Some($client_id),
plugin_permission.permissions,
PermissionStatus::Granted,
Some(cache_path.clone()),
),
);
} else {
let _ = plugin_thread_sender.send(
PluginInstruction::PermissionRequestResult(
0,
Some($client_id),
plugin_permission.permissions,
PermissionStatus::Denied,
Some(cache_path.clone()),
),
);
}
},
_ => {
log.lock().unwrap().push(event);
},
}
}
})
.unwrap()
};
}
macro_rules! deny_permissions_and_log_actions_in_thread {
( $arc_mutex_log:expr, $exit_event:path, $receiver:expr, $exit_after_count:expr, $permission_type:expr, $cache_path:expr, $plugin_thread_sender:expr, $client_id:expr ) => {
std::thread::Builder::new()
.name("fake_screen_thread".to_string())
.spawn({
let log = $arc_mutex_log.clone();
let mut exit_event_count = 0;
let cache_path = $cache_path.clone();
let plugin_thread_sender = $plugin_thread_sender.clone();
move || loop {
let (event, _err_ctx) = $receiver
.recv()
.expect("failed to receive event on channel");
match event {
$exit_event(..) => {
exit_event_count += 1;
log.lock().unwrap().push(event);
if exit_event_count == $exit_after_count {
break;
}
},
ScreenInstruction::RequestPluginPermissions(_, plugin_permission) => {
let _ = plugin_thread_sender.send(
PluginInstruction::PermissionRequestResult(
0,
Some($client_id),
plugin_permission.permissions,
PermissionStatus::Denied,
Some(cache_path.clone()),
),
);
break;
},
_ => {
log.lock().unwrap().push(event);
},
}
}
})
.unwrap()
};
}
macro_rules! grant_permissions_and_log_actions_in_thread_naked_variant {
( $arc_mutex_log:expr, $exit_event:path, $receiver:expr, $exit_after_count:expr, $permission_type:expr, $cache_path:expr, $plugin_thread_sender:expr, $client_id:expr ) => {
std::thread::Builder::new()
.name("fake_screen_thread".to_string())
.spawn({
let log = $arc_mutex_log.clone();
let mut exit_event_count = 0;
let cache_path = $cache_path.clone();
let plugin_thread_sender = $plugin_thread_sender.clone();
move || loop {
let (event, _err_ctx) = $receiver
.recv()
.expect("failed to receive event on channel");
match event {
$exit_event => {
exit_event_count += 1;
log.lock().unwrap().push(event);
if exit_event_count == $exit_after_count {
break;
}
},
ScreenInstruction::RequestPluginPermissions(_, plugin_permission) => {
if plugin_permission.permissions.contains($permission_type) {
let _ = plugin_thread_sender.send(
PluginInstruction::PermissionRequestResult(
0,
Some($client_id),
plugin_permission.permissions,
PermissionStatus::Granted,
Some(cache_path.clone()),
),
);
} else {
let _ = plugin_thread_sender.send(
PluginInstruction::PermissionRequestResult(
0,
Some($client_id),
plugin_permission.permissions,
PermissionStatus::Denied,
Some(cache_path.clone()),
),
);
}
},
_ => {
log.lock().unwrap().push(event);
},
}
}
})
.unwrap()
};
}
macro_rules! grant_permissions_and_log_actions_in_thread_struct_variant {
( $arc_mutex_log:expr, $exit_event:path, $receiver:expr, $exit_after_count:expr, $permission_type:expr, $cache_path:expr, $plugin_thread_sender:expr, $client_id:expr ) => {
std::thread::Builder::new()
.name("fake_screen_thread".to_string())
.spawn({
let log = $arc_mutex_log.clone();
let mut exit_event_count = 0;
let cache_path = $cache_path.clone();
let plugin_thread_sender = $plugin_thread_sender.clone();
move || loop {
let (event, _err_ctx) = $receiver
.recv()
.expect("failed to receive event on channel");
match event {
$exit_event { .. } => {
exit_event_count += 1;
log.lock().unwrap().push(event);
if exit_event_count == $exit_after_count {
break;
}
},
ScreenInstruction::RequestPluginPermissions(_, plugin_permission) => {
if plugin_permission.permissions.contains($permission_type) {
let _ = plugin_thread_sender.send(
PluginInstruction::PermissionRequestResult(
0,
Some($client_id),
plugin_permission.permissions,
PermissionStatus::Granted,
Some(cache_path.clone()),
),
);
} else {
let _ = plugin_thread_sender.send(
PluginInstruction::PermissionRequestResult(
0,
Some($client_id),
plugin_permission.permissions,
PermissionStatus::Denied,
Some(cache_path.clone()),
),
);
}
},
_ => {
log.lock().unwrap().push(event);
},
}
}
})
.unwrap()
};
}
fn create_plugin_thread(
zellij_cwd: Option<PathBuf>,
) -> (
SenderWithContext<PluginInstruction>,
Receiver<(ScreenInstruction, ErrorContext)>,
Box<dyn FnOnce()>,
) {
let zellij_cwd = zellij_cwd.unwrap_or_else(|| PathBuf::from("."));
let initiating_client_id = 1;
let (to_server, _server_receiver): ChannelWithContext<ServerInstruction> =
channels::bounded(50);
let to_server = SenderWithContext::new(to_server);
let (to_screen, screen_receiver): ChannelWithContext<ScreenInstruction> = channels::unbounded();
let to_screen = SenderWithContext::new(to_screen);
let (to_plugin, plugin_receiver): ChannelWithContext<PluginInstruction> = channels::unbounded();
let to_plugin = SenderWithContext::new(to_plugin);
let (to_pty, _pty_receiver): ChannelWithContext<PtyInstruction> = channels::unbounded();
let to_pty = SenderWithContext::new(to_pty);
let (to_pty_writer, _pty_writer_receiver): ChannelWithContext<PtyWriteInstruction> =
channels::unbounded();
let to_pty_writer = SenderWithContext::new(to_pty_writer);
let (to_background_jobs, _background_jobs_receiver): ChannelWithContext<BackgroundJob> =
channels::unbounded();
let to_background_jobs = SenderWithContext::new(to_background_jobs);
let plugin_bus = Bus::new(
vec![plugin_receiver],
Some(&to_screen),
Some(&to_pty),
Some(&to_plugin),
Some(&to_server),
Some(&to_pty_writer),
Some(&to_background_jobs),
None,
)
.should_silently_fail();
let mut config = wasmi::Config::default();
config.set_max_stack_height(1024 * 1024);
config.set_max_recursion_depth(1000);
let engine = Engine::new(&config);
let data_dir = PathBuf::from(tempdir().unwrap().path());
let default_shell = PathBuf::from(".");
let plugin_capabilities = PluginCapabilities::default();
let client_attributes = ClientAttributes::default();
let default_shell_action = None; // TODO: change me
let mut plugin_aliases = PluginAliases::default();
plugin_aliases.aliases.insert(
"fixture_plugin_for_tests".to_owned(),
RunPlugin::from_url(&format!(
"file:{}/../target/e2e-data/plugins/fixture-plugin-for-tests.wasm",
std::env::var_os("CARGO_MANIFEST_DIR")
.unwrap()
.to_string_lossy()
))
.unwrap(),
);
let plugin_thread = std::thread::Builder::new()
.name("plugin_thread".to_string())
.spawn(move || {
set_var("ZELLIJ_SESSION_NAME", "zellij-test");
plugin_thread_main(
plugin_bus,
engine,
data_dir,
Box::new(Layout::default()),
None,
default_shell,
zellij_cwd,
plugin_capabilities,
client_attributes,
default_shell_action,
plugin_aliases,
InputMode::Normal,
Keybinds::default(),
Default::default(),
initiating_client_id,
)
.expect("TEST")
})
.unwrap();
let teardown = {
let to_plugin = to_plugin.clone();
move || {
let _ = to_pty.send(PtyInstruction::Exit);
let _ = to_pty_writer.send(PtyWriteInstruction::Exit);
let _ = to_screen.send(ScreenInstruction::Exit);
let _ = to_server.send(ServerInstruction::KillSession);
let _ = to_plugin.send(PluginInstruction::Exit);
let _ = plugin_thread.join();
}
};
(to_plugin, screen_receiver, Box::new(teardown))
}
fn create_plugin_thread_with_server_receiver(
zellij_cwd: Option<PathBuf>,
) -> (
SenderWithContext<PluginInstruction>,
Receiver<(ServerInstruction, ErrorContext)>,
Receiver<(ScreenInstruction, ErrorContext)>,
Box<dyn FnOnce()>,
) {
let zellij_cwd = zellij_cwd.unwrap_or_else(|| PathBuf::from("."));
let (to_server, server_receiver): ChannelWithContext<ServerInstruction> = channels::bounded(50);
let to_server = SenderWithContext::new(to_server);
let (to_screen, screen_receiver): ChannelWithContext<ScreenInstruction> = channels::unbounded();
let to_screen = SenderWithContext::new(to_screen);
let (to_plugin, plugin_receiver): ChannelWithContext<PluginInstruction> = channels::unbounded();
let to_plugin = SenderWithContext::new(to_plugin);
let (to_pty, _pty_receiver): ChannelWithContext<PtyInstruction> = channels::unbounded();
let to_pty = SenderWithContext::new(to_pty);
let (to_pty_writer, _pty_writer_receiver): ChannelWithContext<PtyWriteInstruction> =
channels::unbounded();
let to_pty_writer = SenderWithContext::new(to_pty_writer);
let (to_background_jobs, _background_jobs_receiver): ChannelWithContext<BackgroundJob> =
channels::unbounded();
let to_background_jobs = SenderWithContext::new(to_background_jobs);
let plugin_bus = Bus::new(
vec![plugin_receiver],
Some(&to_screen),
Some(&to_pty),
Some(&to_plugin),
Some(&to_server),
Some(&to_pty_writer),
Some(&to_background_jobs),
None,
)
.should_silently_fail();
let mut config = wasmi::Config::default();
config.set_max_stack_height(1024 * 1024);
config.set_max_recursion_depth(1000);
let engine = Engine::new(&config);
let data_dir = PathBuf::from(tempdir().unwrap().path());
let default_shell = PathBuf::from(".");
let plugin_capabilities = PluginCapabilities::default();
let client_attributes = ClientAttributes::default();
let default_shell_action = None; // TODO: change me
let initiating_client_id = 1;
let plugin_thread = std::thread::Builder::new()
.name("plugin_thread".to_string())
.spawn(move || {
set_var("ZELLIJ_SESSION_NAME", "zellij-test");
plugin_thread_main(
plugin_bus,
engine,
data_dir,
Box::new(Layout::default()),
None,
default_shell,
zellij_cwd,
plugin_capabilities,
client_attributes,
default_shell_action,
PluginAliases::default(),
InputMode::Normal,
Keybinds::default(),
Default::default(),
initiating_client_id,
)
.expect("TEST");
})
.unwrap();
let teardown = {
let to_plugin = to_plugin.clone();
move || {
let _ = to_pty.send(PtyInstruction::Exit);
let _ = to_pty_writer.send(PtyWriteInstruction::Exit);
let _ = to_screen.send(ScreenInstruction::Exit);
let _ = to_server.send(ServerInstruction::KillSession);
let _ = to_plugin.send(PluginInstruction::Exit);
let _ = plugin_thread.join();
}
};
(
to_plugin,
server_receiver,
screen_receiver,
Box::new(teardown),
)
}
fn create_plugin_thread_with_pty_receiver(
zellij_cwd: Option<PathBuf>,
) -> (
SenderWithContext<PluginInstruction>,
Receiver<(PtyInstruction, ErrorContext)>,
Receiver<(ScreenInstruction, ErrorContext)>,
Box<dyn FnOnce()>,
) {
let zellij_cwd = zellij_cwd.unwrap_or_else(|| PathBuf::from("."));
let (to_server, _server_receiver): ChannelWithContext<ServerInstruction> =
channels::bounded(50);
let to_server = SenderWithContext::new(to_server);
let (to_screen, screen_receiver): ChannelWithContext<ScreenInstruction> = channels::unbounded();
let to_screen = SenderWithContext::new(to_screen);
let (to_plugin, plugin_receiver): ChannelWithContext<PluginInstruction> = channels::unbounded();
let to_plugin = SenderWithContext::new(to_plugin);
let (to_pty, pty_receiver): ChannelWithContext<PtyInstruction> = channels::unbounded();
let to_pty = SenderWithContext::new(to_pty);
let (to_pty_writer, _pty_writer_receiver): ChannelWithContext<PtyWriteInstruction> =
channels::unbounded();
let to_pty_writer = SenderWithContext::new(to_pty_writer);
let (to_background_jobs, _background_jobs_receiver): ChannelWithContext<BackgroundJob> =
channels::unbounded();
let to_background_jobs = SenderWithContext::new(to_background_jobs);
let plugin_bus = Bus::new(
vec![plugin_receiver],
Some(&to_screen),
Some(&to_pty),
Some(&to_plugin),
Some(&to_server),
Some(&to_pty_writer),
Some(&to_background_jobs),
None,
)
.should_silently_fail();
let mut config = wasmi::Config::default();
config.set_max_stack_height(1024 * 1024);
config.set_max_recursion_depth(1000);
let engine = Engine::new(&config);
let data_dir = PathBuf::from(tempdir().unwrap().path());
let default_shell = PathBuf::from(".");
let plugin_capabilities = PluginCapabilities::default();
let client_attributes = ClientAttributes::default();
let default_shell_action = None; // TODO: change me
let initiating_client_id = 1;
let plugin_thread = std::thread::Builder::new()
.name("plugin_thread".to_string())
.spawn(move || {
set_var("ZELLIJ_SESSION_NAME", "zellij-test");
plugin_thread_main(
plugin_bus,
engine,
data_dir,
Box::new(Layout::default()),
None,
default_shell,
zellij_cwd,
plugin_capabilities,
client_attributes,
default_shell_action,
PluginAliases::default(),
InputMode::Normal,
Keybinds::default(),
Default::default(),
initiating_client_id,
)
.expect("TEST")
})
.unwrap();
let teardown = {
let to_plugin = to_plugin.clone();
move || {
let _ = to_pty.send(PtyInstruction::Exit);
let _ = to_pty_writer.send(PtyWriteInstruction::Exit);
let _ = to_screen.send(ScreenInstruction::Exit);
let _ = to_server.send(ServerInstruction::KillSession);
let _ = to_plugin.send(PluginInstruction::Exit);
let _ = plugin_thread.join();
}
};
(to_plugin, pty_receiver, screen_receiver, Box::new(teardown))
}
fn create_plugin_thread_with_background_jobs_receiver(
zellij_cwd: Option<PathBuf>,
) -> (
SenderWithContext<PluginInstruction>,
Receiver<(BackgroundJob, ErrorContext)>,
Receiver<(ScreenInstruction, ErrorContext)>,
Box<dyn FnOnce()>,
) {
let zellij_cwd = zellij_cwd.unwrap_or_else(|| PathBuf::from("."));
let (to_server, _server_receiver): ChannelWithContext<ServerInstruction> =
channels::bounded(50);
let to_server = SenderWithContext::new(to_server);
let (to_screen, screen_receiver): ChannelWithContext<ScreenInstruction> = channels::unbounded();
let to_screen = SenderWithContext::new(to_screen);
let (to_plugin, plugin_receiver): ChannelWithContext<PluginInstruction> = channels::unbounded();
let to_plugin = SenderWithContext::new(to_plugin);
let (to_pty, _pty_receiver): ChannelWithContext<PtyInstruction> = channels::unbounded();
let to_pty = SenderWithContext::new(to_pty);
let (to_pty_writer, _pty_writer_receiver): ChannelWithContext<PtyWriteInstruction> =
channels::unbounded();
let to_pty_writer = SenderWithContext::new(to_pty_writer);
let (to_background_jobs, background_jobs_receiver): ChannelWithContext<BackgroundJob> =
channels::unbounded();
let to_background_jobs = SenderWithContext::new(to_background_jobs);
let plugin_bus = Bus::new(
vec![plugin_receiver],
Some(&to_screen),
Some(&to_pty),
Some(&to_plugin),
Some(&to_server),
Some(&to_pty_writer),
Some(&to_background_jobs),
None,
)
.should_silently_fail();
let mut config = wasmi::Config::default();
config.set_max_stack_height(1024 * 1024);
config.set_max_recursion_depth(1000);
let engine = Engine::new(&config);
let data_dir = PathBuf::from(tempdir().unwrap().path());
let default_shell = PathBuf::from(".");
let plugin_capabilities = PluginCapabilities::default();
let client_attributes = ClientAttributes::default();
let default_shell_action = None; // TODO: change me
let initiating_client_id = 1;
let plugin_thread = std::thread::Builder::new()
.name("plugin_thread".to_string())
.spawn(move || {
set_var("ZELLIJ_SESSION_NAME", "zellij-test");
plugin_thread_main(
plugin_bus,
engine,
data_dir,
Box::new(Layout::default()),
None,
default_shell,
zellij_cwd,
plugin_capabilities,
client_attributes,
default_shell_action,
PluginAliases::default(),
InputMode::Normal,
Keybinds::default(),
Default::default(),
initiating_client_id,
)
.expect("TEST")
})
.unwrap();
let teardown = {
let to_plugin = to_plugin.clone();
move || {
let _ = to_pty.send(PtyInstruction::Exit);
let _ = to_pty_writer.send(PtyWriteInstruction::Exit);
let _ = to_screen.send(ScreenInstruction::Exit);
let _ = to_server.send(ServerInstruction::KillSession);
let _ = to_plugin.send(PluginInstruction::Exit);
let _ = to_background_jobs.send(BackgroundJob::Exit);
let _ = plugin_thread.join();
}
};
(
to_plugin,
background_jobs_receiver,
screen_receiver,
Box::new(teardown),
)
}
lazy_static! {
static ref PLUGIN_FIXTURE: String = format!(
// to populate this file, make sure to run the build-e2e CI job
// (or compile the fixture plugin and copy the resulting .wasm blob to the below location)
"{}/../target/e2e-data/plugins/fixture-plugin-for-tests.wasm",
std::env::var_os("CARGO_MANIFEST_DIR")
.unwrap()
.to_string_lossy()
);
}
#[test]
#[ignore]
pub fn load_new_plugin_from_hd() {
// here we load our fixture plugin into the plugin thread, and then send it an update message
// expecting tha thte plugin will log the received event and render it later after the update
// message (this is what the fixture plugin does)
// we then listen on our mock screen receiver to make sure we got a PluginBytes instruction
// that contains said render, and assert against it
let temp_folder = tempdir().unwrap(); // placed explicitly in the test scope because its
let plugin_host_folder = PathBuf::from(temp_folder.path());
let cache_path = plugin_host_folder.join("permissions_test.kdl");
let (plugin_thread_sender, screen_receiver, teardown) = create_plugin_thread(None);
let plugin_should_float = Some(false);
let plugin_title = Some("test_plugin".to_owned());
let run_plugin = RunPluginOrAlias::RunPlugin(RunPlugin {
_allow_exec_host_cmd: false,
location: RunPluginLocation::File(PathBuf::from(&*PLUGIN_FIXTURE)),
configuration: Default::default(),
..Default::default()
});
let tab_index = 1;
let client_id = 1;
let size = Size {
cols: 121,
rows: 20,
};
let received_screen_instructions = Arc::new(Mutex::new(vec![]));
let screen_thread = grant_permissions_and_log_actions_in_thread!(
received_screen_instructions,
ScreenInstruction::PluginBytes,
screen_receiver,
2,
&PermissionType::ChangeApplicationState,
cache_path,
plugin_thread_sender,
client_id
);
let _ = plugin_thread_sender.send(PluginInstruction::AddClient(client_id));
let _ = plugin_thread_sender.send(PluginInstruction::Load(
plugin_should_float,
false,
plugin_title,
run_plugin,
Some(tab_index),
None,
client_id,
size,
None,
None,
false,
None,
None,
None,
));
std::thread::sleep(std::time::Duration::from_millis(500));
let _ = plugin_thread_sender.send(PluginInstruction::Update(vec![(
None,
Some(client_id),
Event::InputReceived,
)])); // will be cached and sent to the plugin once it's loaded
screen_thread.join().unwrap(); // this might take a while if the cache is cold
teardown();
let plugin_bytes_event = received_screen_instructions
.lock()
.unwrap()
.iter()
.find_map(|i| {
if let ScreenInstruction::PluginBytes(plugin_render_assets) = i {
for plugin_render_asset in plugin_render_assets {
let plugin_id = plugin_render_asset.plugin_id;
let client_id = plugin_render_asset.client_id;
let plugin_bytes = plugin_render_asset.bytes.clone();
let plugin_bytes = String::from_utf8_lossy(plugin_bytes.as_slice()).to_string();
if plugin_bytes.contains("InputReceived") {
return Some((plugin_id, client_id, plugin_bytes));
}
}
}
None
});
assert_snapshot!(format!("{:#?}", plugin_bytes_event));
}
#[test]
#[ignore]
pub fn load_new_plugin_with_plugin_alias() {
// here we load our fixture plugin into the plugin thread, and then send it an update message
// expecting tha thte plugin will log the received event and render it later after the update
// message (this is what the fixture plugin does)
// we then listen on our mock screen receiver to make sure we got a PluginBytes instruction
// that contains said render, and assert against it
let temp_folder = tempdir().unwrap(); // placed explicitly in the test scope because its
let plugin_host_folder = PathBuf::from(temp_folder.path());
let cache_path = plugin_host_folder.join("permissions_test.kdl");
let (plugin_thread_sender, screen_receiver, teardown) = create_plugin_thread(None);
let plugin_should_float = Some(false);
let plugin_title = Some("test_plugin".to_owned());
let run_plugin = RunPluginOrAlias::Alias(PluginAlias {
name: "fixture_plugin_for_tests".to_owned(),
configuration: Default::default(),
run_plugin: None,
..Default::default()
});
let tab_index = 1;
let client_id = 1;
let size = Size {
cols: 121,
rows: 20,
};
let received_screen_instructions = Arc::new(Mutex::new(vec![]));
let screen_thread = grant_permissions_and_log_actions_in_thread!(
received_screen_instructions,
ScreenInstruction::PluginBytes,
screen_receiver,
2,
&PermissionType::ChangeApplicationState,
cache_path,
plugin_thread_sender,
client_id
);
let _ = plugin_thread_sender.send(PluginInstruction::AddClient(client_id));
let _ = plugin_thread_sender.send(PluginInstruction::Load(
plugin_should_float,
false,
plugin_title,
run_plugin,
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/panes/active_panes.rs | zellij-server/src/panes/active_panes.rs | use crate::tab::Pane;
use crate::{os_input_output::ServerOsApi, panes::PaneId, ClientId};
use std::collections::{BTreeMap, HashMap};
#[derive(Clone)]
pub struct ActivePanes {
active_panes: HashMap<ClientId, PaneId>,
os_api: Box<dyn ServerOsApi>,
}
impl std::fmt::Debug for ActivePanes {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self.active_panes)
}
}
impl ActivePanes {
pub fn new(os_api: &Box<dyn ServerOsApi>) -> Self {
let os_api = os_api.clone();
ActivePanes {
active_panes: HashMap::new(),
os_api,
}
}
pub fn get(&self, client_id: &ClientId) -> Option<&PaneId> {
self.active_panes.get(client_id)
}
pub fn insert(
&mut self,
client_id: ClientId,
pane_id: PaneId,
panes: &mut BTreeMap<PaneId, Box<dyn Pane>>,
) {
self.unfocus_pane_for_client(client_id, panes);
self.active_panes.insert(client_id, pane_id);
self.focus_pane(pane_id, panes);
}
pub fn clear(&mut self, panes: &mut BTreeMap<PaneId, Box<dyn Pane>>) {
for pane_id in self.active_panes.values() {
self.unfocus_pane(*pane_id, panes);
}
self.active_panes.clear();
}
pub fn is_empty(&self) -> bool {
self.active_panes.is_empty()
}
pub fn iter(&self) -> impl Iterator<Item = (&ClientId, &PaneId)> {
self.active_panes.iter()
}
pub fn values(&self) -> impl Iterator<Item = &PaneId> {
self.active_panes.values()
}
pub fn remove(
&mut self,
client_id: &ClientId,
panes: &mut BTreeMap<PaneId, Box<dyn Pane>>,
) -> Option<PaneId> {
if let Some(pane_id_to_unfocus) = self.active_panes.get(&client_id) {
self.unfocus_pane(*pane_id_to_unfocus, panes);
}
self.active_panes.remove(client_id)
}
pub fn unfocus_all_panes(&self, panes: &mut BTreeMap<PaneId, Box<dyn Pane>>) {
for (_client_id, pane_id) in &self.active_panes {
self.unfocus_pane(*pane_id, panes);
}
}
pub fn focus_all_panes(&self, panes: &mut BTreeMap<PaneId, Box<dyn Pane>>) {
for (_client_id, pane_id) in &self.active_panes {
self.focus_pane(*pane_id, panes);
}
}
pub fn clone_active_panes(&self) -> HashMap<ClientId, PaneId> {
self.active_panes.clone()
}
pub fn contains_key(&self, client_id: &ClientId) -> bool {
self.active_panes.contains_key(client_id)
}
fn unfocus_pane_for_client(
&self,
client_id: ClientId,
panes: &mut BTreeMap<PaneId, Box<dyn Pane>>,
) {
if let Some(pane_id_to_unfocus) = self.active_panes.get(&client_id) {
self.unfocus_pane(*pane_id_to_unfocus, panes);
}
}
fn unfocus_pane(&self, pane_id: PaneId, panes: &mut BTreeMap<PaneId, Box<dyn Pane>>) {
if let PaneId::Terminal(terminal_id) = pane_id {
if let Some(focus_event) = panes.get(&pane_id).and_then(|p| p.unfocus_event()) {
let _ = self
.os_api
.write_to_tty_stdin(terminal_id, focus_event.as_bytes());
}
}
}
fn focus_pane(&self, pane_id: PaneId, panes: &mut BTreeMap<PaneId, Box<dyn Pane>>) {
if let PaneId::Terminal(terminal_id) = pane_id {
if let Some(focus_event) = panes.get(&pane_id).and_then(|p| p.focus_event()) {
let _ = self
.os_api
.write_to_tty_stdin(terminal_id, focus_event.as_bytes());
}
}
}
pub fn pane_id_is_focused(&self, pane_id: &PaneId) -> bool {
self.active_panes
.values()
.find(|p_id| **p_id == *pane_id)
.is_some()
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/panes/terminal_pane.rs | zellij-server/src/panes/terminal_pane.rs | use crate::output::{CharacterChunk, SixelImageChunk};
use crate::panes::sixel::SixelImageStore;
use crate::panes::LinkHandler;
use crate::panes::{
grid::Grid,
terminal_character::{render_first_run_banner, TerminalCharacter, EMPTY_TERMINAL_CHARACTER},
};
use crate::pty::VteBytes;
use crate::route::NotificationEnd;
use crate::tab::{AdjustedInput, Pane};
use crate::ClientId;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::fmt::Debug;
use std::rc::Rc;
use std::time::{self, Instant};
use vte;
use zellij_utils::data::PaneContents;
use zellij_utils::input::command::RunCommand;
use zellij_utils::input::mouse::{MouseEvent, MouseEventType};
use zellij_utils::pane_size::Offset;
use zellij_utils::{
data::{
BareKey, InputMode, KeyWithModifier, Palette, PaletteColor, PaneId as ZellijUtilsPaneId,
Style, Styling,
},
errors::prelude::*,
input::layout::Run,
pane_size::PaneGeom,
pane_size::SizeInPixels,
position::Position,
shared::make_terminal_title,
};
use crate::ui::pane_boundaries_frame::{FrameParams, PaneFrame};
pub const SELECTION_SCROLL_INTERVAL_MS: u64 = 10;
// Some keys in different formats but are used in the code
const LEFT_ARROW: &[u8] = &[27, 91, 68];
const RIGHT_ARROW: &[u8] = &[27, 91, 67];
const UP_ARROW: &[u8] = &[27, 91, 65];
const DOWN_ARROW: &[u8] = &[27, 91, 66];
const HOME_KEY: &[u8] = &[27, 91, 72];
const END_KEY: &[u8] = &[27, 91, 70];
pub const BRACKETED_PASTE_BEGIN: &[u8] = &[27, 91, 50, 48, 48, 126];
pub const BRACKETED_PASTE_END: &[u8] = &[27, 91, 50, 48, 49, 126];
const ENTER_NEWLINE: &[u8] = &[10];
const ESC: &[u8] = &[27];
const ENTER_CARRIAGE_RETURN: &[u8] = &[13];
const SPACE: &[u8] = &[32];
const CTRL_C: &[u8] = &[3]; // TODO: check this to be sure it fits all types of CTRL_C (with mac, etc)
const TERMINATING_STRING: &str = "\0";
const DELETE_KEY: &str = "\u{007F}";
const BACKSPACE_KEY: &str = "\u{0008}";
/// The ansi encoding of some keys
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum AnsiEncoding {
Left,
Right,
Up,
Down,
Home,
End,
}
impl AnsiEncoding {
/// Returns the ANSI representation of the entries.
/// NOTE: There is an ANSI escape code (27) at the beginning of the string,
/// some editors will not show this
pub fn as_bytes(&self) -> &[u8] {
match self {
Self::Left => "OD".as_bytes(),
Self::Right => "OC".as_bytes(),
Self::Up => "OA".as_bytes(),
Self::Down => "OB".as_bytes(),
Self::Home => &[27, 79, 72], // ESC O H
Self::End => &[27, 79, 70], // ESC O F
}
}
pub fn as_vec_bytes(&self) -> Vec<u8> {
self.as_bytes().to_vec()
}
}
#[derive(PartialEq, Eq, Ord, PartialOrd, Hash, Clone, Copy, Debug)]
pub enum PaneId {
Terminal(u32),
Plugin(u32), // FIXME: Drop the trait object, make this a wrapper for the struct?
}
// because crate architecture and reasons...
impl From<ZellijUtilsPaneId> for PaneId {
fn from(zellij_utils_pane_id: ZellijUtilsPaneId) -> Self {
match zellij_utils_pane_id {
ZellijUtilsPaneId::Terminal(id) => PaneId::Terminal(id),
ZellijUtilsPaneId::Plugin(id) => PaneId::Plugin(id),
}
}
}
impl Into<ZellijUtilsPaneId> for PaneId {
fn into(self) -> ZellijUtilsPaneId {
match self {
PaneId::Terminal(id) => ZellijUtilsPaneId::Terminal(id),
PaneId::Plugin(id) => ZellijUtilsPaneId::Plugin(id),
}
}
}
type IsFirstRun = bool;
// FIXME: This should hold an os_api handle so that terminal panes can set their own size via FD in
// their `reflow_lines()` method. Drop a Box<dyn ServerOsApi> in here somewhere.
#[allow(clippy::too_many_arguments)]
pub struct TerminalPane {
pub grid: Grid,
pub pid: u32,
pub selectable: bool,
pub geom: PaneGeom,
pub geom_override: Option<PaneGeom>,
pub active_at: Instant,
pub style: Style,
vte_parser: vte::Parser,
selection_scrolled_at: time::Instant,
content_offset: Offset,
pane_title: String,
pane_name: String,
prev_pane_name: String,
frame: HashMap<ClientId, PaneFrame>,
borderless: bool,
exclude_from_sync: bool,
fake_cursor_locations: HashSet<(usize, usize)>, // (x, y) - these hold a record of previous fake cursors which we need to clear on render
search_term: String,
is_held: Option<(Option<i32>, IsFirstRun, RunCommand)>, // a "held" pane means that its command has either exited and the pane is waiting for a
// possible user instruction to be re-run, or that the command has not yet been run
banner: Option<String>, // a banner to be rendered inside this TerminalPane, used for panes
// held on startup and can possibly be used to display some errors
pane_frame_color_override: Option<(PaletteColor, Option<String>)>,
invoked_with: Option<Run>,
#[allow(dead_code)]
arrow_fonts: bool,
notification_end: Option<NotificationEnd>,
}
impl Pane for TerminalPane {
fn x(&self) -> usize {
self.get_x()
}
fn y(&self) -> usize {
self.get_y()
}
fn rows(&self) -> usize {
self.get_rows()
}
fn cols(&self) -> usize {
self.get_columns()
}
fn get_content_x(&self) -> usize {
self.get_x() + self.content_offset.left
}
fn get_content_y(&self) -> usize {
self.get_y() + self.content_offset.top
}
fn get_content_columns(&self) -> usize {
// content columns might differ from the pane's columns if the pane has a frame
// in that case they would be 2 less
self.get_columns()
.saturating_sub(self.content_offset.left + self.content_offset.right)
}
fn get_content_rows(&self) -> usize {
// content rows might differ from the pane's rows if the pane has a frame
// in that case they would be 2 less
self.get_rows()
.saturating_sub(self.content_offset.top + self.content_offset.bottom)
}
fn reset_size_and_position_override(&mut self) {
self.geom_override = None;
self.reflow_lines();
}
fn set_geom(&mut self, position_and_size: PaneGeom) {
let is_pinned = self.geom.is_pinned;
self.geom = position_and_size;
self.geom.is_pinned = is_pinned;
self.reflow_lines();
self.render_full_viewport();
}
fn set_geom_override(&mut self, pane_geom: PaneGeom) {
self.geom_override = Some(pane_geom);
self.reflow_lines();
}
fn handle_pty_bytes(&mut self, bytes: VteBytes) {
self.set_should_render(true);
for &byte in &bytes {
self.vte_parser.advance(&mut self.grid, byte);
}
}
fn cursor_coordinates(&self, _client_id: Option<ClientId>) -> Option<(usize, usize)> {
// (x, y)
if self.get_content_rows() < 1 || self.get_content_columns() < 1 {
// do not render cursor if there's no room for it
return None;
}
let Offset { top, left, .. } = self.content_offset;
self.grid
.cursor_coordinates()
.map(|(x, y)| (x + left, y + top))
}
fn is_mid_frame(&self) -> bool {
self.grid.is_mid_frame()
}
fn adjust_input_to_terminal(
&mut self,
key_with_modifier: &Option<KeyWithModifier>,
raw_input_bytes: Vec<u8>,
raw_input_bytes_are_kitty: bool,
client_id: Option<ClientId>,
) -> Option<AdjustedInput> {
// there are some cases in which the terminal state means that input sent to it
// needs to be adjusted.
// here we match against those cases - if need be, we adjust the input and if not
// we send back the original input
self.reset_selection(client_id);
if !self.grid.bracketed_paste_mode {
// Zellij itself operates in bracketed paste mode, so the terminal sends these
// instructions (bracketed paste start and bracketed paste end respectively)
// when pasting input. We only need to make sure not to send them to terminal
// panes who do not work in this mode
match raw_input_bytes.as_slice() {
BRACKETED_PASTE_BEGIN | BRACKETED_PASTE_END => {
return Some(AdjustedInput::WriteBytesToTerminal(vec![]))
},
_ => {},
}
}
if self.is_held.is_some() {
if key_with_modifier
.as_ref()
.map(|k| k.is_key_without_modifier(BareKey::Enter))
.unwrap_or(false)
{
self.handle_held_run()
} else if key_with_modifier
.as_ref()
.map(|k| k.is_key_without_modifier(BareKey::Esc))
.unwrap_or(false)
{
self.handle_held_drop_to_shell()
} else if key_with_modifier
.as_ref()
.map(|k| k.is_key_with_ctrl_modifier(BareKey::Char('c')))
.unwrap_or(false)
{
Some(AdjustedInput::CloseThisPane)
} else {
match raw_input_bytes.as_slice() {
ENTER_CARRIAGE_RETURN | ENTER_NEWLINE | SPACE => self.handle_held_run(),
ESC => self.handle_held_drop_to_shell(),
CTRL_C => Some(AdjustedInput::CloseThisPane),
_ => None,
}
}
} else {
if self.grid.supports_kitty_keyboard_protocol {
self.adjust_input_to_terminal_with_kitty_keyboard_protocol(
key_with_modifier,
raw_input_bytes,
raw_input_bytes_are_kitty,
)
} else {
self.adjust_input_to_terminal_without_kitty_keyboard_protocol(
key_with_modifier,
raw_input_bytes,
raw_input_bytes_are_kitty,
)
}
}
}
fn position_and_size(&self) -> PaneGeom {
self.geom
}
fn current_geom(&self) -> PaneGeom {
self.geom_override.unwrap_or(self.geom)
}
fn geom_override(&self) -> Option<PaneGeom> {
self.geom_override
}
fn should_render(&self) -> bool {
self.grid.should_render
}
fn set_should_render(&mut self, should_render: bool) {
self.grid.should_render = should_render;
}
fn render_full_viewport(&mut self) {
// this marks the pane for a full re-render, rather than just rendering the
// diff as it usually does with the OutputBuffer
self.frame.clear();
self.grid.render_full_viewport();
}
fn selectable(&self) -> bool {
self.selectable
}
fn set_selectable(&mut self, selectable: bool) {
self.selectable = selectable;
}
fn render(
&mut self,
_client_id: Option<ClientId>,
) -> Result<Option<(Vec<CharacterChunk>, Option<String>, Vec<SixelImageChunk>)>> {
if self.should_render() {
let content_x = self.get_content_x();
let content_y = self.get_content_y();
let rows = self.get_content_rows();
let columns = self.get_content_columns();
if rows < 1 || columns < 1 {
return Ok(None);
}
match self.grid.render(content_x, content_y, &self.style) {
Ok(rendered_assets) => {
self.set_should_render(false);
return Ok(rendered_assets);
},
e => return e,
}
} else {
Ok(None)
}
}
fn render_frame(
&mut self,
client_id: ClientId,
frame_params: FrameParams,
input_mode: InputMode,
) -> Result<Option<(Vec<CharacterChunk>, Option<String>)>> {
let err_context = || format!("failed to render frame for client {client_id}");
// TODO: remove the cursor stuff from here
let pane_title = if let Some(text_color_override) = self
.pane_frame_color_override
.as_ref()
.and_then(|(_color, text)| text.as_ref())
{
text_color_override.into()
} else if self.pane_name.is_empty()
&& input_mode == InputMode::RenamePane
&& frame_params.is_main_client
{
String::from("Enter name...")
} else if input_mode == InputMode::EnterSearch
&& frame_params.is_main_client
&& self.search_term.is_empty()
{
String::from("Enter search...")
} else if (input_mode == InputMode::EnterSearch || input_mode == InputMode::Search)
&& !self.search_term.is_empty()
{
let mut modifier_text = String::new();
if self.grid.search_results.has_modifiers_set() {
let mut modifiers = Vec::new();
modifier_text.push_str(" [");
if self.grid.search_results.case_insensitive {
modifiers.push("c")
}
if self.grid.search_results.whole_word_only {
modifiers.push("o")
}
if self.grid.search_results.wrap_search {
modifiers.push("w")
}
modifier_text.push_str(&modifiers.join(", "));
modifier_text.push(']');
}
format!("SEARCHING: {}{}", self.search_term, modifier_text)
} else if self.pane_name.is_empty() {
self.grid
.title
.clone()
.unwrap_or_else(|| self.pane_title.clone())
} else {
self.pane_name.clone()
};
let frame_geom = self.current_geom();
let is_pinned = frame_geom.is_pinned;
let mut frame = PaneFrame::new(
frame_geom.into(),
self.grid.scrollback_position_and_length(),
pane_title,
frame_params,
)
.is_pinned(is_pinned);
if let Some((exit_status, is_first_run, _run_command)) = &self.is_held {
if *is_first_run {
frame.indicate_first_run();
} else {
frame.add_exit_status(exit_status.as_ref().copied());
}
}
if let Some((frame_color_override, _text)) = self.pane_frame_color_override.as_ref() {
frame.override_color(*frame_color_override);
}
let res = match self.frame.get(&client_id) {
// TODO: use and_then or something?
Some(last_frame) => {
if &frame != last_frame {
if !self.borderless {
let frame_output = frame.render().with_context(err_context)?;
self.frame.insert(client_id, frame);
Some(frame_output)
} else {
None
}
} else {
None
}
},
None => {
if !self.borderless {
let frame_output = frame.render().with_context(err_context)?;
self.frame.insert(client_id, frame);
Some(frame_output)
} else {
None
}
},
};
Ok(res)
}
fn render_fake_cursor(
&mut self,
cursor_color: PaletteColor,
text_color: PaletteColor,
) -> Option<String> {
let mut vte_output = None;
if let Some((cursor_x, cursor_y)) = self.cursor_coordinates() {
let mut character_under_cursor = self
.grid
.get_character_under_cursor()
.unwrap_or(EMPTY_TERMINAL_CHARACTER);
character_under_cursor.styles.update(|styles| {
styles.background = Some(cursor_color.into());
styles.foreground = Some(text_color.into());
});
// we keep track of these so that we can clear them up later (see render function)
self.fake_cursor_locations.insert((cursor_y, cursor_x));
let mut fake_cursor = format!(
"\u{1b}[{};{}H\u{1b}[m{}", // goto row column and clear styles
self.get_content_y() + cursor_y + 1, // + 1 because goto is 1 indexed
self.get_content_x() + cursor_x + 1,
&character_under_cursor.styles,
);
fake_cursor.push(character_under_cursor.character);
vte_output = Some(fake_cursor);
}
vte_output
}
fn render_terminal_title(&mut self, input_mode: InputMode) -> String {
let pane_title = if self.pane_name.is_empty() && input_mode == InputMode::RenamePane {
"Enter name..."
} else if self.pane_name.is_empty() {
self.grid.title.as_deref().unwrap_or("")
} else {
&self.pane_name
};
make_terminal_title(pane_title)
}
fn update_name(&mut self, name: &str) {
match name {
TERMINATING_STRING => {
self.pane_name = String::new();
},
DELETE_KEY | BACKSPACE_KEY => {
self.pane_name.pop();
},
c => {
self.pane_name.push_str(c);
},
}
self.set_should_render(true);
}
fn pid(&self) -> PaneId {
PaneId::Terminal(self.pid)
}
fn reduce_height(&mut self, percent: f64) {
if let Some(p) = self.geom.rows.as_percent() {
self.geom.rows.set_percent(p - percent);
self.set_should_render(true);
}
}
fn increase_height(&mut self, percent: f64) {
if let Some(p) = self.geom.rows.as_percent() {
self.geom.rows.set_percent(p + percent);
self.set_should_render(true);
}
}
fn reduce_width(&mut self, percent: f64) {
if let Some(p) = self.geom.cols.as_percent() {
self.geom.cols.set_percent(p - percent);
self.set_should_render(true);
}
}
fn increase_width(&mut self, percent: f64) {
if let Some(p) = self.geom.cols.as_percent() {
self.geom.cols.set_percent(p + percent);
self.set_should_render(true);
}
}
fn push_down(&mut self, count: usize) {
self.geom.y += count;
self.reflow_lines();
}
fn push_right(&mut self, count: usize) {
self.geom.x += count;
self.reflow_lines();
}
fn pull_left(&mut self, count: usize) {
self.geom.x -= count;
self.reflow_lines();
}
fn pull_up(&mut self, count: usize) {
self.geom.y -= count;
self.reflow_lines();
}
fn dump_screen(&self, full: bool, _client_id: Option<ClientId>) -> String {
self.grid.dump_screen(full)
}
fn clear_screen(&mut self) {
self.grid.clear_screen()
}
fn scroll_up(&mut self, count: usize, _client_id: ClientId) {
self.grid.move_viewport_up(count);
self.set_should_render(true);
}
fn scroll_down(&mut self, count: usize, _client_id: ClientId) {
self.grid.move_viewport_down(count);
self.set_should_render(true);
}
fn clear_scroll(&mut self) {
self.grid.reset_viewport();
self.set_should_render(true);
}
fn is_scrolled(&self) -> bool {
self.grid.is_scrolled
}
fn active_at(&self) -> Instant {
self.active_at
}
fn set_active_at(&mut self, time: Instant) {
self.active_at = time;
}
fn cursor_shape_csi(&self) -> String {
self.grid.cursor_shape().get_csi_str().to_string()
}
fn drain_messages_to_pty(&mut self) -> Vec<Vec<u8>> {
self.grid.pending_messages_to_pty.drain(..).collect()
}
fn drain_clipboard_update(&mut self) -> Option<String> {
self.grid.pending_clipboard_update.take()
}
fn start_selection(&mut self, start: &Position, _client_id: ClientId) {
self.grid.start_selection(start);
self.set_should_render(true);
}
fn update_selection(&mut self, to: &Position, _client_id: ClientId) {
let should_scroll = self.selection_scrolled_at.elapsed()
>= time::Duration::from_millis(SELECTION_SCROLL_INTERVAL_MS);
let cursor_at_the_bottom = to.line.0 < 0 && should_scroll;
let cursor_at_the_top = to.line.0 as usize >= self.grid.height && should_scroll;
let cursor_in_the_middle = to.line.0 >= 0 && (to.line.0 as usize) < self.grid.height;
// TODO: check how far up/down mouse is relative to pane, to increase scroll lines?
if cursor_at_the_bottom {
self.grid.scroll_up_one_line();
self.selection_scrolled_at = time::Instant::now();
self.set_should_render(true);
} else if cursor_at_the_top {
self.grid.scroll_down_one_line();
self.selection_scrolled_at = time::Instant::now();
self.set_should_render(true);
} else if cursor_in_the_middle {
// here we'll only render if the selection was updated, and that'll be handled by the
// grid
self.grid.update_selection(to);
}
}
fn end_selection(&mut self, end: &Position, _client_id: ClientId) {
self.grid.end_selection(end);
self.set_should_render(true);
}
fn reset_selection(&mut self, _client_id: Option<ClientId>) {
self.grid.reset_selection();
}
fn get_selected_text(&self, _client_id: ClientId) -> Option<String> {
self.grid.get_selected_text()
}
fn set_frame(&mut self, _frame: bool) {
self.frame.clear();
}
fn set_content_offset(&mut self, offset: Offset) {
self.content_offset = offset;
self.reflow_lines();
}
fn get_content_offset(&self) -> Offset {
self.content_offset
}
fn store_pane_name(&mut self) {
if self.pane_name != self.prev_pane_name {
self.prev_pane_name = self.pane_name.clone()
}
}
fn load_pane_name(&mut self) {
if self.pane_name != self.prev_pane_name {
self.pane_name = self.prev_pane_name.clone()
}
}
fn set_borderless(&mut self, borderless: bool) {
self.borderless = borderless;
}
fn borderless(&self) -> bool {
self.borderless
}
fn set_exclude_from_sync(&mut self, exclude_from_sync: bool) {
self.exclude_from_sync = exclude_from_sync;
}
fn exclude_from_sync(&self) -> bool {
self.exclude_from_sync
}
fn mouse_event(&self, event: &MouseEvent, _client_id: ClientId) -> Option<String> {
self.grid.mouse_event_signal(event)
}
fn mouse_left_click(&self, position: &Position, is_held: bool) -> Option<String> {
self.grid.mouse_left_click_signal(position, is_held)
}
fn mouse_left_click_release(&self, position: &Position) -> Option<String> {
self.grid.mouse_left_click_release_signal(position)
}
fn mouse_right_click(&self, position: &Position, is_held: bool) -> Option<String> {
self.grid.mouse_right_click_signal(position, is_held)
}
fn mouse_right_click_release(&self, position: &Position) -> Option<String> {
self.grid.mouse_right_click_release_signal(position)
}
fn mouse_middle_click(&self, position: &Position, is_held: bool) -> Option<String> {
self.grid.mouse_middle_click_signal(position, is_held)
}
fn mouse_middle_click_release(&self, position: &Position) -> Option<String> {
self.grid.mouse_middle_click_release_signal(position)
}
fn mouse_scroll_up(&self, position: &Position) -> Option<String> {
self.grid.mouse_scroll_up_signal(position)
}
fn mouse_scroll_down(&self, position: &Position) -> Option<String> {
self.grid.mouse_scroll_down_signal(position)
}
fn focus_event(&self) -> Option<String> {
self.grid.focus_event()
}
fn unfocus_event(&self) -> Option<String> {
self.grid.unfocus_event()
}
fn get_line_number(&self) -> Option<usize> {
// + 1 because the absolute position in the scrollback is 0 indexed and this should be 1 indexed
Some(self.grid.absolute_position_in_scrollback() + 1)
}
fn update_search_term(&mut self, needle: &str) {
match needle {
TERMINATING_STRING => {
self.search_term = String::new();
},
DELETE_KEY | BACKSPACE_KEY => {
self.search_term.pop();
},
c => {
self.search_term.push_str(c);
},
}
self.grid.clear_search();
if !self.search_term.is_empty() {
self.grid.set_search_string(&self.search_term);
}
self.set_should_render(true);
}
fn search_down(&mut self) {
if self.search_term.is_empty() {
return; // No-op
}
self.grid.search_down();
self.set_should_render(true);
}
fn search_up(&mut self) {
if self.search_term.is_empty() {
return; // No-op
}
self.grid.search_up();
self.set_should_render(true);
}
fn toggle_search_case_sensitivity(&mut self) {
self.grid.toggle_search_case_sensitivity();
self.set_should_render(true);
}
fn toggle_search_whole_words(&mut self) {
self.grid.toggle_search_whole_words();
self.set_should_render(true);
}
fn toggle_search_wrap(&mut self) {
self.grid.toggle_search_wrap();
}
fn clear_search(&mut self) {
self.grid.clear_search();
self.search_term.clear();
}
fn is_alternate_mode_active(&self) -> bool {
self.grid.is_alternate_mode_active()
}
fn hold(&mut self, exit_status: Option<i32>, is_first_run: bool, run_command: RunCommand) {
self.invoked_with = Some(Run::Command(run_command.clone()));
self.is_held = Some((exit_status, is_first_run, run_command));
if let Some(notification_end) = self.notification_end.as_mut() {
if let Some(exit_status) = exit_status {
notification_end.set_exit_status(exit_status);
// Check if unblock condition is met
if let Some(condition) = notification_end.unblock_condition() {
if condition.is_met(exit_status) {
// Condition met - drop the NotificationEnd now to unblock
drop(self.notification_end.take());
}
}
}
}
if is_first_run {
self.render_first_run_banner();
}
self.set_should_render(true);
}
fn add_red_pane_frame_color_override(&mut self, error_text: Option<String>) {
self.pane_frame_color_override = Some((self.style.colors.exit_code_error.base, error_text));
}
fn add_highlight_pane_frame_color_override(
&mut self,
text: Option<String>,
_client_id: Option<ClientId>,
) {
// TODO: if we have a client_id, we should only highlight the frame for this client
self.pane_frame_color_override = Some((self.style.colors.frame_highlight.base, text));
}
fn clear_pane_frame_color_override(&mut self, _client_id: Option<ClientId>) {
// TODO: if we have a client_id, we should only clear the highlight for this client
self.pane_frame_color_override = None;
}
fn frame_color_override(&self) -> Option<PaletteColor> {
self.pane_frame_color_override
.as_ref()
.map(|(color, _text)| *color)
}
fn invoked_with(&self) -> &Option<Run> {
&self.invoked_with
}
fn set_title(&mut self, title: String) {
self.pane_title = title;
}
fn current_title(&self) -> String {
if self.pane_name.is_empty() {
self.grid
.title
.as_deref()
.unwrap_or(&self.pane_title)
.into()
} else {
self.pane_name.to_owned()
}
}
fn custom_title(&self) -> Option<String> {
if self.pane_name.is_empty() {
None
} else {
Some(self.pane_name.clone())
}
}
fn exit_status(&self) -> Option<i32> {
self.is_held
.as_ref()
.and_then(|(exit_status, _, _)| *exit_status)
}
fn is_held(&self) -> bool {
self.is_held.is_some()
}
fn exited(&self) -> bool {
match self.is_held {
Some((_, is_first_run, _)) => !is_first_run,
None => false,
}
}
fn rename(&mut self, buf: Vec<u8>) {
self.pane_name = String::from_utf8_lossy(&buf).to_string();
self.set_should_render(true);
}
fn serialize(&self, scrollback_lines_to_serialize: Option<usize>) -> Option<String> {
self.grid.serialize(scrollback_lines_to_serialize)
}
fn rerun(&mut self) -> Option<RunCommand> {
// if this is a command pane that has exited or is waiting to be rerun, will return its
// RunCommand, otherwise it is safe to assume this is not the right sort of pane or that it
// is not in the right sort of state
self.is_held.take().map(|(_, _, run_command)| {
self.is_held = None;
self.grid.reset_terminal_state();
self.set_should_render(true);
self.remove_banner();
run_command.clone()
})
}
fn update_theme(&mut self, theme: Styling) {
self.style.colors = theme.clone();
self.grid.update_theme(theme);
if self.banner.is_some() {
// we do this so that the banner will be updated with the new theme colors
self.render_first_run_banner();
}
}
fn update_arrow_fonts(&mut self, should_support_arrow_fonts: bool) {
self.arrow_fonts = should_support_arrow_fonts;
self.grid.update_arrow_fonts(should_support_arrow_fonts);
}
fn update_rounded_corners(&mut self, rounded_corners: bool) {
self.style.rounded_corners = rounded_corners;
self.frame.clear();
}
fn drain_fake_cursors(&mut self) -> Option<HashSet<(usize, usize)>> {
if !self.fake_cursor_locations.is_empty() {
for (y, _x) in &self.fake_cursor_locations {
// we do this because once these fake_cursor_locations
// have been drained, we have to make sure to render the line
// they appeared on so that whatever clears their location
// won't leave a hole
self.grid.update_line_for_rendering(*y);
}
Some(self.fake_cursor_locations.drain().collect())
} else {
None
}
}
fn toggle_pinned(&mut self) {
self.geom.is_pinned = !self.geom.is_pinned;
}
fn set_pinned(&mut self, should_be_pinned: bool) {
self.geom.is_pinned = should_be_pinned;
}
fn intercept_left_mouse_click(&mut self, position: &Position, client_id: ClientId) -> bool {
if self.position_is_on_frame(position) {
let relative_position = self.relative_position(position);
if let Some(client_frame) = self.frame.get_mut(&client_id) {
if client_frame.clicked_on_pinned(relative_position) {
self.toggle_pinned();
return true;
}
}
}
false
}
fn intercept_mouse_event_on_frame(&mut self, event: &MouseEvent, client_id: ClientId) -> bool {
if self.position_is_on_frame(&event.position) {
let relative_position = self.relative_position(&event.position);
if let MouseEventType::Press = event.event_type {
if let Some(client_frame) = self.frame.get_mut(&client_id) {
if client_frame.clicked_on_pinned(relative_position) {
self.toggle_pinned();
return true;
}
}
}
}
false
}
fn reset_logical_position(&mut self) {
self.geom.logical_position = None;
}
fn pane_contents(
&self,
_client_id: Option<ClientId>,
get_full_scrollback: bool,
) -> PaneContents {
self.grid.pane_contents(get_full_scrollback)
}
fn update_exit_status(&mut self, exit_status: i32) {
if let Some(notification_end) = self.notification_end.as_mut() {
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-server/src/panes/link_handler.rs | zellij-server/src/panes/link_handler.rs | use std::collections::HashMap;
use super::LinkAnchor;
const TERMINATOR: &str = "\u{1b}\\";
#[derive(Debug, Clone)]
pub struct LinkHandler {
links: HashMap<u16, Link>,
link_index: u16,
}
#[derive(Debug, Clone)]
pub struct Link {
pub id: Option<String>,
pub uri: String,
}
impl LinkHandler {
pub fn new() -> Self {
Self {
links: HashMap::new(),
link_index: 0,
}
}
pub fn dispatch_osc8(&mut self, params: &[&[u8]]) -> Option<LinkAnchor> {
let (link_params, uri) = (params[1], params[2]);
log::debug!(
"dispatching osc8, params: {:?}, uri: {:?}",
std::str::from_utf8(link_params),
std::str::from_utf8(uri)
);
if !uri.is_empty() {
// save the link, and the id if present to hashmap
String::from_utf8(uri.to_vec()).ok().map(|uri| {
let id = link_params
.split(|&b| b == b':')
.find(|kv| kv.starts_with(b"id="))
.and_then(|kv| String::from_utf8(kv[3..].to_vec()).ok());
let anchor = LinkAnchor::Start(self.link_index);
self.links.insert(self.link_index, Link { id, uri });
self.link_index += 1;
anchor
})
} else {
// there is no link, so consider it a link end
Some(LinkAnchor::End)
}
}
pub fn new_link_from_url(&mut self, url: String) -> LinkAnchor {
let anchor = LinkAnchor::Start(self.link_index);
self.links.insert(
self.link_index,
Link {
id: Some(self.link_index.to_string()),
uri: url,
},
);
self.link_index += 1;
anchor
}
pub fn output_osc8(&self, link_anchor: Option<LinkAnchor>) -> Option<String> {
link_anchor.and_then(|link| match link {
LinkAnchor::Start(index) => {
let link = self.links.get(&index);
let output = link.map(|link| {
let id = link
.id
.as_ref()
.map_or("".to_string(), |id| format!("id={}", id));
format!("\u{1b}]8;{};{}{}", id, link.uri, TERMINATOR)
});
if output.is_none() {
log::warn!(
"attempted to output osc8 link start, but id: {} was not found!",
index
);
}
output
},
LinkAnchor::End => Some(format!("\u{1b}]8;;{}", TERMINATOR)),
})
}
#[cfg(test)]
pub fn links(&self) -> HashMap<u16, Link> {
self.links.clone()
}
}
impl Default for LinkHandler {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dispatch_osc8_link_start() {
let mut link_handler = LinkHandler::default();
let link_params = "id=test";
let uri = "http://test.com";
let params = vec!["8".as_bytes(), link_params.as_bytes(), uri.as_bytes()];
let anchor = link_handler.dispatch_osc8(¶ms);
match anchor {
Some(LinkAnchor::Start(link_id)) => {
let link = link_handler.links.get(&link_id).expect("link was not some");
assert_eq!(link.id, Some("test".to_string()));
assert_eq!(link.uri, uri);
},
_ => panic!("pending link handler was not start"),
}
let expected = format!("\u{1b}]8;id=test;http://test.com{}", TERMINATOR);
assert_eq!(link_handler.output_osc8(anchor).unwrap(), expected);
}
#[test]
fn dispatch_osc8_link_end() {
let mut link_handler = LinkHandler::default();
let params: Vec<&[_]> = vec![b"8", b"", b""];
let anchor = link_handler.dispatch_osc8(¶ms);
assert_eq!(anchor, Some(LinkAnchor::End));
let expected = format!("\u{1b}]8;;{}", TERMINATOR);
assert_eq!(link_handler.output_osc8(anchor).unwrap(), expected);
}
#[test]
fn return_none_on_missing_link_id() {
let link_handler = LinkHandler::default();
let anchor = LinkAnchor::Start(100);
assert_eq!(link_handler.output_osc8(Some(anchor)), None);
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.