Debian Codegraph @

helix-view/src/graphics.rs

raw symbols SCIP
1 use bitflags::bitflags;
2 use serde::{Deserialize, Serialize};
3 use std::{
4 cmp::{max, min},
5 fmt,
6 str::FromStr,
7 };
8
9 #[must_use]
10 const fn from_nibble(h: u8) -> u8 {
11 match h {
12 b'A'..=b'F' => h - b'A' + 10,
13 b'a'..=b'f' => h - b'a' + 10,
14 b'0'..=b'9' => h - b'0',
15 _ => 0xff, // Err
16 }
17 }
18
19 /// Decodes nibble, repeating its value on each half,
20 /// i.e. the value is its own padding.
21 ///
22 /// # Errors
23 /// If `h` isn't a nibble
24 #[must_use]
25 const fn dupe_from_nibble(mut h: u8) -> Option<u8> {
26 h = from_nibble(h);
27 if h > 0xf {
28 return None;
29 }
30 Some((h << 4) | h)
31 }
32
33 /// Decodes big-endian nibble-pair.
34 ///
35 /// # Errors
36 /// If any byte isn't a nibble
37 const fn byte_from_hex(mut h: [u8; 2]) -> Option<u8> {
38 // reuse memory
39 h[0] = from_nibble(h[0]);
40 h[1] = from_nibble(h[1]);
41 // we could split this in 2 `if`s,
42 // to avoid calling `from_nibble`,
43 // but that might be slower
44 if h[0] > 0xf || h[1] > 0xf {
45 return None;
46 }
47 Some((h[0] << 4) | h[1])
48 }
49
50 #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
51 #[serde(rename_all = "lowercase")]
52 /// UNSTABLE
53 #[derive(Default)]
54 pub enum CursorKind {
55 /// █
56 #[default]
57 Block,
58 /// |
59 Bar,
60 /// _
61 Underline,
62 /// Hidden cursor, can set cursor position with this to let IME have correct cursor position.
63 Hidden,
64 }
65
66 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
67 pub struct Margin {
68 pub horizontal: u16,
69 pub vertical: u16,
70 }
71
72 impl Margin {
73 pub fn none() -> Self {
74 Self {
75 horizontal: 0,
76 vertical: 0,
77 }
78 }
79
80 /// Set uniform margin for all sides.
81 pub const fn all(value: u16) -> Self {
82 Self {
83 horizontal: value,
84 vertical: value,
85 }
86 }
87
88 /// Set the margin of left and right sides to specified value.
89 pub const fn horizontal(value: u16) -> Self {
90 Self {
91 horizontal: value,
92 vertical: 0,
93 }
94 }
95
96 /// Set the margin of top and bottom sides to specified value.
97 pub const fn vertical(value: u16) -> Self {
98 Self {
99 horizontal: 0,
100 vertical: value,
101 }
102 }
103
104 /// Get the total width of the margin (left + right)
105 pub const fn width(&self) -> u16 {
106 self.horizontal * 2
107 }
108
109 /// Get the total height of the margin (top + bottom)
110 pub const fn height(&self) -> u16 {
111 self.vertical * 2
112 }
113 }
114
115 /// A simple rectangle used in the computation of the layout and to give widgets an hint about the
116 /// area they are supposed to render to. (x, y) = (0, 0) is at the top left corner of the screen.
117 #[derive(Debug, Default, Clone, Copy, Hash, PartialEq, Eq)]
118 pub struct Rect {
119 pub x: u16,
120 pub y: u16,
121 pub width: u16,
122 pub height: u16,
123 }
124
125 impl Rect {
126 /// Creates a new rect, with width and height
127 pub fn new(x: u16, y: u16, width: u16, height: u16) -> Rect {
128 Rect {
129 x,
130 y,
131 width,
132 height,
133 }
134 }
135
136 #[inline]
137 pub fn area(self) -> usize {
138 (self.width as usize) * (self.height as usize)
139 }
140
141 #[inline]
142 pub fn left(self) -> u16 {
143 self.x
144 }
145
146 #[inline]
147 pub fn right(self) -> u16 {
148 self.x.saturating_add(self.width)
149 }
150
151 #[inline]
152 pub fn top(self) -> u16 {
153 self.y
154 }
155
156 #[inline]
157 pub fn bottom(self) -> u16 {
158 self.y.saturating_add(self.height)
159 }
160
161 // Returns a new Rect with width reduced from the left side.
162 // This changes the `x` coordinate and clamps it to the right
163 // edge of the original Rect.
164 pub fn clip_left(self, width: u16) -> Rect {
165 let width = std::cmp::min(width, self.width);
166 Rect {
167 x: self.x.saturating_add(width),
168 width: self.width.saturating_sub(width),
169 ..self
170 }
171 }
172
173 // Returns a new Rect with width reduced from the right side.
174 // This does _not_ change the `x` coordinate.
175 pub fn clip_right(self, width: u16) -> Rect {
176 Rect {
177 width: self.width.saturating_sub(width),
178 ..self
179 }
180 }
181
182 // Returns a new Rect with height reduced from the top.
183 // This changes the `y` coordinate and clamps it to the bottom
184 // edge of the original Rect.
185 pub fn clip_top(self, height: u16) -> Rect {
186 let height = std::cmp::min(height, self.height);
187 Rect {
188 y: self.y.saturating_add(height),
189 height: self.height.saturating_sub(height),
190 ..self
191 }
192 }
193
194 // Returns a new Rect with height reduced from the bottom.
195 // This does _not_ change the `y` coordinate.
196 pub fn clip_bottom(self, height: u16) -> Rect {
197 Rect {
198 height: self.height.saturating_sub(height),
199 ..self
200 }
201 }
202
203 pub fn with_height(self, height: u16) -> Rect {
204 // new height may make area > u16::max_value, so use new()
205 Self::new(self.x, self.y, self.width, height)
206 }
207
208 pub fn with_width(self, width: u16) -> Rect {
209 Self::new(self.x, self.y, width, self.height)
210 }
211
212 pub fn inner(self, margin: Margin) -> Rect {
213 if self.width < margin.width() || self.height < margin.height() {
214 Rect::default()
215 } else {
216 Rect {
217 x: self.x + margin.horizontal,
218 y: self.y + margin.vertical,
219 width: self.width - margin.width(),
220 height: self.height - margin.height(),
221 }
222 }
223 }
224
225 /// Calculate the union between two [`Rect`]s.
226 pub fn union(self, other: Rect) -> Rect {
227 // Example:
228 //
229 // If `Rect` A is positioned at `(0, 0)` with a width and height of `5`,
230 // and `Rect` B is positioned at `(5, 0)` with a width and height of `2`,
231 // then this is the resulting union:
232 //
233 // x1 = min(0, 5) => x1 = 0
234 // y1 = min(0, 0) => y1 = 0
235 // x2 = max(0 + 5, 5 + 2) => x2 = 7
236 // y2 = max(0 + 5, 0 + 2) => y2 = 5
237 let x1 = min(self.x, other.x);
238 let y1 = min(self.y, other.y);
239 let x2 = max(self.x + self.width, other.x + other.width);
240 let y2 = max(self.y + self.height, other.y + other.height);
241 Rect {
242 x: x1,
243 y: y1,
244 width: x2 - x1,
245 height: y2 - y1,
246 }
247 }
248
249 /// Calculate the intersection between two [`Rect`]s.
250 pub fn intersection(self, other: Rect) -> Rect {
251 // Example:
252 //
253 // If `Rect` A is positioned at `(0, 0)` with a width and height of `5`,
254 // and `Rect` B is positioned at `(5, 0)` with a width and height of `2`,
255 // then this is the resulting intersection:
256 //
257 // x1 = max(0, 5) => x1 = 5
258 // y1 = max(0, 0) => y1 = 0
259 // x2 = min(0 + 5, 5 + 2) => x2 = 5
260 // y2 = min(0 + 5, 0 + 2) => y2 = 2
261 let x1 = max(self.x, other.x);
262 let y1 = max(self.y, other.y);
263 let x2 = min(self.x + self.width, other.x + other.width);
264 let y2 = min(self.y + self.height, other.y + other.height);
265 Rect {
266 x: x1,
267 y: y1,
268 width: x2.saturating_sub(x1),
269 height: y2.saturating_sub(y1),
270 }
271 }
272
273 pub fn intersects(self, other: Rect) -> bool {
274 self.x < other.x + other.width
275 && self.x + self.width > other.x
276 && self.y < other.y + other.height
277 && self.y + self.height > other.y
278 }
279 }
280
281 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
282 pub enum Color {
283 Reset,
284 Black,
285 Red,
286 Green,
287 Yellow,
288 Blue,
289 Magenta,
290 Cyan,
291 Gray,
292 LightRed,
293 LightGreen,
294 LightYellow,
295 LightBlue,
296 LightMagenta,
297 LightCyan,
298 LightGray,
299 White,
300 Rgb(u8, u8, u8),
301 Indexed(u8),
302 }
303
304 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
305 pub enum MalformedHex {
306 NoHash,
307 LenOOB,
308 NotANibble,
309 }
310 impl fmt::Display for MalformedHex {
311 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312 write!(
313 f,
314 "Malformed hex color code: {}",
315 match self {
316 Self::NoHash => "Missing hash prefix",
317 Self::LenOOB => "Must be 12 or 24 bit RGB",
318 Self::NotANibble => "One or more chars is not hex digit (nibble)",
319 }
320 )
321 }
322 }
323
324 impl Color {
325 /// Creates a `Color` from a hex string of the form
326 /// "#RRGGBB" or "#RGB"
327 ///
328 /// # Examples
329 ///
330 /// ```rust
331 /// use helix_view::theme::Color;
332 ///
333 /// let color1 = Color::from_hex("#c0ffee").unwrap();
334 /// let color2 = Color::Rgb(192, 255, 238);
335 ///
336 /// assert_eq!(color1, color2);
337 ///
338 /// let color3 = Color::from_hex("#012").unwrap();
339 /// assert_eq!(color3, Color::Rgb(0, 17, 34));
340 /// ```
341 pub fn from_hex(h: &str) -> Result<Self, MalformedHex> {
342 let h = h.as_bytes();
343 if !h.starts_with(b"#") {
344 return Err(MalformedHex::NoHash);
345 }
346
347 use byte_from_hex as pair;
348 use dupe_from_nibble as nibble;
349
350 match h.len() {
351 7 => match (|| {
352 Some(Self::Rgb(
353 pair([h[1], h[2]])?,
354 pair([h[3], h[4]])?,
355 pair([h[5], h[6]])?,
356 ))
357 })() {
358 Some(c) => Ok(c),
359 None => Err(MalformedHex::NotANibble),
360 },
361 4 => match (|| Some(Self::Rgb(nibble(h[1])?, nibble(h[2])?, nibble(h[3])?)))() {
362 Some(c) => Ok(c),
363 None => Err(MalformedHex::NotANibble),
364 },
365 _ => Err(MalformedHex::LenOOB),
366 }
367 }
368 }
369
370 #[cfg(feature = "term")]
371 impl From<Color> for termina::style::ColorSpec {
372 fn from(color: Color) -> Self {
373 match color {
374 Color::Reset => Self::Reset,
375 Color::Black => Self::BLACK,
376 Color::Red => Self::RED,
377 Color::Green => Self::GREEN,
378 Color::Yellow => Self::YELLOW,
379 Color::Blue => Self::BLUE,
380 Color::Magenta => Self::MAGENTA,
381 Color::Cyan => Self::CYAN,
382 Color::Gray => Self::BRIGHT_BLACK,
383 Color::White => Self::BRIGHT_WHITE,
384 Color::LightRed => Self::BRIGHT_RED,
385 Color::LightGreen => Self::BRIGHT_GREEN,
386 Color::LightBlue => Self::BRIGHT_BLUE,
387 Color::LightYellow => Self::BRIGHT_YELLOW,
388 Color::LightMagenta => Self::BRIGHT_MAGENTA,
389 Color::LightCyan => Self::BRIGHT_CYAN,
390 Color::LightGray => Self::WHITE,
391 Color::Indexed(i) => Self::PaletteIndex(i),
392 Color::Rgb(r, g, b) => termina::style::RgbColor::new(r, g, b).into(),
393 }
394 }
395 }
396
397 #[cfg(all(feature = "term", windows))]
398 impl From<Color> for crossterm::style::Color {
399 fn from(color: Color) -> Self {
400 use crossterm::style::Color as CColor;
401
402 match color {
403 Color::Reset => CColor::Reset,
404 Color::Black => CColor::Black,
405 Color::Red => CColor::DarkRed,
406 Color::Green => CColor::DarkGreen,
407 Color::Yellow => CColor::DarkYellow,
408 Color::Blue => CColor::DarkBlue,
409 Color::Magenta => CColor::DarkMagenta,
410 Color::Cyan => CColor::DarkCyan,
411 Color::Gray => CColor::DarkGrey,
412 Color::LightRed => CColor::Red,
413 Color::LightGreen => CColor::Green,
414 Color::LightBlue => CColor::Blue,
415 Color::LightYellow => CColor::Yellow,
416 Color::LightMagenta => CColor::Magenta,
417 Color::LightCyan => CColor::Cyan,
418 Color::LightGray => CColor::Grey,
419 Color::White => CColor::White,
420 Color::Indexed(i) => CColor::AnsiValue(i),
421 Color::Rgb(r, g, b) => CColor::Rgb { r, g, b },
422 }
423 }
424 }
425 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
426 pub enum UnderlineStyle {
427 Reset,
428 Line,
429 Curl,
430 Dotted,
431 Dashed,
432 DoubleLine,
433 }
434
435 impl FromStr for UnderlineStyle {
436 type Err = &'static str;
437
438 fn from_str(modifier: &str) -> Result<Self, Self::Err> {
439 match modifier {
440 "line" => Ok(Self::Line),
441 "curl" => Ok(Self::Curl),
442 "dotted" => Ok(Self::Dotted),
443 "dashed" => Ok(Self::Dashed),
444 "double_line" => Ok(Self::DoubleLine),
445 _ => Err("Invalid underline style"),
446 }
447 }
448 }
449
450 #[cfg(feature = "term")]
451 impl From<UnderlineStyle> for termina::style::Underline {
452 fn from(style: UnderlineStyle) -> Self {
453 match style {
454 UnderlineStyle::Reset => Self::None,
455 UnderlineStyle::Line => Self::Single,
456 UnderlineStyle::Curl => Self::Curly,
457 UnderlineStyle::Dotted => Self::Dotted,
458 UnderlineStyle::Dashed => Self::Dashed,
459 UnderlineStyle::DoubleLine => Self::Double,
460 }
461 }
462 }
463
464 #[cfg(all(feature = "term", windows))]
465 impl From<UnderlineStyle> for crossterm::style::Attribute {
466 fn from(style: UnderlineStyle) -> Self {
467 match style {
468 UnderlineStyle::Line => crossterm::style::Attribute::Underlined,
469 UnderlineStyle::Curl => crossterm::style::Attribute::Undercurled,
470 UnderlineStyle::Dotted => crossterm::style::Attribute::Underdotted,
471 UnderlineStyle::Dashed => crossterm::style::Attribute::Underdashed,
472 UnderlineStyle::DoubleLine => crossterm::style::Attribute::DoubleUnderlined,
473 UnderlineStyle::Reset => crossterm::style::Attribute::NoUnderline,
474 }
475 }
476 }
477
478 bitflags! {
479 /// Modifier changes the way a piece of text is displayed.
480 ///
481 /// They are bitflags so they can easily be composed.
482 ///
483 /// ## Examples
484 ///
485 /// ```rust
486 /// # use helix_view::graphics::Modifier;
487 ///
488 /// let m = Modifier::BOLD | Modifier::ITALIC;
489 /// ```
490 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
491 pub struct Modifier: u16 {
492 const BOLD = 0b0000_0000_0001;
493 const DIM = 0b0000_0000_0010;
494 const ITALIC = 0b0000_0000_0100;
495 const SLOW_BLINK = 0b0000_0001_0000;
496 const RAPID_BLINK = 0b0000_0010_0000;
497 const REVERSED = 0b0000_0100_0000;
498 const HIDDEN = 0b0000_1000_0000;
499 const CROSSED_OUT = 0b0001_0000_0000;
500 }
501 }
502
503 impl FromStr for Modifier {
504 type Err = &'static str;
505
506 fn from_str(modifier: &str) -> Result<Self, Self::Err> {
507 match modifier {
508 "bold" => Ok(Self::BOLD),
509 "dim" => Ok(Self::DIM),
510 "italic" => Ok(Self::ITALIC),
511 "slow_blink" => Ok(Self::SLOW_BLINK),
512 "rapid_blink" => Ok(Self::RAPID_BLINK),
513 "reversed" => Ok(Self::REVERSED),
514 "hidden" => Ok(Self::HIDDEN),
515 "crossed_out" => Ok(Self::CROSSED_OUT),
516 _ => Err("Invalid modifier"),
517 }
518 }
519 }
520
521 /// Style let you control the main characteristics of the displayed elements.
522 ///
523 /// ```rust
524 /// # use helix_view::graphics::{Color, Modifier, Style};
525 /// Style::default()
526 /// .fg(Color::Black)
527 /// .bg(Color::Green)
528 /// .add_modifier(Modifier::ITALIC | Modifier::BOLD);
529 /// ```
530 ///
531 /// It represents an incremental change. If you apply the styles S1, S2, S3 to a cell of the
532 /// terminal buffer, the style of this cell will be the result of the merge of S1, S2 and S3, not
533 /// just S3.
534 ///
535 /// ```rust
536 /// # use helix_view::graphics::{Rect, Color, UnderlineStyle, Modifier, Style};
537 /// # use helix_tui::buffer::Buffer;
538 /// let styles = [
539 /// Style::default().fg(Color::Blue).add_modifier(Modifier::BOLD | Modifier::ITALIC),
540 /// Style::default().bg(Color::Red),
541 /// Style::default().fg(Color::Yellow).remove_modifier(Modifier::ITALIC),
542 /// ];
543 /// let mut buffer = Buffer::empty(Rect::new(0, 0, 1, 1));
544 /// for style in &styles {
545 /// buffer[(0, 0)].set_style(*style);
546 /// }
547 /// assert_eq!(
548 /// Style {
549 /// fg: Some(Color::Yellow),
550 /// bg: Some(Color::Red),
551 /// add_modifier: Modifier::BOLD,
552 /// underline_color: Some(Color::Reset),
553 /// underline_style: Some(UnderlineStyle::Reset),
554 /// sub_modifier: Modifier::empty(),
555 /// },
556 /// buffer[(0, 0)].style(),
557 /// );
558 /// ```
559 ///
560 /// The default implementation returns a `Style` that does not modify anything. If you wish to
561 /// reset all properties until that point use [`Style::reset`].
562 ///
563 /// ```
564 /// # use helix_view::graphics::{Rect, Color, UnderlineStyle, Modifier, Style};
565 /// # use helix_tui::buffer::Buffer;
566 /// let styles = [
567 /// Style::default().fg(Color::Blue).add_modifier(Modifier::BOLD | Modifier::ITALIC),
568 /// Style::reset().fg(Color::Yellow),
569 /// ];
570 /// let mut buffer = Buffer::empty(Rect::new(0, 0, 1, 1));
571 /// for style in &styles {
572 /// buffer[(0, 0)].set_style(*style);
573 /// }
574 /// assert_eq!(
575 /// Style {
576 /// fg: Some(Color::Yellow),
577 /// bg: Some(Color::Reset),
578 /// underline_color: Some(Color::Reset),
579 /// underline_style: Some(UnderlineStyle::Reset),
580 /// add_modifier: Modifier::empty(),
581 /// sub_modifier: Modifier::empty(),
582 /// },
583 /// buffer[(0, 0)].style(),
584 /// );
585 /// ```
586 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
587 pub struct Style {
588 pub fg: Option<Color>,
589 pub bg: Option<Color>,
590 pub underline_color: Option<Color>,
591 pub underline_style: Option<UnderlineStyle>,
592 pub add_modifier: Modifier,
593 pub sub_modifier: Modifier,
594 }
595
596 impl Default for Style {
597 fn default() -> Self {
598 Self::new()
599 }
600 }
601
602 impl Style {
603 pub const fn new() -> Self {
604 Style {
605 fg: None,
606 bg: None,
607 underline_color: None,
608 underline_style: None,
609 add_modifier: Modifier::empty(),
610 sub_modifier: Modifier::empty(),
611 }
612 }
613
614 /// Returns a `Style` resetting all properties.
615 pub const fn reset() -> Self {
616 Self {
617 fg: Some(Color::Reset),
618 bg: Some(Color::Reset),
619 underline_color: None,
620 underline_style: None,
621 add_modifier: Modifier::empty(),
622 sub_modifier: Modifier::all(),
623 }
624 }
625
626 /// Changes the foreground color.
627 ///
628 /// ## Examples
629 ///
630 /// ```rust
631 /// # use helix_view::graphics::{Color, Style};
632 /// let style = Style::default().fg(Color::Blue);
633 /// let diff = Style::default().fg(Color::Red);
634 /// assert_eq!(style.patch(diff), Style::default().fg(Color::Red));
635 /// ```
636 pub const fn fg(mut self, color: Color) -> Style {
637 self.fg = Some(color);
638 self
639 }
640
641 /// Changes the background color.
642 ///
643 /// ## Examples
644 ///
645 /// ```rust
646 /// # use helix_view::graphics::{Color, Style};
647 /// let style = Style::default().bg(Color::Blue);
648 /// let diff = Style::default().bg(Color::Red);
649 /// assert_eq!(style.patch(diff), Style::default().bg(Color::Red));
650 /// ```
651 pub const fn bg(mut self, color: Color) -> Style {
652 self.bg = Some(color);
653 self
654 }
655
656 /// Changes the underline color.
657 ///
658 /// ## Examples
659 ///
660 /// ```rust
661 /// # use helix_view::graphics::{Color, Style};
662 /// let style = Style::default().underline_color(Color::Blue);
663 /// let diff = Style::default().underline_color(Color::Red);
664 /// assert_eq!(style.patch(diff), Style::default().underline_color(Color::Red));
665 /// ```
666 pub const fn underline_color(mut self, color: Color) -> Style {
667 self.underline_color = Some(color);
668 self
669 }
670
671 /// Changes the underline style.
672 ///
673 /// ## Examples
674 ///
675 /// ```rust
676 /// # use helix_view::graphics::{UnderlineStyle, Style};
677 /// let style = Style::default().underline_style(UnderlineStyle::Line);
678 /// let diff = Style::default().underline_style(UnderlineStyle::Curl);
679 /// assert_eq!(style.patch(diff), Style::default().underline_style(UnderlineStyle::Curl));
680 /// ```
681 pub const fn underline_style(mut self, style: UnderlineStyle) -> Style {
682 self.underline_style = Some(style);
683 self
684 }
685
686 /// Changes the text emphasis.
687 ///
688 /// When applied, it adds the given modifier to the `Style` modifiers.
689 ///
690 /// ## Examples
691 ///
692 /// ```rust
693 /// # use helix_view::graphics::{Color, Modifier, Style};
694 /// let style = Style::default().add_modifier(Modifier::BOLD);
695 /// let diff = Style::default().add_modifier(Modifier::ITALIC);
696 /// let patched = style.patch(diff);
697 /// assert_eq!(patched.add_modifier, Modifier::BOLD | Modifier::ITALIC);
698 /// assert_eq!(patched.sub_modifier, Modifier::empty());
699 /// ```
700 pub fn add_modifier(mut self, modifier: Modifier) -> Style {
701 self.sub_modifier.remove(modifier);
702 self.add_modifier.insert(modifier);
703 self
704 }
705
706 /// Changes the text emphasis.
707 ///
708 /// When applied, it removes the given modifier from the `Style` modifiers.
709 ///
710 /// ## Examples
711 ///
712 /// ```rust
713 /// # use helix_view::graphics::{Color, Modifier, Style};
714 /// let style = Style::default().add_modifier(Modifier::BOLD | Modifier::ITALIC);
715 /// let diff = Style::default().remove_modifier(Modifier::ITALIC);
716 /// let patched = style.patch(diff);
717 /// assert_eq!(patched.add_modifier, Modifier::BOLD);
718 /// assert_eq!(patched.sub_modifier, Modifier::ITALIC);
719 /// ```
720 pub fn remove_modifier(mut self, modifier: Modifier) -> Style {
721 self.add_modifier.remove(modifier);
722 self.sub_modifier.insert(modifier);
723 self
724 }
725
726 /// Results in a combined style that is equivalent to applying the two individual styles to
727 /// a style one after the other.
728 ///
729 /// ## Examples
730 /// ```
731 /// # use helix_view::graphics::{Color, Modifier, Style};
732 /// let style_1 = Style::default().fg(Color::Yellow);
733 /// let style_2 = Style::default().bg(Color::Red);
734 /// let combined = style_1.patch(style_2);
735 /// assert_eq!(
736 /// Style::default().patch(style_1).patch(style_2),
737 /// Style::default().patch(combined));
738 /// ```
739 pub fn patch(mut self, other: Style) -> Style {
740 self.fg = other.fg.or(self.fg);
741 self.bg = other.bg.or(self.bg);
742 self.underline_color = other.underline_color.or(self.underline_color);
743 self.underline_style = other.underline_style.or(self.underline_style);
744
745 self.add_modifier.remove(other.sub_modifier);
746 self.add_modifier.insert(other.add_modifier);
747 self.sub_modifier.remove(other.add_modifier);
748 self.sub_modifier.insert(other.sub_modifier);
749
750 self
751 }
752 }
753
754 #[cfg(test)]
755 mod tests {
756 use super::*;
757
758 #[test]
759 fn test_rect_size_preservation() {
760 for width in 0..256u16 {
761 for height in 0..256u16 {
762 let rect = Rect::new(0, 0, width, height);
763 rect.area(); // Should not panic.
764 assert_eq!(rect.width, width);
765 assert_eq!(rect.height, height);
766 }
767 }
768
769 // One dimension below 255, one above. Area below max u16.
770 let rect = Rect::new(0, 0, 300, 100);
771 assert_eq!(rect.width, 300);
772 assert_eq!(rect.height, 100);
773 }
774
775 #[test]
776 fn test_rect_chop_from_left() {
777 let rect = Rect::new(0, 0, 20, 30);
778 assert_eq!(Rect::new(10, 0, 10, 30), rect.clip_left(10));
779 assert_eq!(
780 Rect::new(20, 0, 0, 30),
781 rect.clip_left(40),
782 "x should be clamped to original width if new width is bigger"
783 );
784 }
785
786 #[test]
787 fn test_rect_chop_from_right() {
788 let rect = Rect::new(0, 0, 20, 30);
789 assert_eq!(Rect::new(0, 0, 10, 30), rect.clip_right(10));
790 }
791
792 #[test]
793 fn test_rect_chop_from_top() {
794 let rect = Rect::new(0, 0, 20, 30);
795 assert_eq!(Rect::new(0, 10, 20, 20), rect.clip_top(10));
796 assert_eq!(
797 Rect::new(0, 30, 20, 0),
798 rect.clip_top(50),
799 "y should be clamped to original height if new height is bigger"
800 );
801 }
802
803 #[test]
804 fn test_rect_chop_from_bottom() {
805 let rect = Rect::new(0, 0, 20, 30);
806 assert_eq!(Rect::new(0, 0, 20, 20), rect.clip_bottom(10));
807 }
808
809 fn styles() -> Vec<Style> {
810 vec![
811 Style::default(),
812 Style::default().fg(Color::Yellow),
813 Style::default().bg(Color::Yellow),
814 Style::default().add_modifier(Modifier::BOLD),
815 Style::default().remove_modifier(Modifier::BOLD),
816 Style::default().add_modifier(Modifier::ITALIC),
817 Style::default().remove_modifier(Modifier::ITALIC),
818 Style::default().add_modifier(Modifier::ITALIC | Modifier::BOLD),
819 Style::default().remove_modifier(Modifier::ITALIC | Modifier::BOLD),
820 ]
821 }
822
823 #[test]
824 fn combined_patch_gives_same_result_as_individual_patch() {
825 let styles = styles();
826 for &a in &styles {
827 for &b in &styles {
828 for &c in &styles {
829 for &d in &styles {
830 let combined = a.patch(b.patch(c.patch(d)));
831
832 assert_eq!(
833 Style::default().patch(a).patch(b).patch(c).patch(d),
834 Style::default().patch(combined)
835 );
836 }
837 }
838 }
839 }
840 }
841
842 #[test]
843 fn sanity_nibble_lowercase() {
844 for i in 0..0x10_u8 {
845 let c = format!("{:x}", i);
846 assert_eq!(c.len(), 1);
847 assert_eq!(
848 u8::from_str_radix(&c, 0x10).unwrap(),
849 from_nibble(c.as_bytes()[0])
850 );
851 }
852 }
853 #[test]
854 fn sanity_nibble_uppercase() {
855 for i in 0..0x10_u8 {
856 let c = format!("{:X}", i);
857 assert_eq!(c.len(), 1);
858 assert_eq!(
859 u8::from_str_radix(&c, 0x10).unwrap(),
860 from_nibble(c.as_bytes()[0])
861 );
862 }
863 }
864
865 #[test]
866 fn sanity_nibble2() {
867 assert_eq!(dupe_from_nibble(b'0'), Some(0));
868 assert_eq!(dupe_from_nibble(b'1'), Some(0x11));
869 assert_eq!(dupe_from_nibble(b'7'), Some(0x77));
870 assert_eq!(dupe_from_nibble(b'a'), Some(0xaa));
871 assert_eq!(dupe_from_nibble(b'f'), Some(0xff));
872 }
873
874 #[test]
875 fn invalid_nibble() {
876 for c in *b"gGzZ+-" {
877 assert_eq!(from_nibble(c), 0xff);
878 }
879 }
880
881 #[test]
882 fn pair_endian() {
883 assert_eq!(byte_from_hex(*b"00"), Some(0));
884 assert_eq!(byte_from_hex(*b"fF"), Some(0xff));
885 assert_eq!(byte_from_hex(*b"c3"), Some(0xc3));
886 }
887 #[test]
888 fn invalid_pair() {
889 assert!(byte_from_hex(*b"+1").is_none());
890 assert!(byte_from_hex(*b"-1").is_none());
891 assert!(byte_from_hex(*b"Gg").is_none());
892 assert!(byte_from_hex(*b"0x").is_none());
893 }
894
895 #[test]
896 fn hex_color_no_regress() {
897 assert_eq!(Color::from_hex("#+a+b+c"), Err(MalformedHex::NotANibble));
898 assert_eq!(Color::from_hex("#+0+1+2"), Err(MalformedHex::NotANibble));
899 }
900 #[test]
901 fn hex_color_sanity() {
902 assert_eq!(Color::from_hex("#01fe3a"), Ok(Color::Rgb(0x01, 0xfe, 0x3a)));
903 assert_eq!(Color::from_hex("#abc"), Ok(Color::Rgb(0xaa, 0xbb, 0xcc)));
904 }
905 #[test]
906 fn hex_color_invalid_len() {
907 for h in [
908 "#0",
909 "#00",
910 "#0000",
911 "#00000",
912 "#0000000",
913 "#00000000",
914 "#000000000",
915 "#0000000000",
916 ] {
917 assert_eq!(Color::from_hex(h), Err(MalformedHex::LenOOB));
918 }
919 }
920 }