Skip to content

Commit

Permalink
feat: support completely disabling mouse with mouse_events=[]; add …
Browse files Browse the repository at this point in the history
…new `cursor_blink` to control cursor style of input components (#1139)
  • Loading branch information
sxyazi committed Jun 8, 2024
1 parent 94628ca commit 1166f86
Show file tree
Hide file tree
Showing 33 changed files with 205 additions and 157 deletions.
2 changes: 1 addition & 1 deletion cspell.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"words":["Punct","KEYMAP","splitn","crossterm","YAZI","unar","peekable","ratatui","syntect","pbpaste","pbcopy","ffmpegthumbnailer","oneshot","Posix","Lsar","XADDOS","zoxide","cands","Deque","precache","imageops","IFBLK","IFCHR","IFDIR","IFIFO","IFLNK","IFMT","IFSOCK","IRGRP","IROTH","IRUSR","ISGID","ISUID","ISVTX","IWGRP","IWOTH","IWUSR","IXGRP","IXOTH","IXUSR","libc","winsize","TIOCGWINSZ","xpixel","ypixel","ioerr","appender","Catppuccin","macchiato","gitmodules","Dotfiles","bashprofile","vimrc","flac","webp","exiftool","mediainfo","ripgrep","nvim","indexmap","indexmap","unwatch","canonicalize","serde","fsevent","Ueberzug","iterm","wezterm","sixel","chafa","ueberzugpp","️ Überzug","️ Überzug","Konsole","Alacritty","Überzug","pkgs","paru","unarchiver","pdftoppm","poppler","prebuild","singlefile","jpegopt","EXIF","rustfmt","mktemp","nanos","xclip","xsel","natord","Mintty","nixos","nixpkgs","SIGTSTP","SIGCONT","SIGCONT","mlua","nonstatic","userdata","metatable","natsort","backstack","luajit","Succ","Succ","cand","fileencoding","foldmethod","lightgreen","darkgray","lightred","lightyellow","lightcyan","nushell","msvc","aarch","linemode","sxyazi","rsplit","ZELLIJ","bitflags","bitflags","USERPROFILE","Neovim","vergen","gitcl","Renderable","preloaders","prec","imagesize","Upserting","prio","Ghostty","Catmull","Lanczos","cmds","unyank","scrolloff","headsup","unsub","uzers","scopeguard","SPDLOG","globset","filetime","magick","magick","prefetcher","Prework","prefetchers","PREWORKERS","conds","translit"],"version":"0.2","flagWords":[],"language":"en"}
{"version":"0.2","words":["Punct","KEYMAP","splitn","crossterm","YAZI","unar","peekable","ratatui","syntect","pbpaste","pbcopy","ffmpegthumbnailer","oneshot","Posix","Lsar","XADDOS","zoxide","cands","Deque","precache","imageops","IFBLK","IFCHR","IFDIR","IFIFO","IFLNK","IFMT","IFSOCK","IRGRP","IROTH","IRUSR","ISGID","ISUID","ISVTX","IWGRP","IWOTH","IWUSR","IXGRP","IXOTH","IXUSR","libc","winsize","TIOCGWINSZ","xpixel","ypixel","ioerr","appender","Catppuccin","macchiato","gitmodules","Dotfiles","bashprofile","vimrc","flac","webp","exiftool","mediainfo","ripgrep","nvim","indexmap","indexmap","unwatch","canonicalize","serde","fsevent","Ueberzug","iterm","wezterm","sixel","chafa","ueberzugpp","️ Überzug","️ Überzug","Konsole","Alacritty","Überzug","pkgs","paru","unarchiver","pdftoppm","poppler","prebuild","singlefile","jpegopt","EXIF","rustfmt","mktemp","nanos","xclip","xsel","natord","Mintty","nixos","nixpkgs","SIGTSTP","SIGCONT","SIGCONT","mlua","nonstatic","userdata","metatable","natsort","backstack","luajit","Succ","Succ","cand","fileencoding","foldmethod","lightgreen","darkgray","lightred","lightyellow","lightcyan","nushell","msvc","aarch","linemode","sxyazi","rsplit","ZELLIJ","bitflags","bitflags","USERPROFILE","Neovim","vergen","gitcl","Renderable","preloaders","prec","imagesize","Upserting","prio","Ghostty","Catmull","Lanczos","cmds","unyank","scrolloff","headsup","unsub","uzers","scopeguard","SPDLOG","globset","filetime","magick","magick","prefetcher","Prework","prefetchers","PREWORKERS","conds","translit","rxvt","Urxvt"],"language":"en","flagWords":[]}
6 changes: 3 additions & 3 deletions yazi-adaptor/src/chafa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ use std::{io::Write, path::Path, process::Stdio};

use ansi_to_tui::IntoText;
use anyhow::{bail, Result};
use crossterm::{cursor::MoveTo, queue};
use ratatui::layout::Rect;
use tokio::process::Command;
use yazi_shared::term::Term;

use crate::{Adaptor, Emulator};

Expand Down Expand Up @@ -58,7 +58,7 @@ impl Chafa {
Emulator::move_lock((max.x, max.y), |stderr| {
for (i, line) in lines.into_iter().enumerate() {
stderr.write_all(line)?;
Term::move_to(stderr, max.x, max.y + i as u16 + 1)?;
queue!(stderr, MoveTo(max.x, max.y + i as u16 + 1))?;
}
Ok(area)
})
Expand All @@ -68,7 +68,7 @@ impl Chafa {
let s = " ".repeat(area.width as usize);
Emulator::move_lock((0, 0), |stderr| {
for y in area.top()..area.bottom() {
Term::move_to(stderr, area.x, y)?;
queue!(stderr, MoveTo(area.x, y))?;
write!(stderr, "{s}")?;
}
Ok(())
Expand Down
35 changes: 35 additions & 0 deletions yazi-adaptor/src/dimension.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
use std::mem;

use crossterm::terminal::WindowSize;

pub struct Dimension;

impl Dimension {
pub fn available() -> WindowSize {
let mut size = WindowSize { rows: 0, columns: 0, width: 0, height: 0 };
if let Ok(s) = crossterm::terminal::window_size() {
_ = mem::replace(&mut size, s);
}

if size.rows == 0 || size.columns == 0 {
if let Ok(s) = crossterm::terminal::size() {
size.columns = s.0;
size.rows = s.1;
}
}

// TODO: Use `CSI 14 t` to get the actual size of the terminal
// if size.width == 0 || size.height == 0 {}

size
}

#[inline]
pub fn ratio() -> Option<(f64, f64)> {
let s = Self::available();
if s.width == 0 || s.height == 0 {
return None;
}
Some((f64::from(s.width) / f64::from(s.columns), f64::from(s.height) / f64::from(s.rows)))
}
}
36 changes: 31 additions & 5 deletions yazi-adaptor/src/emulator.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use std::{env, io::{stderr, LineWriter}};
use std::{env, io::{stderr, LineWriter}, time::Duration};

use anyhow::{anyhow, Result};
use anyhow::{anyhow, bail, Result};
use crossterm::{cursor::{RestorePosition, SavePosition}, execute, style::Print, terminal::{disable_raw_mode, enable_raw_mode}};
use scopeguard::defer;
use tracing::warn;
use yazi_shared::{env_exists, term::Term};
use tokio::{io::{AsyncReadExt, BufReader}, time::timeout};
use tracing::{error, warn};
use yazi_shared::env_exists;

use crate::{Adaptor, CLOSE, ESCAPE, START, TMUX};

Expand Down Expand Up @@ -129,7 +130,7 @@ impl Emulator {
RestorePosition
)?;

let resp = futures::executor::block_on(Term::read_until_da1())?;
let resp = futures::executor::block_on(Self::read_until_da1())?;
let names = [
("kitty", Self::Kitty),
("Konsole", Self::Konsole),
Expand Down Expand Up @@ -187,4 +188,29 @@ impl Emulator {
buf.flush()?;
result
}

pub async fn read_until_da1() -> Result<String> {
let read = async {
let mut stdin = BufReader::new(tokio::io::stdin());
let mut buf = String::with_capacity(200);
loop {
let mut c = [0; 1];
if stdin.read(&mut c).await? == 0 {
bail!("unexpected EOF");
}
buf.push(c[0] as char);
if c[0] == b'c' && buf.contains("\x1b[?") {
break;
}
}
Ok(buf)
};

let timeout = timeout(Duration::from_secs(10), read).await;
if let Err(ref e) = timeout {
error!("read_until_da1: {e:?}");
}

timeout?
}
}
7 changes: 4 additions & 3 deletions yazi-adaptor/src/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ use exif::{In, Tag};
use image::{codecs::jpeg::JpegEncoder, imageops::{self, FilterType}, io::Limits, DynamicImage};
use ratatui::layout::Rect;
use yazi_config::{PREVIEW, TASKS};
use yazi_shared::term::Term;

use crate::Dimension;

pub struct Image;

Expand Down Expand Up @@ -77,7 +78,7 @@ impl Image {
}

pub(super) fn max_pixel(rect: Rect) -> (u32, u32) {
Term::ratio()
Dimension::ratio()
.map(|(r1, r2)| {
let (w, h) = ((rect.width as f64 * r1) as u32, (rect.height as f64 * r2) as u32);
(w.min(PREVIEW.max_width), h.min(PREVIEW.max_height))
Expand All @@ -86,7 +87,7 @@ impl Image {
}

pub(super) fn pixel_area(size: (u32, u32), rect: Rect) -> Rect {
Term::ratio()
Dimension::ratio()
.map(|(r1, r2)| Rect {
x: rect.x,
y: rect.y,
Expand Down
4 changes: 2 additions & 2 deletions yazi-adaptor/src/iterm2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ use std::{io::Write, path::Path};

use anyhow::Result;
use base64::{engine::{general_purpose::STANDARD, Config}, Engine};
use crossterm::{cursor::MoveTo, queue};
use image::{codecs::jpeg::JpegEncoder, DynamicImage};
use ratatui::layout::Rect;
use yazi_shared::term::Term;

use super::image::Image;
use crate::{adaptor::Adaptor, Emulator, CLOSE, START};
Expand All @@ -29,7 +29,7 @@ impl Iterm2 {
let s = " ".repeat(area.width as usize);
Emulator::move_lock((0, 0), |stderr| {
for y in area.top()..area.bottom() {
Term::move_to(stderr, area.x, y)?;
queue!(stderr, MoveTo(area.x, y))?;
write!(stderr, "{s}")?;
}
Ok(())
Expand Down
4 changes: 2 additions & 2 deletions yazi-adaptor/src/kitty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ use std::{io::Write, path::Path};

use anyhow::Result;
use base64::{engine::general_purpose, Engine};
use crossterm::{cursor::MoveTo, queue};
use image::DynamicImage;
use ratatui::layout::Rect;
use yazi_shared::term::Term;

use super::image::Image;
use crate::{adaptor::Adaptor, Emulator, CLOSE, ESCAPE, START};
Expand Down Expand Up @@ -333,7 +333,7 @@ impl Kitty {
let s = " ".repeat(area.width as usize);
Emulator::move_lock((0, 0), |stderr| {
for y in area.top()..area.bottom() {
Term::move_to(stderr, area.x, y)?;
queue!(stderr, MoveTo(area.x, y))?;
write!(stderr, "{s}")?;
}

Expand Down
2 changes: 2 additions & 0 deletions yazi-adaptor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

mod adaptor;
mod chafa;
mod dimension;
mod emulator;
mod image;
mod iterm2;
Expand All @@ -12,6 +13,7 @@ mod ueberzug;

pub use adaptor::*;
use chafa::*;
pub use dimension::*;
pub use emulator::*;
use iterm2::*;
use kitty::*;
Expand Down
4 changes: 2 additions & 2 deletions yazi-adaptor/src/sixel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ use std::{io::Write, path::Path};

use anyhow::{bail, Result};
use color_quant::NeuQuant;
use crossterm::{cursor::MoveTo, queue};
use image::DynamicImage;
use ratatui::layout::Rect;
use yazi_config::PREVIEW;
use yazi_shared::term::Term;

use crate::{adaptor::Adaptor, Emulator, Image, CLOSE, ESCAPE, START};

Expand All @@ -29,7 +29,7 @@ impl Sixel {
let s = " ".repeat(area.width as usize);
Emulator::move_lock((0, 0), |stderr| {
for y in area.top()..area.bottom() {
Term::move_to(stderr, area.x, y)?;
queue!(stderr, MoveTo(area.x, y))?;
write!(stderr, "{s}")?;
}
Ok(())
Expand Down
6 changes: 4 additions & 2 deletions yazi-config/preset/yazi.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,12 @@ edit = [
{ run = 'code -w "%*"', block = true, desc = "code (block)", for = "windows" },
]
open = [
{ run = 'xdg-open "$@"', desc = "Open", for = "linux" },
{ run = 'xdg-open "$1"', desc = "Open", for = "linux" },
{ run = 'open "$@"', desc = "Open", for = "macos" },
{ run = 'start "" "%1"', orphan = true, desc = "Open", for = "windows" },
]
reveal = [
{ run = 'xdg-open "$(dirname "$0")"', desc = "Reveal", for = "linux" },
{ run = 'xdg-open "$(dirname "$1")"', desc = "Reveal", for = "linux" },
{ run = 'open -R "$1"', desc = "Reveal", for = "macos" },
{ run = 'explorer /select, "%1"', orphan = true, desc = "Reveal", for = "windows" },
{ run = '''exiftool "$1"; echo "Press enter to exit"; read _''', block = true, desc = "Show EXIF", for = "unix" },
Expand Down Expand Up @@ -122,6 +122,8 @@ previewers = [
]

[input]
cursor_blink = true

# cd
cd_title = "Change directory:"
cd_origin = "top-center"
Expand Down
2 changes: 2 additions & 0 deletions yazi-config/src/popup/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ use crate::MERGED_YAZI;

#[derive(Deserialize)]
pub struct Input {
pub cursor_blink: bool,

// cd
pub cd_title: String,
pub cd_origin: Origin,
Expand Down
7 changes: 2 additions & 5 deletions yazi-config/src/popup/position.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use crossterm::terminal::WindowSize;
use ratatui::layout::Rect;
use yazi_shared::term::Term;

use super::{Offset, Origin};

Expand All @@ -14,10 +13,9 @@ impl Position {
#[inline]
pub fn new(origin: Origin, offset: Offset) -> Self { Self { origin, offset } }

pub fn rect(&self) -> Rect {
pub fn rect(&self, WindowSize { columns, rows, .. }: WindowSize) -> Rect {
use Origin::*;
let Offset { x, y, width, height } = self.offset;
let WindowSize { columns, rows, .. } = Term::size();

let max_x = columns.saturating_sub(width);
let new_x = match self.origin {
Expand Down Expand Up @@ -45,9 +43,8 @@ impl Position {
}
}

pub fn sticky(base: Rect, offset: Offset) -> Rect {
pub fn sticky(WindowSize { columns, rows, .. }: WindowSize, base: Rect, offset: Offset) -> Rect {
let Offset { x, y, width, height } = offset;
let WindowSize { columns, rows, .. } = Term::size();

let above =
base.y.saturating_add(base.height).saturating_add(height).saturating_add_signed(y) > rows;
Expand Down
7 changes: 4 additions & 3 deletions yazi-core/src/help/help.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use crossterm::event::KeyCode;
use unicode_width::UnicodeWidthStr;
use yazi_adaptor::Dimension;
use yazi_config::{keymap::{Control, Key}, KEYMAP};
use yazi_shared::{render, render_and, term::Term, Layer};
use yazi_shared::{render, render_and, Layer};

use super::HELP_MARGIN;
use crate::input::Input;
Expand All @@ -22,7 +23,7 @@ pub struct Help {

impl Help {
#[inline]
pub fn limit() -> usize { Term::size().rows.saturating_sub(HELP_MARGIN) as usize }
pub fn limit() -> usize { Dimension::available().rows.saturating_sub(HELP_MARGIN) as usize }

pub fn toggle(&mut self, layer: Layer) {
self.visible = !self.visible;
Expand Down Expand Up @@ -106,7 +107,7 @@ impl Help {
return None;
}
if let Some(kw) = self.keyword() {
return Some((kw.width() as u16, Term::size().rows));
return Some((kw.width() as u16, Dimension::available().rows));
}
None
}
Expand Down
6 changes: 3 additions & 3 deletions yazi-core/src/manager/commands/bulk_rename.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use tokio::{fs::{self, OpenOptions}, io::{stdin, AsyncReadExt, AsyncWriteExt}};
use yazi_config::{OPEN, PREVIEW};
use yazi_dds::Pubsub;
use yazi_proxy::{AppProxy, TasksProxy, HIDER, WATCHER};
use yazi_shared::{fs::{max_common_root, maybe_exists, File, FilesOp, Url}, term::Term};
use yazi_shared::{fs::{max_common_root, maybe_exists, File, FilesOp, Url}, terminal_clear};

use crate::manager::Manager;

Expand Down Expand Up @@ -52,7 +52,7 @@ impl Manager {
old: Vec<PathBuf>,
new: Vec<PathBuf>,
) -> Result<()> {
Term::clear(&mut stderr())?;
terminal_clear(&mut stderr())?;
if old.len() != new.len() {
eprintln!("Number of old and new differ, press ENTER to exit");
stdin().read_exact(&mut [0]).await?;
Expand Down Expand Up @@ -108,7 +108,7 @@ impl Manager {
}

async fn output_failed(failed: Vec<(PathBuf, PathBuf, anyhow::Error)>) -> Result<()> {
Term::clear(&mut stderr())?;
terminal_clear(&mut stderr())?;

{
let mut stderr = BufWriter::new(stderr().lock());
Expand Down
4 changes: 2 additions & 2 deletions yazi-core/src/tasks/commands/inspect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use crossterm::terminal::{disable_raw_mode, enable_raw_mode};
use scopeguard::defer;
use tokio::{io::{stdin, AsyncReadExt}, select, sync::mpsc, time};
use yazi_proxy::{AppProxy, HIDER};
use yazi_shared::{event::Cmd, term::Term};
use yazi_shared::{event::Cmd, terminal_clear};

use crate::tasks::Tasks;

Expand All @@ -30,7 +30,7 @@ impl Tasks {
defer!(AppProxy::resume());
AppProxy::stop().await;

Term::clear(&mut stderr()).ok();
terminal_clear(&mut stderr()).ok();
BufWriter::new(stderr().lock()).write_all(mem::take(&mut buffered).as_bytes()).ok();

defer! { disable_raw_mode().ok(); }
Expand Down
6 changes: 4 additions & 2 deletions yazi-core/src/tasks/tasks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ use std::{sync::Arc, time::Duration};

use parking_lot::Mutex;
use tokio::{task::JoinHandle, time::sleep};
use yazi_adaptor::Dimension;
use yazi_scheduler::{Ongoing, Scheduler, TaskSummary};
use yazi_shared::{emit, event::Cmd, term::Term, Layer};
use yazi_shared::{emit, event::Cmd, Layer};

use super::{TasksProgress, TASKS_BORDER, TASKS_PADDING, TASKS_PERCENT};

Expand Down Expand Up @@ -53,7 +54,8 @@ impl Tasks {

#[inline]
pub fn limit() -> usize {
(Term::size().rows * TASKS_PERCENT / 100).saturating_sub(TASKS_BORDER + TASKS_PADDING) as usize
(Dimension::available().rows * TASKS_PERCENT / 100).saturating_sub(TASKS_BORDER + TASKS_PADDING)
as usize
}

pub fn paginate(&self) -> Vec<TaskSummary> {
Expand Down
4 changes: 2 additions & 2 deletions yazi-fm/src/app/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ use anyhow::Result;
use crossterm::event::KeyEvent;
use yazi_config::keymap::Key;
use yazi_core::input::InputMode;
use yazi_shared::{emit, event::{Cmd, Event, NEED_RENDER}, term::Term, Layer};
use yazi_shared::{emit, event::{Cmd, Event, NEED_RENDER}, Layer};

use crate::{lives::Lives, Ctx, Executor, Router, Signals};
use crate::{lives::Lives, Ctx, Executor, Router, Signals, Term};

pub(crate) struct App {
pub(crate) cx: Ctx,
Expand Down
Loading

0 comments on commit 1166f86

Please sign in to comment.