migrate input
This commit is contained in:
@@ -17,13 +17,7 @@ anyhow.workspace = true
|
||||
itertools.workspace = true
|
||||
log.workspace = true
|
||||
|
||||
unicode-segmentation = "1.12.0"
|
||||
uuid = "1.10"
|
||||
regex = "1"
|
||||
lsp-types = "0.97.0"
|
||||
ropey = { version = "=2.0.0-beta.1", features = ["metric_lines_lf", "metric_utf16"] }
|
||||
sum_tree.workspace = true
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
smol.workspace = true
|
||||
tree-sitter = "0.26"
|
||||
|
||||
@@ -1,184 +0,0 @@
|
||||
use std::fmt::Debug;
|
||||
use instant::{Duration, Instant};
|
||||
|
||||
/// A HistoryItem represents a single change in the history.
|
||||
/// It must implement Clone and PartialEq to be used in the History.
|
||||
pub trait HistoryItem: Clone + PartialEq {
|
||||
fn version(&self) -> usize;
|
||||
fn set_version(&mut self, version: usize);
|
||||
}
|
||||
|
||||
/// The History is used to keep track of changes to a model and to allow undo and redo operations.
|
||||
///
|
||||
/// This is now used in Input for undo/redo operations. You can also use this in
|
||||
/// your own models to keep track of changes, for example to track the tab
|
||||
/// history for prev/next features.
|
||||
///
|
||||
/// ## Use cases
|
||||
///
|
||||
/// - Undo/redo operations in Input
|
||||
/// - Tracking tab history for prev/next features
|
||||
#[derive(Debug)]
|
||||
pub struct History<I: HistoryItem> {
|
||||
undos: Vec<I>,
|
||||
redos: Vec<I>,
|
||||
last_changed_at: Instant,
|
||||
version: usize,
|
||||
pub(crate) ignore: bool,
|
||||
max_undos: usize,
|
||||
group_interval: Option<Duration>,
|
||||
grouping: bool,
|
||||
unique: bool,
|
||||
}
|
||||
|
||||
impl<I> History<I>
|
||||
where
|
||||
I: HistoryItem,
|
||||
{
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
undos: Default::default(),
|
||||
redos: Default::default(),
|
||||
ignore: false,
|
||||
last_changed_at: Instant::now(),
|
||||
version: 0,
|
||||
max_undos: 1000,
|
||||
group_interval: None,
|
||||
grouping: false,
|
||||
unique: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the maximum number of undo steps to keep, defaults to 1000.
|
||||
pub fn max_undos(mut self, max_undos: usize) -> Self {
|
||||
self.max_undos = max_undos;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the history to be unique, defaults to false.
|
||||
/// If set to true, the history will only keep unique changes.
|
||||
pub fn unique(mut self) -> Self {
|
||||
self.unique = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the interval in milliseconds to group changes, defaults to None.
|
||||
pub fn group_interval(mut self, group_interval: Duration) -> Self {
|
||||
self.group_interval = Some(group_interval);
|
||||
self
|
||||
}
|
||||
|
||||
/// Start grouping changes, this will prevent the version from being incremented until `end_grouping` is called.
|
||||
pub fn start_grouping(&mut self) {
|
||||
self.grouping = true;
|
||||
}
|
||||
|
||||
/// End grouping changes, this will allow the version to be incremented again.
|
||||
pub fn end_grouping(&mut self) {
|
||||
self.grouping = false;
|
||||
}
|
||||
|
||||
/// Increment the version number if the last change was made more than `GROUP_INTERVAL` milliseconds ago.
|
||||
fn inc_version(&mut self) -> usize {
|
||||
let t = Instant::now();
|
||||
if !self.grouping && Some(self.last_changed_at.elapsed()) > self.group_interval {
|
||||
self.version += 1;
|
||||
}
|
||||
|
||||
self.last_changed_at = t;
|
||||
self.version
|
||||
}
|
||||
|
||||
/// Get the current version number.
|
||||
pub fn version(&self) -> usize {
|
||||
self.version
|
||||
}
|
||||
|
||||
/// Push a new change to the history.
|
||||
pub fn push(&mut self, item: I) {
|
||||
let version = self.inc_version();
|
||||
|
||||
if self.undos.len() >= self.max_undos {
|
||||
self.undos.remove(0);
|
||||
}
|
||||
|
||||
if self.unique {
|
||||
self.undos.retain(|c| *c != item);
|
||||
self.redos.retain(|c| *c != item);
|
||||
}
|
||||
|
||||
let mut item = item;
|
||||
item.set_version(version);
|
||||
self.undos.push(item);
|
||||
}
|
||||
|
||||
/// Get the undo stack.
|
||||
pub fn undos(&self) -> &Vec<I> {
|
||||
&self.undos
|
||||
}
|
||||
|
||||
/// Get the redo stack.
|
||||
pub fn redos(&self) -> &Vec<I> {
|
||||
&self.redos
|
||||
}
|
||||
|
||||
/// Clear the undo and redo stacks.
|
||||
pub fn clear(&mut self) {
|
||||
self.undos.clear();
|
||||
self.redos.clear();
|
||||
}
|
||||
|
||||
/// Undo the last change and return the changes that were undone.
|
||||
pub fn undo(&mut self) -> Option<Vec<I>> {
|
||||
if let Some(first_change) = self.undos.pop() {
|
||||
let mut changes = vec![first_change.clone()];
|
||||
// pick the next all changes with the same version
|
||||
while self
|
||||
.undos
|
||||
.iter()
|
||||
.filter(|c| c.version() == first_change.version())
|
||||
.count()
|
||||
> 0
|
||||
{
|
||||
let change = self.undos.pop().unwrap();
|
||||
changes.push(change);
|
||||
}
|
||||
|
||||
self.redos.extend(changes.clone());
|
||||
Some(changes)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Redo the last undone change and return the changes that were redone.
|
||||
pub fn redo(&mut self) -> Option<Vec<I>> {
|
||||
if let Some(first_change) = self.redos.pop() {
|
||||
let mut changes = vec![first_change.clone()];
|
||||
// pick the next all changes with the same version
|
||||
while self
|
||||
.redos
|
||||
.iter()
|
||||
.filter(|c| c.version() == first_change.version())
|
||||
.count()
|
||||
> 0
|
||||
{
|
||||
let change = self.redos.pop().unwrap();
|
||||
changes.push(change);
|
||||
}
|
||||
self.undos.extend(changes.clone());
|
||||
Some(changes)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<I> Default for History<I>
|
||||
where
|
||||
I: HistoryItem,
|
||||
{
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
use instant::Duration;
|
||||
|
||||
use gpui::{Context, Pixels, Task, px};
|
||||
|
||||
static INTERVAL: Duration = Duration::from_millis(500);
|
||||
static PAUSE_DELAY: Duration = Duration::from_millis(300);
|
||||
|
||||
// On Windows, Linux, we should use integer to avoid blurry cursor.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub(super) const CURSOR_WIDTH: Pixels = px(2.);
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(super) const CURSOR_WIDTH: Pixels = px(1.5);
|
||||
|
||||
/// To manage the Input cursor blinking.
|
||||
///
|
||||
/// It will start blinking with a interval of 500ms.
|
||||
/// Every loop will notify the view to update the `visible`, and Input will observe this update to touch repaint.
|
||||
///
|
||||
/// The input painter will check if this in visible state, then it will draw the cursor.
|
||||
pub(crate) struct BlinkCursor {
|
||||
visible: bool,
|
||||
paused: bool,
|
||||
epoch: usize,
|
||||
|
||||
_task: Task<()>,
|
||||
}
|
||||
|
||||
impl BlinkCursor {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
visible: false,
|
||||
paused: false,
|
||||
epoch: 0,
|
||||
_task: Task::ready(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Start the blinking
|
||||
pub fn start(&mut self, cx: &mut Context<Self>) {
|
||||
self.blink(self.epoch, cx);
|
||||
}
|
||||
|
||||
pub fn stop(&mut self, cx: &mut Context<Self>) {
|
||||
self.epoch = 0;
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn next_epoch(&mut self) -> usize {
|
||||
self.epoch += 1;
|
||||
self.epoch
|
||||
}
|
||||
|
||||
fn blink(&mut self, epoch: usize, cx: &mut Context<Self>) {
|
||||
if self.paused || epoch != self.epoch {
|
||||
self.visible = true;
|
||||
return;
|
||||
}
|
||||
|
||||
self.visible = !self.visible;
|
||||
cx.notify();
|
||||
|
||||
// Schedule the next blink
|
||||
let epoch = self.next_epoch();
|
||||
self._task = cx.spawn(async move |this, cx| {
|
||||
cx.background_executor().timer(INTERVAL).await;
|
||||
if let Some(this) = this.upgrade() {
|
||||
this.update(cx, |this, cx| this.blink(epoch, cx));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub fn visible(&self) -> bool {
|
||||
// Keep showing the cursor if paused
|
||||
self.paused || self.visible
|
||||
}
|
||||
|
||||
/// Pause the blinking, and delay 500ms to resume the blinking.
|
||||
pub fn pause(&mut self, cx: &mut Context<Self>) {
|
||||
self.paused = true;
|
||||
self.visible = true;
|
||||
cx.notify();
|
||||
|
||||
// delay 500ms to start the blinking
|
||||
let epoch = self.next_epoch();
|
||||
self._task = cx.spawn(async move |this, cx| {
|
||||
cx.background_executor().timer(PAUSE_DELAY).await;
|
||||
|
||||
if let Some(this) = this.upgrade() {
|
||||
this.update(cx, |this, cx| {
|
||||
this.paused = false;
|
||||
this.blink(epoch, cx);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
use std::fmt::Debug;
|
||||
|
||||
use crate::{history::HistoryItem, input::Selection};
|
||||
|
||||
#[derive(Debug, PartialEq, Clone)]
|
||||
pub struct Change {
|
||||
pub(crate) old_range: Selection,
|
||||
pub(crate) old_text: String,
|
||||
pub(crate) new_range: Selection,
|
||||
pub(crate) new_text: String,
|
||||
version: usize,
|
||||
}
|
||||
|
||||
impl Change {
|
||||
pub fn new(
|
||||
old_range: impl Into<Selection>,
|
||||
old_text: &str,
|
||||
new_range: impl Into<Selection>,
|
||||
new_text: &str,
|
||||
) -> Self {
|
||||
Self {
|
||||
old_range: old_range.into(),
|
||||
old_text: old_text.to_string(),
|
||||
new_range: new_range.into(),
|
||||
new_text: new_text.to_string(),
|
||||
version: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryItem for Change {
|
||||
fn version(&self) -> usize {
|
||||
self.version
|
||||
}
|
||||
|
||||
fn set_version(&mut self, version: usize) {
|
||||
self.version = version;
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
use std::ops::{Range, RangeBounds};
|
||||
|
||||
/// A selection in the text, represented by start and end byte indices.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
|
||||
pub struct Selection {
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
}
|
||||
|
||||
impl Selection {
|
||||
pub fn new(start: usize, end: usize) -> Self {
|
||||
Self { start, end }
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.end.saturating_sub(self.start)
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.start == self.end
|
||||
}
|
||||
|
||||
/// Clears the selection, setting start and end to 0.
|
||||
pub fn clear(&mut self) {
|
||||
self.start = 0;
|
||||
self.end = 0;
|
||||
}
|
||||
|
||||
/// Checks if the given offset is within the selection range.
|
||||
pub fn contains(&self, offset: usize) -> bool {
|
||||
offset >= self.start && offset < self.end
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Range<usize>> for Selection {
|
||||
fn from(value: Range<usize>) -> Self {
|
||||
Self::new(value.start, value.end)
|
||||
}
|
||||
}
|
||||
impl From<Selection> for Range<usize> {
|
||||
fn from(value: Selection) -> Self {
|
||||
value.start..value.end
|
||||
}
|
||||
}
|
||||
impl RangeBounds<usize> for Selection {
|
||||
fn start_bound(&self) -> std::ops::Bound<&usize> {
|
||||
std::ops::Bound::Included(&self.start)
|
||||
}
|
||||
|
||||
fn end_bound(&self) -> std::ops::Bound<&usize> {
|
||||
std::ops::Bound::Excluded(&self.end)
|
||||
}
|
||||
}
|
||||
@@ -1,172 +0,0 @@
|
||||
use std::ops::Range;
|
||||
|
||||
use gpui::{App, Font, Pixels};
|
||||
use ropey::Rope;
|
||||
|
||||
use super::text_wrapper::{LineItem, WrapDisplayPoint};
|
||||
use super::wrap_map::WrapMap;
|
||||
use crate::input::Point as TreeSitterPoint;
|
||||
|
||||
/// DisplayMap is the main interface for Input coordinate mapping.
|
||||
pub struct DisplayMap {
|
||||
wrap_map: WrapMap,
|
||||
}
|
||||
|
||||
impl DisplayMap {
|
||||
pub fn new(font: Font, font_size: Pixels, wrap_width: Option<Pixels>) -> Self {
|
||||
Self {
|
||||
wrap_map: WrapMap::new(font, font_size, wrap_width),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get total number of display rows (same as wrap rows without folding)
|
||||
#[inline]
|
||||
pub fn display_row_count(&self) -> usize {
|
||||
self.wrap_map.wrap_row_count()
|
||||
}
|
||||
|
||||
/// Get the buffer line for a given display row
|
||||
pub fn display_row_to_buffer_line(&self, display_row: usize) -> usize {
|
||||
self.wrap_map.wrap_row_to_buffer_line(display_row)
|
||||
}
|
||||
|
||||
/// Get the display row range for a buffer line: [start, end)
|
||||
pub fn buffer_line_to_display_row_range(&self, line: usize) -> Option<Range<usize>> {
|
||||
let range = self.wrap_map.buffer_line_to_wrap_row_range(line);
|
||||
if range.is_empty() { None } else { Some(range) }
|
||||
}
|
||||
|
||||
/// Check if a buffer line is completely hidden (never true without folding)
|
||||
#[inline]
|
||||
pub fn is_buffer_line_hidden(&self, _line: usize) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// All wrap rows are visible since there's no folding.
|
||||
#[inline]
|
||||
pub fn folded_ranges(&self) -> &[()] {
|
||||
&[]
|
||||
}
|
||||
|
||||
/// Adjust folds for edit (no-op without folding)
|
||||
pub fn adjust_folds_for_edit(
|
||||
&mut self,
|
||||
_old_text: &Rope,
|
||||
_range: &Range<usize>,
|
||||
_new_text: &str,
|
||||
) {
|
||||
// No-op: no folding
|
||||
}
|
||||
|
||||
/// Update text (incremental or full)
|
||||
pub fn on_text_changed(
|
||||
&mut self,
|
||||
changed_text: &Rope,
|
||||
range: &Range<usize>,
|
||||
new_text: &Rope,
|
||||
cx: &mut App,
|
||||
) {
|
||||
self.wrap_map
|
||||
.on_text_changed(changed_text, range, new_text, cx);
|
||||
}
|
||||
|
||||
/// Update layout parameters (wrap width or font)
|
||||
pub fn on_layout_changed(&mut self, wrap_width: Option<Pixels>, cx: &mut App) {
|
||||
self.wrap_map.on_layout_changed(wrap_width, cx);
|
||||
}
|
||||
|
||||
/// Set font parameters
|
||||
pub fn set_font(&mut self, font: Font, font_size: Pixels, cx: &mut App) {
|
||||
self.wrap_map.set_font(font, font_size, cx);
|
||||
}
|
||||
|
||||
/// Ensure text is prepared (initializes wrapper if needed)
|
||||
pub fn ensure_text_prepared(&mut self, text: &Rope, cx: &mut App) {
|
||||
self.wrap_map.ensure_text_prepared(text, cx);
|
||||
}
|
||||
|
||||
/// Initialize with text
|
||||
pub fn set_text(&mut self, text: &Rope, cx: &mut App) {
|
||||
self.wrap_map.set_text(text, cx);
|
||||
}
|
||||
|
||||
/// Convert byte offset to wrap display point (with soft wrap info).
|
||||
#[inline]
|
||||
pub(crate) fn offset_to_wrap_display_point(&self, offset: usize) -> WrapDisplayPoint {
|
||||
self.wrap_map.wrapper().offset_to_display_point(offset)
|
||||
}
|
||||
|
||||
/// Convert wrap display point to byte offset.
|
||||
#[inline]
|
||||
pub(crate) fn wrap_display_point_to_offset(&self, point: WrapDisplayPoint) -> usize {
|
||||
self.wrap_map.wrapper().display_point_to_offset(point)
|
||||
}
|
||||
|
||||
/// Convert wrap display point to TreeSitterPoint (buffer line/col).
|
||||
#[inline]
|
||||
pub(crate) fn wrap_display_point_to_point(&self, point: WrapDisplayPoint) -> TreeSitterPoint {
|
||||
self.wrap_map.wrapper().display_point_to_point(point)
|
||||
}
|
||||
|
||||
/// Since there's no folding, wrap row == display row.
|
||||
#[inline]
|
||||
pub fn wrap_row_to_display_row(&self, wrap_row: usize) -> Option<usize> {
|
||||
if wrap_row < self.wrap_row_count() {
|
||||
Some(wrap_row)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Since there's no folding, nearest visible row is the row itself.
|
||||
#[inline]
|
||||
pub fn nearest_visible_display_row(&self, wrap_row: usize) -> usize {
|
||||
wrap_row.min(self.wrap_row_count().saturating_sub(1))
|
||||
}
|
||||
|
||||
/// Since there's no folding, display row == wrap row.
|
||||
#[inline]
|
||||
pub fn display_row_to_wrap_row(&self, display_row: usize) -> Option<usize> {
|
||||
if display_row < self.wrap_row_count() {
|
||||
Some(display_row)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the longest row index (by byte length).
|
||||
#[inline]
|
||||
pub(crate) fn longest_row(&self) -> usize {
|
||||
self.wrap_map.wrapper().longest_row.row
|
||||
}
|
||||
|
||||
/// Get access to line items (for rendering)
|
||||
#[inline]
|
||||
pub(crate) fn lines(&self) -> &[LineItem] {
|
||||
self.wrap_map.lines()
|
||||
}
|
||||
|
||||
/// Get the rope text
|
||||
#[inline]
|
||||
pub fn text(&self) -> &Rope {
|
||||
self.wrap_map.text()
|
||||
}
|
||||
|
||||
/// Calculate how many wrap rows of a buffer line are visible
|
||||
#[inline]
|
||||
pub fn visible_wrap_row_count_for_buffer_line(&self, line: usize) -> usize {
|
||||
self.wrap_map.visible_wrap_row_count_for_buffer_line(line)
|
||||
}
|
||||
|
||||
/// Get the wrap row count
|
||||
#[inline]
|
||||
pub fn wrap_row_count(&self) -> usize {
|
||||
self.wrap_map.wrap_row_count()
|
||||
}
|
||||
|
||||
/// Get the buffer line count (logical lines)
|
||||
#[inline]
|
||||
pub fn buffer_line_count(&self) -> usize {
|
||||
self.wrap_map.buffer_line_count()
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
#[allow(clippy::module_inception)]
|
||||
mod display_map;
|
||||
mod text_wrapper;
|
||||
mod wrap_map;
|
||||
|
||||
pub use self::display_map::DisplayMap;
|
||||
pub(crate) use self::text_wrapper::LineLayout;
|
||||
@@ -1,582 +0,0 @@
|
||||
use std::ops::Range;
|
||||
|
||||
use gpui::{
|
||||
App, Font, Half, LineFragment, Pixels, Point, ShapedLine, Size, TextAlign, Window, point, px,
|
||||
size,
|
||||
};
|
||||
use ropey::Rope;
|
||||
use smallvec::SmallVec;
|
||||
|
||||
use crate::input::{LastLayout, Point as TreeSitterPoint, RopeExt, WhitespaceIndicators};
|
||||
|
||||
/// A line with soft wrapped lines info.
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct LineItem {
|
||||
/// The original line text, without end `\n`.
|
||||
line: Rope,
|
||||
/// The soft wrapped lines relative byte range (0..line.len) of this line (Include first line).
|
||||
///
|
||||
/// Not contains the line end `\n`.
|
||||
pub(crate) wrapped_lines: Vec<Range<usize>>,
|
||||
}
|
||||
|
||||
impl LineItem {
|
||||
/// Get the bytes length of this line.
|
||||
#[inline]
|
||||
pub(crate) fn len(&self) -> usize {
|
||||
self.line.len()
|
||||
}
|
||||
|
||||
/// Get number of soft wrapped lines of this line (include the first line).
|
||||
#[inline]
|
||||
pub(crate) fn lines_len(&self) -> usize {
|
||||
self.wrapped_lines.len()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct LongestRow {
|
||||
/// The 0-based row index.
|
||||
pub row: usize,
|
||||
/// The bytes length of the longest line.
|
||||
pub len: usize,
|
||||
}
|
||||
|
||||
/// Used to prepare the text with soft wrap to be get lines to displayed in the Editor.
|
||||
///
|
||||
/// After use lines to calculate the scroll size of the Editor.
|
||||
pub(crate) struct TextWrapper {
|
||||
text: Rope,
|
||||
/// Total wrapped lines (Inlucde the first line), value is start and end index of the line.
|
||||
soft_lines: usize,
|
||||
font: Font,
|
||||
font_size: Pixels,
|
||||
/// If is none, it means the text is not wrapped
|
||||
wrap_width: Option<Pixels>,
|
||||
/// The longest (row, bytes len) in characters, used to calculate the horizontal scroll width.
|
||||
pub(crate) longest_row: LongestRow,
|
||||
/// The lines by split \n
|
||||
pub(crate) lines: Vec<LineItem>,
|
||||
|
||||
_initialized: bool,
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
impl TextWrapper {
|
||||
pub(crate) fn new(font: Font, font_size: Pixels, wrap_width: Option<Pixels>) -> Self {
|
||||
Self {
|
||||
text: Rope::new(),
|
||||
font,
|
||||
font_size,
|
||||
wrap_width,
|
||||
soft_lines: 0,
|
||||
longest_row: LongestRow::default(),
|
||||
lines: Vec::new(),
|
||||
_initialized: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn set_default_text(&mut self, text: &Rope) {
|
||||
self.text = text.clone();
|
||||
}
|
||||
|
||||
/// Get reference to the rope text.
|
||||
#[inline]
|
||||
pub(crate) fn text(&self) -> &Rope {
|
||||
&self.text
|
||||
}
|
||||
|
||||
/// Get the total number of lines including wrapped lines.
|
||||
#[inline]
|
||||
pub(crate) fn len(&self) -> usize {
|
||||
self.soft_lines
|
||||
}
|
||||
|
||||
/// Get the line item by row index.
|
||||
#[inline]
|
||||
pub(crate) fn line(&self, row: usize) -> Option<&LineItem> {
|
||||
self.lines.get(row)
|
||||
}
|
||||
|
||||
pub(crate) fn set_wrap_width(&mut self, wrap_width: Option<Pixels>, cx: &mut App) {
|
||||
if wrap_width == self.wrap_width {
|
||||
return;
|
||||
}
|
||||
|
||||
self.wrap_width = wrap_width;
|
||||
self.update_all(&self.text.clone(), cx);
|
||||
}
|
||||
|
||||
pub(crate) fn set_font(&mut self, font: Font, font_size: Pixels, cx: &mut App) {
|
||||
if self.font.eq(&font) && self.font_size == font_size {
|
||||
return;
|
||||
}
|
||||
|
||||
self.font = font;
|
||||
self.font_size = font_size;
|
||||
self.update_all(&self.text.clone(), cx);
|
||||
}
|
||||
|
||||
pub(crate) fn prepare_if_need(&mut self, text: &Rope, cx: &mut App) -> bool {
|
||||
if self._initialized {
|
||||
return false;
|
||||
}
|
||||
self._initialized = true;
|
||||
self.update_all(text, cx);
|
||||
true
|
||||
}
|
||||
|
||||
/// Update the text wrapper and recalculate the wrapped lines.
|
||||
///
|
||||
/// If the `text` is the same as the current text, do nothing.
|
||||
///
|
||||
/// - `changed_text`: The text [`Rope`] that has changed.
|
||||
/// - `range`: The `selected_range` before change.
|
||||
/// - `new_text`: The inserted text.
|
||||
/// - `force`: Whether to force the update, if false, the update will be skipped if the text is the same.
|
||||
/// - `cx`: The application context.
|
||||
pub(crate) fn update(
|
||||
&mut self,
|
||||
changed_text: &Rope,
|
||||
range: &Range<usize>,
|
||||
new_text: &Rope,
|
||||
cx: &mut App,
|
||||
) {
|
||||
let mut line_wrapper = cx
|
||||
.text_system()
|
||||
.line_wrapper(self.font.clone(), self.font_size);
|
||||
self._update(
|
||||
changed_text,
|
||||
range,
|
||||
new_text,
|
||||
&mut |line_str, wrap_width| {
|
||||
line_wrapper
|
||||
.wrap_line(&[LineFragment::text(line_str)], wrap_width)
|
||||
.collect()
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn _update<F>(
|
||||
&mut self,
|
||||
changed_text: &Rope,
|
||||
range: &Range<usize>,
|
||||
new_text: &Rope,
|
||||
wrap_line: &mut F,
|
||||
) where
|
||||
F: FnMut(&str, Pixels) -> Vec<gpui::Boundary>,
|
||||
{
|
||||
// Remove the old changed lines.
|
||||
let start_row = self.text.offset_to_point(range.start).row;
|
||||
let start_row = start_row.min(self.lines.len().saturating_sub(1));
|
||||
let end_row = self.text.offset_to_point(range.end).row;
|
||||
let end_row = end_row.min(self.lines.len().saturating_sub(1));
|
||||
let rows_range = start_row..=end_row;
|
||||
|
||||
if rows_range.contains(&self.longest_row.row) {
|
||||
self.longest_row = LongestRow::default();
|
||||
}
|
||||
|
||||
let mut longest_row_ix = self.longest_row.row;
|
||||
let mut longest_row_len = self.longest_row.len;
|
||||
|
||||
// To add the new lines.
|
||||
let new_start_row = changed_text.offset_to_point(range.start).row;
|
||||
let new_start_offset = changed_text.line_start_offset(new_start_row);
|
||||
let new_end_row = changed_text
|
||||
.offset_to_point(range.start + new_text.len())
|
||||
.row;
|
||||
let new_end_offset = changed_text.line_end_offset(new_end_row);
|
||||
let new_range = new_start_offset..new_end_offset;
|
||||
|
||||
let mut new_lines = vec![];
|
||||
let wrap_width = self.wrap_width;
|
||||
|
||||
// line not contains `\n`.
|
||||
for (ix, line) in Rope::from(changed_text.slice(new_range))
|
||||
.iter_lines()
|
||||
.enumerate()
|
||||
{
|
||||
let line_str = line.to_string();
|
||||
let mut wrapped_lines = vec![];
|
||||
let mut prev_boundary_ix = 0;
|
||||
|
||||
if line_str.len() > longest_row_len {
|
||||
longest_row_ix = new_start_row + ix;
|
||||
longest_row_len = line_str.len();
|
||||
}
|
||||
|
||||
// If wrap_width is Pixels::MAX, skip wrapping to disable word wrap
|
||||
if let Some(wrap_width) = wrap_width {
|
||||
// Here only have wrapped line, if there is no wrap meet, the `line_wraps` result will empty.
|
||||
for boundary in wrap_line(&line_str, wrap_width) {
|
||||
wrapped_lines.push(prev_boundary_ix..boundary.ix);
|
||||
prev_boundary_ix = boundary.ix;
|
||||
}
|
||||
}
|
||||
|
||||
// Reset of the line
|
||||
if !line_str[prev_boundary_ix..].is_empty() || prev_boundary_ix == 0 {
|
||||
wrapped_lines.push(prev_boundary_ix..line.len());
|
||||
}
|
||||
|
||||
new_lines.push(LineItem {
|
||||
line: Rope::from(line),
|
||||
wrapped_lines,
|
||||
});
|
||||
}
|
||||
|
||||
if self.lines.is_empty() {
|
||||
self.lines = new_lines;
|
||||
} else {
|
||||
self.lines.splice(rows_range, new_lines);
|
||||
}
|
||||
|
||||
self.text = changed_text.clone();
|
||||
self.soft_lines = self.lines.iter().map(|l| l.lines_len()).sum();
|
||||
self.longest_row = LongestRow {
|
||||
row: longest_row_ix,
|
||||
len: longest_row_len,
|
||||
}
|
||||
}
|
||||
|
||||
/// Update the text wrapper and recalculate the wrapped lines.
|
||||
///
|
||||
/// If the `text` is the same as the current text, do nothing.
|
||||
fn update_all(&mut self, text: &Rope, cx: &mut App) {
|
||||
self.update(text, &(0..text.len()), text, cx);
|
||||
}
|
||||
|
||||
/// Return display point (with soft wrap) from the given byte offset in the text.
|
||||
///
|
||||
/// Panics if the `offset` is out of bounds.
|
||||
pub(crate) fn offset_to_display_point(&self, offset: usize) -> WrapDisplayPoint {
|
||||
let row = self.text.offset_to_point(offset).row;
|
||||
let start = self.text.line_start_offset(row);
|
||||
let line = &self.lines[row];
|
||||
|
||||
let mut wrapped_row = self
|
||||
.lines
|
||||
.iter()
|
||||
.take(row)
|
||||
.map(|l| l.lines_len())
|
||||
.sum::<usize>();
|
||||
|
||||
let local_offset = offset.saturating_sub(start);
|
||||
for (ix, range) in line.wrapped_lines.iter().enumerate() {
|
||||
if range.contains(&local_offset) {
|
||||
return WrapDisplayPoint::new(
|
||||
wrapped_row + ix,
|
||||
ix,
|
||||
local_offset.saturating_sub(range.start),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Otherwise return the eof of the line.
|
||||
let last_range = line.wrapped_lines.last().unwrap_or(&(0..0));
|
||||
let ix = line.lines_len().saturating_sub(1);
|
||||
|
||||
WrapDisplayPoint::new(wrapped_row + ix, ix, last_range.len())
|
||||
}
|
||||
|
||||
/// Return byte offset in the text from the given display point (with soft wrap).
|
||||
///
|
||||
/// Panics if the `point.row` is out of bounds.
|
||||
pub(crate) fn display_point_to_offset(&self, point: WrapDisplayPoint) -> usize {
|
||||
let mut wrapped_row = 0;
|
||||
for (row, line) in self.lines.iter().enumerate() {
|
||||
if wrapped_row + line.lines_len() > point.row {
|
||||
let line_start = self.text.line_start_offset(row);
|
||||
let local_row = point.row.saturating_sub(wrapped_row);
|
||||
if let Some(range) = line.wrapped_lines.get(local_row) {
|
||||
return line_start + (range.start + point.column).min(range.end);
|
||||
} else {
|
||||
// If not found, return the end of the line.
|
||||
return line_start + line.len();
|
||||
}
|
||||
}
|
||||
|
||||
wrapped_row += line.lines_len();
|
||||
}
|
||||
|
||||
self.text.len()
|
||||
}
|
||||
|
||||
pub(crate) fn display_point_to_point(&self, point: WrapDisplayPoint) -> TreeSitterPoint {
|
||||
let offset = self.display_point_to_offset(point);
|
||||
self.text.offset_to_point(offset)
|
||||
}
|
||||
|
||||
pub(crate) fn point_to_display_point(&self, point: TreeSitterPoint) -> WrapDisplayPoint {
|
||||
let offset = self.text.point_to_offset(point);
|
||||
self.offset_to_display_point(offset)
|
||||
}
|
||||
}
|
||||
|
||||
/// A display point within the soft-wrapped text.
|
||||
///
|
||||
/// This represents a position in the text after soft-wrapping,
|
||||
/// with an additional `local_row` field tracking the wrap line
|
||||
/// within the original buffer line.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) struct WrapDisplayPoint {
|
||||
/// The 0-based soft wrapped row index in the text.
|
||||
pub row: usize,
|
||||
/// The 0-based row index in local line (include first line).
|
||||
///
|
||||
/// This value only valid when return from [`TextWrapper::offset_to_display_point`], otherwise it will be ignored.
|
||||
pub local_row: usize,
|
||||
/// The 0-based column byte index in the display line (with soft wrap).
|
||||
pub column: usize,
|
||||
}
|
||||
|
||||
impl WrapDisplayPoint {
|
||||
pub fn new(row: usize, local_row: usize, column: usize) -> Self {
|
||||
Self {
|
||||
row,
|
||||
local_row,
|
||||
column,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The layout info of a line with soft wrapped lines.
|
||||
pub(crate) struct LineLayout {
|
||||
/// Total bytes length of this line.
|
||||
len: usize,
|
||||
/// The soft wrapped lines of this line (Include the first line).
|
||||
pub(crate) wrapped_lines: SmallVec<[ShapedLine; 1]>,
|
||||
pub(crate) longest_width: Pixels,
|
||||
pub(crate) whitespace_indicators: Option<WhitespaceIndicators>,
|
||||
/// Whitespace indicators: (line_index, x_position, is_tab)
|
||||
pub(crate) whitespace_chars: Vec<(usize, Pixels, bool)>,
|
||||
}
|
||||
|
||||
impl LineLayout {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
len: 0,
|
||||
longest_width: px(0.),
|
||||
wrapped_lines: SmallVec::new(),
|
||||
whitespace_chars: Vec::new(),
|
||||
whitespace_indicators: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn lines(mut self, wrapped_lines: SmallVec<[ShapedLine; 1]>) -> Self {
|
||||
self.set_wrapped_lines(wrapped_lines);
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn set_wrapped_lines(&mut self, wrapped_lines: SmallVec<[ShapedLine; 1]>) {
|
||||
self.len = wrapped_lines.iter().map(|l| l.len).sum();
|
||||
let width = wrapped_lines
|
||||
.iter()
|
||||
.map(|l| l.width)
|
||||
.max()
|
||||
.unwrap_or_default();
|
||||
self.longest_width = width;
|
||||
self.wrapped_lines = wrapped_lines;
|
||||
}
|
||||
|
||||
pub(crate) fn with_whitespaces(mut self, indicators: Option<WhitespaceIndicators>) -> Self {
|
||||
self.whitespace_indicators = indicators;
|
||||
let Some(indicators) = self.whitespace_indicators.as_ref() else {
|
||||
return self;
|
||||
};
|
||||
|
||||
let space_indicator_offset = indicators.space.width.half();
|
||||
|
||||
for (line_index, wrapped_line) in self.wrapped_lines.iter().enumerate() {
|
||||
for (relative_offset, c) in wrapped_line.text.char_indices() {
|
||||
if matches!(c, ' ' | '\t') {
|
||||
let is_tab = c == '\t';
|
||||
let start_x = wrapped_line.x_for_index(relative_offset);
|
||||
let end_x = wrapped_line.x_for_index(relative_offset + c.len_utf8());
|
||||
// Center the indicator in the actual character's space
|
||||
let x_position = if c == ' ' {
|
||||
(start_x + end_x).half() - space_indicator_offset
|
||||
} else {
|
||||
start_x
|
||||
};
|
||||
|
||||
self.whitespace_chars.push((line_index, x_position, is_tab));
|
||||
}
|
||||
}
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn len(&self) -> usize {
|
||||
self.len
|
||||
}
|
||||
|
||||
/// Get the position (x, y) for the given index in this line layout.
|
||||
///
|
||||
/// - The `offset` is a local byte index in this line layout.
|
||||
/// - When `line_end_affinity` is true, an offset at a soft wrap boundary is placed at
|
||||
/// the end of the current visual line rather than the start of the next one.
|
||||
/// - The return value is relative to the top-left corner of this line layout, start from (0, 0)
|
||||
pub(crate) fn position_for_index(
|
||||
&self,
|
||||
offset: usize,
|
||||
last_layout: &LastLayout,
|
||||
line_end_affinity: bool,
|
||||
) -> Option<Point<Pixels>> {
|
||||
let mut acc_len = 0;
|
||||
let mut offset_y = px(0.);
|
||||
|
||||
let x_offset = last_layout.alignment_offset(self.longest_width);
|
||||
|
||||
for (i, line) in self.wrapped_lines.iter().enumerate() {
|
||||
let is_last = i + 1 == self.wrapped_lines.len();
|
||||
|
||||
let matches = if line.len == 0 {
|
||||
// Empty visual lines still own their boundary offset.
|
||||
offset == acc_len
|
||||
} else if is_last || line_end_affinity {
|
||||
// Inclusive: cursor can sit at end of this visual line.
|
||||
offset >= acc_len && offset <= acc_len + line.len
|
||||
} else {
|
||||
// Exclusive: boundary offset belongs to the next visual line.
|
||||
offset >= acc_len && offset < acc_len + line.len
|
||||
};
|
||||
|
||||
if matches {
|
||||
let x = line.x_for_index(offset.saturating_sub(acc_len)) + x_offset;
|
||||
return Some(point(x, offset_y));
|
||||
}
|
||||
|
||||
// Always advance by actual line length. The last line gets +1 so the
|
||||
// cursor can be placed after the final character.
|
||||
acc_len += if is_last { line.len + 1 } else { line.len };
|
||||
offset_y += last_layout.line_height;
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// Get the closest index for the given x in this line layout.
|
||||
pub(crate) fn closest_index_for_x(&self, x: Pixels, last_layout: &LastLayout) -> usize {
|
||||
let mut acc_len = 0;
|
||||
let x_offset = last_layout.alignment_offset(self.longest_width);
|
||||
let x = x - x_offset;
|
||||
|
||||
for (i, line) in self.wrapped_lines.iter().enumerate() {
|
||||
let is_last = i + 1 == self.wrapped_lines.len();
|
||||
if x <= line.width {
|
||||
let mut ix = line.closest_index_for_x(x);
|
||||
if !is_last && ix == line.text.len() {
|
||||
// For soft wrap line, we can't put the cursor at the end of the line.
|
||||
let c_len = line.text.chars().last().map(|c| c.len_utf8()).unwrap_or(0);
|
||||
ix = ix.saturating_sub(c_len);
|
||||
}
|
||||
|
||||
return acc_len + ix;
|
||||
}
|
||||
acc_len += line.text.len();
|
||||
}
|
||||
|
||||
acc_len
|
||||
}
|
||||
|
||||
/// Get the index for the given position (x, y) in this line layout.
|
||||
///
|
||||
/// The `pos` is relative to the top-left corner of this line layout, start from (0, 0)
|
||||
/// The return value is a local byte index in this line layout, start from 0.
|
||||
pub(crate) fn closest_index_for_position(
|
||||
&self,
|
||||
pos: Point<Pixels>,
|
||||
last_layout: &LastLayout,
|
||||
) -> Option<usize> {
|
||||
let mut offset = 0;
|
||||
let mut line_top = px(0.);
|
||||
let x_offset = last_layout.alignment_offset(self.longest_width);
|
||||
for (i, line) in self.wrapped_lines.iter().enumerate() {
|
||||
let is_last = i + 1 == self.wrapped_lines.len();
|
||||
let line_bottom = line_top + last_layout.line_height;
|
||||
if pos.y >= line_top && pos.y < line_bottom {
|
||||
let mut ix = line.closest_index_for_x(pos.x - x_offset);
|
||||
if !is_last && ix == line.text.len() {
|
||||
// For soft wrap line, we can't put the cursor at the end of the line.
|
||||
let c_len = line.text.chars().last().map(|c| c.len_utf8()).unwrap_or(0);
|
||||
ix = ix.saturating_sub(c_len);
|
||||
}
|
||||
return Some(offset + ix);
|
||||
}
|
||||
|
||||
offset += line.text.len();
|
||||
line_top = line_bottom;
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
pub(crate) fn index_for_position(
|
||||
&self,
|
||||
pos: Point<Pixels>,
|
||||
last_layout: &LastLayout,
|
||||
) -> Option<usize> {
|
||||
let mut offset = 0;
|
||||
let mut line_top = px(0.);
|
||||
let x_offset = last_layout.alignment_offset(self.longest_width);
|
||||
for line in self.wrapped_lines.iter() {
|
||||
let line_bottom = line_top + last_layout.line_height;
|
||||
if pos.y >= line_top && pos.y < line_bottom {
|
||||
let ix = line.index_for_x(pos.x - x_offset)?;
|
||||
return Some(offset + ix);
|
||||
}
|
||||
|
||||
offset += line.text.len();
|
||||
line_top = line_bottom;
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
pub(crate) fn size(&self, line_height: Pixels) -> Size<Pixels> {
|
||||
size(self.longest_width, self.wrapped_lines.len() * line_height)
|
||||
}
|
||||
|
||||
pub(crate) fn paint(
|
||||
&self,
|
||||
pos: Point<Pixels>,
|
||||
line_height: Pixels,
|
||||
text_align: TextAlign,
|
||||
align_width: Option<Pixels>,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
for (ix, line) in self.wrapped_lines.iter().enumerate() {
|
||||
_ = line.paint(
|
||||
pos + point(px(0.), ix * line_height),
|
||||
line_height,
|
||||
text_align,
|
||||
align_width,
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
}
|
||||
|
||||
// Paint whitespace indicators
|
||||
if let Some(indicators) = self.whitespace_indicators.as_ref() {
|
||||
for (line_index, x_position, is_tab) in &self.whitespace_chars {
|
||||
let invisible = if *is_tab {
|
||||
indicators.tab.clone()
|
||||
} else {
|
||||
indicators.space.clone()
|
||||
};
|
||||
|
||||
let origin = point(
|
||||
pos.x + *x_position,
|
||||
pos.y + *line_index as f32 * line_height,
|
||||
);
|
||||
|
||||
_ = invisible.paint(origin, line_height, text_align, align_width, window, cx);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,172 +0,0 @@
|
||||
/// WrapMap: Soft-wrapping layer (Buffer → Wrap rows).
|
||||
///
|
||||
/// This module wraps the existing TextWrapper and provides:
|
||||
/// - BufferPoint ↔ WrapPoint mapping
|
||||
/// - Efficient buffer_line → wrap_row queries via prefix sum cache
|
||||
/// - Incremental updates when text or layout changes
|
||||
use std::ops::Range;
|
||||
|
||||
use gpui::{App, Font, Pixels};
|
||||
use ropey::Rope;
|
||||
|
||||
use super::text_wrapper::{LineItem, TextWrapper};
|
||||
|
||||
/// WrapMap manages soft-wrapping and provides buffer ↔ wrap coordinate mapping.
|
||||
pub struct WrapMap {
|
||||
/// The underlying text wrapper (reuses existing implementation)
|
||||
wrapper: TextWrapper,
|
||||
|
||||
/// Prefix sum cache: buffer_line_starts[line] = first wrap_row for buffer line `line`
|
||||
/// This allows O(1) lookup of buffer_line → wrap_row
|
||||
buffer_line_starts: Vec<usize>,
|
||||
|
||||
/// Cached line count from last rebuild
|
||||
cached_line_count: usize,
|
||||
|
||||
/// Cached total wrap row count from last rebuild.
|
||||
/// Used together with `cached_line_count` to detect if the cache is stale.
|
||||
/// When soft wrap changes a line's wrap count without changing buffer line count,
|
||||
/// this catches the staleness.
|
||||
cached_wrap_row_count: usize,
|
||||
}
|
||||
|
||||
impl WrapMap {
|
||||
pub fn new(font: Font, font_size: Pixels, wrap_width: Option<Pixels>) -> Self {
|
||||
Self {
|
||||
wrapper: TextWrapper::new(font, font_size, wrap_width),
|
||||
buffer_line_starts: Vec::new(),
|
||||
cached_line_count: 0,
|
||||
cached_wrap_row_count: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get total number of wrap rows (visual rows after soft-wrapping)
|
||||
#[inline]
|
||||
pub fn wrap_row_count(&self) -> usize {
|
||||
self.wrapper.len()
|
||||
}
|
||||
|
||||
/// Get total number of buffer lines (logical lines)
|
||||
#[inline]
|
||||
pub fn buffer_line_count(&self) -> usize {
|
||||
self.wrapper.lines.len()
|
||||
}
|
||||
|
||||
/// Get the buffer line for a given wrap row
|
||||
pub fn wrap_row_to_buffer_line(&self, wrap_row: usize) -> usize {
|
||||
if wrap_row >= self.wrap_row_count() {
|
||||
return self.buffer_line_count().saturating_sub(1);
|
||||
}
|
||||
|
||||
// Binary search in prefix sum cache
|
||||
match self.buffer_line_starts.binary_search(&wrap_row) {
|
||||
Ok(line) => line,
|
||||
Err(insert_pos) => insert_pos.saturating_sub(1),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the first wrap row for a given buffer line
|
||||
pub fn buffer_line_to_first_wrap_row(&self, line: usize) -> usize {
|
||||
if line >= self.buffer_line_starts.len() {
|
||||
return self.wrap_row_count();
|
||||
}
|
||||
self.buffer_line_starts[line]
|
||||
}
|
||||
|
||||
/// Get the wrap row range for a buffer line: [start, end)
|
||||
pub fn buffer_line_to_wrap_row_range(&self, line: usize) -> Range<usize> {
|
||||
let start = self.buffer_line_to_first_wrap_row(line);
|
||||
let end = if line + 1 < self.buffer_line_starts.len() {
|
||||
self.buffer_line_starts[line + 1]
|
||||
} else {
|
||||
self.wrap_row_count()
|
||||
};
|
||||
start..end
|
||||
}
|
||||
|
||||
/// Update text (incremental or full)
|
||||
pub fn on_text_changed(
|
||||
&mut self,
|
||||
changed_text: &Rope,
|
||||
range: &Range<usize>,
|
||||
new_text: &Rope,
|
||||
cx: &mut App,
|
||||
) {
|
||||
self.wrapper.update(changed_text, range, new_text, cx);
|
||||
self.rebuild_cache();
|
||||
}
|
||||
|
||||
/// Update layout parameters (wrap width or font)
|
||||
pub fn on_layout_changed(&mut self, wrap_width: Option<Pixels>, cx: &mut App) {
|
||||
self.wrapper.set_wrap_width(wrap_width, cx);
|
||||
self.rebuild_cache();
|
||||
}
|
||||
|
||||
/// Set font parameters
|
||||
pub fn set_font(&mut self, font: Font, font_size: Pixels, cx: &mut App) {
|
||||
self.wrapper.set_font(font, font_size, cx);
|
||||
self.rebuild_cache();
|
||||
}
|
||||
|
||||
/// Ensure text is prepared (initializes wrapper if needed)
|
||||
pub fn ensure_text_prepared(&mut self, text: &Rope, cx: &mut App) -> bool {
|
||||
let did_initialize = self.wrapper.prepare_if_need(text, cx);
|
||||
if did_initialize {
|
||||
self.rebuild_cache();
|
||||
}
|
||||
did_initialize
|
||||
}
|
||||
|
||||
/// Initialize with text
|
||||
pub fn set_text(&mut self, text: &Rope, cx: &mut App) {
|
||||
self.wrapper.set_default_text(text);
|
||||
self.wrapper.prepare_if_need(text, cx);
|
||||
self.rebuild_cache();
|
||||
}
|
||||
|
||||
/// Rebuild the prefix sum cache: buffer_line_starts
|
||||
fn rebuild_cache(&mut self) {
|
||||
let line_count = self.wrapper.lines.len();
|
||||
let wrap_row_count = self.wrapper.len();
|
||||
|
||||
// Skip if nothing changed: both buffer line count and total wrap row count must match.
|
||||
if line_count == self.cached_line_count
|
||||
&& wrap_row_count == self.cached_wrap_row_count
|
||||
&& !self.buffer_line_starts.is_empty()
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
self.buffer_line_starts.clear();
|
||||
|
||||
let mut wrap_row = 0;
|
||||
for line_item in &self.wrapper.lines {
|
||||
self.buffer_line_starts.push(wrap_row);
|
||||
wrap_row += line_item.lines_len();
|
||||
}
|
||||
|
||||
self.cached_line_count = line_count;
|
||||
self.cached_wrap_row_count = wrap_row_count;
|
||||
}
|
||||
|
||||
/// Get access to the underlying wrapper (for rendering/hit-testing)
|
||||
pub(crate) fn wrapper(&self) -> &TextWrapper {
|
||||
&self.wrapper
|
||||
}
|
||||
|
||||
/// Get access to line items (for rendering)
|
||||
pub(crate) fn lines(&self) -> &[LineItem] {
|
||||
&self.wrapper.lines
|
||||
}
|
||||
|
||||
/// Get the rope text
|
||||
pub fn text(&self) -> &Rope {
|
||||
self.wrapper.text()
|
||||
}
|
||||
|
||||
/// Calculate how many wrap rows of a buffer line are visible.
|
||||
/// Without folding, all wrap rows are visible.
|
||||
pub fn visible_wrap_row_count_for_buffer_line(&self, line: usize) -> usize {
|
||||
self.buffer_line_to_wrap_row_range(line).len()
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,269 +0,0 @@
|
||||
use gpui::{Context, EntityInputHandler, SharedString, Window};
|
||||
use ropey::RopeSlice;
|
||||
|
||||
use crate::input::mode::InputMode;
|
||||
use crate::input::{Indent, IndentInline, InputState, Outdent, OutdentInline};
|
||||
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub struct TabSize {
|
||||
/// Default is 2
|
||||
pub tab_size: usize,
|
||||
/// Set true to use `\t` as tab indent, default is false
|
||||
pub hard_tabs: bool,
|
||||
}
|
||||
|
||||
impl Default for TabSize {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
tab_size: 2,
|
||||
hard_tabs: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TabSize {
|
||||
pub(super) fn to_string(self) -> SharedString {
|
||||
if self.hard_tabs {
|
||||
"\t".into()
|
||||
} else {
|
||||
" ".repeat(self.tab_size).into()
|
||||
}
|
||||
}
|
||||
|
||||
/// Count the indent size of the line in spaces.
|
||||
pub fn indent_count(&self, line: &RopeSlice) -> usize {
|
||||
let mut count = 0;
|
||||
for ch in line.chars() {
|
||||
match ch {
|
||||
'\t' => count += self.tab_size,
|
||||
' ' => count += 1,
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
|
||||
count
|
||||
}
|
||||
}
|
||||
|
||||
impl InputState {
|
||||
/// Set the tab size for the input.
|
||||
///
|
||||
/// Only for [`InputMode::PlainText`] mode with multi_line.
|
||||
pub fn tab_size(mut self, tab: TabSize) -> Self {
|
||||
debug_assert!(self.mode.is_multi_line());
|
||||
if let InputMode::PlainText { tab: t, .. } = &mut self.mode {
|
||||
*t = tab;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
pub(super) fn indent_inline(
|
||||
&mut self,
|
||||
_: &IndentInline,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
self.indent(false, window, cx);
|
||||
}
|
||||
|
||||
pub(super) fn indent_block(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
|
||||
self.indent(true, window, cx);
|
||||
}
|
||||
|
||||
pub(super) fn outdent_inline(
|
||||
&mut self,
|
||||
_: &OutdentInline,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
self.outdent(false, window, cx);
|
||||
}
|
||||
|
||||
pub(super) fn outdent_block(
|
||||
&mut self,
|
||||
_: &Outdent,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
self.outdent(true, window, cx);
|
||||
}
|
||||
|
||||
pub(super) fn indent(&mut self, block: bool, window: &mut Window, cx: &mut Context<Self>) {
|
||||
if !self.mode.is_indentable() {
|
||||
cx.propagate();
|
||||
return;
|
||||
};
|
||||
|
||||
let tab_indent = self.mode.tab_size().to_string();
|
||||
let selected_range = self.selected_range;
|
||||
let mut added_len = 0;
|
||||
let is_selected = !self.selected_range.is_empty();
|
||||
|
||||
if is_selected || block {
|
||||
let start_offset = self.start_of_line_of_selection(window, cx);
|
||||
let mut offset = start_offset;
|
||||
|
||||
let selected_text = self
|
||||
.text_for_range(
|
||||
self.range_to_utf16(&(offset..selected_range.end)),
|
||||
&mut None,
|
||||
window,
|
||||
cx,
|
||||
)
|
||||
.unwrap_or("".into());
|
||||
|
||||
for line in selected_text.split('\n') {
|
||||
self.replace_text_in_range_silent(
|
||||
Some(self.range_to_utf16(&(offset..offset))),
|
||||
&tab_indent,
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
added_len += tab_indent.len();
|
||||
// +1 for "\n", the `\r` is included in the `line`.
|
||||
offset += line.len() + tab_indent.len() + 1;
|
||||
}
|
||||
|
||||
if is_selected {
|
||||
self.selected_range = (start_offset..selected_range.end + added_len).into();
|
||||
} else {
|
||||
self.selected_range =
|
||||
(selected_range.start + added_len..selected_range.end + added_len).into();
|
||||
}
|
||||
} else {
|
||||
// Selected none
|
||||
let offset = self.selected_range.start;
|
||||
self.replace_text_in_range_silent(
|
||||
Some(self.range_to_utf16(&(offset..offset))),
|
||||
&tab_indent,
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
added_len = tab_indent.len();
|
||||
|
||||
self.selected_range =
|
||||
(selected_range.start + added_len..selected_range.end + added_len).into();
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn outdent(&mut self, block: bool, window: &mut Window, cx: &mut Context<Self>) {
|
||||
if !self.mode.is_indentable() {
|
||||
cx.propagate();
|
||||
return;
|
||||
};
|
||||
|
||||
let tab_indent = self.mode.tab_size().to_string();
|
||||
let selected_range = self.selected_range;
|
||||
let mut removed_len = 0;
|
||||
let is_selected = !self.selected_range.is_empty();
|
||||
|
||||
if is_selected || block {
|
||||
let start_offset = self.start_of_line_of_selection(window, cx);
|
||||
let mut offset = start_offset;
|
||||
|
||||
let selected_text = self
|
||||
.text_for_range(
|
||||
self.range_to_utf16(&(offset..selected_range.end)),
|
||||
&mut None,
|
||||
window,
|
||||
cx,
|
||||
)
|
||||
.unwrap_or("".into());
|
||||
|
||||
for line in selected_text.split('\n') {
|
||||
if line.starts_with(tab_indent.as_ref()) {
|
||||
self.replace_text_in_range_silent(
|
||||
Some(self.range_to_utf16(&(offset..offset + tab_indent.len()))),
|
||||
"",
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
removed_len += tab_indent.len();
|
||||
|
||||
// +1 for "\n"
|
||||
offset += line.len().saturating_sub(tab_indent.len()) + 1;
|
||||
} else {
|
||||
offset += line.len() + 1;
|
||||
}
|
||||
}
|
||||
|
||||
if is_selected {
|
||||
self.selected_range =
|
||||
(start_offset..selected_range.end.saturating_sub(removed_len)).into();
|
||||
} else {
|
||||
self.selected_range = (selected_range.start.saturating_sub(removed_len)
|
||||
..selected_range.end.saturating_sub(removed_len))
|
||||
.into();
|
||||
}
|
||||
} else {
|
||||
// Selected none
|
||||
let start_offset = self.selected_range.start;
|
||||
let offset = self.start_of_line_of_selection(window, cx);
|
||||
let offset = self.offset_from_utf16(self.offset_to_utf16(offset));
|
||||
// FIXME: To improve performance
|
||||
if self
|
||||
.text
|
||||
.slice(offset..self.text.len())
|
||||
.to_string()
|
||||
.starts_with(tab_indent.as_ref())
|
||||
{
|
||||
self.replace_text_in_range_silent(
|
||||
Some(self.range_to_utf16(&(offset..offset + tab_indent.len()))),
|
||||
"",
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
removed_len = tab_indent.len();
|
||||
let new_offset = start_offset.saturating_sub(removed_len);
|
||||
self.selected_range = (new_offset..new_offset).into();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use ropey::RopeSlice;
|
||||
|
||||
use super::TabSize;
|
||||
|
||||
#[test]
|
||||
fn test_tab_size() {
|
||||
let tab = TabSize {
|
||||
tab_size: 2,
|
||||
hard_tabs: false,
|
||||
};
|
||||
assert_eq!(tab.to_string(), " ");
|
||||
let tab = TabSize {
|
||||
tab_size: 4,
|
||||
hard_tabs: false,
|
||||
};
|
||||
assert_eq!(tab.to_string(), " ");
|
||||
|
||||
let tab = TabSize {
|
||||
tab_size: 2,
|
||||
hard_tabs: true,
|
||||
};
|
||||
assert_eq!(tab.to_string(), "\t");
|
||||
let tab = TabSize {
|
||||
tab_size: 4,
|
||||
hard_tabs: true,
|
||||
};
|
||||
assert_eq!(tab.to_string(), "\t");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tab_size_indent_count() {
|
||||
let tab = TabSize {
|
||||
tab_size: 4,
|
||||
hard_tabs: false,
|
||||
};
|
||||
assert_eq!(tab.indent_count(&RopeSlice::from("abc")), 0);
|
||||
assert_eq!(tab.indent_count(&RopeSlice::from(" abc")), 2);
|
||||
assert_eq!(tab.indent_count(&RopeSlice::from(" abc")), 4);
|
||||
assert_eq!(tab.indent_count(&RopeSlice::from("\tabc")), 4);
|
||||
assert_eq!(tab.indent_count(&RopeSlice::from(" \tabc")), 6);
|
||||
assert_eq!(tab.indent_count(&RopeSlice::from(" \t abc ")), 6);
|
||||
assert_eq!(tab.indent_count(&RopeSlice::from("abc")), 0);
|
||||
}
|
||||
}
|
||||
+112
-169
@@ -1,31 +1,76 @@
|
||||
use gpui::prelude::FluentBuilder as _;
|
||||
use gpui::{
|
||||
AnyElement, App, DefiniteLength, Edges, EdgesRefinement, Entity, Hsla, InteractiveElement as _,
|
||||
IntoElement, MouseButton, ParentElement as _, Rems, RenderOnce, StyleRefinement, Styled,
|
||||
TextAlign, Window, div, px, relative,
|
||||
AnyElement, App, DefiniteLength, Edges, Entity, Hsla, InteractiveElement as _, IntoElement,
|
||||
MouseButton, ParentElement as _, Pixels, Rems, RenderOnce, StyleRefinement, Styled, TextAlign,
|
||||
Window, div, px, relative,
|
||||
};
|
||||
use gpui_base::InputBase;
|
||||
use gpui_base::input::{InputBaseState, InputEditorStyle, InputMode, InputModeKind, TextareaMode};
|
||||
use theme::ActiveTheme;
|
||||
|
||||
use super::InputState;
|
||||
use super::element::EditorScrollbar;
|
||||
use crate::button::{Button, ButtonVariants as _};
|
||||
use crate::indicator::Indicator;
|
||||
use crate::input::clear_button;
|
||||
use crate::{IconName, Selectable, Sizable, Size, StyleSized, StyledExt, h_flex, v_flex};
|
||||
|
||||
/// Returns `(background, foreground)` colors for input-like components.
|
||||
pub(crate) fn input_style(disabled: bool, cx: &App) -> (Hsla, Hsla) {
|
||||
/// The background of an input frame, which reads muted while the input is disabled.
|
||||
fn input_background(disabled: bool, cx: &App) -> Hsla {
|
||||
if disabled {
|
||||
(cx.theme().surface_background, cx.theme().text_muted)
|
||||
cx.theme().surface_background
|
||||
} else {
|
||||
(cx.theme().elevated_surface_background, cx.theme().text)
|
||||
cx.theme().elevated_surface_background
|
||||
}
|
||||
}
|
||||
|
||||
/// A text input element bind to an [`InputState`].
|
||||
/// The colors base paints input text with, read from the coop theme.
|
||||
///
|
||||
/// Base fills in any color left transparent from its own palette, and that
|
||||
/// palette is only a projection of this one, so every color coop paints with is
|
||||
/// named here rather than left to resolve.
|
||||
fn input_editor_style(cx: &App) -> InputEditorStyle {
|
||||
let theme = cx.theme();
|
||||
InputEditorStyle {
|
||||
foreground: theme.text,
|
||||
muted_foreground: theme.text_muted,
|
||||
background: theme.elevated_surface_background,
|
||||
border: theme.border,
|
||||
selection: theme.selection,
|
||||
caret: theme.cursor,
|
||||
..InputEditorStyle::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The input's own padding, resolved to pixels.
|
||||
///
|
||||
/// Base applies the multi-line padding itself so that the text, the gutter, and
|
||||
/// the scrollbar share one inset, and the single-line frame carries its own.
|
||||
/// Both come from the same size table, resolved through the window's rem size.
|
||||
fn input_paddings(size: Size, style: &StyleRefinement, window: &Window) -> Edges<Pixels> {
|
||||
let mut probe = div().input_px(size).input_py(size).refine_style(style);
|
||||
let padding = probe.style().padding.clone();
|
||||
let base_size = window.text_style().font_size;
|
||||
let rem_size = window.rem_size();
|
||||
let resolve = |value: Option<DefiniteLength>| {
|
||||
value
|
||||
.map(|value| value.to_pixels(base_size, rem_size))
|
||||
.unwrap_or(px(0.))
|
||||
};
|
||||
|
||||
Edges {
|
||||
left: resolve(padding.left),
|
||||
right: resolve(padding.right),
|
||||
top: resolve(padding.top),
|
||||
bottom: resolve(padding.bottom),
|
||||
}
|
||||
}
|
||||
|
||||
/// A text input element bound to an [`InputState`] or a [`TextareaState`].
|
||||
///
|
||||
/// The editing kind lives on the state, so `Input::new` accepts either and
|
||||
/// infers which one is rendered.
|
||||
#[derive(IntoElement)]
|
||||
pub struct Input {
|
||||
state: Entity<InputState>,
|
||||
pub struct Input<M: InputModeKind = InputMode> {
|
||||
state: Entity<InputBaseState<M>>,
|
||||
style: StyleRefinement,
|
||||
size: Size,
|
||||
prefix: Option<AnyElement>,
|
||||
@@ -39,14 +84,17 @@ pub struct Input {
|
||||
selected: bool,
|
||||
}
|
||||
|
||||
impl Sizable for Input {
|
||||
/// A styled multi-line text input.
|
||||
pub type Textarea = Input<TextareaMode>;
|
||||
|
||||
impl<M: InputModeKind> Sizable for Input<M> {
|
||||
fn with_size(mut self, size: impl Into<Size>) -> Self {
|
||||
self.size = size.into();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Selectable for Input {
|
||||
impl<M: InputModeKind> Selectable for Input<M> {
|
||||
fn selected(mut self, selected: bool) -> Self {
|
||||
self.selected = selected;
|
||||
self
|
||||
@@ -57,9 +105,9 @@ impl Selectable for Input {
|
||||
}
|
||||
}
|
||||
|
||||
impl Input {
|
||||
/// Create a new [`Input`] element bind to the [`InputState`].
|
||||
pub fn new(state: &Entity<InputState>) -> Self {
|
||||
impl<M: InputModeKind> Input<M> {
|
||||
/// Create a new [`Input`] element bind to the given state.
|
||||
pub fn new(state: &Entity<InputBaseState<M>>) -> Self {
|
||||
Self {
|
||||
state: state.clone(),
|
||||
size: Size::default(),
|
||||
@@ -128,8 +176,7 @@ impl Input {
|
||||
self
|
||||
}
|
||||
|
||||
fn render_toggle_mask_button(state: &Entity<InputState>, cx: &App) -> impl IntoElement {
|
||||
let _masked = state.read(cx).masked;
|
||||
fn render_toggle_mask_button(state: &Entity<InputBaseState<M>>) -> impl IntoElement {
|
||||
Button::new("toggle-mask")
|
||||
.icon(IconName::Eye)
|
||||
.xsmall()
|
||||
@@ -137,78 +184,42 @@ impl Input {
|
||||
.tab_stop(false)
|
||||
.on_click({
|
||||
let state = state.clone();
|
||||
move |_, window, cx| {
|
||||
state.update(cx, |state, cx| {
|
||||
state.set_masked(!state.masked, window, cx);
|
||||
})
|
||||
}
|
||||
move |_, window, cx| state.update(cx, |state, cx| state.toggle_masked(window, cx))
|
||||
})
|
||||
}
|
||||
|
||||
/// This method must after the refine_style.
|
||||
fn render_editor(
|
||||
paddings: EdgesRefinement<DefiniteLength>,
|
||||
input_state: &Entity<InputState>,
|
||||
state: &InputState,
|
||||
window: &Window,
|
||||
) -> impl IntoElement {
|
||||
let base_size = window.text_style().font_size;
|
||||
let rem_size = window.rem_size();
|
||||
|
||||
let paddings = Edges {
|
||||
left: paddings
|
||||
.left
|
||||
.map(|v| v.to_pixels(base_size, rem_size))
|
||||
.unwrap_or(px(0.)),
|
||||
right: paddings
|
||||
.right
|
||||
.map(|v| v.to_pixels(base_size, rem_size))
|
||||
.unwrap_or(px(0.)),
|
||||
top: paddings
|
||||
.top
|
||||
.map(|v| v.to_pixels(base_size, rem_size))
|
||||
.unwrap_or(px(0.)),
|
||||
bottom: paddings
|
||||
.bottom
|
||||
.map(|v| v.to_pixels(base_size, rem_size))
|
||||
.unwrap_or(px(0.)),
|
||||
};
|
||||
|
||||
state.editor_scrollbar_paddings.set(paddings);
|
||||
state.editor_scrollbar_snapshot.set(None);
|
||||
|
||||
v_flex().size_full().child(
|
||||
div()
|
||||
.relative()
|
||||
.flex_1()
|
||||
.child(input_state.clone())
|
||||
.child(EditorScrollbar::new(input_state.clone())),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Styled for Input {
|
||||
impl<M: InputModeKind> Styled for Input<M> {
|
||||
fn style(&mut self) -> &mut StyleRefinement {
|
||||
&mut self.style
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderOnce for Input {
|
||||
impl<M: InputModeKind> RenderOnce for Input<M> {
|
||||
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
|
||||
const LINE_HEIGHT: Rems = Rems(1.25);
|
||||
let text_align = self.style.text.text_align.unwrap_or(TextAlign::Left);
|
||||
|
||||
self.state.update(cx, |state, _| {
|
||||
state.disabled = self.disabled;
|
||||
state.size = self.size;
|
||||
// Only for single line mode
|
||||
if state.mode.is_single_line() {
|
||||
state.text_align = text_align;
|
||||
let multi_line = self.state.read(cx).is_multi_line();
|
||||
let editor_paddings = if multi_line {
|
||||
input_paddings(self.size, &self.style, window)
|
||||
} else {
|
||||
Edges::default()
|
||||
};
|
||||
self.state.update(cx, |state, cx| {
|
||||
state.set_editor_style(input_editor_style(cx));
|
||||
state.set_editor_paddings(editor_paddings);
|
||||
state.set_disabled(self.disabled, cx);
|
||||
if state.is_single_line() {
|
||||
state.set_text_align(text_align, cx);
|
||||
}
|
||||
});
|
||||
|
||||
let state = self.state.read(cx);
|
||||
let _focused = state.focus_handle.is_focused(window) && !state.disabled;
|
||||
let presentation = state.presentation();
|
||||
let disabled = presentation.is_disabled();
|
||||
let loading = presentation.is_loading();
|
||||
let text_is_empty = state.text().len() == 0;
|
||||
|
||||
let gap_x = match self.size {
|
||||
Size::Small => px(4.),
|
||||
@@ -216,117 +227,49 @@ impl RenderOnce for Input {
|
||||
_ => px(6.),
|
||||
};
|
||||
|
||||
let (bg, _) = input_style(state.disabled, cx);
|
||||
let background = input_background(disabled, cx);
|
||||
let show_clear_button =
|
||||
self.cleanable && state.is_editable() && !loading && !text_is_empty && !multi_line;
|
||||
let has_suffix = self.suffix.is_some() || loading || self.mask_toggle || show_clear_button;
|
||||
|
||||
let prefix = self.prefix;
|
||||
let suffix = self.suffix;
|
||||
let show_clear_button = self.cleanable
|
||||
&& !state.disabled
|
||||
&& !state.loading
|
||||
&& state.text.len() > 0
|
||||
&& state.mode.is_single_line();
|
||||
let has_suffix = suffix.is_some() || state.loading || self.mask_toggle || show_clear_button;
|
||||
let state_entity = self.state.clone();
|
||||
|
||||
div()
|
||||
.id(("input", self.state.entity_id()))
|
||||
InputBase::new(("input", self.state.entity_id()))
|
||||
.flex()
|
||||
.key_context(crate::input::CONTEXT)
|
||||
.track_focus(&state.focus_handle.clone())
|
||||
.tab_index(self.tab_index)
|
||||
.when(!state.disabled, |this| {
|
||||
this.on_action(window.listener_for(&self.state, InputState::backspace))
|
||||
.on_action(window.listener_for(&self.state, InputState::delete))
|
||||
.on_action(
|
||||
window.listener_for(&self.state, InputState::delete_to_beginning_of_line),
|
||||
)
|
||||
.on_action(window.listener_for(&self.state, InputState::delete_to_end_of_line))
|
||||
.on_action(window.listener_for(&self.state, InputState::delete_previous_word))
|
||||
.on_action(window.listener_for(&self.state, InputState::delete_next_word))
|
||||
.on_action(window.listener_for(&self.state, InputState::enter))
|
||||
.on_action(window.listener_for(&self.state, InputState::escape))
|
||||
.on_action(window.listener_for(&self.state, InputState::paste))
|
||||
.on_action(window.listener_for(&self.state, InputState::cut))
|
||||
.on_action(window.listener_for(&self.state, InputState::undo))
|
||||
.on_action(window.listener_for(&self.state, InputState::redo))
|
||||
.when(state.mode.is_multi_line(), |this| {
|
||||
this.on_action(window.listener_for(&self.state, InputState::indent_inline))
|
||||
.on_action(window.listener_for(&self.state, InputState::outdent_inline))
|
||||
.on_action(window.listener_for(&self.state, InputState::indent_block))
|
||||
.on_action(window.listener_for(&self.state, InputState::outdent_block))
|
||||
})
|
||||
})
|
||||
.on_action(window.listener_for(&self.state, InputState::left))
|
||||
.on_action(window.listener_for(&self.state, InputState::right))
|
||||
.on_action(window.listener_for(&self.state, InputState::select_left))
|
||||
.on_action(window.listener_for(&self.state, InputState::select_right))
|
||||
.when(state.mode.is_multi_line(), |this| {
|
||||
this.on_action(window.listener_for(&self.state, InputState::up))
|
||||
.on_action(window.listener_for(&self.state, InputState::down))
|
||||
.on_action(window.listener_for(&self.state, InputState::select_up))
|
||||
.on_action(window.listener_for(&self.state, InputState::select_down))
|
||||
.on_action(window.listener_for(&self.state, InputState::page_up))
|
||||
.on_action(window.listener_for(&self.state, InputState::page_down))
|
||||
})
|
||||
.on_action(window.listener_for(&self.state, InputState::select_all))
|
||||
.on_action(window.listener_for(&self.state, InputState::select_to_start_of_line))
|
||||
.on_action(window.listener_for(&self.state, InputState::select_to_end_of_line))
|
||||
.on_action(window.listener_for(&self.state, InputState::select_to_previous_word))
|
||||
.on_action(window.listener_for(&self.state, InputState::select_to_next_word))
|
||||
.on_action(window.listener_for(&self.state, InputState::home))
|
||||
.on_action(window.listener_for(&self.state, InputState::end))
|
||||
.on_action(window.listener_for(&self.state, InputState::move_to_start))
|
||||
.on_action(window.listener_for(&self.state, InputState::move_to_end))
|
||||
.on_action(window.listener_for(&self.state, InputState::move_to_previous_word))
|
||||
.on_action(window.listener_for(&self.state, InputState::move_to_next_word))
|
||||
.on_action(window.listener_for(&self.state, InputState::select_to_start))
|
||||
.on_action(window.listener_for(&self.state, InputState::select_to_end))
|
||||
.on_action(window.listener_for(&self.state, InputState::show_character_palette))
|
||||
.on_action(window.listener_for(&self.state, InputState::copy))
|
||||
.on_key_down(window.listener_for(&self.state, InputState::on_key_down))
|
||||
.on_mouse_down(
|
||||
MouseButton::Left,
|
||||
window.listener_for(&self.state, InputState::on_mouse_down),
|
||||
)
|
||||
.on_mouse_down(
|
||||
MouseButton::Right,
|
||||
window.listener_for(&self.state, InputState::on_mouse_down),
|
||||
)
|
||||
.on_mouse_up(
|
||||
MouseButton::Left,
|
||||
window.listener_for(&self.state, InputState::on_mouse_up),
|
||||
)
|
||||
.on_mouse_up(
|
||||
MouseButton::Right,
|
||||
window.listener_for(&self.state, InputState::on_mouse_up),
|
||||
)
|
||||
.on_scroll_wheel(window.listener_for(&self.state, InputState::on_scroll_wheel))
|
||||
.size_full()
|
||||
.line_height(LINE_HEIGHT)
|
||||
.input_px(self.size)
|
||||
.input_py(self.size)
|
||||
.when(!multi_line, |this| {
|
||||
this.input_px(self.size).input_py(self.size)
|
||||
})
|
||||
.input_h(self.size)
|
||||
.input_font_size(self.size)
|
||||
.when(!self.disabled, |this| this.cursor_text())
|
||||
.when(!disabled, |this| this.cursor_text())
|
||||
.on_mouse_down(MouseButton::Left, {
|
||||
let state_entity = state_entity.clone();
|
||||
move |_, window, cx| state_entity.update(cx, |state, cx| state.focus(window, cx))
|
||||
})
|
||||
.items_center()
|
||||
.when(state.mode.is_multi_line(), |this| {
|
||||
.when(multi_line, |this| {
|
||||
this.h_auto()
|
||||
.when_some(self.height, |this, height| this.h(height))
|
||||
})
|
||||
.when(self.appearance, |this| {
|
||||
this.bg(bg)
|
||||
this.bg(background)
|
||||
.when(self.disabled, |this| this.opacity(0.5))
|
||||
.rounded(cx.theme().radius)
|
||||
})
|
||||
.items_center()
|
||||
.tab_index(self.tab_index)
|
||||
.gap(gap_x)
|
||||
.refine_style(&self.style)
|
||||
.children(prefix)
|
||||
.when(state.mode.is_multi_line(), |mut this| {
|
||||
let paddings = this.style().padding.clone();
|
||||
this.child(Self::render_editor(paddings, &self.state, state, window))
|
||||
})
|
||||
.when(!state.mode.is_multi_line(), |this| {
|
||||
this.child(self.state.clone())
|
||||
.when(!multi_line, |this| this.child(state_entity.clone()))
|
||||
.when(multi_line, |this| {
|
||||
this.child(
|
||||
v_flex()
|
||||
.size_full()
|
||||
.child(div().relative().flex_1().child(state_entity.clone())),
|
||||
)
|
||||
})
|
||||
.when(has_suffix, |this| {
|
||||
this.pr_2().child(
|
||||
@@ -334,13 +277,13 @@ impl RenderOnce for Input {
|
||||
.id("suffix")
|
||||
.gap(gap_x)
|
||||
.items_center()
|
||||
.when(state.loading, |this| this.child(Indicator::new()))
|
||||
.when(loading, |this| this.child(Indicator::new()))
|
||||
.when(self.mask_toggle, |this| {
|
||||
this.child(Self::render_toggle_mask_button(&self.state, cx))
|
||||
this.child(Self::render_toggle_mask_button(&state_entity))
|
||||
})
|
||||
.when(show_clear_button, |this| {
|
||||
this.child(clear_button(cx).on_click({
|
||||
let state = self.state.clone();
|
||||
let state = state_entity.clone();
|
||||
move |_, window, cx| {
|
||||
state.update(cx, |state, cx| {
|
||||
state.clean(window, cx);
|
||||
|
||||
@@ -1,409 +0,0 @@
|
||||
use gpui::SharedString;
|
||||
|
||||
#[derive(Clone, PartialEq, Debug)]
|
||||
pub enum MaskToken {
|
||||
/// 0 Digit, equivalent to `[0]`
|
||||
// Digit0,
|
||||
/// Digit, equivalent to `[0-9]`
|
||||
Digit,
|
||||
/// Letter, equivalent to `[a-zA-Z]`
|
||||
Letter,
|
||||
/// Letter or digit, equivalent to `[a-zA-Z0-9]`
|
||||
LetterOrDigit,
|
||||
/// Separator
|
||||
Sep(char),
|
||||
/// Any character
|
||||
Any,
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
impl MaskToken {
|
||||
/// Check if the token is any character.
|
||||
pub fn is_any(&self) -> bool {
|
||||
matches!(self, MaskToken::Any)
|
||||
}
|
||||
|
||||
/// Check if the token is a match for the given character.
|
||||
///
|
||||
/// The separator is always a match any input character.
|
||||
fn is_match(&self, ch: char) -> bool {
|
||||
match self {
|
||||
MaskToken::Digit => ch.is_ascii_digit(),
|
||||
MaskToken::Letter => ch.is_ascii_alphabetic(),
|
||||
MaskToken::LetterOrDigit => ch.is_ascii_alphanumeric(),
|
||||
MaskToken::Any => true,
|
||||
MaskToken::Sep(c) => *c == ch,
|
||||
}
|
||||
}
|
||||
|
||||
/// Is the token a separator (Can be ignored)
|
||||
fn is_sep(&self) -> bool {
|
||||
matches!(self, MaskToken::Sep(_))
|
||||
}
|
||||
|
||||
/// Check if the token is a number.
|
||||
pub fn is_number(&self) -> bool {
|
||||
matches!(self, MaskToken::Digit)
|
||||
}
|
||||
|
||||
pub fn placeholder(&self) -> char {
|
||||
match self {
|
||||
MaskToken::Sep(c) => *c,
|
||||
_ => '_',
|
||||
}
|
||||
}
|
||||
|
||||
fn mask_char(&self, ch: char) -> char {
|
||||
match self {
|
||||
MaskToken::Digit | MaskToken::LetterOrDigit | MaskToken::Letter => ch,
|
||||
MaskToken::Sep(c) => *c,
|
||||
MaskToken::Any => ch,
|
||||
}
|
||||
}
|
||||
|
||||
fn unmask_char(&self, ch: char) -> Option<char> {
|
||||
match self {
|
||||
MaskToken::Digit => Some(ch),
|
||||
MaskToken::Letter => Some(ch),
|
||||
MaskToken::LetterOrDigit => Some(ch),
|
||||
MaskToken::Any => Some(ch),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub enum MaskPattern {
|
||||
#[default]
|
||||
None,
|
||||
Pattern {
|
||||
pattern: SharedString,
|
||||
tokens: Vec<MaskToken>,
|
||||
},
|
||||
Number {
|
||||
/// Group separator, e.g. "," or " "
|
||||
separator: Option<char>,
|
||||
/// Number of fraction digits, e.g. 2 for 123.45
|
||||
fraction: Option<usize>,
|
||||
},
|
||||
}
|
||||
|
||||
impl From<&str> for MaskPattern {
|
||||
fn from(pattern: &str) -> Self {
|
||||
Self::new(pattern)
|
||||
}
|
||||
}
|
||||
|
||||
impl MaskPattern {
|
||||
/// Create a new mask pattern
|
||||
///
|
||||
/// - `9` - Digit
|
||||
/// - `A` - Letter
|
||||
/// - `#` - Letter or Digit
|
||||
/// - `*` - Any character
|
||||
/// - other characters - Separator
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// - `(999)999-9999` - US phone number: (123)456-7890
|
||||
/// - `99999-9999` - ZIP code: 12345-6789
|
||||
/// - `AAAA-99-####` - Custom pattern: ABCD-12-3AB4
|
||||
/// - `*999*` - Custom pattern: (123) or [123]
|
||||
pub fn new(pattern: &str) -> Self {
|
||||
let tokens = pattern
|
||||
.chars()
|
||||
.map(|ch| match ch {
|
||||
// '0' => MaskToken::Digit0,
|
||||
'9' => MaskToken::Digit,
|
||||
'A' => MaskToken::Letter,
|
||||
'#' => MaskToken::LetterOrDigit,
|
||||
'*' => MaskToken::Any,
|
||||
_ => MaskToken::Sep(ch),
|
||||
})
|
||||
.collect();
|
||||
|
||||
Self::Pattern {
|
||||
pattern: pattern.to_owned().into(),
|
||||
tokens,
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
fn tokens(&self) -> Option<&Vec<MaskToken>> {
|
||||
match self {
|
||||
Self::Pattern { tokens, .. } => Some(tokens),
|
||||
Self::Number { .. } => None,
|
||||
Self::None => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new mask pattern with group separator, e.g. "," or " "
|
||||
pub fn number(sep: Option<char>) -> Self {
|
||||
Self::Number {
|
||||
separator: sep,
|
||||
fraction: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn placeholder(&self) -> Option<String> {
|
||||
match self {
|
||||
Self::Pattern { tokens, .. } => {
|
||||
Some(tokens.iter().map(|token| token.placeholder()).collect())
|
||||
}
|
||||
Self::Number { .. } => None,
|
||||
Self::None => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Return true if the mask pattern is None or no any pattern.
|
||||
pub fn is_none(&self) -> bool {
|
||||
match self {
|
||||
Self::Pattern { tokens, .. } => tokens.is_empty(),
|
||||
Self::Number { .. } => false,
|
||||
Self::None => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Check is the mask text is valid.
|
||||
///
|
||||
/// If the mask pattern is None, always return true.
|
||||
pub fn is_valid(&self, mask_text: &str) -> bool {
|
||||
if self.is_none() {
|
||||
return true;
|
||||
}
|
||||
|
||||
let mut text_index = 0;
|
||||
let mask_text_chars: Vec<char> = mask_text.chars().collect();
|
||||
match self {
|
||||
Self::Pattern { tokens, .. } => {
|
||||
for token in tokens {
|
||||
if text_index >= mask_text_chars.len() {
|
||||
break;
|
||||
}
|
||||
|
||||
let ch = mask_text_chars[text_index];
|
||||
if token.is_match(ch) {
|
||||
text_index += 1;
|
||||
}
|
||||
}
|
||||
text_index == mask_text.len()
|
||||
}
|
||||
Self::Number { separator, .. } => {
|
||||
if mask_text.is_empty() {
|
||||
return true;
|
||||
}
|
||||
|
||||
// check if the text is valid number
|
||||
let mut parts = mask_text.split('.');
|
||||
let int_part = parts.next().unwrap_or("");
|
||||
let frac_part = parts.next();
|
||||
|
||||
if int_part.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let sign_positions: Vec<usize> = int_part
|
||||
.chars()
|
||||
.enumerate()
|
||||
.filter_map(|(i, ch)| match is_sign(&ch) {
|
||||
true => Some(i),
|
||||
false => None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
// only one sign is valid
|
||||
// sign is only valid at the beginning of the string
|
||||
if sign_positions.len() > 1 || sign_positions.first() > Some(&0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// check if the integer part is valid
|
||||
if !int_part.chars().enumerate().all(|(i, ch)| {
|
||||
ch.is_ascii_digit() || is_sign(&ch) && i == 0 || Some(ch) == *separator
|
||||
}) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// check if the fraction part is valid
|
||||
if let Some(frac) = frac_part
|
||||
&& !frac
|
||||
.chars()
|
||||
.all(|ch| ch.is_ascii_digit() || Some(ch) == *separator)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
Self::None => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if valid input char at the given position.
|
||||
pub fn is_valid_at(&self, ch: char, pos: usize) -> bool {
|
||||
if self.is_none() {
|
||||
return true;
|
||||
}
|
||||
|
||||
match self {
|
||||
Self::Pattern { tokens, .. } => {
|
||||
if let Some(token) = tokens.get(pos) {
|
||||
if token.is_match(ch) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if token.is_sep() {
|
||||
// If next token is match, it's valid
|
||||
if let Some(next_token) = tokens.get(pos + 1)
|
||||
&& next_token.is_match(ch)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
Self::Number { .. } => true,
|
||||
Self::None => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Format the text according to the mask pattern
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// - pattern: (999)999-999
|
||||
/// - text: 123456789
|
||||
/// - mask_text: (123)456-789
|
||||
pub fn mask(&self, text: &str) -> SharedString {
|
||||
if self.is_none() {
|
||||
return text.to_owned().into();
|
||||
}
|
||||
|
||||
match self {
|
||||
Self::Number {
|
||||
separator,
|
||||
fraction,
|
||||
} => {
|
||||
if let Some(sep) = *separator {
|
||||
// Remove the existing group separator
|
||||
let text = text.replace(sep, "");
|
||||
|
||||
let mut parts = text.split('.');
|
||||
let int_part = parts.next().unwrap_or("");
|
||||
|
||||
// Limit the fraction part to the given range, if not enough, pad with 0
|
||||
let frac_part = parts.next().map(|part| {
|
||||
part.chars()
|
||||
.take(fraction.unwrap_or(usize::MAX))
|
||||
.collect::<String>()
|
||||
});
|
||||
|
||||
// Reverse the integer part for easier grouping
|
||||
let mut chars: Vec<char> = int_part.chars().rev().collect();
|
||||
|
||||
// Removing the sign from formatting to avoid cases such as: -,123
|
||||
let maybe_signed = chars.iter().position(is_sign).map(|pos| chars.remove(pos));
|
||||
|
||||
let mut result = String::new();
|
||||
for (i, ch) in chars.iter().enumerate() {
|
||||
if i > 0 && i % 3 == 0 {
|
||||
result.push(sep);
|
||||
}
|
||||
result.push(*ch);
|
||||
}
|
||||
let int_with_sep: String = result.chars().rev().collect();
|
||||
|
||||
let final_str = if let Some(frac) = frac_part {
|
||||
if fraction == &Some(0) {
|
||||
int_with_sep
|
||||
} else {
|
||||
format!("{}.{}", int_with_sep, frac)
|
||||
}
|
||||
} else {
|
||||
int_with_sep
|
||||
};
|
||||
|
||||
let final_str = if let Some(sign) = maybe_signed {
|
||||
format!("{}{}", sign, final_str)
|
||||
} else {
|
||||
final_str
|
||||
};
|
||||
|
||||
return final_str.into();
|
||||
}
|
||||
|
||||
text.to_owned().into()
|
||||
}
|
||||
Self::Pattern { tokens, .. } => {
|
||||
let mut result = String::new();
|
||||
let mut text_index = 0;
|
||||
let text_chars: Vec<char> = text.chars().collect();
|
||||
for (pos, token) in tokens.iter().enumerate() {
|
||||
if text_index >= text_chars.len() {
|
||||
break;
|
||||
}
|
||||
let ch = text_chars[text_index];
|
||||
// Break if expected char is not match
|
||||
if !token.is_sep() && !self.is_valid_at(ch, pos) {
|
||||
break;
|
||||
}
|
||||
let mask_ch = token.mask_char(ch);
|
||||
result.push(mask_ch);
|
||||
if ch == mask_ch {
|
||||
text_index += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
result.into()
|
||||
}
|
||||
Self::None => text.to_owned().into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract original text from masked text
|
||||
pub fn unmask(&self, mask_text: &str) -> String {
|
||||
match self {
|
||||
Self::Number { separator, .. } => {
|
||||
if let Some(sep) = *separator {
|
||||
let mut result = String::new();
|
||||
for ch in mask_text.chars() {
|
||||
if ch == sep {
|
||||
continue;
|
||||
}
|
||||
result.push(ch);
|
||||
}
|
||||
|
||||
if result.contains('.') {
|
||||
result = result.trim_end_matches('0').to_string();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
mask_text.to_owned()
|
||||
}
|
||||
Self::Pattern { tokens, .. } => {
|
||||
let mut result = String::new();
|
||||
let mask_text_chars: Vec<char> = mask_text.chars().collect();
|
||||
for (text_index, token) in tokens.iter().enumerate() {
|
||||
if text_index >= mask_text_chars.len() {
|
||||
break;
|
||||
}
|
||||
let ch = mask_text_chars[text_index];
|
||||
let unmask_ch = token.unmask_char(ch);
|
||||
if let Some(ch) = unmask_ch {
|
||||
result.push(ch);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
Self::None => mask_text.to_owned(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn is_sign(ch: &char) -> bool {
|
||||
matches!(ch, '+' | '-')
|
||||
}
|
||||
@@ -1,27 +1,7 @@
|
||||
pub(super) const MASK_CHAR: char = '*';
|
||||
|
||||
mod blink_cursor;
|
||||
mod change;
|
||||
mod clear_button;
|
||||
mod cursor;
|
||||
mod display_map;
|
||||
mod element;
|
||||
mod indent;
|
||||
#[allow(clippy::module_inception)]
|
||||
mod input;
|
||||
mod mask_pattern;
|
||||
mod mode;
|
||||
mod movement;
|
||||
mod rope_ext;
|
||||
mod selection;
|
||||
mod state;
|
||||
|
||||
pub(crate) use clear_button::*;
|
||||
pub use cursor::*;
|
||||
pub use display_map::DisplayMap;
|
||||
pub use indent::TabSize;
|
||||
pub use gpui_base::input::{InputEvent, InputState, TextareaState};
|
||||
pub use input::*;
|
||||
pub use mask_pattern::MaskPattern;
|
||||
pub use rope_ext::{InputEdit, Point, RopeExt, RopeLines};
|
||||
pub use ropey::Rope;
|
||||
pub use state::*;
|
||||
|
||||
@@ -1,145 +0,0 @@
|
||||
use super::display_map::DisplayMap;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) enum InputMode {
|
||||
/// A plain text input mode.
|
||||
PlainText {
|
||||
multi_line: bool,
|
||||
tab: crate::input::indent::TabSize,
|
||||
rows: usize,
|
||||
},
|
||||
/// An auto grow input mode.
|
||||
AutoGrow {
|
||||
rows: usize,
|
||||
min_rows: usize,
|
||||
max_rows: usize,
|
||||
},
|
||||
}
|
||||
|
||||
impl Default for InputMode {
|
||||
fn default() -> Self {
|
||||
InputMode::plain_text()
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
impl InputMode {
|
||||
/// Create a plain input mode with default settings.
|
||||
pub(super) fn plain_text() -> Self {
|
||||
InputMode::PlainText {
|
||||
multi_line: false,
|
||||
tab: crate::input::indent::TabSize::default(),
|
||||
rows: 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create an auto grow input mode with given min and max rows.
|
||||
pub(super) fn auto_grow(min_rows: usize, max_rows: usize) -> Self {
|
||||
InputMode::AutoGrow {
|
||||
rows: min_rows,
|
||||
min_rows,
|
||||
max_rows,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn multi_line(mut self, multi_line: bool) -> Self {
|
||||
match &mut self {
|
||||
InputMode::PlainText { multi_line: ml, .. } => *ml = multi_line,
|
||||
InputMode::AutoGrow { .. } => {}
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(super) fn is_single_line(&self) -> bool {
|
||||
!self.is_multi_line()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(super) fn is_auto_grow(&self) -> bool {
|
||||
matches!(self, InputMode::AutoGrow { .. })
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(super) fn is_multi_line(&self) -> bool {
|
||||
match self {
|
||||
InputMode::PlainText { multi_line, .. } => *multi_line,
|
||||
InputMode::AutoGrow { max_rows, .. } => *max_rows > 1,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn set_rows(&mut self, new_rows: usize) {
|
||||
match self {
|
||||
InputMode::PlainText { rows, .. } => {
|
||||
*rows = new_rows;
|
||||
}
|
||||
InputMode::AutoGrow {
|
||||
rows,
|
||||
min_rows,
|
||||
max_rows,
|
||||
} => {
|
||||
*rows = new_rows.clamp(*min_rows, *max_rows);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn update_auto_grow(&mut self, display_map: &DisplayMap) {
|
||||
if self.is_single_line() {
|
||||
return;
|
||||
}
|
||||
|
||||
let wrapped_lines = display_map.wrap_row_count();
|
||||
self.set_rows(wrapped_lines);
|
||||
}
|
||||
|
||||
/// At least 1 row be return.
|
||||
pub(super) fn rows(&self) -> usize {
|
||||
if !self.is_multi_line() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
match self {
|
||||
InputMode::PlainText { rows, .. } => *rows,
|
||||
InputMode::AutoGrow { rows, .. } => *rows,
|
||||
}
|
||||
.max(1)
|
||||
}
|
||||
|
||||
/// At least 1 row be return.
|
||||
#[allow(unused)]
|
||||
pub(super) fn min_rows(&self) -> usize {
|
||||
match self {
|
||||
InputMode::AutoGrow { min_rows, .. } => *min_rows,
|
||||
_ => 1,
|
||||
}
|
||||
.max(1)
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
pub(super) fn max_rows(&self) -> usize {
|
||||
if !self.is_multi_line() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
match self {
|
||||
InputMode::AutoGrow { max_rows, .. } => *max_rows,
|
||||
_ => usize::MAX,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(super) fn is_indentable(&self) -> bool {
|
||||
match self {
|
||||
InputMode::PlainText { multi_line, .. } => *multi_line,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(super) fn tab_size(&self) -> crate::input::indent::TabSize {
|
||||
match self {
|
||||
InputMode::PlainText { tab, .. } => *tab,
|
||||
_ => crate::input::indent::TabSize::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,264 +0,0 @@
|
||||
use gpui::{Context, Point, Window};
|
||||
|
||||
use crate::input::{
|
||||
InputState, MoveDown, MoveEnd, MoveHome, MoveLeft, MovePageDown, MovePageUp, MoveRight,
|
||||
MoveToEnd, MoveToNextWord, MoveToPreviousWord, MoveToStart, MoveUp, RopeExt as _,
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum MoveDirection {
|
||||
Up,
|
||||
Down,
|
||||
}
|
||||
|
||||
impl InputState {
|
||||
/// Called after moving the cursor. Updates preferred_column if we know where the cursor now is.
|
||||
pub(super) fn update_preferred_column(&mut self) {
|
||||
let Some(last_layout) = &self.last_layout else {
|
||||
self.preferred_column = None;
|
||||
return;
|
||||
};
|
||||
|
||||
let point = self.text.offset_to_point(self.cursor());
|
||||
let Some(line) = last_layout.line(point.row) else {
|
||||
self.preferred_column = None;
|
||||
return;
|
||||
};
|
||||
|
||||
let Some(pos) = line.position_for_index(point.column, last_layout, false) else {
|
||||
self.preferred_column = None;
|
||||
return;
|
||||
};
|
||||
|
||||
self.preferred_column = Some((pos.x, point.column));
|
||||
}
|
||||
|
||||
/// Move the cursor to the given offset.
|
||||
///
|
||||
/// The offset is the UTF-8 offset.
|
||||
///
|
||||
/// Ensure the offset use self.next_boundary or self.previous_boundary to get the correct offset.
|
||||
pub(crate) fn move_to(
|
||||
&mut self,
|
||||
offset: usize,
|
||||
direction: Option<MoveDirection>,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let offset = offset.clamp(0, self.text.len());
|
||||
self.cursor_line_end_affinity = false;
|
||||
self.selected_range = (offset..offset).into();
|
||||
self.scroll_to(offset, direction, cx);
|
||||
self.pause_blink_cursor(cx);
|
||||
self.update_preferred_column();
|
||||
cx.notify()
|
||||
}
|
||||
|
||||
/// Move the cursor vertically by one line (up or down) while preserving the column if possible.
|
||||
///
|
||||
/// move_lines: Number of lines to move vertically (positive for down, negative for up).
|
||||
pub(super) fn move_vertical(
|
||||
&mut self,
|
||||
move_lines: isize,
|
||||
_: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
if self.mode.is_single_line() {
|
||||
return;
|
||||
}
|
||||
let Some(last_layout) = &self.last_layout else {
|
||||
return;
|
||||
};
|
||||
|
||||
let offset = self.cursor();
|
||||
let was_preferred_column = self.preferred_column;
|
||||
|
||||
let mut display_point = self.display_map.offset_to_wrap_display_point(offset);
|
||||
|
||||
// Convert wrap row → display row (skips folded rows), move, then convert back
|
||||
let current_display_row = self
|
||||
.display_map
|
||||
.wrap_row_to_display_row(display_point.row)
|
||||
.unwrap_or_else(|| {
|
||||
self.display_map
|
||||
.nearest_visible_display_row(display_point.row)
|
||||
});
|
||||
let max_display_row = self.display_map.display_row_count().saturating_sub(1);
|
||||
let target_display_row = current_display_row
|
||||
.saturating_add_signed(move_lines)
|
||||
.min(max_display_row);
|
||||
let target_wrap_row = self
|
||||
.display_map
|
||||
.display_row_to_wrap_row(target_display_row)
|
||||
.unwrap_or(display_point.row);
|
||||
|
||||
display_point.row = target_wrap_row;
|
||||
display_point.column = 0;
|
||||
let mut new_offset = self.display_map.wrap_display_point_to_offset(display_point);
|
||||
|
||||
if let Some((preferred_x, column)) = was_preferred_column {
|
||||
// Get display point again to update local_row.
|
||||
let mut next_display_point = self.display_map.offset_to_wrap_display_point(new_offset);
|
||||
next_display_point.column = 0;
|
||||
let next_point = self
|
||||
.display_map
|
||||
.wrap_display_point_to_point(next_display_point);
|
||||
let line_start_offset = self.text.line_start_offset(next_point.row);
|
||||
|
||||
// If in visible range, prefer to use position to get column.
|
||||
if let Some(line) = last_layout.line(next_point.row) {
|
||||
if let Some(x) = line.closest_index_for_position(
|
||||
Point {
|
||||
x: preferred_x,
|
||||
y: next_display_point.local_row * last_layout.line_height,
|
||||
},
|
||||
last_layout,
|
||||
) {
|
||||
new_offset = line_start_offset + x;
|
||||
}
|
||||
} else {
|
||||
// Not in visible range, use column directly.
|
||||
let max_line_len = self.text.slice_line(next_point.row).len();
|
||||
new_offset = line_start_offset + column.min(max_line_len);
|
||||
}
|
||||
}
|
||||
|
||||
self.pause_blink_cursor(cx);
|
||||
let direction = if move_lines < 0 {
|
||||
MoveDirection::Up
|
||||
} else {
|
||||
MoveDirection::Down
|
||||
};
|
||||
self.move_to(new_offset, Some(direction), cx);
|
||||
// Set back the preferred_column
|
||||
self.preferred_column = was_preferred_column;
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
pub(super) fn left(&mut self, _: &MoveLeft, _: &mut Window, cx: &mut Context<Self>) {
|
||||
self.pause_blink_cursor(cx);
|
||||
if self.selected_range.is_empty() {
|
||||
self.move_to(self.previous_boundary(self.cursor()), None, cx);
|
||||
} else {
|
||||
self.move_to(self.selected_range.start, None, cx)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn right(&mut self, _: &MoveRight, _: &mut Window, cx: &mut Context<Self>) {
|
||||
self.pause_blink_cursor(cx);
|
||||
if self.selected_range.is_empty() {
|
||||
self.move_to(self.next_boundary(self.selected_range.end), None, cx);
|
||||
} else {
|
||||
self.move_to(self.selected_range.end, None, cx)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn up(&mut self, _action: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
|
||||
if self.mode.is_single_line() {
|
||||
return;
|
||||
}
|
||||
|
||||
if !self.selected_range.is_empty() {
|
||||
self.move_to(
|
||||
self.previous_boundary(self.selected_range.start.saturating_sub(1)),
|
||||
Some(MoveDirection::Up),
|
||||
cx,
|
||||
);
|
||||
}
|
||||
self.pause_blink_cursor(cx);
|
||||
self.move_vertical(-1, window, cx);
|
||||
}
|
||||
|
||||
pub(super) fn down(&mut self, _action: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
|
||||
if self.mode.is_single_line() {
|
||||
return;
|
||||
}
|
||||
|
||||
if !self.selected_range.is_empty() {
|
||||
self.move_to(
|
||||
self.next_boundary(self.selected_range.end.saturating_sub(1)),
|
||||
Some(MoveDirection::Down),
|
||||
cx,
|
||||
);
|
||||
}
|
||||
|
||||
self.pause_blink_cursor(cx);
|
||||
self.move_vertical(1, window, cx);
|
||||
}
|
||||
|
||||
pub(super) fn page_up(&mut self, _: &MovePageUp, window: &mut Window, cx: &mut Context<Self>) {
|
||||
if self.mode.is_single_line() {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(last_layout) = &self.last_layout else {
|
||||
return;
|
||||
};
|
||||
|
||||
let display_lines = (self.input_bounds.size.height / last_layout.line_height) as isize;
|
||||
self.move_vertical(-display_lines, window, cx);
|
||||
}
|
||||
|
||||
pub(super) fn page_down(
|
||||
&mut self,
|
||||
_: &MovePageDown,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
if self.mode.is_single_line() {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(last_layout) = &self.last_layout else {
|
||||
return;
|
||||
};
|
||||
|
||||
let display_lines = (self.input_bounds.size.height / last_layout.line_height) as isize;
|
||||
self.move_vertical(display_lines, window, cx);
|
||||
}
|
||||
|
||||
pub(super) fn home(&mut self, _: &MoveHome, _: &mut Window, cx: &mut Context<Self>) {
|
||||
self.pause_blink_cursor(cx);
|
||||
let offset = self.start_of_line();
|
||||
self.move_to(offset, Some(MoveDirection::Up), cx);
|
||||
}
|
||||
|
||||
pub(super) fn end(&mut self, _: &MoveEnd, _: &mut Window, cx: &mut Context<Self>) {
|
||||
self.pause_blink_cursor(cx);
|
||||
let offset = self.end_of_line();
|
||||
self.move_to(offset, Some(MoveDirection::Down), cx);
|
||||
self.cursor_line_end_affinity = true;
|
||||
}
|
||||
|
||||
pub(super) fn move_to_start(
|
||||
&mut self,
|
||||
_: &MoveToStart,
|
||||
_: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
self.move_to(0, None, cx);
|
||||
}
|
||||
|
||||
pub(super) fn move_to_end(&mut self, _: &MoveToEnd, _: &mut Window, cx: &mut Context<Self>) {
|
||||
self.move_to(self.text.len(), None, cx);
|
||||
}
|
||||
|
||||
pub(super) fn move_to_previous_word(
|
||||
&mut self,
|
||||
_: &MoveToPreviousWord,
|
||||
_: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let offset = self.previous_start_of_word();
|
||||
self.move_to(offset, None, cx);
|
||||
}
|
||||
|
||||
pub(super) fn move_to_next_word(
|
||||
&mut self,
|
||||
_: &MoveToNextWord,
|
||||
_: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let offset = self.next_end_of_word();
|
||||
self.move_to(offset, None, cx);
|
||||
}
|
||||
}
|
||||
@@ -1,456 +0,0 @@
|
||||
use std::ops::Range;
|
||||
|
||||
use ropey::{LineType, Rope, RopeSlice};
|
||||
use sum_tree::Bias;
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub use tree_sitter::{InputEdit, Point};
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
/// Stub type for tree-sitter Point on WASM (tree-sitter not available).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct Point {
|
||||
pub row: usize,
|
||||
pub column: usize,
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
impl Point {
|
||||
pub fn new(row: usize, column: usize) -> Self {
|
||||
Self { row, column }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
/// Stub type for tree-sitter InputEdit on WASM (tree-sitter not available).
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct InputEdit {
|
||||
pub start_byte: usize,
|
||||
pub old_end_byte: usize,
|
||||
pub new_end_byte: usize,
|
||||
pub start_position: Point,
|
||||
pub old_end_position: Point,
|
||||
pub new_end_position: Point,
|
||||
}
|
||||
|
||||
pub type Position = lsp_types::Position;
|
||||
|
||||
/// An iterator over the lines of a `Rope`.
|
||||
pub struct RopeLines<'a> {
|
||||
rope: &'a Rope,
|
||||
row: usize,
|
||||
end_row: usize,
|
||||
}
|
||||
|
||||
impl<'a> RopeLines<'a> {
|
||||
/// Create a new `RopeLines` iterator.
|
||||
pub fn new(rope: &'a Rope) -> Self {
|
||||
let end_row = rope.lines_len();
|
||||
Self {
|
||||
row: 0,
|
||||
end_row,
|
||||
rope,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<'a> Iterator for RopeLines<'a> {
|
||||
type Item = RopeSlice<'a>;
|
||||
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.row >= self.end_row {
|
||||
return None;
|
||||
}
|
||||
|
||||
let line = self.rope.slice_line(self.row);
|
||||
self.row += 1;
|
||||
Some(line)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn nth(&mut self, n: usize) -> Option<Self::Item> {
|
||||
self.row = self.row.saturating_add(n);
|
||||
self.next()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let len = self.end_row - self.row;
|
||||
(len, Some(len))
|
||||
}
|
||||
}
|
||||
|
||||
impl std::iter::ExactSizeIterator for RopeLines<'_> {}
|
||||
impl std::iter::FusedIterator for RopeLines<'_> {}
|
||||
|
||||
/// An extension trait for [`Rope`] to provide additional utility methods.
|
||||
pub trait RopeExt {
|
||||
/// Start offset of the line at the given row (0-based) index.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use gpui_component::{Rope, RopeExt};
|
||||
///
|
||||
/// let rope = Rope::from("Hello\nWorld\r\nThis is a test 中文\nRope");
|
||||
/// assert_eq!(rope.line_start_offset(0), 0);
|
||||
/// assert_eq!(rope.line_start_offset(1), 6);
|
||||
/// ```
|
||||
fn line_start_offset(&self, row: usize) -> usize;
|
||||
|
||||
/// Line the end offset (including `\n`) of the line at the given row (0-based) index.
|
||||
///
|
||||
/// Return the end of the rope if the row is out of bounds.
|
||||
///
|
||||
/// ```
|
||||
/// use gpui_component::{Rope, RopeExt};
|
||||
/// let rope = Rope::from("Hello\nWorld\r\nThis is a test 中文\nRope");
|
||||
/// assert_eq!(rope.line_end_offset(0), 5); // "Hello\n"
|
||||
/// assert_eq!(rope.line_end_offset(1), 12); // "World\r\n"
|
||||
/// ```
|
||||
fn line_end_offset(&self, row: usize) -> usize;
|
||||
|
||||
/// Return a line slice at the given row (0-based) index. including `\r` if present, but not `\n`.
|
||||
///
|
||||
/// ```
|
||||
/// use gpui_component::{Rope, RopeExt};
|
||||
/// let rope = Rope::from("Hello\nWorld\r\nThis is a test 中文\nRope");
|
||||
/// assert_eq!(rope.slice_line(0).to_string(), "Hello");
|
||||
/// assert_eq!(rope.slice_line(1).to_string(), "World\r");
|
||||
/// assert_eq!(rope.slice_line(2).to_string(), "This is a test 中文");
|
||||
/// assert_eq!(rope.slice_line(6).to_string(), ""); // out of bounds
|
||||
/// ```
|
||||
fn slice_line(&self, row: usize) -> RopeSlice<'_>;
|
||||
|
||||
/// Return a slice of rows in the given range (0-based, end exclusive).
|
||||
///
|
||||
/// If the range is out of bounds, it will be clamped to the valid range.
|
||||
///
|
||||
/// ```
|
||||
/// use gpui_component::{Rope, RopeExt};
|
||||
/// let rope = Rope::from("Hello\nWorld\r\nThis is a test 中文\nRope");
|
||||
/// assert_eq!(rope.slice_lines(0..2).to_string(), "Hello\nWorld\r");
|
||||
/// assert_eq!(rope.slice_lines(1..3).to_string(), "World\r\nThis is a test 中文");
|
||||
/// assert_eq!(rope.slice_lines(2..5).to_string(), "This is a test 中文\nRope");
|
||||
/// assert_eq!(rope.slice_lines(3..10).to_string(), "Rope");
|
||||
/// assert_eq!(rope.slice_lines(5..10).to_string(), ""); // out of bounds
|
||||
/// ```
|
||||
fn slice_lines(&self, rows_range: Range<usize>) -> RopeSlice<'_>;
|
||||
|
||||
/// Return an iterator over all lines in the rope.
|
||||
///
|
||||
/// Each line slice includes `\r` if present, but not `\n`.
|
||||
///
|
||||
/// ```
|
||||
/// use gpui_component::{Rope, RopeExt};
|
||||
/// let rope = Rope::from("Hello\nWorld\r\nThis is a test 中文\nRope");
|
||||
/// let lines: Vec<_> = rope.iter_lines().map(|r| r.to_string()).collect();
|
||||
/// assert_eq!(lines, vec!["Hello", "World\r", "This is a test 中文", "Rope"]);
|
||||
/// ```
|
||||
fn iter_lines(&self) -> RopeLines<'_>;
|
||||
|
||||
/// Return the number of lines in the rope.
|
||||
///
|
||||
/// ```
|
||||
/// use gpui_component::{Rope, RopeExt};
|
||||
/// let rope = Rope::from("Hello\nWorld\r\nThis is a test 中文\nRope");
|
||||
/// assert_eq!(rope.lines_len(), 4);
|
||||
/// ```
|
||||
fn lines_len(&self) -> usize;
|
||||
|
||||
/// Return the length of the row (0-based) in characters, including `\r` if present, but not `\n`.
|
||||
///
|
||||
/// If the row is out of bounds, return 0.
|
||||
///
|
||||
/// ```
|
||||
/// use gpui_component::{Rope, RopeExt};
|
||||
/// let rope = Rope::from("Hello\nWorld\r\nThis is a test 中文\nRope");
|
||||
/// assert_eq!(rope.line_len(0), 5); // "Hello"
|
||||
/// assert_eq!(rope.line_len(1), 6); // "World\r"
|
||||
/// assert_eq!(rope.line_len(2), 21); // "This is a test 中文"
|
||||
/// assert_eq!(rope.line_len(4), 0); // out of bounds
|
||||
/// ```
|
||||
fn line_len(&self, row: usize) -> usize;
|
||||
|
||||
/// Replace the text in the given byte range with new text.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// - If the range is not on char boundary.
|
||||
/// - If the range is out of bounds.
|
||||
///
|
||||
/// ```
|
||||
/// use gpui_component::{Rope, RopeExt};
|
||||
/// let mut rope = Rope::from("Hello\nWorld\r\nThis is a test 中文\nRope");
|
||||
/// rope.replace(6..11, "Universe");
|
||||
/// assert_eq!(rope.to_string(), "Hello\nUniverse\r\nThis is a test 中文\nRope");
|
||||
/// ```
|
||||
fn replace(&mut self, range: Range<usize>, new_text: &str);
|
||||
|
||||
/// Get char at the given offset (byte).
|
||||
///
|
||||
/// - If the offset is in the middle of a multi-byte character will panic.
|
||||
/// - If the offset is out of bounds, return None.
|
||||
fn char_at(&self, offset: usize) -> Option<char>;
|
||||
|
||||
/// Get the byte offset from the given line, column [`Position`] (0-based).
|
||||
///
|
||||
/// The column is in characters.
|
||||
fn position_to_offset(&self, line_col: &Position) -> usize;
|
||||
|
||||
/// Get the line, column [`Position`] (0-based) from the given byte offset.
|
||||
///
|
||||
/// The column is in characters.
|
||||
fn offset_to_position(&self, offset: usize) -> Position;
|
||||
|
||||
/// Get point (row, column) from the given byte offset.
|
||||
///
|
||||
/// The column is in bytes.
|
||||
fn offset_to_point(&self, offset: usize) -> Point;
|
||||
|
||||
/// Get byte offset from the given point (row, column).
|
||||
///
|
||||
/// The column is 0-based in bytes.
|
||||
fn point_to_offset(&self, point: Point) -> usize;
|
||||
|
||||
/// Get the word byte range at the given byte offset (0-based).
|
||||
fn word_range(&self, offset: usize) -> Option<Range<usize>>;
|
||||
|
||||
/// Get word at the given byte offset (0-based).
|
||||
fn word_at(&self, offset: usize) -> String;
|
||||
|
||||
/// Convert offset in UTF-16 to byte offset (0-based).
|
||||
///
|
||||
/// Runs in O(log N) time.
|
||||
fn offset_utf16_to_offset(&self, offset_utf16: usize) -> usize;
|
||||
|
||||
/// Convert byte offset (0-based) to offset in UTF-16.
|
||||
///
|
||||
/// Runs in O(log N) time.
|
||||
fn offset_to_offset_utf16(&self, offset: usize) -> usize;
|
||||
|
||||
/// Get a clipped offset (avoid in a char boundary).
|
||||
///
|
||||
/// - If Bias::Left and inside the char boundary, return the ix - 1;
|
||||
/// - If Bias::Right and in inside char boundary, return the ix + 1;
|
||||
/// - Otherwise return the ix.
|
||||
///
|
||||
/// ```
|
||||
/// use gpui_component::{Rope, RopeExt};
|
||||
/// use sum_tree::Bias;
|
||||
///
|
||||
/// let rope = Rope::from("Hello 中文🎉 test\nRope");
|
||||
/// assert_eq!(rope.clip_offset(5, Bias::Left), 5);
|
||||
/// // Inside multi-byte character '中' (3 bytes)
|
||||
/// assert_eq!(rope.clip_offset(7, Bias::Left), 6);
|
||||
/// assert_eq!(rope.clip_offset(7, Bias::Right), 9);
|
||||
/// ```
|
||||
fn clip_offset(&self, offset: usize, bias: Bias) -> usize;
|
||||
|
||||
/// Convert offset in characters to byte offset (0-based).
|
||||
///
|
||||
/// Run in O(n) time.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use gpui_component::{Rope, RopeExt};
|
||||
/// let rope = Rope::from("a 中文🎉 test\nRope");
|
||||
/// assert_eq!(rope.char_index_to_offset(0), 0);
|
||||
/// assert_eq!(rope.char_index_to_offset(1), 1);
|
||||
/// assert_eq!(rope.char_index_to_offset(3), "a 中".len());
|
||||
/// assert_eq!(rope.char_index_to_offset(5), "a 中文🎉".len());
|
||||
/// ```
|
||||
fn char_index_to_offset(&self, char_index: usize) -> usize;
|
||||
|
||||
/// Convert byte offset (0-based) to offset in characters.
|
||||
///
|
||||
/// Run in O(n) time.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use gpui_component::{Rope, RopeExt};
|
||||
/// let rope = Rope::from("a 中文🎉 test\nRope");
|
||||
/// assert_eq!(rope.offset_to_char_index(0), 0);
|
||||
/// assert_eq!(rope.offset_to_char_index(1), 1);
|
||||
/// assert_eq!(rope.offset_to_char_index(3), 3);
|
||||
/// assert_eq!(rope.offset_to_char_index(4), 3);
|
||||
/// ```
|
||||
fn offset_to_char_index(&self, offset: usize) -> usize;
|
||||
}
|
||||
|
||||
impl RopeExt for Rope {
|
||||
fn slice_line(&self, row: usize) -> RopeSlice<'_> {
|
||||
let total_lines = self.lines_len();
|
||||
if row >= total_lines {
|
||||
return self.slice(0..0);
|
||||
}
|
||||
|
||||
let line = self.line(row, LineType::LF);
|
||||
if line.len() > 0 {
|
||||
let line_end = line.len() - 1;
|
||||
if line.is_char_boundary(line_end) && line.char(line_end) == '\n' {
|
||||
return line.slice(..line_end);
|
||||
}
|
||||
}
|
||||
|
||||
line
|
||||
}
|
||||
|
||||
fn slice_lines(&self, rows_range: Range<usize>) -> RopeSlice<'_> {
|
||||
let start = self.line_start_offset(rows_range.start);
|
||||
let end = self.line_end_offset(rows_range.end.saturating_sub(1));
|
||||
self.slice(start..end)
|
||||
}
|
||||
|
||||
fn iter_lines(&self) -> RopeLines<'_> {
|
||||
RopeLines::new(self)
|
||||
}
|
||||
|
||||
fn line_len(&self, row: usize) -> usize {
|
||||
self.slice_line(row).len()
|
||||
}
|
||||
|
||||
fn line_start_offset(&self, row: usize) -> usize {
|
||||
self.point_to_offset(Point::new(row, 0))
|
||||
}
|
||||
|
||||
fn offset_to_point(&self, offset: usize) -> Point {
|
||||
let offset = self.clip_offset(offset, Bias::Left);
|
||||
let row = self.byte_to_line_idx(offset, LineType::LF);
|
||||
let line_start = self.line_to_byte_idx(row, LineType::LF);
|
||||
let column = offset.saturating_sub(line_start);
|
||||
Point::new(row, column)
|
||||
}
|
||||
|
||||
fn point_to_offset(&self, point: Point) -> usize {
|
||||
if point.row >= self.lines_len() {
|
||||
return self.len();
|
||||
}
|
||||
|
||||
let line_start = self.line_to_byte_idx(point.row, LineType::LF);
|
||||
line_start + point.column
|
||||
}
|
||||
|
||||
fn position_to_offset(&self, pos: &Position) -> usize {
|
||||
let line = self.slice_line(pos.line as usize);
|
||||
self.line_start_offset(pos.line as usize)
|
||||
+ line
|
||||
.chars()
|
||||
.take(pos.character as usize)
|
||||
.map(|c| c.len_utf8())
|
||||
.sum::<usize>()
|
||||
}
|
||||
|
||||
fn offset_to_position(&self, offset: usize) -> Position {
|
||||
let point = self.offset_to_point(offset);
|
||||
let line = self.slice_line(point.row);
|
||||
let offset = line.utf16_to_byte_idx(line.byte_to_utf16_idx(point.column));
|
||||
let character = line.slice(..offset).chars().count();
|
||||
Position::new(point.row as u32, character as u32)
|
||||
}
|
||||
|
||||
fn line_end_offset(&self, row: usize) -> usize {
|
||||
if row > self.lines_len() {
|
||||
return self.len();
|
||||
}
|
||||
|
||||
self.line_start_offset(row) + self.line_len(row)
|
||||
}
|
||||
|
||||
fn lines_len(&self) -> usize {
|
||||
self.len_lines(LineType::LF)
|
||||
}
|
||||
|
||||
fn char_at(&self, offset: usize) -> Option<char> {
|
||||
if offset > self.len() {
|
||||
return None;
|
||||
}
|
||||
|
||||
self.get_char(offset).ok()
|
||||
}
|
||||
|
||||
fn word_range(&self, offset: usize) -> Option<Range<usize>> {
|
||||
if offset >= self.len() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut left = String::new();
|
||||
let offset = self.clip_offset(offset, Bias::Left);
|
||||
for c in self.chars_at(offset).reversed() {
|
||||
if c.is_alphanumeric() || c == '_' {
|
||||
left.insert(0, c);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let start = offset.saturating_sub(left.len());
|
||||
|
||||
let right = self
|
||||
.chars_at(offset)
|
||||
.take_while(|c| c.is_alphanumeric() || *c == '_')
|
||||
.collect::<String>();
|
||||
|
||||
let end = offset + right.len();
|
||||
|
||||
if start == end { None } else { Some(start..end) }
|
||||
}
|
||||
|
||||
fn word_at(&self, offset: usize) -> String {
|
||||
if let Some(range) = self.word_range(offset) {
|
||||
self.slice(range).to_string()
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn offset_utf16_to_offset(&self, offset_utf16: usize) -> usize {
|
||||
if offset_utf16 > self.len_utf16() {
|
||||
return self.len();
|
||||
}
|
||||
|
||||
self.utf16_to_byte_idx(offset_utf16)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn offset_to_offset_utf16(&self, offset: usize) -> usize {
|
||||
if offset > self.len() {
|
||||
return self.len_utf16();
|
||||
}
|
||||
|
||||
self.byte_to_utf16_idx(offset)
|
||||
}
|
||||
|
||||
fn replace(&mut self, range: Range<usize>, new_text: &str) {
|
||||
let range =
|
||||
self.clip_offset(range.start, Bias::Left)..self.clip_offset(range.end, Bias::Right);
|
||||
self.remove(range.clone());
|
||||
self.insert(range.start, new_text);
|
||||
}
|
||||
|
||||
fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
|
||||
if offset > self.len() {
|
||||
return self.len();
|
||||
}
|
||||
|
||||
if self.is_char_boundary(offset) {
|
||||
return offset;
|
||||
}
|
||||
|
||||
if bias == Bias::Left {
|
||||
self.floor_char_boundary(offset)
|
||||
} else {
|
||||
self.ceil_char_boundary(offset)
|
||||
}
|
||||
}
|
||||
|
||||
fn char_index_to_offset(&self, char_offset: usize) -> usize {
|
||||
self.chars().take(char_offset).map(|c| c.len_utf8()).sum()
|
||||
}
|
||||
|
||||
fn offset_to_char_index(&self, offset: usize) -> usize {
|
||||
let offset = self.clip_offset(offset, Bias::Right);
|
||||
self.slice(..offset).chars().count()
|
||||
}
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
use std::ops::Range;
|
||||
|
||||
use gpui::{Context, Window};
|
||||
use ropey::Rope;
|
||||
use sum_tree::Bias;
|
||||
|
||||
use crate::input::{InputState, RopeExt};
|
||||
|
||||
impl InputState {
|
||||
/// Select the word at the given offset on double-click.
|
||||
///
|
||||
/// The offset is the UTF-8 offset.
|
||||
pub(super) fn select_word(&mut self, offset: usize, _: &mut Window, cx: &mut Context<Self>) {
|
||||
let Some(range) = TextSelector::word_range(&self.text, offset) else {
|
||||
return;
|
||||
};
|
||||
|
||||
self.selected_range = (range.start..range.end).into();
|
||||
self.selected_word_range = Some(self.selected_range);
|
||||
cx.notify()
|
||||
}
|
||||
|
||||
/// Select the line at the given offset on triple-click.
|
||||
///
|
||||
/// The offset is the UTF-8 offset.
|
||||
pub(super) fn select_line(&mut self, offset: usize, _: &mut Window, cx: &mut Context<Self>) {
|
||||
let range = TextSelector::line_range(&self.text, offset);
|
||||
self.selected_range = (range.start..range.end).into();
|
||||
self.selected_word_range = None;
|
||||
cx.notify()
|
||||
}
|
||||
}
|
||||
|
||||
struct TextSelector;
|
||||
impl TextSelector {
|
||||
/// Select a line in the given text at the specified offset.
|
||||
///
|
||||
/// The offset is the UTF-8 offset.
|
||||
///
|
||||
/// Returns the start and end offsets of the selected line.
|
||||
pub fn line_range(text: &Rope, offset: usize) -> Range<usize> {
|
||||
let offset = text.clip_offset(offset, Bias::Left);
|
||||
let row = text.offset_to_point(offset).row;
|
||||
let start = text.line_start_offset(row);
|
||||
let end = text.line_end_offset(row);
|
||||
|
||||
start..end
|
||||
}
|
||||
|
||||
/// Select a word in the given text at the specified offset.
|
||||
///
|
||||
/// The offset is the UTF-8 offset.
|
||||
///
|
||||
/// Returns the start and end offsets of the selected word.
|
||||
pub fn word_range(text: &Rope, offset: usize) -> Option<Range<usize>> {
|
||||
let offset = text.clip_offset(offset, Bias::Left);
|
||||
let char = text.char_at(offset)?;
|
||||
let end = offset + char.len_utf8();
|
||||
let prev_chars = text.chars_at(offset).reversed().take(128);
|
||||
let next_chars = text.chars_at(end).take(128);
|
||||
|
||||
Some(word_range_from_chars(offset, char, prev_chars, next_chars))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum CharType {
|
||||
/// a-z, A-Z, 0-9, _
|
||||
Word,
|
||||
/// '\t', ' ', '\u{00A0}' etc.
|
||||
Whitespace,
|
||||
/// \n, \r
|
||||
Newline,
|
||||
/// . , ; : ( ) [ ] { } ... or CJK characters: `汉`, `🎉` etc.
|
||||
Other,
|
||||
}
|
||||
|
||||
impl From<char> for CharType {
|
||||
fn from(c: char) -> Self {
|
||||
match c {
|
||||
c if is_word_char(c) => CharType::Word,
|
||||
c if c == '\n' || c == '\r' => CharType::Newline,
|
||||
c if c.is_whitespace() => CharType::Whitespace,
|
||||
_ => CharType::Other,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CharType {
|
||||
fn is_connectable(self, c: char) -> bool {
|
||||
matches!(
|
||||
(self, CharType::from(c)),
|
||||
(CharType::Word, CharType::Word) | (CharType::Whitespace, CharType::Whitespace)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn is_word_char(c: char) -> bool {
|
||||
matches!(c, '_')
|
||||
// ASCII alphanumeric characters, for English, numbers: `Hello123`, etc.
|
||||
|| c.is_ascii_alphanumeric()
|
||||
// Latin script in Unicode for French, German, Spanish, etc.
|
||||
|| matches!(c, '\u{00C0}'..='\u{00FF}')
|
||||
|| matches!(c, '\u{0100}'..='\u{017F}')
|
||||
|| matches!(c, '\u{0180}'..='\u{024F}')
|
||||
// Cyrillic for Russian, Ukrainian, etc.
|
||||
|| matches!(c, '\u{0400}'..='\u{04FF}')
|
||||
// Vietnamese
|
||||
|| matches!(c, '\u{1E00}'..='\u{1EFF}')
|
||||
|| matches!(c, '\u{0300}'..='\u{036F}')
|
||||
}
|
||||
|
||||
pub(crate) fn word_range_from_chars(
|
||||
offset: usize,
|
||||
c: char,
|
||||
prev_chars: impl Iterator<Item = char>,
|
||||
next_chars: impl Iterator<Item = char>,
|
||||
) -> Range<usize> {
|
||||
let char_type = CharType::from(c);
|
||||
let mut start = offset;
|
||||
let mut end = offset + c.len_utf8();
|
||||
|
||||
for prev in prev_chars.take(128) {
|
||||
if char_type.is_connectable(prev) {
|
||||
start -= prev.len_utf8();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for next in next_chars.take(128) {
|
||||
if char_type.is_connectable(next) {
|
||||
end += next.len_utf8();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
start..end
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -15,7 +15,6 @@ pub mod button;
|
||||
pub mod divider;
|
||||
pub mod dock;
|
||||
pub mod group_box;
|
||||
pub mod history;
|
||||
pub mod indicator;
|
||||
pub mod input;
|
||||
pub mod menu;
|
||||
@@ -43,7 +42,6 @@ mod window_ext;
|
||||
pub fn init(cx: &mut gpui::App) {
|
||||
gpui_base::init(cx);
|
||||
theme::sync_base(cx);
|
||||
input::init(cx);
|
||||
modal::init(cx);
|
||||
popover::init(cx);
|
||||
menu::init(cx);
|
||||
|
||||
@@ -13,7 +13,6 @@ use theme::{
|
||||
CLIENT_SIDE_DECORATION_SHADOW,
|
||||
};
|
||||
|
||||
use crate::input::InputState;
|
||||
use crate::modal::Modal;
|
||||
use crate::notification::{Notification, NotificationList};
|
||||
|
||||
@@ -50,9 +49,6 @@ pub struct Root {
|
||||
/// Notification layer
|
||||
pub(crate) notification: Entity<NotificationList>,
|
||||
|
||||
/// Current focused input
|
||||
pub(crate) focused_input: Option<Entity<InputState>>,
|
||||
|
||||
/// App view
|
||||
view: AnyView,
|
||||
}
|
||||
@@ -60,7 +56,6 @@ pub struct Root {
|
||||
impl Root {
|
||||
pub fn new(view: AnyView, window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
Self {
|
||||
focused_input: None,
|
||||
active_modals: Vec::new(),
|
||||
notification: cx.new(|cx| NotificationList::new(window, cx)),
|
||||
view,
|
||||
@@ -171,8 +166,6 @@ impl Root {
|
||||
|
||||
/// Close the topmost modal.
|
||||
pub fn close_modal(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
self.focused_input = None;
|
||||
|
||||
if let Some(handle) = self
|
||||
.active_modals
|
||||
.pop()
|
||||
@@ -187,7 +180,6 @@ impl Root {
|
||||
|
||||
/// Close all modals.
|
||||
pub fn close_all_modals(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
self.focused_input = None;
|
||||
self.active_modals.clear();
|
||||
|
||||
let previous_focused_handle = self
|
||||
|
||||
@@ -3,7 +3,6 @@ use std::rc::Rc;
|
||||
use gpui::{App, ElementId, Entity, Window};
|
||||
|
||||
use crate::Root;
|
||||
use crate::input::InputState;
|
||||
use crate::modal::Modal;
|
||||
use crate::notification::Notification;
|
||||
|
||||
@@ -43,12 +42,6 @@ pub trait WindowExtension: Sized {
|
||||
|
||||
/// Clear all notifications
|
||||
fn clear_notifications(&mut self, cx: &mut App);
|
||||
|
||||
/// Return current focused Input entity.
|
||||
fn focused_input(&mut self, cx: &mut App) -> Option<Entity<InputState>>;
|
||||
|
||||
/// Returns true if there is a focused Input entity.
|
||||
fn has_focused_input(&mut self, cx: &mut App) -> bool;
|
||||
}
|
||||
|
||||
impl WindowExtension for Window {
|
||||
@@ -122,12 +115,4 @@ impl WindowExtension for Window {
|
||||
let entity = Root::read(self, cx).notification.clone();
|
||||
Rc::new(entity.read(cx).notifications())
|
||||
}
|
||||
|
||||
fn has_focused_input(&mut self, cx: &mut App) -> bool {
|
||||
Root::read(self, cx).focused_input.is_some()
|
||||
}
|
||||
|
||||
fn focused_input(&mut self, cx: &mut App) -> Option<Entity<InputState>> {
|
||||
Root::read(self, cx).focused_input.clone()
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user