on master help sign in
reverse the dependency between helix-tui and helix-view (#366)
4418e17Keith Simmons
Cargo.lock+2
@@ -371,6 +371,7 @@ dependencies = [
371 "cassowary",
371 "cassowary",
372 "crossterm",
372 "crossterm",
373 "helix-core",
373 "helix-core",
374+ "helix-view",
374 "serde",
375 "serde",
375 "unicode-segmentation",
376 "unicode-segmentation",
376 "unicode-width",
377 "unicode-width",
@@ -381,6 +382,7 @@ name = "helix-view"
381version = "0.2.0"
382version = "0.2.0"
382dependencies = [
383dependencies = [
383 "anyhow",
384 "anyhow",
385+ "bitflags",
384 "chardetng",
386 "chardetng",
385 "crossterm",
387 "crossterm",
386 "encoding_rs",
388 "encoding_rs",
helix-term/Cargo.toml+2−2
@@ -23,8 +23,8 @@ path = "src/main.rs"
23
23
24[dependencies]
24[dependencies]
25helix-core = { version = "0.2", path = "../helix-core" }
25helix-core = { version = "0.2", path = "../helix-core" }
26−helix-view = { version = "0.2", path = "../helix-view", features = ["term"]}
26+helix-view = { version = "0.2", path = "../helix-view" }
27−helix-lsp = { version = "0.2", path = "../helix-lsp"}
27+helix-lsp = { version = "0.2", path = "../helix-lsp" }
28
28
29anyhow = "1"
29anyhow = "1"
30once_cell = "1.8"
30once_cell = "1.8"
helix-term/src/application.rs+1−3
@@ -1,6 +1,6 @@
1use helix_core::syntax;
1use helix_core::syntax;
2use helix_lsp::{lsp, LspProgressMap};
2use helix_lsp::{lsp, LspProgressMap};
3−use helix_view::{document::Mode, theme, Document, Editor, Theme, View};
3+use helix_view::{document::Mode, graphics::Rect, theme, Document, Editor, Theme, View};
4
4
5use crate::{
5use crate::{
6 args::Args,
6 args::Args,
@@ -29,8 +29,6 @@ use crossterm::{
29 execute, terminal,
29 execute, terminal,
30};
30};
31
31
32−use tui::layout::Rect;
33−
34use futures_util::{future, stream::FuturesUnordered};
32use futures_util::{future, stream::FuturesUnordered};
35
33
36type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
34type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
helix-term/src/commands.rs+2−1
@@ -15,7 +15,8 @@ use helix_core::{
15
15
16use helix_view::{
16use helix_view::{
17 document::{IndentStyle, Mode},
17 document::{IndentStyle, Mode},
18− input::{KeyCode, KeyEvent},
18+ input::KeyEvent,
19+ keyboard::KeyCode,
19 view::{View, PADDING},
20 view::{View, PADDING},
20 Document, DocumentId, Editor, ViewId,
21 Document, DocumentId, Editor, ViewId,
21};
22};
helix-term/src/compositor.rs+2−1
@@ -3,9 +3,10 @@
3// cursive does compositor.screen_mut().add_layer_at(pos::absolute(x, y), <component>)
3// cursive does compositor.screen_mut().add_layer_at(pos::absolute(x, y), <component>)
4use helix_core::Position;
4use helix_core::Position;
5use helix_lsp::LspProgressMap;
5use helix_lsp::LspProgressMap;
6+use helix_view::graphics::{CursorKind, Rect};
6
7
7use crossterm::event::Event;
8use crossterm::event::Event;
8−use tui::{buffer::Buffer as Surface, layout::Rect, terminal::CursorKind};
9+use tui::buffer::Buffer as Surface;
9
10
10pub type Callback = Box<dyn FnOnce(&mut Compositor)>;
11pub type Callback = Box<dyn FnOnce(&mut Compositor)>;
11
12
helix-term/src/config.rs+5−2
@@ -23,8 +23,11 @@ pub struct LspConfig {
23#[test]
23#[test]
24fn parsing_keymaps_config_file() {
24fn parsing_keymaps_config_file() {
25 use helix_core::hashmap;
25 use helix_core::hashmap;
26− use helix_view::document::Mode;
26+ use helix_view::{
27+ document::Mode,
27− use helix_view::input::{KeyCode, KeyEvent, KeyModifiers};
28+ input::KeyEvent,
29+ keyboard::{KeyCode, KeyModifiers},
30+ };
28
31
29 let sample_keymaps = r#"
32 let sample_keymaps = r#"
30 [keys.insert]
33 [keys.insert]
helix-term/src/keymap.rs+5−2
@@ -3,8 +3,11 @@ pub use crate::commands::Command;
3use crate::config::Config;
3use crate::config::Config;
4use anyhow::{anyhow, Error, Result};
4use anyhow::{anyhow, Error, Result};
5use helix_core::hashmap;
5use helix_core::hashmap;
6−use helix_view::document::Mode;
6+use helix_view::{
7+ document::Mode,
7−use helix_view::input::{KeyCode, KeyEvent, KeyModifiers};
8+ input::KeyEvent,
9+ keyboard::{KeyCode, KeyModifiers},
10+};
8use serde::Deserialize;
11use serde::Deserialize;
9use std::{
12use std::{
10 collections::HashMap,
13 collections::HashMap,
helix-term/src/ui/completion.rs+5−6
@@ -1,15 +1,14 @@
1use crate::compositor::{Component, Compositor, Context, EventResult};
1use crate::compositor::{Component, Compositor, Context, EventResult};
2use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
2use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
3−use tui::{
4− buffer::Buffer as Surface,
3+use tui::buffer::Buffer as Surface;
5− layout::Rect,
6− style::{Color, Style},
7−};
8
4
9use std::borrow::Cow;
5use std::borrow::Cow;
10
6
11use helix_core::{Position, Transaction};
7use helix_core::{Position, Transaction};
12−use helix_view::Editor;
8+use helix_view::{
9+ graphics::{Color, Rect, Style},
10+ Editor,
11+};
13
12
14use crate::commands;
13use crate::commands;
15use crate::ui::{menu, Markdown, Menu, Popup, PromptEvent};
14use crate::ui::{menu, Markdown, Menu, Popup, PromptEvent};
helix-term/src/ui/editor.rs+8−9
@@ -12,21 +12,20 @@ use helix_core::{
12 LineEnding, Position, Range,
12 LineEnding, Position, Range,
13};
13};
14use helix_lsp::LspProgressMap;
14use helix_lsp::LspProgressMap;
15+use helix_view::{
16+ document::Mode,
17+ graphics::{Color, CursorKind, Modifier, Rect, Style},
18+ input::KeyEvent,
15−use helix_view::input::{KeyCode, KeyEvent, KeyModifiers};
19+ keyboard::{KeyCode, KeyModifiers},
16−use helix_view::{document::Mode, Document, Editor, Theme, View};
20+ Document, Editor, Theme, View,
21+};
17use std::borrow::Cow;
22use std::borrow::Cow;
18
23
19use crossterm::{
24use crossterm::{
20 cursor,
25 cursor,
21 event::{read, Event, EventStream},
26 event::{read, Event, EventStream},
22};
27};
23−use tui::{
24− backend::CrosstermBackend,
28+use tui::{backend::CrosstermBackend, buffer::Buffer as Surface};
25− buffer::Buffer as Surface,
26− layout::Rect,
27− style::{Color, Modifier, Style},
28− terminal::CursorKind,
29−};
30
29
31pub struct EditorView {
30pub struct EditorView {
32 keymaps: Keymaps,
31 keymaps: Keymaps,
helix-term/src/ui/markdown.rs+5−7
@@ -1,16 +1,14 @@
1use crate::compositor::{Component, Compositor, Context, EventResult};
1use crate::compositor::{Component, Compositor, Context, EventResult};
2use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
2use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
3−use tui::{
4− buffer::Buffer as Surface,
3+use tui::{buffer::Buffer as Surface, text::Text};
5− layout::Rect,
6− style::{Color, Style},
7− text::Text,
8−};
9
4
10use std::{borrow::Cow, sync::Arc};
5use std::{borrow::Cow, sync::Arc};
11
6
12use helix_core::{syntax, Position};
7use helix_core::{syntax, Position};
13−use helix_view::{Editor, Theme};
8+use helix_view::{
9+ graphics::{Color, Rect, Style},
10+ Editor, Theme,
11+};
14
12
15pub struct Markdown {
13pub struct Markdown {
16 contents: String,
14 contents: String,
helix-term/src/ui/menu.rs+5−7
@@ -1,11 +1,6 @@
1use crate::compositor::{Component, Compositor, Context, EventResult};
1use crate::compositor::{Component, Compositor, Context, EventResult};
2use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
2use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
3−use tui::{
4− buffer::Buffer as Surface,
3+use tui::{buffer::Buffer as Surface, widgets::Table};
5− layout::Rect,
6− style::{Color, Style},
7− widgets::Table,
8−};
9
4
10pub use tui::widgets::{Cell, Row};
5pub use tui::widgets::{Cell, Row};
11
6
@@ -15,7 +10,10 @@ use fuzzy_matcher::skim::SkimMatcherV2 as Matcher;
15use fuzzy_matcher::FuzzyMatcher;
10use fuzzy_matcher::FuzzyMatcher;
16
11
17use helix_core::Position;
12use helix_core::Position;
18−use helix_view::Editor;
13+use helix_view::{
14+ graphics::{Color, Rect, Style},
15+ Editor,
16+};
19
17
20pub trait Item {
18pub trait Item {
21 // TODO: sort_text
19 // TODO: sort_text
helix-term/src/ui/mod.rs+4−4
@@ -18,12 +18,12 @@ pub use prompt::{Prompt, PromptEvent};
18pub use spinner::{ProgressSpinners, Spinner};
18pub use spinner::{ProgressSpinners, Spinner};
19pub use text::Text;
19pub use text::Text;
20
20
21−pub use tui::layout::Rect;
22−pub use tui::style::{Color, Modifier, Style};
23−
24use helix_core::regex::Regex;
21use helix_core::regex::Regex;
25use helix_core::register::Registers;
22use helix_core::register::Registers;
23+use helix_view::{
24+ graphics::{Color, Modifier, Rect, Style},
26−use helix_view::{Document, Editor, View};
25+ Document, Editor, View,
26+};
27
27
28use std::path::{Path, PathBuf};
28use std::path::{Path, PathBuf};
29
29
helix-term/src/ui/picker.rs+5−5
@@ -2,8 +2,6 @@ use crate::compositor::{Component, Compositor, Context, EventResult};
2use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
2use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
3use tui::{
3use tui::{
4 buffer::Buffer as Surface,
4 buffer::Buffer as Surface,
5− layout::Rect,
6− style::{Color, Style},
7 widgets::{Block, BorderType, Borders},
5 widgets::{Block, BorderType, Borders},
8};
6};
9
7
@@ -14,9 +12,11 @@ use std::borrow::Cow;
14
12
15use crate::ui::{Prompt, PromptEvent};
13use crate::ui::{Prompt, PromptEvent};
16use helix_core::Position;
14use helix_core::Position;
17−use helix_view::editor::Action;
15+use helix_view::{
18−use helix_view::Editor;
16+ editor::Action,
19−use tui::terminal::CursorKind;
17+ graphics::{Color, CursorKind, Rect, Style},
18+ Editor,
19+};
20
20
21pub struct Picker<T> {
21pub struct Picker<T> {
22 options: Vec<T>,
22 options: Vec<T>,
helix-term/src/ui/popup.rs+5−6
@@ -1,15 +1,14 @@
1use crate::compositor::{Component, Compositor, Context, EventResult};
1use crate::compositor::{Component, Compositor, Context, EventResult};
2use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
2use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
3−use tui::{
4− buffer::Buffer as Surface,
3+use tui::buffer::Buffer as Surface;
5− layout::Rect,
6− style::{Color, Style},
7−};
8
4
9use std::borrow::Cow;
5use std::borrow::Cow;
10
6
11use helix_core::Position;
7use helix_core::Position;
12−use helix_view::Editor;
8+use helix_view::{
9+ graphics::{Color, Rect, Style},
10+ Editor,
11+};
13
12
14// TODO: share logic with Menu, it's essentially Popup(render_fn), but render fn needs to return
13// TODO: share logic with Menu, it's essentially Popup(render_fn), but render fn needs to return
15// a width/height hint. maybe Popup(Box<Component>)
14// a width/height hint. maybe Popup(Box<Component>)
helix-term/src/ui/prompt.rs+6−10
@@ -1,14 +1,17 @@
1use crate::compositor::{Component, Compositor, Context, EventResult};
1use crate::compositor::{Component, Compositor, Context, EventResult};
2use crate::ui;
2use crate::ui;
3use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
3use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
4−use helix_core::Position;
5−use helix_view::{Editor, Theme};
6use std::{borrow::Cow, ops::RangeFrom};
4use std::{borrow::Cow, ops::RangeFrom};
7−use tui::terminal::CursorKind;
5+use tui::buffer::Buffer as Surface;
8
6
9use helix_core::{
7use helix_core::{
10 unicode::segmentation::{GraphemeCursor, GraphemeIncomplete},
8 unicode::segmentation::{GraphemeCursor, GraphemeIncomplete},
11 unicode::width::UnicodeWidthStr,
9 unicode::width::UnicodeWidthStr,
10+ Position,
11+};
12+use helix_view::{
13+ graphics::{Color, CursorKind, Margin, Modifier, Rect, Style},
14+ Editor, Theme,
12};
15};
13
16
14pub type Completion = (RangeFrom<usize>, Cow<'static, str>);
17pub type Completion = (RangeFrom<usize>, Cow<'static, str>);
@@ -251,12 +254,6 @@ impl Prompt {
251 }
254 }
252}
255}
253
256
254−use tui::{
255− buffer::Buffer as Surface,
256− layout::Rect,
257− style::{Color, Modifier, Style},
258−};
259−
260const BASE_WIDTH: u16 = 30;
257const BASE_WIDTH: u16 = 30;
261
258
262impl Prompt {
259impl Prompt {
@@ -343,7 +340,6 @@ impl Prompt {
343 let background = theme.get("ui.help");
340 let background = theme.get("ui.help");
344 surface.clear_with(area, background);
341 surface.clear_with(area, background);
345
342
346− use tui::layout::Margin;
347 text.render(
343 text.render(
348 area.inner(&Margin {
344 area.inner(&Margin {
349 vertical: 1,
345 vertical: 1,
helix-term/src/ui/text.rs+5−6
@@ -1,15 +1,14 @@
1use crate::compositor::{Component, Compositor, Context, EventResult};
1use crate::compositor::{Component, Compositor, Context, EventResult};
2use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
2use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
3−use tui::{
4− buffer::Buffer as Surface,
3+use tui::buffer::Buffer as Surface;
5− layout::Rect,
6− style::{Color, Style},
7−};
8
4
9use std::borrow::Cow;
5use std::borrow::Cow;
10
6
11use helix_core::Position;
7use helix_core::Position;
12−use helix_view::Editor;
8+use helix_view::{
9+ graphics::{Color, Rect, Style},
10+ Editor,
11+};
13
12
14pub struct Text {
13pub struct Text {
15 contents: String,
14 contents: String,
helix-tui/Cargo.toml+1
@@ -22,4 +22,5 @@ unicode-segmentation = "1.2"
22unicode-width = "0.1"
22unicode-width = "0.1"
23crossterm = { version = "0.20", optional = true }
23crossterm = { version = "0.20", optional = true }
24serde = { version = "1", "optional" = true, features = ["derive"]}
24serde = { version = "1", "optional" = true, features = ["derive"]}
25+helix-view = { path = "../helix-view", features = ["term"] }
25helix-core = { version = "0.2", path = "../helix-core" }
26helix-core = { version = "0.2", path = "../helix-core" }
helix-tui/src/backend/crossterm.rs+2−33
@@ -1,10 +1,4 @@
1−use crate::{
2− backend::Backend,
1+use crate::{backend::Backend, buffer::Cell};
3− buffer::Cell,
4− layout::Rect,
5− style::{Color, Modifier},
6− terminal::CursorKind,
7−};
8use crossterm::{
2use crossterm::{
9 cursor::{CursorShape, Hide, MoveTo, SetCursorShape, Show},
3 cursor::{CursorShape, Hide, MoveTo, SetCursorShape, Show},
10 execute, queue,
4 execute, queue,
@@ -14,6 +8,7 @@ use crossterm::{
14 },
8 },
15 terminal::{self, Clear, ClearType},
9 terminal::{self, Clear, ClearType},
16};
10};
11+use helix_view::graphics::{Color, CursorKind, Modifier, Rect};
17use std::io::{self, Write};
12use std::io::{self, Write};
18
13
19pub struct CrosstermBackend<W: Write> {
14pub struct CrosstermBackend<W: Write> {
@@ -133,32 +128,6 @@ fn map_error(error: crossterm::Result<()>) -> io::Result<()> {
133 error.map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string()))
128 error.map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string()))
134}
129}
135
130
136−impl From<Color> for CColor {
137− fn from(color: Color) -> Self {
138− match color {
139− Color::Reset => CColor::Reset,
140− Color::Black => CColor::Black,
141− Color::Red => CColor::DarkRed,
142− Color::Green => CColor::DarkGreen,
143− Color::Yellow => CColor::DarkYellow,
144− Color::Blue => CColor::DarkBlue,
145− Color::Magenta => CColor::DarkMagenta,
146− Color::Cyan => CColor::DarkCyan,
147− Color::Gray => CColor::Grey,
148− Color::DarkGray => CColor::DarkGrey,
149− Color::LightRed => CColor::Red,
150− Color::LightGreen => CColor::Green,
151− Color::LightBlue => CColor::Blue,
152− Color::LightYellow => CColor::Yellow,
153− Color::LightMagenta => CColor::Magenta,
154− Color::LightCyan => CColor::Cyan,
155− Color::White => CColor::White,
156− Color::Indexed(i) => CColor::AnsiValue(i),
157− Color::Rgb(r, g, b) => CColor::Rgb { r, g, b },
158− }
159− }
160−}
161−
162#[derive(Debug)]
131#[derive(Debug)]
163struct ModifierDiff {
132struct ModifierDiff {
164 pub from: Modifier,
133 pub from: Modifier,
helix-tui/src/backend/mod.rs+2−2
@@ -1,8 +1,8 @@
1use std::io;
1use std::io;
2
2
3use crate::buffer::Cell;
3use crate::buffer::Cell;
4−use crate::layout::Rect;
4+
5−use crate::terminal::CursorKind;
5+use helix_view::graphics::{CursorKind, Rect};
6
6
7#[cfg(feature = "crossterm")]
7#[cfg(feature = "crossterm")]
8mod crossterm;
8mod crossterm;
helix-tui/src/backend/test.rs+1−2
@@ -1,9 +1,8 @@
1use crate::{
1use crate::{
2 backend::Backend,
2 backend::Backend,
3 buffer::{Buffer, Cell},
3 buffer::{Buffer, Cell},
4− layout::Rect,
5− terminal::CursorKind,
6};
4};
5+use helix_view::graphics::{CursorKind, Rect};
7use std::{fmt::Write, io};
6use std::{fmt::Write, io};
8use unicode_width::UnicodeWidthStr;
7use unicode_width::UnicodeWidthStr;
9
8
helix-tui/src/buffer.rs+6−9
@@ -1,12 +1,10 @@
1−use crate::{
2− layout::Rect,
3− style::{Color, Modifier, Style},
4− text::{Span, Spans},
1+use crate::text::{Span, Spans};
5−};
6use std::cmp::min;
2use std::cmp::min;
7use unicode_segmentation::UnicodeSegmentation;
3use unicode_segmentation::UnicodeSegmentation;
8use unicode_width::UnicodeWidthStr;
4use unicode_width::UnicodeWidthStr;
9
5
6+use helix_view::graphics::{Color, Modifier, Rect, Style};
7+
10/// A buffer cell
8/// A buffer cell
11#[derive(Debug, Clone, PartialEq)]
9#[derive(Debug, Clone, PartialEq)]
12pub struct Cell {
10pub struct Cell {
@@ -89,8 +87,7 @@ impl Default for Cell {
89///
87///
90/// ```
88/// ```
91/// use helix_tui::buffer::{Buffer, Cell};
89/// use helix_tui::buffer::{Buffer, Cell};
92−/// use helix_tui::layout::Rect;
93−/// use helix_tui::style::{Color, Style, Modifier};
90+/// use helix_view::graphics::{Rect, Color, Style, Modifier};
94///
91///
95/// let mut buf = Buffer::empty(Rect{x: 0, y: 0, width: 10, height: 5});
92/// let mut buf = Buffer::empty(Rect{x: 0, y: 0, width: 10, height: 5});
96/// buf.get_mut(0, 2).set_symbol("x");
93/// buf.get_mut(0, 2).set_symbol("x");
@@ -193,7 +190,7 @@ impl Buffer {
193 ///
190 ///
194 /// ```
191 /// ```
195 /// # use helix_tui::buffer::Buffer;
192 /// # use helix_tui::buffer::Buffer;
196− /// # use helix_tui::layout::Rect;
193+ /// # use helix_view::graphics::Rect;
197 /// let rect = Rect::new(200, 100, 10, 10);
194 /// let rect = Rect::new(200, 100, 10, 10);
198 /// let buffer = Buffer::empty(rect);
195 /// let buffer = Buffer::empty(rect);
199 /// // Global coordinates to the top corner of this buffer's area
196 /// // Global coordinates to the top corner of this buffer's area
@@ -225,7 +222,7 @@ impl Buffer {
225 ///
222 ///
226 /// ```
223 /// ```
227 /// # use helix_tui::buffer::Buffer;
224 /// # use helix_tui::buffer::Buffer;
228− /// # use helix_tui::layout::Rect;
225+ /// # use helix_view::graphics::Rect;
229 /// let rect = Rect::new(200, 100, 10, 10);
226 /// let rect = Rect::new(200, 100, 10, 10);
230 /// let buffer = Buffer::empty(rect);
227 /// let buffer = Buffer::empty(rect);
231 /// assert_eq!(buffer.pos_of(0), (200, 100));
228 /// assert_eq!(buffer.pos_of(0), (200, 100));
helix-tui/src/layout.rs+4−163
@@ -1,11 +1,12 @@
1use std::cell::RefCell;
1use std::cell::RefCell;
2−use std::cmp::{max, min};
3use std::collections::HashMap;
2use std::collections::HashMap;
4
3
5use cassowary::strength::{REQUIRED, WEAK};
4use cassowary::strength::{REQUIRED, WEAK};
6use cassowary::WeightedRelation::*;
5use cassowary::WeightedRelation::*;
7use cassowary::{Constraint as CassowaryConstraint, Expression, Solver, Variable};
6use cassowary::{Constraint as CassowaryConstraint, Expression, Solver, Variable};
8
7
8+use helix_view::graphics::{Margin, Rect};
9+
9#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq)]
10#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq)]
10pub enum Corner {
11pub enum Corner {
11 TopLeft,
12 TopLeft,
@@ -45,12 +46,6 @@ impl Constraint {
45 }
46 }
46}
47}
47
48
48−#[derive(Debug, Clone, PartialEq, Eq, Hash)]
49−pub struct Margin {
50− pub vertical: u16,
51− pub horizontal: u16,
52−}
53−
54#[derive(Debug, Clone, Copy, PartialEq)]
49#[derive(Debug, Clone, Copy, PartialEq)]
55pub enum Alignment {
50pub enum Alignment {
56 Left,
51 Left,
@@ -119,7 +114,8 @@ impl Layout {
119 ///
114 ///
120 /// # Examples
115 /// # Examples
121 /// ```
116 /// ```
122− /// # use helix_tui::layout::{Rect, Constraint, Direction, Layout};
117+ /// # use helix_tui::layout::{Constraint, Direction, Layout};
118+ /// # use helix_view::graphics::Rect;
123 /// let chunks = Layout::default()
119 /// let chunks = Layout::default()
124 /// .direction(Direction::Vertical)
120 /// .direction(Direction::Vertical)
125 /// .constraints([Constraint::Length(5), Constraint::Min(0)].as_ref())
121 /// .constraints([Constraint::Length(5), Constraint::Min(0)].as_ref())
@@ -348,117 +344,6 @@ impl Element {
348 }
344 }
349}
345}
350
346
351−/// A simple rectangle used in the computation of the layout and to give widgets an hint about the
352−/// area they are supposed to render to.
353−#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
354−pub struct Rect {
355− pub x: u16,
356− pub y: u16,
357− pub width: u16,
358− pub height: u16,
359−}
360−
361−impl Default for Rect {
362− fn default() -> Rect {
363− Rect {
364− x: 0,
365− y: 0,
366− width: 0,
367− height: 0,
368− }
369− }
370−}
371−
372−impl Rect {
373− /// Creates a new rect, with width and height limited to keep the area under max u16.
374− /// If clipped, aspect ratio will be preserved.
375− pub fn new(x: u16, y: u16, width: u16, height: u16) -> Rect {
376− let max_area = u16::max_value();
377− let (clipped_width, clipped_height) =
378− if u32::from(width) * u32::from(height) > u32::from(max_area) {
379− let aspect_ratio = f64::from(width) / f64::from(height);
380− let max_area_f = f64::from(max_area);
381− let height_f = (max_area_f / aspect_ratio).sqrt();
382− let width_f = height_f * aspect_ratio;
383− (width_f as u16, height_f as u16)
384− } else {
385− (width, height)
386− };
387− Rect {
388− x,
389− y,
390− width: clipped_width,
391− height: clipped_height,
392− }
393− }
394−
395− pub fn area(self) -> u16 {
396− self.width * self.height
397− }
398−
399− pub fn left(self) -> u16 {
400− self.x
401− }
402−
403− pub fn right(self) -> u16 {
404− self.x.saturating_add(self.width)
405− }
406−
407− pub fn top(self) -> u16 {
408− self.y
409− }
410−
411− pub fn bottom(self) -> u16 {
412− self.y.saturating_add(self.height)
413− }
414−
415− pub fn inner(self, margin: &Margin) -> Rect {
416− if self.width < 2 * margin.horizontal || self.height < 2 * margin.vertical {
417− Rect::default()
418− } else {
419− Rect {
420− x: self.x + margin.horizontal,
421− y: self.y + margin.vertical,
422− width: self.width - 2 * margin.horizontal,
423− height: self.height - 2 * margin.vertical,
424− }
425− }
426− }
427−
428− pub fn union(self, other: Rect) -> Rect {
429− let x1 = min(self.x, other.x);
430− let y1 = min(self.y, other.y);
431− let x2 = max(self.x + self.width, other.x + other.width);
432− let y2 = max(self.y + self.height, other.y + other.height);
433− Rect {
434− x: x1,
435− y: y1,
436− width: x2 - x1,
437− height: y2 - y1,
438− }
439− }
440−
441− pub fn intersection(self, other: Rect) -> Rect {
442− let x1 = max(self.x, other.x);
443− let y1 = max(self.y, other.y);
444− let x2 = min(self.x + self.width, other.x + other.width);
445− let y2 = min(self.y + self.height, other.y + other.height);
446− Rect {
447− x: x1,
448− y: y1,
449− width: x2 - x1,
450− height: y2 - y1,
451− }
452− }
453−
454− pub fn intersects(self, other: Rect) -> bool {
455− self.x < other.x + other.width
456− && self.x + self.width > other.x
457− && self.y < other.y + other.height
458− && self.y + self.height > other.y
459− }
460−}
461−
462#[cfg(test)]
347#[cfg(test)]
463mod tests {
348mod tests {
464 use super::*;
349 use super::*;
@@ -487,48 +372,4 @@ mod tests {
487 assert_eq!(target.height, chunks.iter().map(|r| r.height).sum::<u16>());
372 assert_eq!(target.height, chunks.iter().map(|r| r.height).sum::<u16>());
488 chunks.windows(2).for_each(|w| assert!(w[0].y <= w[1].y));
373 chunks.windows(2).for_each(|w| assert!(w[0].y <= w[1].y));
489 }
374 }
490−
491− #[test]
492− fn test_rect_size_truncation() {
493− for width in 256u16..300u16 {
494− for height in 256u16..300u16 {
495− let rect = Rect::new(0, 0, width, height);
496− rect.area(); // Should not panic.
497− assert!(rect.width < width || rect.height < height);
498− // The target dimensions are rounded down so the math will not be too precise
499− // but let's make sure the ratios don't diverge crazily.
500− assert!(
501− (f64::from(rect.width) / f64::from(rect.height)
502− - f64::from(width) / f64::from(height))
503− .abs()
504− < 1.0
505− )
506− }
507− }
508−
509− // One dimension below 255, one above. Area above max u16.
510− let width = 900;
511− let height = 100;
512− let rect = Rect::new(0, 0, width, height);
513− assert_ne!(rect.width, 900);
514− assert_ne!(rect.height, 100);
515− assert!(rect.width < width || rect.height < height);
516− }
517−
518− #[test]
519− fn test_rect_size_preservation() {
520− for width in 0..256u16 {
521− for height in 0..256u16 {
522− let rect = Rect::new(0, 0, width, height);
523− rect.area(); // Should not panic.
524− assert_eq!(rect.width, width);
525− assert_eq!(rect.height, height);
526− }
527− }
528−
529− // One dimension below 255, one above. Area below max u16.
530− let rect = Rect::new(0, 0, 300, 100);
531− assert_eq!(rect.width, 300);
532− assert_eq!(rect.height, 100);
533− }
534}
375}
helix-tui/src/lib.rs−1
@@ -125,7 +125,6 @@
125pub mod backend;
125pub mod backend;
126pub mod buffer;
126pub mod buffer;
127pub mod layout;
127pub mod layout;
128−pub mod style;
129pub mod symbols;
128pub mod symbols;
130pub mod terminal;
129pub mod terminal;
131pub mod text;
130pub mod text;
helix-tui/src/terminal.rs+2−14
@@ -1,4 +1,5 @@
1−use crate::{backend::Backend, buffer::Buffer, layout::Rect};
1+use crate::{backend::Backend, buffer::Buffer};
2+use helix_view::graphics::{CursorKind, Rect};
2use std::io;
3use std::io;
3
4
4#[derive(Debug, Clone, PartialEq)]
5#[derive(Debug, Clone, PartialEq)]
@@ -8,19 +9,6 @@ enum ResizeBehavior {
8 Auto,
9 Auto,
9}
10}
10
11
11−#[derive(Debug)]
12−/// UNSTABLE
13−pub enum CursorKind {
14− /// █
15− Block,
16− /// |
17− Bar,
18− /// _
19− Underline,
20− /// Hidden cursor, can set cursor position with this to let IME have correct cursor position.
21− Hidden,
22−}
23−
24#[derive(Debug, Clone, PartialEq)]
12#[derive(Debug, Clone, PartialEq)]
25/// UNSTABLE
13/// UNSTABLE
26pub struct Viewport {
14pub struct Viewport {
helix-tui/src/text.rs+8−8
@@ -21,7 +21,7 @@
21//! ```rust
21//! ```rust
22//! # use helix_tui::widgets::Block;
22//! # use helix_tui::widgets::Block;
23//! # use helix_tui::text::{Span, Spans};
23//! # use helix_tui::text::{Span, Spans};
24−//! # use helix_tui::style::{Color, Style};
24+//! # use helix_view::graphics::{Color, Style};
25//! // A simple string with no styling.
25//! // A simple string with no styling.
26//! // Converted to Spans(vec![
26//! // Converted to Spans(vec![
27//! // Span { content: Cow::Borrowed("My title"), style: Style { .. } }
27//! // Span { content: Cow::Borrowed("My title"), style: Style { .. } }
@@ -46,8 +46,8 @@
46//! Span::raw(" title"),
46//! Span::raw(" title"),
47//! ]);
47//! ]);
48//! ```
48//! ```
49−use crate::style::Style;
50use helix_core::line_ending::str_is_line_ending;
49use helix_core::line_ending::str_is_line_ending;
50+use helix_view::graphics::Style;
51use std::borrow::Cow;
51use std::borrow::Cow;
52use unicode_segmentation::UnicodeSegmentation;
52use unicode_segmentation::UnicodeSegmentation;
53use unicode_width::UnicodeWidthStr;
53use unicode_width::UnicodeWidthStr;
@@ -92,7 +92,7 @@ impl<'a> Span<'a> {
92 ///
92 ///
93 /// ```rust
93 /// ```rust
94 /// # use helix_tui::text::Span;
94 /// # use helix_tui::text::Span;
95− /// # use helix_tui::style::{Color, Modifier, Style};
95+ /// # use helix_view::graphics::{Color, Modifier, Style};
96 /// let style = Style::default().fg(Color::Yellow).add_modifier(Modifier::ITALIC);
96 /// let style = Style::default().fg(Color::Yellow).add_modifier(Modifier::ITALIC);
97 /// Span::styled("My text", style);
97 /// Span::styled("My text", style);
98 /// Span::styled(String::from("My text"), style);
98 /// Span::styled(String::from("My text"), style);
@@ -121,7 +121,7 @@ impl<'a> Span<'a> {
121 ///
121 ///
122 /// ```rust
122 /// ```rust
123 /// # use helix_tui::text::{Span, StyledGrapheme};
123 /// # use helix_tui::text::{Span, StyledGrapheme};
124− /// # use helix_tui::style::{Color, Modifier, Style};
124+ /// # use helix_view::graphics::{Color, Modifier, Style};
125 /// # use std::iter::Iterator;
125 /// # use std::iter::Iterator;
126 /// let style = Style::default().fg(Color::Yellow);
126 /// let style = Style::default().fg(Color::Yellow);
127 /// let span = Span::styled("Text", style);
127 /// let span = Span::styled("Text", style);
@@ -211,7 +211,7 @@ impl<'a> Spans<'a> {
211 ///
211 ///
212 /// ```rust
212 /// ```rust
213 /// # use helix_tui::text::{Span, Spans};
213 /// # use helix_tui::text::{Span, Spans};
214− /// # use helix_tui::style::{Color, Style};
214+ /// # use helix_view::graphics::{Color, Style};
215 /// let spans = Spans::from(vec![
215 /// let spans = Spans::from(vec![
216 /// Span::styled("My", Style::default().fg(Color::Yellow)),
216 /// Span::styled("My", Style::default().fg(Color::Yellow)),
217 /// Span::raw(" text"),
217 /// Span::raw(" text"),
@@ -265,7 +265,7 @@ impl<'a> From<Spans<'a>> for String {
265///
265///
266/// ```rust
266/// ```rust
267/// # use helix_tui::text::Text;
267/// # use helix_tui::text::Text;
268−/// # use helix_tui::style::{Color, Modifier, Style};
268+/// # use helix_view::graphics::{Color, Modifier, Style};
269/// let style = Style::default().fg(Color::Yellow).add_modifier(Modifier::ITALIC);
269/// let style = Style::default().fg(Color::Yellow).add_modifier(Modifier::ITALIC);
270///
270///
271/// // An initial two lines of `Text` built from a `&str`
271/// // An initial two lines of `Text` built from a `&str`
@@ -319,7 +319,7 @@ impl<'a> Text<'a> {
319 ///
319 ///
320 /// ```rust
320 /// ```rust
321 /// # use helix_tui::text::Text;
321 /// # use helix_tui::text::Text;
322− /// # use helix_tui::style::{Color, Modifier, Style};
322+ /// # use helix_view::graphics::{Color, Modifier, Style};
323 /// let style = Style::default().fg(Color::Yellow).add_modifier(Modifier::ITALIC);
323 /// let style = Style::default().fg(Color::Yellow).add_modifier(Modifier::ITALIC);
324 /// Text::styled("The first line\nThe second line", style);
324 /// Text::styled("The first line\nThe second line", style);
325 /// Text::styled(String::from("The first line\nThe second line"), style);
325 /// Text::styled(String::from("The first line\nThe second line"), style);
@@ -369,7 +369,7 @@ impl<'a> Text<'a> {
369 ///
369 ///
370 /// ```rust
370 /// ```rust
371 /// # use helix_tui::text::Text;
371 /// # use helix_tui::text::Text;
372− /// # use helix_tui::style::{Color, Modifier, Style};
372+ /// # use helix_view::graphics::{Color, Modifier, Style};
373 /// let style = Style::default().fg(Color::Yellow).add_modifier(Modifier::ITALIC);
373 /// let style = Style::default().fg(Color::Yellow).add_modifier(Modifier::ITALIC);
374 /// let mut raw_text = Text::raw("The first line\nThe second line");
374 /// let mut raw_text = Text::raw("The first line\nThe second line");
375 /// let styled_text = Text::styled(String::from("The first line\nThe second line"), style);
375 /// let styled_text = Text::styled(String::from("The first line\nThe second line"), style);
helix-tui/src/widgets/block.rs+2−4
@@ -1,11 +1,10 @@
1use crate::{
1use crate::{
2 buffer::Buffer,
2 buffer::Buffer,
3− layout::Rect,
4− style::Style,
5 symbols::line,
3 symbols::line,
6 text::{Span, Spans},
4 text::{Span, Spans},
7 widgets::{Borders, Widget},
5 widgets::{Borders, Widget},
8};
6};
7+use helix_view::graphics::{Rect, Style};
9
8
10#[derive(Debug, Clone, Copy, PartialEq)]
9#[derive(Debug, Clone, Copy, PartialEq)]
11pub enum BorderType {
10pub enum BorderType {
@@ -33,7 +32,7 @@ impl BorderType {
33///
32///
34/// ```
33/// ```
35/// # use helix_tui::widgets::{Block, BorderType, Borders};
34/// # use helix_tui::widgets::{Block, BorderType, Borders};
36−/// # use helix_tui::style::{Style, Color};
35+/// # use helix_view::graphics::{Style, Color};
37/// Block::default()
36/// Block::default()
38/// .title("Block")
37/// .title("Block")
39/// .borders(Borders::LEFT | Borders::RIGHT)
38/// .borders(Borders::LEFT | Borders::RIGHT)
@@ -212,7 +211,6 @@ impl<'a> Widget for Block<'a> {
212#[cfg(test)]
211#[cfg(test)]
213mod tests {
212mod tests {
214 use super::*;
213 use super::*;
215− use crate::layout::Rect;
216
214
217 #[test]
215 #[test]
218 fn inner_takes_into_account_the_borders() {
216 fn inner_takes_into_account_the_borders() {
helix-tui/src/widgets/mod.rs+3−1
@@ -20,9 +20,11 @@ pub use self::block::{Block, BorderType};
20pub use self::paragraph::{Paragraph, Wrap};
20pub use self::paragraph::{Paragraph, Wrap};
21pub use self::table::{Cell, Row, Table, TableState};
21pub use self::table::{Cell, Row, Table, TableState};
22
22
23−use crate::{buffer::Buffer, layout::Rect};
23+use crate::buffer::Buffer;
24use bitflags::bitflags;
24use bitflags::bitflags;
25
25
26+use helix_view::graphics::Rect;
27+
26bitflags! {
28bitflags! {
27 /// Bitflags that can be composed to set the visible borders essentially on the block widget.
29 /// Bitflags that can be composed to set the visible borders essentially on the block widget.
28 pub struct Borders: u32 {
30 pub struct Borders: u32 {
helix-tui/src/widgets/paragraph.rs+3−3
@@ -1,13 +1,13 @@
1use crate::{
1use crate::{
2 buffer::Buffer,
2 buffer::Buffer,
3− layout::{Alignment, Rect},
3+ layout::Alignment,
4− style::Style,
5 text::{StyledGrapheme, Text},
4 text::{StyledGrapheme, Text},
6 widgets::{
5 widgets::{
7 reflow::{LineComposer, LineTruncator, WordWrapper},
6 reflow::{LineComposer, LineTruncator, WordWrapper},
8 Block, Widget,
7 Block, Widget,
9 },
8 },
10};
9};
10+use helix_view::graphics::{Rect, Style};
11use std::iter;
11use std::iter;
12use unicode_width::UnicodeWidthStr;
12use unicode_width::UnicodeWidthStr;
13
13
@@ -26,8 +26,8 @@ fn get_line_offset(line_width: u16, text_area_width: u16, alignment: Alignment)
26/// ```
26/// ```
27/// # use helix_tui::text::{Text, Spans, Span};
27/// # use helix_tui::text::{Text, Spans, Span};
28/// # use helix_tui::widgets::{Block, Borders, Paragraph, Wrap};
28/// # use helix_tui::widgets::{Block, Borders, Paragraph, Wrap};
29−/// # use helix_tui::style::{Style, Color, Modifier};
30/// # use helix_tui::layout::{Alignment};
29/// # use helix_tui::layout::{Alignment};
30+/// # use helix_view::graphics::{Style, Color, Modifier};
31/// let text = vec![
31/// let text = vec![
32/// Spans::from(vec![
32/// Spans::from(vec![
33/// Span::raw("First"),
33/// Span::raw("First"),
helix-tui/src/widgets/table.rs+5−5
@@ -1,7 +1,6 @@
1use crate::{
1use crate::{
2 buffer::Buffer,
2 buffer::Buffer,
3− layout::{Constraint, Rect},
3+ layout::Constraint,
4− style::Style,
5 text::Text,
4 text::Text,
6 widgets::{Block, Widget},
5 widgets::{Block, Widget},
7};
6};
@@ -10,6 +9,7 @@ use cassowary::{
10 WeightedRelation::*,
9 WeightedRelation::*,
11 {Expression, Solver},
10 {Expression, Solver},
12};
11};
12+use helix_view::graphics::{Rect, Style};
13use std::{
13use std::{
14 collections::HashMap,
14 collections::HashMap,
15 iter::{self, Iterator},
15 iter::{self, Iterator},
@@ -21,8 +21,8 @@ use unicode_width::UnicodeWidthStr;
21/// It can be created from anything that can be converted to a [`Text`].
21/// It can be created from anything that can be converted to a [`Text`].
22/// ```rust
22/// ```rust
23/// # use helix_tui::widgets::Cell;
23/// # use helix_tui::widgets::Cell;
24−/// # use helix_tui::style::{Style, Modifier};
25/// # use helix_tui::text::{Span, Spans, Text};
24/// # use helix_tui::text::{Span, Spans, Text};
25+/// # use helix_view::graphics::{Style, Modifier};
26/// Cell::from("simple string");
26/// Cell::from("simple string");
27///
27///
28/// Cell::from(Span::from("span"));
28/// Cell::from(Span::from("span"));
@@ -74,7 +74,7 @@ where
74/// But if you need a bit more control over individual cells, you can explicity create [`Cell`]s:
74/// But if you need a bit more control over individual cells, you can explicity create [`Cell`]s:
75/// ```rust
75/// ```rust
76/// # use helix_tui::widgets::{Row, Cell};
76/// # use helix_tui::widgets::{Row, Cell};
77−/// # use helix_tui::style::{Style, Color};
77+/// # use helix_view::graphics::{Style, Color};
78/// Row::new(vec![
78/// Row::new(vec![
79/// Cell::from("Cell1"),
79/// Cell::from("Cell1"),
80/// Cell::from("Cell2").style(Style::default().fg(Color::Yellow)),
80/// Cell::from("Cell2").style(Style::default().fg(Color::Yellow)),
@@ -137,7 +137,7 @@ impl<'a> Row<'a> {
137/// ```rust
137/// ```rust
138/// # use helix_tui::widgets::{Block, Borders, Table, Row, Cell};
138/// # use helix_tui::widgets::{Block, Borders, Table, Row, Cell};
139/// # use helix_tui::layout::Constraint;
139/// # use helix_tui::layout::Constraint;
140−/// # use helix_tui::style::{Style, Color, Modifier};
140+/// # use helix_view::graphics::{Style, Color, Modifier};
141/// # use helix_tui::text::{Text, Spans, Span};
141/// # use helix_tui::text::{Text, Spans, Span};
142/// Table::new(vec![
142/// Table::new(vec![
143/// // Row can be created from simple strings.
143/// // Row can be created from simple strings.
helix-view/Cargo.toml+7−6
@@ -9,20 +9,18 @@ categories = ["editor"]
9repository = "https://github.com/helix-editor/helix"
9repository = "https://github.com/helix-editor/helix"
10homepage = "https://helix-editor.com"
10homepage = "https://helix-editor.com"
11
11
12−# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
13−
14[features]
12[features]
15−term = ["tui", "crossterm"]
16−default = ["term"]
13+default = []
14+term = ["crossterm"]
17
15
18[dependencies]
16[dependencies]
17+bitflags = "1.0"
19anyhow = "1"
18anyhow = "1"
20helix-core = { version = "0.2", path = "../helix-core" }
19helix-core = { version = "0.2", path = "../helix-core" }
21helix-lsp = { version = "0.2", path = "../helix-lsp"}
20helix-lsp = { version = "0.2", path = "../helix-lsp"}
21+crossterm = { version = "0.20", optional = true }
22
22
23# Conversion traits
23# Conversion traits
24−tui = { path = "../helix-tui", package = "helix-tui", default-features = false, features = ["crossterm"], optional = true }
25−crossterm = { version = "0.20", features = ["event-stream"], optional = true }
26once_cell = "1.8"
24once_cell = "1.8"
27url = "2"
25url = "2"
28
26
@@ -39,3 +37,6 @@ toml = "0.5"
39log = "~0.4"
37log = "~0.4"
40
38
41which = "4.1"
39which = "4.1"
40+
41+[dev-dependencies]
42+helix-tui = { path = "../helix-tui" }
helix-view/src/editor.rs+4−5
@@ -1,12 +1,10 @@
1−use crate::clipboard::{get_clipboard_provider, ClipboardProvider};
2use crate::{
1use crate::{
2+ clipboard::{get_clipboard_provider, ClipboardProvider},
3+ graphics::{CursorKind, Rect},
3 theme::{self, Theme},
4 theme::{self, Theme},
4 tree::Tree,
5 tree::Tree,
5 Document, DocumentId, RegisterSelection, View, ViewId,
6 Document, DocumentId, RegisterSelection, View, ViewId,
6};
7};
7−use helix_core::syntax;
8−use tui::layout::Rect;
9−use tui::terminal::CursorKind;
10
8
11use futures_util::future;
9use futures_util::future;
12use std::{path::PathBuf, sync::Arc, time::Duration};
10use std::{path::PathBuf, sync::Arc, time::Duration};
@@ -17,6 +15,7 @@ use anyhow::Error;
17
15
18pub use helix_core::diagnostic::Severity;
16pub use helix_core::diagnostic::Severity;
19pub use helix_core::register::Registers;
17pub use helix_core::register::Registers;
18+use helix_core::syntax;
20use helix_core::Position;
19use helix_core::Position;
21
20
22#[derive(Debug)]
21#[derive(Debug)]
@@ -45,7 +44,7 @@ pub enum Action {
45
44
46impl Editor {
45impl Editor {
47 pub fn new(
46 pub fn new(
48− mut area: tui::layout::Rect,
47+ mut area: Rect,
49 themes: Arc<theme::Loader>,
48 themes: Arc<theme::Loader>,
50 config_loader: Arc<syntax::Loader>,
49 config_loader: Arc<syntax::Loader>,
51 ) -> Self {
50 ) -> Self {
helix-tui/src/style.rs → helix-view/src/graphics.rsrenamed+481−281
@@ -1,281 +1,481 @@
1−//! `style` contains the primitives used to control how your user interface will look.
1+use bitflags::bitflags;
2−
2+use std::cmp::{max, min};
3−use bitflags::bitflags;
3+
4−
4+#[derive(Debug)]
5+/// UNSTABLE
6+pub enum CursorKind {
7+ /// █
8+ Block,
9+ /// |
10+ Bar,
11+ /// _
12+ Underline,
13+ /// Hidden cursor, can set cursor position with this to let IME have correct cursor position.
14+ Hidden,
15+}
16+
17+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
18+pub struct Margin {
19+ pub vertical: u16,
20+ pub horizontal: u16,
21+}
22+
23+/// A simple rectangle used in the computation of the layout and to give widgets an hint about the
24+/// area they are supposed to render to.
5−#[derive(Debug, Clone, Copy, PartialEq)]
25+#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
6−#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
26+pub struct Rect {
7−pub enum Color {
27+ pub x: u16,
8− Reset,
28+ pub y: u16,
9− Black,
29+ pub width: u16,
10− Red,
30+ pub height: u16,
11− Green,
31+}
12− Yellow,
32+
13− Blue,
33+impl Default for Rect {
14− Magenta,
34+ fn default() -> Rect {
15− Cyan,
35+ Rect {
16− Gray,
36+ x: 0,
17− DarkGray,
37+ y: 0,
18− LightRed,
38+ width: 0,
19− LightGreen,
39+ height: 0,
20− LightYellow,
40+ }
21− LightBlue,
41+ }
22− LightMagenta,
42+}
23− LightCyan,
43+
24− White,
44+impl Rect {
25− Rgb(u8, u8, u8),
45+ /// Creates a new rect, with width and height limited to keep the area under max u16.
26− Indexed(u8),
46+ /// If clipped, aspect ratio will be preserved.
47+ pub fn new(x: u16, y: u16, width: u16, height: u16) -> Rect {
48+ let max_area = u16::max_value();
49+ let (clipped_width, clipped_height) =
50+ if u32::from(width) * u32::from(height) > u32::from(max_area) {
51+ let aspect_ratio = f64::from(width) / f64::from(height);
52+ let max_area_f = f64::from(max_area);
53+ let height_f = (max_area_f / aspect_ratio).sqrt();
54+ let width_f = height_f * aspect_ratio;
55+ (width_f as u16, height_f as u16)
56+ } else {
57+ (width, height)
58+ };
59+ Rect {
60+ x,
61+ y,
62+ width: clipped_width,
63+ height: clipped_height,
64+ }
65+ }
66+
67+ pub fn area(self) -> u16 {
68+ self.width * self.height
69+ }
70+
71+ pub fn left(self) -> u16 {
72+ self.x
73+ }
74+
75+ pub fn right(self) -> u16 {
76+ self.x.saturating_add(self.width)
77+ }
78+
79+ pub fn top(self) -> u16 {
80+ self.y
81+ }
82+
83+ pub fn bottom(self) -> u16 {
84+ self.y.saturating_add(self.height)
85+ }
86+
87+ pub fn inner(self, margin: &Margin) -> Rect {
88+ if self.width < 2 * margin.horizontal || self.height < 2 * margin.vertical {
89+ Rect::default()
90+ } else {
91+ Rect {
92+ x: self.x + margin.horizontal,
93+ y: self.y + margin.vertical,
94+ width: self.width - 2 * margin.horizontal,
95+ height: self.height - 2 * margin.vertical,
96+ }
97+ }
98+ }
99+
100+ pub fn union(self, other: Rect) -> Rect {
101+ let x1 = min(self.x, other.x);
102+ let y1 = min(self.y, other.y);
103+ let x2 = max(self.x + self.width, other.x + other.width);
104+ let y2 = max(self.y + self.height, other.y + other.height);
105+ Rect {
106+ x: x1,
107+ y: y1,
108+ width: x2 - x1,
109+ height: y2 - y1,
110+ }
111+ }
112+
113+ pub fn intersection(self, other: Rect) -> Rect {
114+ let x1 = max(self.x, other.x);
115+ let y1 = max(self.y, other.y);
116+ let x2 = min(self.x + self.width, other.x + other.width);
117+ let y2 = min(self.y + self.height, other.y + other.height);
118+ Rect {
119+ x: x1,
120+ y: y1,
121+ width: x2 - x1,
122+ height: y2 - y1,
123+ }
124+ }
125+
126+ pub fn intersects(self, other: Rect) -> bool {
127+ self.x < other.x + other.width
128+ && self.x + self.width > other.x
129+ && self.y < other.y + other.height
130+ && self.y + self.height > other.y
131+ }
132+}
133+
134+#[derive(Debug, Clone, Copy, PartialEq)]
135+#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
136+pub enum Color {
137+ Reset,
138+ Black,
139+ Red,
140+ Green,
141+ Yellow,
142+ Blue,
143+ Magenta,
144+ Cyan,
145+ Gray,
146+ DarkGray,
147+ LightRed,
148+ LightGreen,
149+ LightYellow,
150+ LightBlue,
151+ LightMagenta,
152+ LightCyan,
153+ White,
154+ Rgb(u8, u8, u8),
155+ Indexed(u8),
156+}
157+
158+#[cfg(feature = "term")]
159+impl From<Color> for crossterm::style::Color {
160+ fn from(color: Color) -> Self {
161+ use crossterm::style::Color as CColor;
162+
163+ match color {
164+ Color::Reset => CColor::Reset,
165+ Color::Black => CColor::Black,
166+ Color::Red => CColor::DarkRed,
167+ Color::Green => CColor::DarkGreen,
168+ Color::Yellow => CColor::DarkYellow,
169+ Color::Blue => CColor::DarkBlue,
170+ Color::Magenta => CColor::DarkMagenta,
171+ Color::Cyan => CColor::DarkCyan,
172+ Color::Gray => CColor::Grey,
173+ Color::DarkGray => CColor::DarkGrey,
174+ Color::LightRed => CColor::Red,
175+ Color::LightGreen => CColor::Green,
176+ Color::LightBlue => CColor::Blue,
177+ Color::LightYellow => CColor::Yellow,
178+ Color::LightMagenta => CColor::Magenta,
179+ Color::LightCyan => CColor::Cyan,
180+ Color::White => CColor::White,
181+ Color::Indexed(i) => CColor::AnsiValue(i),
182+ Color::Rgb(r, g, b) => CColor::Rgb { r, g, b },
183+ }
184+ }
27−}
185+}
28−
186+
29−bitflags! {
187+bitflags! {
30− /// Modifier changes the way a piece of text is displayed.
188+ /// Modifier changes the way a piece of text is displayed.
31− ///
189+ ///
32− /// They are bitflags so they can easily be composed.
190+ /// They are bitflags so they can easily be composed.
33− ///
191+ ///
34− /// ## Examples
192+ /// ## Examples
35− ///
193+ ///
36− /// ```rust
194+ /// ```rust
37− /// # use helix_tui::style::Modifier;
195+ /// # use helix_view::graphics::Modifier;
38− ///
196+ ///
39− /// let m = Modifier::BOLD | Modifier::ITALIC;
197+ /// let m = Modifier::BOLD | Modifier::ITALIC;
40− /// ```
198+ /// ```
41− #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
199+ #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
42− pub struct Modifier: u16 {
200+ pub struct Modifier: u16 {
43− const BOLD = 0b0000_0000_0001;
201+ const BOLD = 0b0000_0000_0001;
44− const DIM = 0b0000_0000_0010;
202+ const DIM = 0b0000_0000_0010;
45− const ITALIC = 0b0000_0000_0100;
203+ const ITALIC = 0b0000_0000_0100;
46− const UNDERLINED = 0b0000_0000_1000;
204+ const UNDERLINED = 0b0000_0000_1000;
47− const SLOW_BLINK = 0b0000_0001_0000;
205+ const SLOW_BLINK = 0b0000_0001_0000;
48− const RAPID_BLINK = 0b0000_0010_0000;
206+ const RAPID_BLINK = 0b0000_0010_0000;
49− const REVERSED = 0b0000_0100_0000;
207+ const REVERSED = 0b0000_0100_0000;
50− const HIDDEN = 0b0000_1000_0000;
208+ const HIDDEN = 0b0000_1000_0000;
51− const CROSSED_OUT = 0b0001_0000_0000;
209+ const CROSSED_OUT = 0b0001_0000_0000;
52− }
210+ }
53−}
211+}
54−
212+
55−/// Style let you control the main characteristics of the displayed elements.
213+/// Style let you control the main characteristics of the displayed elements.
56−///
214+///
57−/// ```rust
215+/// ```rust
58−/// # use helix_tui::style::{Color, Modifier, Style};
216+/// # use helix_view::graphics::{Color, Modifier, Style};
59−/// Style::default()
217+/// Style::default()
60−/// .fg(Color::Black)
218+/// .fg(Color::Black)
61−/// .bg(Color::Green)
219+/// .bg(Color::Green)
62−/// .add_modifier(Modifier::ITALIC | Modifier::BOLD);
220+/// .add_modifier(Modifier::ITALIC | Modifier::BOLD);
63−/// ```
221+/// ```
64−///
222+///
65−/// It represents an incremental change. If you apply the styles S1, S2, S3 to a cell of the
223+/// It represents an incremental change. If you apply the styles S1, S2, S3 to a cell of the
66−/// terminal buffer, the style of this cell will be the result of the merge of S1, S2 and S3, not
224+/// terminal buffer, the style of this cell will be the result of the merge of S1, S2 and S3, not
67−/// just S3.
225+/// just S3.
68−///
226+///
69−/// ```rust
227+/// ```rust
70−/// # use helix_tui::style::{Color, Modifier, Style};
228+/// # use helix_view::graphics::{Rect, Color, Modifier, Style};
71−/// # use helix_tui::buffer::Buffer;
229+/// # use helix_tui::buffer::Buffer;
72−/// # use helix_tui::layout::Rect;
73−/// let styles = [
230+/// let styles = [
74−/// Style::default().fg(Color::Blue).add_modifier(Modifier::BOLD | Modifier::ITALIC),
231+/// Style::default().fg(Color::Blue).add_modifier(Modifier::BOLD | Modifier::ITALIC),
75−/// Style::default().bg(Color::Red),
232+/// Style::default().bg(Color::Red),
76−/// Style::default().fg(Color::Yellow).remove_modifier(Modifier::ITALIC),
233+/// Style::default().fg(Color::Yellow).remove_modifier(Modifier::ITALIC),
77−/// ];
234+/// ];
78−/// let mut buffer = Buffer::empty(Rect::new(0, 0, 1, 1));
235+/// let mut buffer = Buffer::empty(Rect::new(0, 0, 1, 1));
79−/// for style in &styles {
236+/// for style in &styles {
80−/// buffer.get_mut(0, 0).set_style(*style);
237+/// buffer.get_mut(0, 0).set_style(*style);
81−/// }
238+/// }
82−/// assert_eq!(
239+/// assert_eq!(
83−/// Style {
240+/// Style {
84−/// fg: Some(Color::Yellow),
241+/// fg: Some(Color::Yellow),
85−/// bg: Some(Color::Red),
242+/// bg: Some(Color::Red),
86−/// add_modifier: Modifier::BOLD,
243+/// add_modifier: Modifier::BOLD,
87−/// sub_modifier: Modifier::empty(),
244+/// sub_modifier: Modifier::empty(),
88−/// },
245+/// },
89−/// buffer.get(0, 0).style(),
246+/// buffer.get(0, 0).style(),
90−/// );
247+/// );
91−/// ```
248+/// ```
92−///
249+///
93−/// The default implementation returns a `Style` that does not modify anything. If you wish to
250+/// The default implementation returns a `Style` that does not modify anything. If you wish to
94−/// reset all properties until that point use [`Style::reset`].
251+/// reset all properties until that point use [`Style::reset`].
95−///
252+///
96−/// ```
253+/// ```
97−/// # use helix_tui::style::{Color, Modifier, Style};
254+/// # use helix_view::graphics::{Rect, Color, Modifier, Style};
98−/// # use helix_tui::buffer::Buffer;
255+/// # use helix_tui::buffer::Buffer;
99−/// # use helix_tui::layout::Rect;
100−/// let styles = [
256+/// let styles = [
101−/// Style::default().fg(Color::Blue).add_modifier(Modifier::BOLD | Modifier::ITALIC),
257+/// Style::default().fg(Color::Blue).add_modifier(Modifier::BOLD | Modifier::ITALIC),
102−/// Style::reset().fg(Color::Yellow),
258+/// Style::reset().fg(Color::Yellow),
103−/// ];
259+/// ];
104−/// let mut buffer = Buffer::empty(Rect::new(0, 0, 1, 1));
260+/// let mut buffer = Buffer::empty(Rect::new(0, 0, 1, 1));
105−/// for style in &styles {
261+/// for style in &styles {
106−/// buffer.get_mut(0, 0).set_style(*style);
262+/// buffer.get_mut(0, 0).set_style(*style);
107−/// }
263+/// }
108−/// assert_eq!(
264+/// assert_eq!(
109−/// Style {
265+/// Style {
110−/// fg: Some(Color::Yellow),
266+/// fg: Some(Color::Yellow),
111−/// bg: Some(Color::Reset),
267+/// bg: Some(Color::Reset),
112−/// add_modifier: Modifier::empty(),
268+/// add_modifier: Modifier::empty(),
113−/// sub_modifier: Modifier::empty(),
269+/// sub_modifier: Modifier::empty(),
114−/// },
270+/// },
115−/// buffer.get(0, 0).style(),
271+/// buffer.get(0, 0).style(),
116−/// );
272+/// );
117−/// ```
273+/// ```
118−#[derive(Debug, Clone, Copy, PartialEq)]
274+#[derive(Debug, Clone, Copy, PartialEq)]
119−#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
275+#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
120−pub struct Style {
276+pub struct Style {
121− pub fg: Option<Color>,
277+ pub fg: Option<Color>,
122− pub bg: Option<Color>,
278+ pub bg: Option<Color>,
123− pub add_modifier: Modifier,
279+ pub add_modifier: Modifier,
124− pub sub_modifier: Modifier,
280+ pub sub_modifier: Modifier,
125−}
281+}
126−
282+
127−impl Default for Style {
283+impl Default for Style {
128− fn default() -> Style {
284+ fn default() -> Style {
129− Style {
285+ Style {
130− fg: None,
286+ fg: None,
131− bg: None,
287+ bg: None,
132− add_modifier: Modifier::empty(),
288+ add_modifier: Modifier::empty(),
133− sub_modifier: Modifier::empty(),
289+ sub_modifier: Modifier::empty(),
134− }
290+ }
135− }
291+ }
136−}
292+}
137−
293+
138−impl Style {
294+impl Style {
139− /// Returns a `Style` resetting all properties.
295+ /// Returns a `Style` resetting all properties.
140− pub fn reset() -> Style {
296+ pub fn reset() -> Style {
141− Style {
297+ Style {
142− fg: Some(Color::Reset),
298+ fg: Some(Color::Reset),
143− bg: Some(Color::Reset),
299+ bg: Some(Color::Reset),
144− add_modifier: Modifier::empty(),
300+ add_modifier: Modifier::empty(),
145− sub_modifier: Modifier::all(),
301+ sub_modifier: Modifier::all(),
146− }
302+ }
147− }
303+ }
148−
304+
149− /// Changes the foreground color.
305+ /// Changes the foreground color.
150− ///
306+ ///
151− /// ## Examples
307+ /// ## Examples
152− ///
308+ ///
153− /// ```rust
309+ /// ```rust
154− /// # use helix_tui::style::{Color, Style};
310+ /// # use helix_view::graphics::{Color, Style};
155− /// let style = Style::default().fg(Color::Blue);
311+ /// let style = Style::default().fg(Color::Blue);
156− /// let diff = Style::default().fg(Color::Red);
312+ /// let diff = Style::default().fg(Color::Red);
157− /// assert_eq!(style.patch(diff), Style::default().fg(Color::Red));
313+ /// assert_eq!(style.patch(diff), Style::default().fg(Color::Red));
158− /// ```
314+ /// ```
159− pub fn fg(mut self, color: Color) -> Style {
315+ pub fn fg(mut self, color: Color) -> Style {
160− self.fg = Some(color);
316+ self.fg = Some(color);
161− self
317+ self
162− }
318+ }
163−
319+
164− /// Changes the background color.
320+ /// Changes the background color.
165− ///
321+ ///
166− /// ## Examples
322+ /// ## Examples
167− ///
323+ ///
168− /// ```rust
324+ /// ```rust
169− /// # use helix_tui::style::{Color, Style};
325+ /// # use helix_view::graphics::{Color, Style};
170− /// let style = Style::default().bg(Color::Blue);
326+ /// let style = Style::default().bg(Color::Blue);
171− /// let diff = Style::default().bg(Color::Red);
327+ /// let diff = Style::default().bg(Color::Red);
172− /// assert_eq!(style.patch(diff), Style::default().bg(Color::Red));
328+ /// assert_eq!(style.patch(diff), Style::default().bg(Color::Red));
173− /// ```
329+ /// ```
174− pub fn bg(mut self, color: Color) -> Style {
330+ pub fn bg(mut self, color: Color) -> Style {
175− self.bg = Some(color);
331+ self.bg = Some(color);
176− self
332+ self
177− }
333+ }
178−
334+
179− /// Changes the text emphasis.
335+ /// Changes the text emphasis.
180− ///
336+ ///
181− /// When applied, it adds the given modifier to the `Style` modifiers.
337+ /// When applied, it adds the given modifier to the `Style` modifiers.
182− ///
338+ ///
183− /// ## Examples
339+ /// ## Examples
184− ///
340+ ///
185− /// ```rust
341+ /// ```rust
186− /// # use helix_tui::style::{Color, Modifier, Style};
342+ /// # use helix_view::graphics::{Color, Modifier, Style};
187− /// let style = Style::default().add_modifier(Modifier::BOLD);
343+ /// let style = Style::default().add_modifier(Modifier::BOLD);
188− /// let diff = Style::default().add_modifier(Modifier::ITALIC);
344+ /// let diff = Style::default().add_modifier(Modifier::ITALIC);
189− /// let patched = style.patch(diff);
345+ /// let patched = style.patch(diff);
190− /// assert_eq!(patched.add_modifier, Modifier::BOLD | Modifier::ITALIC);
346+ /// assert_eq!(patched.add_modifier, Modifier::BOLD | Modifier::ITALIC);
191− /// assert_eq!(patched.sub_modifier, Modifier::empty());
347+ /// assert_eq!(patched.sub_modifier, Modifier::empty());
192− /// ```
348+ /// ```
193− pub fn add_modifier(mut self, modifier: Modifier) -> Style {
349+ pub fn add_modifier(mut self, modifier: Modifier) -> Style {
194− self.sub_modifier.remove(modifier);
350+ self.sub_modifier.remove(modifier);
195− self.add_modifier.insert(modifier);
351+ self.add_modifier.insert(modifier);
196− self
352+ self
197− }
353+ }
198−
354+
199− /// Changes the text emphasis.
355+ /// Changes the text emphasis.
200− ///
356+ ///
201− /// When applied, it removes the given modifier from the `Style` modifiers.
357+ /// When applied, it removes the given modifier from the `Style` modifiers.
202− ///
358+ ///
203− /// ## Examples
359+ /// ## Examples
204− ///
360+ ///
205− /// ```rust
361+ /// ```rust
206− /// # use helix_tui::style::{Color, Modifier, Style};
362+ /// # use helix_view::graphics::{Color, Modifier, Style};
207− /// let style = Style::default().add_modifier(Modifier::BOLD | Modifier::ITALIC);
363+ /// let style = Style::default().add_modifier(Modifier::BOLD | Modifier::ITALIC);
208− /// let diff = Style::default().remove_modifier(Modifier::ITALIC);
364+ /// let diff = Style::default().remove_modifier(Modifier::ITALIC);
209− /// let patched = style.patch(diff);
365+ /// let patched = style.patch(diff);
210− /// assert_eq!(patched.add_modifier, Modifier::BOLD);
366+ /// assert_eq!(patched.add_modifier, Modifier::BOLD);
211− /// assert_eq!(patched.sub_modifier, Modifier::ITALIC);
367+ /// assert_eq!(patched.sub_modifier, Modifier::ITALIC);
212− /// ```
368+ /// ```
213− pub fn remove_modifier(mut self, modifier: Modifier) -> Style {
369+ pub fn remove_modifier(mut self, modifier: Modifier) -> Style {
214− self.add_modifier.remove(modifier);
370+ self.add_modifier.remove(modifier);
215− self.sub_modifier.insert(modifier);
371+ self.sub_modifier.insert(modifier);
216− self
372+ self
217− }
373+ }
218−
374+
219− /// Results in a combined style that is equivalent to applying the two individual styles to
375+ /// Results in a combined style that is equivalent to applying the two individual styles to
220− /// a style one after the other.
376+ /// a style one after the other.
221− ///
377+ ///
222− /// ## Examples
378+ /// ## Examples
223− /// ```
379+ /// ```
224− /// # use helix_tui::style::{Color, Modifier, Style};
380+ /// # use helix_view::graphics::{Color, Modifier, Style};
225− /// let style_1 = Style::default().fg(Color::Yellow);
381+ /// let style_1 = Style::default().fg(Color::Yellow);
226− /// let style_2 = Style::default().bg(Color::Red);
382+ /// let style_2 = Style::default().bg(Color::Red);
227− /// let combined = style_1.patch(style_2);
383+ /// let combined = style_1.patch(style_2);
228− /// assert_eq!(
384+ /// assert_eq!(
229− /// Style::default().patch(style_1).patch(style_2),
385+ /// Style::default().patch(style_1).patch(style_2),
230− /// Style::default().patch(combined));
386+ /// Style::default().patch(combined));
231− /// ```
387+ /// ```
232− pub fn patch(mut self, other: Style) -> Style {
388+ pub fn patch(mut self, other: Style) -> Style {
233− self.fg = other.fg.or(self.fg);
389+ self.fg = other.fg.or(self.fg);
234− self.bg = other.bg.or(self.bg);
390+ self.bg = other.bg.or(self.bg);
235−
391+
236− self.add_modifier.remove(other.sub_modifier);
392+ self.add_modifier.remove(other.sub_modifier);
237− self.add_modifier.insert(other.add_modifier);
393+ self.add_modifier.insert(other.add_modifier);
238− self.sub_modifier.remove(other.add_modifier);
394+ self.sub_modifier.remove(other.add_modifier);
239− self.sub_modifier.insert(other.sub_modifier);
395+ self.sub_modifier.insert(other.sub_modifier);
240−
396+
241− self
397+ self
242− }
398+ }
243−}
399+}
244−
400+
245−#[cfg(test)]
401+#[cfg(test)]
246−mod tests {
402+mod tests {
247− use super::*;
403+ use super::*;
248−
404+
405+ #[test]
406+ fn test_rect_size_truncation() {
407+ for width in 256u16..300u16 {
408+ for height in 256u16..300u16 {
409+ let rect = Rect::new(0, 0, width, height);
410+ rect.area(); // Should not panic.
411+ assert!(rect.width < width || rect.height < height);
412+ // The target dimensions are rounded down so the math will not be too precise
413+ // but let's make sure the ratios don't diverge crazily.
414+ assert!(
415+ (f64::from(rect.width) / f64::from(rect.height)
416+ - f64::from(width) / f64::from(height))
417+ .abs()
418+ < 1.0
419+ )
420+ }
421+ }
422+
423+ // One dimension below 255, one above. Area above max u16.
424+ let width = 900;
425+ let height = 100;
426+ let rect = Rect::new(0, 0, width, height);
427+ assert_ne!(rect.width, 900);
428+ assert_ne!(rect.height, 100);
429+ assert!(rect.width < width || rect.height < height);
430+ }
431+
432+ #[test]
433+ fn test_rect_size_preservation() {
434+ for width in 0..256u16 {
435+ for height in 0..256u16 {
436+ let rect = Rect::new(0, 0, width, height);
437+ rect.area(); // Should not panic.
438+ assert_eq!(rect.width, width);
439+ assert_eq!(rect.height, height);
440+ }
441+ }
442+
443+ // One dimension below 255, one above. Area below max u16.
444+ let rect = Rect::new(0, 0, 300, 100);
445+ assert_eq!(rect.width, 300);
446+ assert_eq!(rect.height, 100);
447+ }
448+
249− fn styles() -> Vec<Style> {
449+ fn styles() -> Vec<Style> {
250− vec![
450+ vec![
251− Style::default(),
451+ Style::default(),
252− Style::default().fg(Color::Yellow),
452+ Style::default().fg(Color::Yellow),
253− Style::default().bg(Color::Yellow),
453+ Style::default().bg(Color::Yellow),
254− Style::default().add_modifier(Modifier::BOLD),
454+ Style::default().add_modifier(Modifier::BOLD),
255− Style::default().remove_modifier(Modifier::BOLD),
455+ Style::default().remove_modifier(Modifier::BOLD),
256− Style::default().add_modifier(Modifier::ITALIC),
456+ Style::default().add_modifier(Modifier::ITALIC),
257− Style::default().remove_modifier(Modifier::ITALIC),
457+ Style::default().remove_modifier(Modifier::ITALIC),
258− Style::default().add_modifier(Modifier::ITALIC | Modifier::BOLD),
458+ Style::default().add_modifier(Modifier::ITALIC | Modifier::BOLD),
259− Style::default().remove_modifier(Modifier::ITALIC | Modifier::BOLD),
459+ Style::default().remove_modifier(Modifier::ITALIC | Modifier::BOLD),
260− ]
460+ ]
261− }
461+ }
262−
462+
263− #[test]
463+ #[test]
264− fn combined_patch_gives_same_result_as_individual_patch() {
464+ fn combined_patch_gives_same_result_as_individual_patch() {
265− let styles = styles();
465+ let styles = styles();
266− for &a in &styles {
466+ for &a in &styles {
267− for &b in &styles {
467+ for &b in &styles {
268− for &c in &styles {
468+ for &c in &styles {
269− for &d in &styles {
469+ for &d in &styles {
270− let combined = a.patch(b.patch(c.patch(d)));
470+ let combined = a.patch(b.patch(c.patch(d)));
271−
471+
272− assert_eq!(
472+ assert_eq!(
273− Style::default().patch(a).patch(b).patch(c).patch(d),
473+ Style::default().patch(a).patch(b).patch(c).patch(d),
274− Style::default().patch(combined)
474+ Style::default().patch(combined)
275− );
475+ );
276− }
476+ }
277− }
477+ }
278− }
478+ }
279− }
479+ }
280− }
480+ }
281−}
481+}
helix-view/src/input.rs+10−5
@@ -1,10 +1,9 @@
1//! Input event handling, currently backed by crossterm.
1//! Input event handling, currently backed by crossterm.
2use anyhow::{anyhow, Error};
2use anyhow::{anyhow, Error};
3−use crossterm::event;
4use serde::de::{self, Deserialize, Deserializer};
3use serde::de::{self, Deserialize, Deserializer};
5use std::fmt;
4use std::fmt;
6
5
7−pub use crossterm::event::{KeyCode, KeyModifiers};
6+use crate::keyboard::{KeyCode, KeyModifiers};
8
7
9/// Represents a key event.
8/// Represents a key event.
10// We use a newtype here because we want to customize Deserialize and Display.
9// We use a newtype here because we want to customize Deserialize and Display.
@@ -132,9 +131,15 @@ impl<'de> Deserialize<'de> for KeyEvent {
132 }
131 }
133}
132}
134
133
134+#[cfg(feature = "term")]
135−impl From<event::KeyEvent> for KeyEvent {
135+impl From<crossterm::event::KeyEvent> for KeyEvent {
136+ fn from(
136− fn from(event::KeyEvent { code, modifiers }: event::KeyEvent) -> KeyEvent {
137+ crossterm::event::KeyEvent { code, modifiers }: crossterm::event::KeyEvent,
138+ ) -> KeyEvent {
137− KeyEvent { code, modifiers }
139+ KeyEvent {
140+ code: code.into(),
141+ modifiers: modifiers.into(),
142+ }
138 }
143 }
139}
144}
140
145
helix-view/src/keyboard.rsnew file+160
@@ -0,0 +1,160 @@
1+use bitflags::bitflags;
2+
3+bitflags! {
4+ /// Represents key modifiers (shift, control, alt).
5+ #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6+ pub struct KeyModifiers: u8 {
7+ const SHIFT = 0b0000_0001;
8+ const CONTROL = 0b0000_0010;
9+ const ALT = 0b0000_0100;
10+ const NONE = 0b0000_0000;
11+ }
12+}
13+
14+#[cfg(feature = "term")]
15+impl From<KeyModifiers> for crossterm::event::KeyModifiers {
16+ fn from(key_modifiers: KeyModifiers) -> Self {
17+ use crossterm::event::KeyModifiers as CKeyModifiers;
18+
19+ let mut result = CKeyModifiers::NONE;
20+
21+ if key_modifiers & KeyModifiers::SHIFT != KeyModifiers::NONE {
22+ result &= CKeyModifiers::SHIFT;
23+ }
24+
25+ if key_modifiers & KeyModifiers::CONTROL != KeyModifiers::NONE {
26+ result &= CKeyModifiers::CONTROL;
27+ }
28+
29+ if key_modifiers & KeyModifiers::ALT != KeyModifiers::NONE {
30+ result &= CKeyModifiers::ALT;
31+ }
32+
33+ result
34+ }
35+}
36+
37+#[cfg(feature = "term")]
38+impl From<crossterm::event::KeyModifiers> for KeyModifiers {
39+ fn from(val: crossterm::event::KeyModifiers) -> Self {
40+ use crossterm::event::KeyModifiers as CKeyModifiers;
41+
42+ let mut result = KeyModifiers::NONE;
43+
44+ if val & CKeyModifiers::SHIFT != CKeyModifiers::NONE {
45+ result &= KeyModifiers::SHIFT;
46+ }
47+
48+ if val & CKeyModifiers::CONTROL != CKeyModifiers::NONE {
49+ result &= KeyModifiers::CONTROL;
50+ }
51+
52+ if val & CKeyModifiers::ALT != CKeyModifiers::NONE {
53+ result &= KeyModifiers::ALT;
54+ }
55+
56+ result
57+ }
58+}
59+
60+/// Represents a key.
61+#[derive(Debug, PartialOrd, PartialEq, Eq, Clone, Copy, Hash)]
62+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
63+pub enum KeyCode {
64+ /// Backspace key.
65+ Backspace,
66+ /// Enter key.
67+ Enter,
68+ /// Left arrow key.
69+ Left,
70+ /// Right arrow key.
71+ Right,
72+ /// Up arrow key.
73+ Up,
74+ /// Down arrow key.
75+ Down,
76+ /// Home key.
77+ Home,
78+ /// End key.
79+ End,
80+ /// Page up key.
81+ PageUp,
82+ /// Page dow key.
83+ PageDown,
84+ /// Tab key.
85+ Tab,
86+ /// Shift + Tab key.
87+ BackTab,
88+ /// Delete key.
89+ Delete,
90+ /// Insert key.
91+ Insert,
92+ /// F key.
93+ ///
94+ /// `KeyCode::F(1)` represents F1 key, etc.
95+ F(u8),
96+ /// A character.
97+ ///
98+ /// `KeyCode::Char('c')` represents `c` character, etc.
99+ Char(char),
100+ /// Null.
101+ Null,
102+ /// Escape key.
103+ Esc,
104+}
105+
106+#[cfg(feature = "term")]
107+impl From<KeyCode> for crossterm::event::KeyCode {
108+ fn from(key_code: KeyCode) -> Self {
109+ use crossterm::event::KeyCode as CKeyCode;
110+
111+ match key_code {
112+ KeyCode::Backspace => CKeyCode::Backspace,
113+ KeyCode::Enter => CKeyCode::Enter,
114+ KeyCode::Left => CKeyCode::Left,
115+ KeyCode::Right => CKeyCode::Right,
116+ KeyCode::Up => CKeyCode::Up,
117+ KeyCode::Down => CKeyCode::Down,
118+ KeyCode::Home => CKeyCode::Home,
119+ KeyCode::End => CKeyCode::End,
120+ KeyCode::PageUp => CKeyCode::PageUp,
121+ KeyCode::PageDown => CKeyCode::PageDown,
122+ KeyCode::Tab => CKeyCode::Tab,
123+ KeyCode::BackTab => CKeyCode::BackTab,
124+ KeyCode::Delete => CKeyCode::Delete,
125+ KeyCode::Insert => CKeyCode::Insert,
126+ KeyCode::F(f_number) => CKeyCode::F(f_number),
127+ KeyCode::Char(character) => CKeyCode::Char(character),
128+ KeyCode::Null => CKeyCode::Null,
129+ KeyCode::Esc => CKeyCode::Esc,
130+ }
131+ }
132+}
133+
134+#[cfg(feature = "term")]
135+impl From<crossterm::event::KeyCode> for KeyCode {
136+ fn from(val: crossterm::event::KeyCode) -> Self {
137+ use crossterm::event::KeyCode as CKeyCode;
138+
139+ match val {
140+ CKeyCode::Backspace => KeyCode::Backspace,
141+ CKeyCode::Enter => KeyCode::Enter,
142+ CKeyCode::Left => KeyCode::Left,
143+ CKeyCode::Right => KeyCode::Right,
144+ CKeyCode::Up => KeyCode::Up,
145+ CKeyCode::Down => KeyCode::Down,
146+ CKeyCode::Home => KeyCode::Home,
147+ CKeyCode::End => KeyCode::End,
148+ CKeyCode::PageUp => KeyCode::PageUp,
149+ CKeyCode::PageDown => KeyCode::PageDown,
150+ CKeyCode::Tab => KeyCode::Tab,
151+ CKeyCode::BackTab => KeyCode::BackTab,
152+ CKeyCode::Delete => KeyCode::Delete,
153+ CKeyCode::Insert => KeyCode::Insert,
154+ CKeyCode::F(f_number) => KeyCode::F(f_number),
155+ CKeyCode::Char(character) => KeyCode::Char(character),
156+ CKeyCode::Null => KeyCode::Null,
157+ CKeyCode::Esc => KeyCode::Esc,
158+ }
159+ }
160+}
helix-view/src/lib.rs+2
@@ -4,7 +4,9 @@ pub mod macros;
4pub mod clipboard;
4pub mod clipboard;
5pub mod document;
5pub mod document;
6pub mod editor;
6pub mod editor;
7+pub mod graphics;
7pub mod input;
8pub mod input;
9+pub mod keyboard;
8pub mod register_selection;
10pub mod register_selection;
9pub mod theme;
11pub mod theme;
10pub mod tree;
12pub mod tree;
helix-view/src/theme.rs+1−80
@@ -9,86 +9,7 @@ use once_cell::sync::Lazy;
9use serde::{Deserialize, Deserializer};
9use serde::{Deserialize, Deserializer};
10use toml::Value;
10use toml::Value;
11
11
12−#[cfg(feature = "term")]
13−pub use tui::style::{Color, Modifier, Style};
12+pub use crate::graphics::{Color, Modifier, Style};
14−
15−// #[derive(Clone, Copy, PartialEq, Eq, Default, Hash)]
16−// pub struct Color {
17−// pub r: u8,
18−// pub g: u8,
19−// pub b: u8,
20−// }
21−
22−// impl Color {
23−// pub fn new(r: u8, g: u8, b: u8) -> Self {
24−// Self { r, g, b }
25−// }
26−// }
27−
28−// #[cfg(feature = "term")]
29−// impl Into<tui::style::Color> for Color {
30−// fn into(self) -> tui::style::Color {
31−// tui::style::Color::Rgb(self.r, self.g, self.b)
32−// }
33−// }
34−
35−// impl std::str::FromStr for Color {
36−// type Err = ();
37−
38−// /// Tries to parse a string (`'#FFFFFF'` or `'FFFFFF'`) into RGB.
39−// fn from_str(input: &str) -> Result<Self, Self::Err> {
40−// let input = input.trim();
41−// let input = match (input.chars().next(), input.len()) {
42−// (Some('#'), 7) => &input[1..],
43−// (_, 6) => input,
44−// _ => return Err(()),
45−// };
46−
47−// u32::from_str_radix(&input, 16)
48−// .map(|s| Color {
49−// r: ((s >> 16) & 0xFF) as u8,
50−// g: ((s >> 8) & 0xFF) as u8,
51−// b: (s & 0xFF) as u8,
52−// })
53−// .map_err(|_| ())
54−// }
55−// }
56−
57−// #[derive(Clone, Copy, PartialEq, Eq, Default, Hash)]
58−// pub struct Style {
59−// pub fg: Option<Color>,
60−// pub bg: Option<Color>,
61−// // TODO: modifiers (bold, underline, italic, etc)
62−// }
63−
64−// impl Style {
65−// pub fn fg(mut self, fg: Color) -> Self {
66−// self.fg = Some(fg);
67−// self
68−// }
69−
70−// pub fn bg(mut self, bg: Color) -> Self {
71−// self.bg = Some(bg);
72−// self
73−// }
74−// }
75−
76−// #[cfg(feature = "term")]
77−// impl Into<tui::style::Style> for Style {
78−// fn into(self) -> tui::style::Style {
79−// let style = tui::style::Style::default();
80−
81−// if let Some(fg) = self.fg {
82−// style.fg(fg.into());
83−// }
84−
85−// if let Some(bg) = self.bg {
86−// style.bg(bg.into());
87−// }
88−
89−// style
90−// }
91−// }
92
13
93/// Color theme for syntax highlighting.
14/// Color theme for syntax highlighting.
94
15
helix-view/src/tree.rs+1−2
@@ -1,6 +1,5 @@
1−use crate::{View, ViewId};
1+use crate::{graphics::Rect, View, ViewId};
2use slotmap::HopSlotMap;
2use slotmap::HopSlotMap;
3−use tui::layout::Rect;
4
3
5// the dimensions are recomputed on windo resize/tree change.
4// the dimensions are recomputed on windo resize/tree change.
6//
5//
helix-view/src/view.rs+1−2
@@ -1,12 +1,11 @@
1use std::borrow::Cow;
1use std::borrow::Cow;
2
2
3−use crate::{Document, DocumentId, ViewId};
3+use crate::{graphics::Rect, Document, DocumentId, ViewId};
4use helix_core::{
4use helix_core::{
5 coords_at_pos,
5 coords_at_pos,
6 graphemes::{grapheme_width, RopeGraphemes},
6 graphemes::{grapheme_width, RopeGraphemes},
7 Position, RopeSlice, Selection,
7 Position, RopeSlice, Selection,
8};
8};
9−use tui::layout::Rect;
10
9
11pub const PADDING: usize = 5;
10pub const PADDING: usize = 5;
12
11