uncurses/cell/mod.rs
1//! Terminal cell values and grapheme segmentation.
2//!
3//! This module defines [`Cell`], the value stored by buffers and surfaces.
4//! A cell combines grapheme content, visual style, and the number of
5//! terminal columns the content occupies.
6//!
7//! ## Cell value type
8//!
9//! A [`Cell`] stores three pieces of state:
10//!
11//! - `content`: the grapheme cluster to display. Continuation cells have no
12//! content of their own.
13//! - Presentation: visual colors, attributes, underline data, and a shared
14//! hyperlink. [`Cell::style`] returns visual fields as a copyable [`Style`].
15//! [`Cell::link`] borrows the separate hyperlink handle.
16//! - `width`: the cell's column footprint, returned by [`Cell::width`].
17//!
18//! Width also encodes the cell's structural role. A width of `1` or more
19//! marks a primary cell that owns that many columns. A width of `0` marks a
20//! continuation placeholder, whose column is owned by the primary to its
21//! left.
22//!
23//! ## Construction
24//!
25//! Construct a cell with [`Cell::new`], passing its content and width.
26//! Use [`Cell::with_style`] and [`Cell::with_link`] to set its presentation.
27//! Measure the width with
28//! [`WidthMode::grapheme_width`](crate::text::WidthMode::grapheme_width)
29//! rather than assuming it. Use [`Style::EMPTY`] for the default style.
30//! Use [`Cell::set_style`] to change the style of an existing cell.
31//!
32//! [`Cell::CONTINUATION`] is the placeholder that stands in the columns
33//! after a multi-column grapheme. Most callers never write one; writing a
34//! multi-column cell through
35//! [`Buffer::set`](crate::buffer::Buffer::set) or
36//! [`SurfaceMut::set_cell`](crate::buffer::SurfaceMut::set_cell) creates the
37//! placeholders automatically.
38//!
39//! ```rust,ignore
40//! use uncurses::cell::Cell;
41//!
42//! let a = Cell::new("a", 1);
43//! assert_eq!(a.width(), 1);
44//!
45//! let wide = Cell::new("中", 2);
46//! assert_eq!(wide.width(), 2);
47//! ```
48//!
49//! ## Multi-column cells
50//!
51//! A grapheme wider than one column occupies that many adjacent grid
52//! columns. The leftmost column stores the primary and every column after it
53//! stores a continuation placeholder:
54//!
55//! ```text
56//! col: 0 1 2
57//! ┌───────┬───────┬───┐
58//! row 0 │ 中 │ cont. │ A │
59//! └───────┴───────┴───┘
60//! width=2 width=0 width=1
61//! ```
62//!
63//! Most graphemes are one or two columns wide. A cell may be wider: under
64//! [`WidthMode::Wc`](crate::text::WidthMode::Wc) a joined emoji sequence
65//! measures the sum of its code points, so a four-person family emoji is
66//! eight columns and owns seven continuations.
67//!
68//! Continuations preserve the one-`Cell`-per-column layout for wide
69//! graphemes. [`Cell::is_blank`] identifies a cell that claims one column
70//! and draws a space, regardless of style. A continuation claims zero
71//! columns, so it returns `false`.
72
73use std::sync::Arc;
74
75use compact_str::CompactString;
76
77use crate::color::Color;
78use crate::style::{AttrFlags, Link, Style, UnderlineStyle};
79
80/// A single terminal-grid cell.
81///
82/// `Cell` is the value stored in buffers and surfaces. It contains the
83/// grapheme content for a column, the style applied to that content, and the
84/// number of columns the content occupies.
85///
86/// Use [`Cell::new`] for construction and [`Cell::BLANK`] for an empty
87/// styled-as-default space. Continuations are normally produced by the
88/// surface write path rather than by application code.
89#[derive(Debug)]
90pub struct Cell {
91 /// The grapheme cluster content. Empty string for a continuation
92 /// placeholder.
93 pub(crate) content: CompactString,
94 pub(crate) fg: Option<Color>,
95 pub(crate) bg: Option<Color>,
96 pub(crate) underline_color: Option<Color>,
97 pub(crate) attrs: AttrFlags,
98 pub(crate) underline: UnderlineStyle,
99 pub(crate) link: Option<Arc<Link>>,
100 /// Column footprint. `0` marks a continuation placeholder; `1` or more
101 /// marks a primary owning that many columns.
102 pub(crate) width: u8,
103}
104
105impl PartialEq for Cell {
106 #[inline]
107 fn eq(&self, other: &Self) -> bool {
108 self.width == other.width && self.content == other.content && self.same_style(other)
109 }
110}
111
112impl Clone for Cell {
113 #[inline]
114 fn clone(&self) -> Self {
115 Self {
116 content: self.content.clone(),
117 fg: self.fg,
118 bg: self.bg,
119 underline_color: self.underline_color,
120 attrs: self.attrs,
121 underline: self.underline,
122 link: self.link.clone(),
123 width: self.width,
124 }
125 }
126
127 #[inline]
128 fn clone_from(&mut self, source: &Self) {
129 self.content.clone_from(&source.content);
130 self.copy_style_from(source);
131 self.width = source.width;
132 }
133}
134
135impl Eq for Cell {}
136
137impl Default for Cell {
138 fn default() -> Self {
139 Self::BLANK
140 }
141}
142
143impl Cell {
144 /// A blank one-column cell with default style.
145 ///
146 /// The blank cell stores a single space (`" "`), uses [`Style::EMPTY`],
147 /// and has width `1`.
148 ///
149 /// # Returns
150 ///
151 /// This is a constant value, so use it directly wherever a default blank
152 /// cell is needed.
153 ///
154 /// # Panics
155 ///
156 /// Never panics.
157 ///
158 /// # Usage notes
159 ///
160 /// Clearing and newly allocated buffers use `BLANK`. Clone it when an
161 /// owned value is required.
162 pub const BLANK: Cell = Cell {
163 content: CompactString::const_new(" "),
164 fg: None,
165 bg: None,
166 underline_color: None,
167 attrs: AttrFlags::empty(),
168 underline: UnderlineStyle::None,
169 link: None,
170 width: 1,
171 };
172
173 /// A continuation placeholder with default style.
174 ///
175 /// The placeholder stores no content, uses [`Style::EMPTY`], and has
176 /// width `0`. [`Cell::is_continuation`] reports `true` for it.
177 ///
178 /// # Returns
179 ///
180 /// This is a constant value, so use it directly wherever a continuation
181 /// is needed.
182 ///
183 /// # Panics
184 ///
185 /// Never panics.
186 ///
187 /// # Usage notes
188 ///
189 /// A wide cell is followed by [`width`](Cell::width) `- 1` of these, one
190 /// for every column the cell owns beyond its first. The surface write
191 /// path lays them down; application code needs them only when it builds
192 /// a row by hand.
193 ///
194 /// Under background color erase a continuation carries the style of the
195 /// cell that owns it, so clone the constant and give it that style
196 /// rather than leaving it default.
197 pub const CONTINUATION: Cell = Cell {
198 content: CompactString::const_new(""),
199 fg: None,
200 bg: None,
201 underline_color: None,
202 attrs: AttrFlags::empty(),
203 underline: UnderlineStyle::None,
204 link: None,
205 width: 0,
206 };
207
208 /// Create a cell with `content` and `width` terminal columns.
209 ///
210 /// The cell starts with the default visual style and no hyperlink.
211 /// Use [`Self::with_style`] and [`Self::with_link`] to set its presentation.
212 ///
213 /// # Parameters
214 ///
215 /// - `content`: grapheme content to store in the cell.
216 /// - `width`: number of terminal columns the content occupies. Width `0`
217 /// makes a continuation placeholder whatever the content, so use
218 /// [`Cell::CONTINUATION`] when that is what you mean.
219 ///
220 /// # Returns
221 ///
222 /// A cell with the given content and width.
223 ///
224 /// # Panics
225 ///
226 /// Never panics.
227 ///
228 /// # Usage notes
229 ///
230 /// This constructor does not validate that `width` matches the display
231 /// width of `content`; the caller chooses the measurement policy. Use
232 /// [`WidthMode::grapheme_width`](crate::text::WidthMode::grapheme_width)
233 /// to measure, so the stored width matches what the terminal advances.
234 ///
235 /// When a cell wider than one column is written through the
236 /// buffer/surface write path, the `width - 1` slots to its right are
237 /// filled with continuation placeholders automatically. If there is no
238 /// room for them at the row's right edge,
239 /// [`Buffer::set`](crate::buffer::Buffer::set) stores a blank instead of
240 /// part of a grapheme.
241 #[inline]
242 pub fn new(content: impl Into<CompactString>, width: u8) -> Self {
243 Cell {
244 content: content.into(),
245 width,
246 ..Self::BLANK
247 }
248 }
249
250 /// Set the visual style and return the cell.
251 ///
252 /// The cell keeps its hyperlink, content, and width.
253 #[inline]
254 pub fn with_style(mut self, style: impl Into<Style>) -> Self {
255 self.set_style(style);
256 self
257 }
258
259 /// Attach an owned or shared hyperlink and return the cell.
260 ///
261 /// An empty URL clears the link. The cell keeps its visual style,
262 /// content, and width.
263 #[inline]
264 pub fn with_link(mut self, link: impl Into<Arc<Link>>) -> Self {
265 self.set_link(Some(link.into()));
266 self
267 }
268
269 /// Test whether this cell occupies more than one column.
270 ///
271 /// # Returns
272 ///
273 /// `true` when [`Cell::width`] is `2` or more.
274 ///
275 /// # Panics
276 ///
277 /// Never panics.
278 ///
279 /// # Usage notes
280 ///
281 /// Width alone decides the answer, because width alone decides how many
282 /// columns the cell takes. A cell that stores no content still owns the
283 /// columns its width names, and the blank drawn in its place covers all
284 /// of them.
285 ///
286 /// In a well-formed surface, such a cell is followed immediately by
287 /// `width - 1` continuation placeholders.
288 #[inline]
289 pub fn is_wide(&self) -> bool {
290 self.width > 1
291 }
292
293 /// Test whether this is a continuation placeholder.
294 ///
295 /// # Returns
296 ///
297 /// `true` when [`Cell::width`] is `0`.
298 ///
299 /// # Panics
300 ///
301 /// Never panics.
302 ///
303 /// # Usage notes
304 ///
305 /// Width alone decides, as it does for [`Cell::is_wide`]: a cell that
306 /// claims no column has none to draw in, so whatever it stores is never
307 /// reached. Width `0`, `1`, and `2` or more partition every cell into a
308 /// continuation, a narrow cell, and a wide one.
309 #[inline]
310 pub fn is_continuation(&self) -> bool {
311 self.width == 0
312 }
313
314 /// Test whether this cell is a single blank column.
315 ///
316 /// # Returns
317 ///
318 /// `true` when the cell claims one column and draws a space in it, which
319 /// is the shape of [`Cell::BLANK`].
320 ///
321 /// # Panics
322 ///
323 /// Never panics.
324 ///
325 /// # Usage notes
326 ///
327 /// Style is not considered. A styled space is still blank, because this
328 /// method answers what the cell occupies rather than how it is painted.
329 ///
330 /// Width is considered, so the answer stays about one column. A
331 /// continuation claims none, and a cell claiming several stands for a
332 /// span rather than a single blank; each is something other than a blank
333 /// column, and each reports `false`.
334 ///
335 /// A cell that claims its one column while storing nothing draws a space
336 /// there, the same as [`Cell::BLANK`], and answers the same way. The
337 /// question is what reaches the column, so two cells that put the same
338 /// thing in it give one answer.
339 pub fn is_blank(&self) -> bool {
340 self.width == 1 && (self.content == " " || self.content.is_empty())
341 }
342
343 /// The bytes that draw this cell.
344 ///
345 /// A cell storing no content still owns the columns its width names, so
346 /// it draws as a blank in every one of them. Writing the content alone
347 /// would close a gap the grid is holding open, and put everything after
348 /// it on the row a column short for each one skipped.
349 ///
350 /// Call this only on a cell that is not a continuation; a continuation
351 /// draws nothing at all, and its caller returns before reaching here.
352 pub(crate) fn draw_bytes(&self) -> &[u8] {
353 /// Enough spaces to stand in for any width a cell can claim.
354 const BLANKS: [u8; u8::MAX as usize] = [b' '; u8::MAX as usize];
355
356 if self.content.is_empty() {
357 &BLANKS[..self.width as usize]
358 } else {
359 self.content.as_bytes()
360 }
361 }
362
363 /// Return the cell's grapheme-cluster content.
364 ///
365 /// # Returns
366 ///
367 /// The stored content as `&str`. Continuation cells return an empty
368 /// string.
369 ///
370 /// # Panics
371 ///
372 /// Never panics.
373 ///
374 /// # Usage notes
375 ///
376 /// This returns the stored content exactly; it does not derive or append
377 /// the neighboring continuations for multi-column cells.
378 #[inline]
379 pub fn content(&self) -> &str {
380 self.content.as_str()
381 }
382
383 /// Column footprint of this cell on the grid.
384 ///
385 /// # Returns
386 ///
387 /// The number of terminal columns owned by this cell: `0` for a
388 /// continuation placeholder, otherwise the width passed to
389 /// [`Cell::new`].
390 ///
391 /// # Panics
392 ///
393 /// Never panics.
394 ///
395 /// # Usage notes
396 ///
397 /// Row walkers generally advance by `cell.width().max(1)` after handling
398 /// continuations, so they make progress even when encountering a
399 /// continuation placeholder.
400 #[inline]
401 pub fn width(&self) -> u8 {
402 self.width
403 }
404
405 /// Return the visual style as an owned value.
406 ///
407 /// The returned value contains the visual fields. Use [`Self::link`] for the hyperlink.
408 /// Changes to the returned style take effect after [`Self::set_style`].
409 #[inline]
410 pub fn style(&self) -> Style {
411 Style {
412 fg: self.fg,
413 bg: self.bg,
414 underline_color: self.underline_color,
415 attrs: self.attrs,
416 underline: self.underline,
417 }
418 }
419
420 /// Replace the visual style without changing content or width.
421 ///
422 /// The cell keeps its hyperlink.
423 #[inline]
424 pub fn set_style(&mut self, style: impl Into<Style>) {
425 let style = style.into();
426 self.fg = style.fg;
427 self.bg = style.bg;
428 self.underline_color = style.underline_color;
429 self.attrs = style.attrs;
430 self.underline = style.underline;
431 }
432
433 /// Borrow the shared OSC 8 hyperlink handle.
434 pub fn link(&self) -> Option<&Arc<Link>> {
435 self.link.as_ref()
436 }
437
438 /// Set the OSC 8 hyperlink by moving its shared handle.
439 ///
440 /// `None` or a link with an empty URL clears the current hyperlink.
441 /// The cell keeps its visual style, content, and width.
442 #[inline]
443 pub fn set_link(&mut self, link: Option<Arc<Link>>) {
444 self.link = link.filter(|link| !link.url.is_empty());
445 }
446
447 #[inline]
448 pub(crate) fn copy_style_from(&mut self, source: &Self) {
449 self.fg = source.fg;
450 self.bg = source.bg;
451 self.underline_color = source.underline_color;
452 self.attrs = source.attrs;
453 self.underline = source.underline;
454 self.link.clone_from(&source.link);
455 }
456
457 #[inline]
458 pub(crate) fn same_style(&self, other: &Self) -> bool {
459 self.fg == other.fg
460 && self.bg == other.bg
461 && self.underline_color == other.underline_color
462 && self.attrs == other.attrs
463 && self.underline == other.underline
464 && self.link == other.link
465 }
466
467 #[inline]
468 pub(crate) fn matches_style(&self, style: &Style, link: Option<&Arc<Link>>) -> bool {
469 self.fg == style.fg
470 && self.bg == style.bg
471 && self.underline_color == style.underline_color
472 && self.attrs == style.attrs
473 && self.underline == style.underline
474 && self.link.as_ref() == link
475 }
476}
477
478#[cfg(test)]
479mod tests {
480 use super::*;
481
482 #[test]
483 fn test_blank_cell() {
484 let c = Cell::BLANK;
485 assert_eq!(c.width(), 1);
486 assert!(c.is_blank());
487 assert!(c.style().is_empty());
488 }
489
490 #[test]
491 fn test_narrow_cell() {
492 let c = Cell::new("A", 1);
493 assert_eq!(c.content(), "A");
494 assert!(!c.is_wide());
495 assert_eq!(c.width(), 1);
496 assert_eq!(c.style(), Style::EMPTY);
497 assert!(c.link().is_none());
498 }
499
500 #[test]
501 fn test_wide_cell() {
502 let c = Cell::new("中", 2);
503 assert_eq!(c.content(), "中");
504 assert!(c.is_wide());
505 assert_eq!(c.width(), 2);
506 }
507
508 #[test]
509 fn test_continuation_cell() {
510 let c = Cell::CONTINUATION;
511 assert!(c.is_continuation());
512 assert_eq!(c.width(), 0);
513 assert!(!c.is_blank());
514 }
515
516 /// `is_blank` answers for one blank column, so width decides as much as
517 /// content does.
518 ///
519 /// Reading it as "holds nothing to draw" put a continuation and a blank
520 /// in the same class, though one claims no column and the other claims
521 /// exactly one. A caller scanning a row for the columns it can drop then
522 /// had to re-check the width every time to tell them apart.
523 #[test]
524 fn only_a_cell_drawing_one_blank_column_is_blank() {
525 assert!(Cell::new(" ", 1).is_blank());
526 // Storing nothing in one column still draws a space there, which is
527 // what `draw_bytes` puts on the screen.
528 let empty = Cell::new("", 1);
529 assert_eq!(empty.draw_bytes(), b" ");
530 assert!(empty.is_blank());
531 // Style rides along; it says how the column is painted, not what it
532 // holds.
533 assert!(
534 {
535 let mut styled_cell = Cell::BLANK;
536 styled_cell.set_style(Style::default().bold());
537 styled_cell
538 }
539 .is_blank()
540 );
541
542 // A span of blank columns is not one blank column.
543 assert!(!Cell::new(" ", 2).is_blank());
544 assert!(!Cell::new("", 2).is_blank());
545 assert!(!Cell::new("x", 1).is_blank());
546 }
547
548 #[test]
549 fn the_continuation_constant_matches_one_built_by_hand() {
550 // Rows built before the constant existed pass `Cell::new("", 0)`,
551 // and `PartialEq` weighs content, width, and style. A constant that
552 // differed in any of the three would compare unequal and make the
553 // renderer redraw a column that did not change.
554 assert_eq!(Cell::CONTINUATION, Cell::new("", 0));
555 }
556
557 #[test]
558 fn a_cell_may_own_more_than_two_columns() {
559 // Under `WidthMode::Wc` a joined emoji sequence measures the sum of
560 // its code points, so the grid must be able to credit one cell with
561 // more columns than a CJK ideograph takes.
562 let family = "\u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}\u{200d}\u{1f466}";
563 let c = Cell::new(family, 8);
564 assert_eq!(c.width(), 8);
565 assert!(c.is_wide());
566 assert!(!c.is_continuation());
567 }
568
569 #[test]
570 fn width_alone_decides_the_structural_role() {
571 // Width `0`, `1`, and `2` or more partition every cell into a
572 // continuation, a narrow cell, and a wide one. Content never enters
573 // into it: a cell that claims no column has none to draw in, and one
574 // that stores nothing still owns every column it claims.
575 assert!(Cell::new("a", 0).is_continuation());
576 assert!(Cell::new("", 2).is_wide());
577 assert!(Cell::new("\u{1f469}", 2).is_wide());
578 }
579
580 #[test]
581 fn a_cell_claiming_no_column_is_a_continuation_whatever_it_stores() {
582 // `grapheme_width` measures a lone combining mark as zero, and
583 // `Cell::new`'s own advice is to measure with it, so a cell holding
584 // content at width zero is one step from the documented path. It
585 // claims no column, so the grid treats it as the placeholder it
586 // structurally is and the surface declines to plant it loose.
587 use crate::buffer::{Buffer, Surface, SurfaceMut};
588 use crate::text::Encode;
589
590 let mut buf = Buffer::new(3, 1);
591 buf.set_cell((0, 0).into(), &Cell::new("A", 1));
592 buf.set_cell((1, 0).into(), &Cell::new("\u{301}", 0));
593 buf.set_cell((2, 0).into(), &Cell::new("B", 1));
594
595 assert!(Cell::new("\u{301}", 0).is_continuation());
596 assert_eq!(
597 buf.cell((1, 0).into()).unwrap().content(),
598 " ",
599 "a loose continuation is declined, leaving the blank"
600 );
601 assert_eq!(buf.display().to_string(), "A B");
602 }
603
604 #[test]
605 fn test_cell_with_style() {
606 let style = Style::new()
607 .bold()
608 .fg(Color::Green)
609 .bg(Color::Blue)
610 .underline_color(Color::Red)
611 .underline_style(UnderlineStyle::Curly);
612 let shared = crate::style::test_link("https://example.test", "id=builders");
613 let styled_first = Cell::new("中", 2)
614 .with_style(style)
615 .with_link(shared.clone());
616 let linked_first = Cell::new("中", 2)
617 .with_link(shared.clone())
618 .with_style(style);
619 assert_eq!(styled_first, linked_first);
620 assert_eq!(styled_first.style(), style);
621 assert_eq!((styled_first.content(), styled_first.width()), ("中", 2));
622 assert!(Arc::ptr_eq(styled_first.link().unwrap(), &shared));
623 assert!(Arc::ptr_eq(linked_first.link().unwrap(), &shared));
624 let owned_link = Cell::new("中", 2)
625 .with_style(style)
626 .with_link(shared.as_ref().clone());
627 assert_eq!(owned_link, styled_first);
628 }
629
630 #[test]
631 fn style_roundtrip_preserves_all_fields() {
632 for underline in [
633 UnderlineStyle::None,
634 UnderlineStyle::Single,
635 UnderlineStyle::Double,
636 UnderlineStyle::Curly,
637 UnderlineStyle::Dotted,
638 UnderlineStyle::Dashed,
639 ] {
640 let style = Style::new()
641 .fg(Color::Rgb(12, 34, 56))
642 .bg(Color::Indexed(200))
643 .underline_color(Color::BrightCyan)
644 .underline_style(underline)
645 .attrs(AttrFlags::from_bits_retain(u16::MAX));
646 let mut cell = Cell::new("中", 2).with_style(style);
647 assert!(cell.link().is_none());
648 cell.set_link(Some(Arc::new(Link {
649 url: "https://example.test/flat".into(),
650 params: "id=roundtrip".into(),
651 })));
652 assert_eq!(cell.style(), style);
653 assert_eq!(cell.fg, style.fg);
654 assert_eq!(cell.bg, style.bg);
655 assert_eq!(cell.underline_color, style.underline_color);
656 assert_eq!(cell.underline, underline);
657 assert_eq!(cell.attrs.bits(), u16::MAX);
658
659 let mut changed = cell.style();
660 changed.bg = None;
661 let mut copy = cell.clone();
662 copy.set_style(changed);
663 assert_ne!(cell.style(), copy.style());
664 assert_eq!(cell.style(), style);
665 copy.set_style(Style::EMPTY);
666 assert_eq!(copy.style(), Style::EMPTY);
667 assert!(Arc::ptr_eq(copy.link().unwrap(), cell.link().unwrap()));
668 copy.set_link(None);
669 assert!(copy.link().is_none());
670 assert_eq!((copy.content(), copy.width()), ("中", 2));
671 }
672
673 #[cfg(target_pointer_width = "64")]
674 assert_eq!(std::mem::size_of::<Cell>(), 48);
675 }
676
677 #[test]
678 fn style_copies_and_long_text_clones_share_the_hyperlink() {
679 use crate::buffer::{Buffer, Surface};
680
681 let text = format!("中{}", "\u{301}".repeat(40));
682 let style = Style::new()
683 .fg(Color::Green)
684 .bg(Color::Blue)
685 .underline_color(Color::Red)
686 .attrs(AttrFlags::from_bits_retain(u16::MAX))
687 .underline_style(UnderlineStyle::Curly);
688 let shared = &Arc::new(Link {
689 url: "https://example.test/shared".into(),
690 params: "id=long".into(),
691 });
692 let mut source = Cell::new(text.as_str(), 2).with_style(style);
693 source.set_link(Some(shared.clone()));
694 let mut continuation = Cell::CONTINUATION;
695 continuation.copy_style_from(&source);
696 assert_eq!(continuation.style(), source.style());
697 assert!(continuation.is_continuation());
698 assert_eq!(continuation.content(), "");
699 assert!(std::ptr::eq(
700 continuation.link.as_deref().unwrap(),
701 shared.as_ref()
702 ));
703 continuation.copy_style_from(&Cell::BLANK);
704 assert_eq!(continuation.style(), Style::EMPTY);
705 assert_eq!((continuation.content(), continuation.width()), ("", 0));
706
707 let mut copy = Cell::new("old", 1).with_style(Style::new().bold());
708 copy.clone_from(&source);
709 let mut buffer = Buffer::new(4, 1);
710 buffer.set((0, 0), &source);
711 source.set_style(Style::EMPTY);
712 drop(source);
713 assert_eq!(copy.content(), text);
714 assert_eq!(copy.width(), 2);
715 let extracted = copy.style();
716 assert_eq!(extracted, style);
717 assert!(Arc::ptr_eq(copy.link().unwrap(), shared));
718 assert!(std::ptr::eq(copy.link.as_deref().unwrap(), shared.as_ref()));
719 for x in 0..2 {
720 let cell = buffer.cell((x, 0).into()).unwrap();
721 assert_eq!(cell.style(), copy.style());
722 assert!(std::ptr::eq(cell.link.as_deref().unwrap(), shared.as_ref()));
723 assert_eq!(cell.is_continuation(), x == 1);
724 }
725 assert_eq!(buffer.cell((0, 0).into()).unwrap().content(), text);
726 }
727
728 #[test]
729 fn style_comparisons_use_link_values_and_empty_urls_clear() {
730 let mut a = Cell::new("A", 1);
731 let mut b = Cell::new("中", 2);
732 for cell in [&mut a, &mut b] {
733 cell.set_link(Some(Arc::new(Link {
734 url: "https://example.test".into(),
735 params: "id=same".into(),
736 })));
737 }
738 assert!(!std::ptr::eq(
739 a.link.as_deref().unwrap(),
740 b.link.as_deref().unwrap()
741 ));
742 assert_eq!(a.style(), b.style());
743 assert!(a.same_style(&b));
744 assert!(a.matches_style(&b.style(), b.link()));
745 let mut same = b.clone();
746 same.content.clone_from(&a.content);
747 same.width = a.width;
748 assert_eq!(a, same);
749 assert_ne!(a, b);
750
751 let empty = Arc::new(Link {
752 url: String::new(),
753 params: "id=empty".into(),
754 });
755 let builder_cleared = a.clone().with_link(empty.as_ref().clone());
756 let mut cell = a.clone();
757 cell.set_link(Some(empty));
758 assert_eq!(cell, builder_cleared);
759 assert!(cell.link().is_none());
760 assert!(cell.same_style(&Cell::BLANK));
761 assert!(cell.matches_style(&Style::EMPTY, None));
762 assert_ne!(a, cell);
763
764 for style in [
765 Style::new().fg(Color::Green),
766 Style::new().bg(Color::Blue),
767 Style::new().underline_color(Color::Red),
768 Style::new().bold(),
769 Style::new().attrs(AttrFlags::from_bits_retain(1 << 15)),
770 Style::new().underline_style(UnderlineStyle::Curly),
771 ] {
772 let changed = Cell::new(" ", 1).with_style(style);
773 assert!(!Cell::BLANK.same_style(&changed), "{style:?}");
774 assert!(!Cell::BLANK.matches_style(&style, None), "{style:?}");
775 }
776 }
777}