返回 CodeWhale
native_composer.rs
根目录 / vendor / codewhale-ratatui / src / components / native_composer.rs
1 //! Pure mounted composer projection over host-owned editor and menu facts.
2 //! Source positions count Unicode scalar values in the original editor text.
3 //! Display sanitation never mutates that text or its source-position authority.
4
5 //! Adapted from Codewhale, licensed under the MIT License:
6 //! Copyright (c) 2024-2025 DeepSeek-TUI Contributors
7 //!
8 //! Permission is hereby granted, free of charge, to any person obtaining a
9 //! copy of this software and associated documentation files (the "Software"),
10 //! to deal in the Software without restriction, including without limitation
11 //! the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 //! and/or sell copies of the Software, and to permit persons to whom the
13 //! Software is furnished to do so, subject to the following conditions:
14 //!
15 //! The above copyright notice and this permission notice shall be included
16 //! in all copies or substantial portions of the Software.
17 //!
18 //! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 //! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 //! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 //! THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 //! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 //! FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 //! DEALINGS IN THE SOFTWARE.
25
26 use crate::{NativeComposerDensity, NativeComposerGeometry, Paint, Theme, text};
27 use ratatui::{
28 buffer::Buffer,
29 layout::{Position, Rect},
30 style::Style,
31 text::{Line, Span},
32 widgets::{Block, BorderType, Borders, Paragraph, Widget, Wrap},
33 };
34 use std::borrow::Cow;
35 use unicode_segmentation::UnicodeSegmentation;
36 use unicode_width::UnicodeWidthStr;
37
38 #[derive(Clone, Debug)]
39 pub enum NativeComposerMenuItem {
40 Line(Line<'static>),
41 Columns {
42 name: String,
43 description: String,
44 prefix: Span<'static>,
45 marker: Span<'static>,
46 name_style: Style,
47 description_style: Style,
48 },
49 }
50 #[derive(Clone, Debug, Default)]
51 pub struct NativeComposerMenu {
52 pub items: Vec<NativeComposerMenuItem>,
53 pub selected: usize,
54 pub reserved_rows: usize,
55 pub pointer_rows: bool,
56 }
57 #[derive(Clone, Copy, Debug, Default)]
58 pub struct NativeComposerStyles {
59 pub background: Style,
60 pub border: Style,
61 pub quiet_border: Style,
62 pub text: Style,
63 pub selection: Style,
64 pub prompt: Style,
65 pub submit: Style,
66 }
67
68 /// Complete render facts. Editing, bindings, menu filtering, history and IME
69 /// remain host-owned; the frame projects their one current snapshot.
70 #[derive(Clone, Debug)]
71 pub struct NativeComposerFrame<'a> {
72 pub text: Cow<'a, str>,
73 pub cursor: usize,
74 pub selection: Option<(usize, usize)>,
75 pub placeholder: Line<'static>,
76 pub enclosed: bool,
77 pub density: NativeComposerDensity,
78 pub history_search: bool,
79 pub focused: bool,
80 pub can_submit: bool,
81 pub ascii: bool,
82 pub top_title: Option<Line<'static>>,
83 pub top_right: Option<Line<'static>>,
84 pub hint: Option<Line<'static>>,
85 pub quiet_hint: Option<Line<'static>>,
86 pub styles: NativeComposerStyles,
87 pub menu: NativeComposerMenu,
88 }
89 #[derive(Clone, Debug)]
90 pub struct NativeComposerPlan {
91 pub area: Rect,
92 pub geometry: NativeComposerGeometry,
93 pub cursor: Option<Position>,
94 pub scroll_offset: usize,
95 pub top_padding: usize,
96 pub input_rows_budget: usize,
97 pub source_rows: Vec<(usize, String)>,
98 pub menu_rects: Vec<(usize, Rect)>,
99 pub truncated: Vec<(Rect, String)>,
100 prompt_position: Option<Position>,
101 lines: Vec<Line<'static>>,
102 frame: NativeComposerFrame<'static>,
103 }
104
105 fn safe_span(span: &Span<'static>) -> Span<'static> {
106 Span::styled(text::display_safe(&span.content).into_owned(), span.style)
107 }
108 fn safe_line(line: &Line<'static>) -> Line<'static> {
109 let mut line = line.clone();
110 line.spans = line.spans.iter().map(safe_span).collect();
111 line
112 }
113 pub fn native_composer_input_budget(height: u16, menu: usize) -> usize {
114 usize::from(height).saturating_sub(menu).max(1)
115 }
116 pub fn native_composer_top_padding(rows: usize, budget: usize) -> usize {
117 budget.saturating_sub(rows.max(1).min(budget.max(1))) / 2
118 }
119 pub fn native_composer_content_geometry(inner: Rect, history_search: bool) -> (Rect, u16) {
120 let inset = if !history_search && inner.width >= 3 {
121 2
122 } else {
123 0
124 };
125 (
126 Rect::new(
127 inner.x.saturating_add(inset),
128 inner.y,
129 inner.width.saturating_sub(inset),
130 inner.height,
131 ),
132 inset,
133 )
134 }
135 pub fn native_composer_geometry(
136 area: Rect,
137 enclosed: bool,
138 history_search: bool,
139 ) -> NativeComposerGeometry {
140 let panel = enclosed && area.width >= NATIVE_COMPOSER_PANEL_MIN_WIDTH && area.height >= 3;
141 let (inner, submit) = if panel {
142 let submit = Rect::new(
143 area.right().saturating_sub(5),
144 area.bottom().saturating_sub(2),
145 3,
146 1,
147 );
148 let x = area.x.saturating_add(1);
149 (
150 Rect::new(
151 x,
152 area.y.saturating_add(1),
153 submit.x.saturating_sub(1).saturating_sub(x),
154 area.height.saturating_sub(2),
155 ),
156 Some(submit),
157 )
158 } else if area.height >= 2 {
159 (
160 Rect::new(
161 area.x,
162 area.y.saturating_add(1),
163 area.width,
164 area.height - 1,
165 ),
166 None,
167 )
168 } else {
169 (area, None)
170 };
171 let (text, inset) = native_composer_content_geometry(inner, history_search);
172 NativeComposerGeometry {
173 inner,
174 text,
175 submit,
176 prompt_x: (inset > 0).then_some(inner.x),
177 }
178 }
179 pub fn native_composer_height(
180 rows: usize,
181 menu: usize,
182 available: u16,
183 density: NativeComposerDensity,
184 panel: bool,
185 ) -> u16 {
186 let available = available.max(1);
187 let floor = match density {
188 NativeComposerDensity::Compact => 1,
189 NativeComposerDensity::Comfortable => 2,
190 NativeComposerDensity::Spacious => 3,
191 };
192 let border = if panel && available >= 3 {
193 2
194 } else {
195 usize::from(available >= 2)
196 };
197 let cap = if menu == 0 {
198 available
199 } else {
200 available.min(density.max_rows())
201 };
202 rows.max(floor)
203 .saturating_add(menu)
204 .saturating_add(border)
205 .clamp(1, usize::from(cap)) as u16
206 }
207
208 /// Display width after the kit's control/bidi guard; raw source scalars remain
209 /// in each row for caret/selection/pointer projection.
210 pub fn native_composer_grapheme_width(value: &str) -> usize {
211 text::display_safe(value).width()
212 }
213 fn source_width(value: &str) -> usize {
214 text::display_safe(value).width()
215 }
216
217 /// Lossless soft wrapping: row concatenation reproduces each logical source
218 /// line, including hidden source scalars; the painter sanitizes display only.
219 pub fn native_composer_wrap_text(value: &str, width: usize) -> Vec<String> {
220 native_composer_wrap_text_bounded(value, width, usize::MAX)
221 }
222
223 /// [`native_composer_wrap_text`] that stops after `limit` complete rows.
224 fn native_composer_wrap_text_bounded(value: &str, width: usize, limit: usize) -> Vec<String> {
225 if width == 0 {
226 return vec![value.to_owned()];
227 }
228 if value.is_empty() {
229 return vec![String::new()];
230 }
231 let mut lines = Vec::new();
232 let mut current = String::new();
233 let mut cells = 0;
234 let mut break_at = None;
235 macro_rules! flush {
236 () => {{
237 match break_at.take() {
238 Some((byte, _)) if byte < current.len() => {
239 let remainder = current.split_off(byte);
240 lines.push(std::mem::replace(&mut current, remainder));
241 cells = source_width(&current)
242 }
243 _ => {
244 lines.push(std::mem::take(&mut current));
245 cells = 0
246 }
247 }
248 }};
249 }
250 for g in value.graphemes(true) {
251 if lines.len() >= limit {
252 return lines;
253 }
254 if g == "\n" {
255 break_at = None;
256 lines.push(std::mem::take(&mut current));
257 cells = 0;
258 continue;
259 }
260 let count = native_composer_grapheme_width(g);
261 if cells + count > width && cells != 0 {
262 flush!()
263 }
264 current.push_str(g);
265 cells += count;
266 if g == " " && !current.trim_start().is_empty() {
267 break_at = Some((current.len(), cells))
268 }
269 if cells >= width {
270 flush!()
271 }
272 }
273 if lines.len() < limit {
274 lines.push(current);
275 }
276 lines
277 }
278 pub fn native_composer_source_rows(value: &str, width: usize) -> Vec<(usize, String)> {
279 if value.is_empty() || width == 0 {
280 return vec![(0, String::new())];
281 }
282 let mut result = Vec::new();
283 let mut start = 0;
284 for raw in value.split('\n') {
285 for row in native_composer_wrap_text(raw, width) {
286 let chars = row.chars().count();
287 result.push((start, row));
288 start += chars
289 }
290 start += 1
291 }
292 result
293 }
294 /// [`native_composer_source_rows`] count, wrapped only as far as `limit`.
295 pub fn native_composer_source_row_count(value: &str, width: usize, limit: usize) -> usize {
296 if value.is_empty() || width == 0 {
297 return 1;
298 }
299 let mut count = 0usize;
300 for raw in value.split('\n') {
301 if count >= limit {
302 break;
303 }
304 count += native_composer_wrap_text_bounded(raw, width, limit - count).len();
305 }
306 count
307 }
308 pub fn native_composer_source_cursor(rows: &[(usize, String)], cursor: usize) -> (usize, usize) {
309 let row = rows
310 .iter()
311 .rposition(|(start, _)| *start <= cursor)
312 .unwrap_or(0);
313 let Some((start, line)) = rows.get(row) else {
314 return (0, 0);
315 };
316 let end = line
317 .char_indices()
318 .nth(cursor.saturating_sub(*start))
319 .map(|(at, _)| at)
320 .unwrap_or(line.len());
321 (row, source_width(&line[..end]))
322 }
323 #[derive(Clone, Debug)]
324 pub struct NativeComposerSourcePlan {
325 pub rows: Vec<(usize, String)>,
326 pub visible: Vec<(usize, String)>,
327 pub cursor_row: usize,
328 pub cursor_col: usize,
329 pub scroll_offset: usize,
330 }
331 pub fn native_composer_source_plan(
332 input: &str,
333 cursor: usize,
334 width: usize,
335 budget: usize,
336 ) -> NativeComposerSourcePlan {
337 let rows = native_composer_source_rows(input, width.max(1));
338 let (row, col) = native_composer_source_cursor(&rows, cursor);
339 let budget = budget.max(1);
340 let mut top = (row + 1).saturating_sub(budget);
341 if top + budget > rows.len() {
342 top = rows.len().saturating_sub(budget)
343 }
344 NativeComposerSourcePlan {
345 visible: rows.iter().skip(top).take(budget).cloned().collect(),
346 cursor_row: row.saturating_sub(top),
347 cursor_col: col.min(width.saturating_sub(1)),
348 scroll_offset: top,
349 rows,
350 }
351 }
352 pub fn native_composer_source_at(
353 input: &str,
354 width: usize,
355 column: usize,
356 row: usize,
357 scroll: usize,
358 padding: usize,
359 ) -> usize {
360 let rows = native_composer_source_rows(input, width.max(1));
361 let absolute = row.saturating_sub(padding).saturating_add(scroll);
362 let Some((start, line)) = rows.get(absolute) else {
363 return input.chars().count();
364 };
365 let mut chars = 0;
366 let mut cells = 0;
367 for g in line.graphemes(true) {
368 let n = native_composer_grapheme_width(g);
369 if cells + n > column {
370 break;
371 }
372 cells += n;
373 chars += g.chars().count()
374 }
375 start + chars
376 }
377 fn selected_line(
378 value: &str,
379 start: usize,
380 selection: Option<(usize, usize)>,
381 styles: NativeComposerStyles,
382 ) -> Line<'static> {
383 let Some((mut a, mut b)) = selection else {
384 return Line::styled(text::display_safe(value).into_owned(), styles.text);
385 };
386 if a > b {
387 std::mem::swap(&mut a, &mut b);
388 }
389 let offsets: Vec<_> = value
390 .char_indices()
391 .map(|(at, _)| at)
392 .chain(std::iter::once(value.len()))
393 .collect();
394 let len = value.chars().count();
395 let a = a.saturating_sub(start).min(len);
396 let b = b.saturating_sub(start).min(len);
397 let mut spans = Vec::new();
398 for (from, to, style) in [
399 (0, a, styles.text),
400 (a, b, styles.selection),
401 (b, len, styles.text),
402 ] {
403 if to > from {
404 spans.push(Span::styled(
405 text::display_safe(&value[offsets[from]..offsets[to]]).into_owned(),
406 style,
407 ))
408 }
409 }
410 Line::from(spans)
411 }
412 fn truncate_columns(value: &str, width: usize) -> String {
413 let safe = text::display_safe(value);
414 if safe.width() <= width {
415 return safe.into_owned();
416 }
417 let budget = if width > 3 { width - 3 } else { width };
418 let mut result = String::new();
419 let mut used = 0;
420 for g in safe.graphemes(true) {
421 let n = g.width();
422 if used + n > budget {
423 break;
424 }
425 result.push_str(g);
426 used += n;
427 }
428 if width > 3 {
429 result.push_str("...");
430 }
431 result
432 }
433 // The prompt inset is raw chrome, independent of placeholder/input ink.
434 // Fold line style into its original spans before adding unstyled padding.
435 fn prompt_inset_line(mut line: Line<'static>, inset: u16) -> Line<'static> {
436 if inset > 0 {
437 for span in &mut line.spans {
438 span.style = line.style.patch(span.style);
439 }
440 line.style = Style::default();
441 line.spans.insert(0, Span::raw(" "));
442 }
443 line
444 }
445
446 impl NativeComposerFrame<'_> {
447 pub fn desired_height(&self, width: u16, available: u16) -> u16 {
448 let panel = native_composer_geometry(
449 Rect::new(0, 0, width, available),
450 self.enclosed,
451 self.history_search,
452 )
453 .submit
454 .is_some();
455 let geometry = native_composer_geometry(
456 Rect::new(0, 0, width, if panel { 3 } else { 1 }),
457 self.enclosed,
458 self.history_search,
459 );
460 let available = available.max(1);
461 let menu = self.menu.reserved_rows;
462 let border = if panel && available >= 3 {
463 2
464 } else {
465 usize::from(available >= 2)
466 };
467 let cap = if menu == 0 {
468 usize::from(available)
469 } else {
470 usize::from(available).min(usize::from(self.density.max_rows()))
471 };
472 let rows = native_composer_source_row_count(
473 &self.text,
474 usize::from(geometry.text.width.max(1)),
475 cap.saturating_sub(menu).saturating_sub(border).max(1),
476 );
477 native_composer_height(rows, menu, available, self.density, panel)
478 }
479 pub fn plan(&self, area: Rect) -> NativeComposerPlan {
480 self.plan_with_source(area, self.source_plan(area))
481 }
482 /// The wrapped rows [`Self::plan`] projects over `area`, computed once
483 /// for callers that need a second plan over the same text.
484 pub fn source_plan(&self, area: Rect) -> NativeComposerSourcePlan {
485 let geometry = native_composer_geometry(area, self.enclosed, self.history_search);
486 let budget = native_composer_input_budget(
487 geometry.inner.height,
488 self.menu.reserved_rows.max(self.menu.items.len()),
489 );
490 native_composer_source_plan(
491 &self.text,
492 self.cursor,
493 usize::from(geometry.text.width.max(1)),
494 budget,
495 )
496 }
497 /// The input-row budget `plan` reports for `area`.
498 pub fn input_rows_budget(&self, area: Rect) -> usize {
499 let geometry = native_composer_geometry(area, self.enclosed, self.history_search);
500 native_composer_input_budget(
501 geometry.inner.height,
502 self.menu.reserved_rows.max(self.menu.items.len()),
503 )
504 }
505 /// [`Self::plan`] over rows already wrapped by [`Self::source_plan`];
506 /// same geometry and menu, so only the projected hints can differ.
507 pub fn plan_with_source(
508 &self,
509 area: Rect,
510 source: NativeComposerSourcePlan,
511 ) -> NativeComposerPlan {
512 let geometry = native_composer_geometry(area, self.enclosed, self.history_search);
513 let budget = native_composer_input_budget(
514 geometry.inner.height,
515 self.menu.reserved_rows.max(self.menu.items.len()),
516 );
517 let visual = if self.text.is_empty() {
518 1
519 } else {
520 source.visible.len()
521 };
522 let padding = native_composer_top_padding(visual, budget);
523 let mut lines = vec![Line::from(""); padding];
524 let inset = geometry.text.x.saturating_sub(geometry.inner.x);
525 if self.text.is_empty() {
526 lines.push(prompt_inset_line(safe_line(&self.placeholder), inset))
527 } else {
528 for (start, value) in &source.visible {
529 lines.push(prompt_inset_line(
530 selected_line(value, *start, self.selection, self.styles),
531 inset,
532 ))
533 }
534 }
535 let mut menu_rects = Vec::new();
536 let mut truncated = Vec::new();
537 let slots = usize::from(geometry.inner.height)
538 .saturating_sub(visual)
539 .saturating_sub(padding)
540 .saturating_sub(1)
541 .max(1);
542 let total = self.menu.items.len();
543 let selected = self.menu.selected.min(total.saturating_sub(1));
544 let half = slots / 2;
545 let top = if total <= slots || selected <= half {
546 0
547 } else if selected + half >= total {
548 total.saturating_sub(slots)
549 } else {
550 selected.saturating_sub(half)
551 };
552 let bottom = top.saturating_add(slots).min(total);
553 let width = usize::from(geometry.inner.width.max(1));
554 let label_width = self
555 .menu
556 .items
557 .iter()
558 .take(bottom)
559 .skip(top)
560 .filter_map(|item| match item {
561 NativeComposerMenuItem::Columns { name, .. } => {
562 Some(text::display_safe(name).width())
563 }
564 _ => None,
565 })
566 .max()
567 .unwrap_or(22)
568 .min(width.saturating_sub(4))
569 .max(8);
570 for (index, item) in self.menu.items.iter().enumerate().take(bottom).skip(top) {
571 let y = geometry
572 .inner
573 .y
574 .saturating_add(composer_wrapped_rows(&lines, geometry.inner.width));
575 let mut rect = Rect::new(geometry.inner.x, y, geometry.inner.width, 0);
576 let mut full_text = None;
577 let line = match item {
578 NativeComposerMenuItem::Line(line) => safe_line(line),
579 NativeComposerMenuItem::Columns {
580 name,
581 description,
582 prefix,
583 marker,
584 name_style,
585 description_style,
586 } => {
587 let name = text::display_safe(name);
588 let description = text::display_safe(description);
589 let prefix = safe_span(prefix);
590 let marker = safe_span(marker);
591 let mut label = truncate_columns(&name, label_width);
592 while label.width() < label_width {
593 label.push(' ')
594 }
595 let capacity = width.saturating_sub(
596 1 + marker.content.width() + prefix.content.width() + label_width + 2,
597 );
598 let desc = truncate_columns(&description, capacity);
599 if name.width() > label_width || description.width() > capacity {
600 full_text = Some(if description.trim().is_empty() {
601 name.into_owned()
602 } else {
603 format!("{name} {description}")
604 });
605 }
606 Line::from(vec![
607 Span::raw(" "),
608 marker,
609 prefix,
610 Span::styled(label, *name_style),
611 Span::styled(" ", *description_style),
612 Span::styled(desc, *description_style),
613 ])
614 }
615 };
616 rect.height = composer_wrapped_rows(std::slice::from_ref(&line), geometry.inner.width)
617 .min(geometry.inner.bottom().saturating_sub(y));
618 if !rect.is_empty() {
619 if self.menu.pointer_rows {
620 menu_rects.push((index, rect));
621 }
622 if let Some(full) = full_text {
623 truncated.push((rect, full));
624 }
625 }
626 lines.push(line);
627 }
628 let x = geometry
629 .text
630 .x
631 .saturating_add(u16::try_from(source.cursor_col).unwrap_or(u16::MAX));
632 let y = geometry
633 .text
634 .y
635 .saturating_add(u16::try_from(source.cursor_row + padding).unwrap_or(u16::MAX));
636 let prompt_position = geometry
637 .text
638 .contains(Position::new(x, y))
639 .then_some(Position::new(x, y));
640 let cursor = if self.focused { prompt_position } else { None };
641 let frame = NativeComposerFrame {
642 text: Cow::Borrowed(""),
643 cursor: self.cursor,
644 selection: self.selection,
645 placeholder: self.placeholder.clone(),
646 enclosed: self.enclosed,
647 density: self.density,
648 history_search: self.history_search,
649 focused: self.focused,
650 can_submit: self.can_submit,
651 ascii: self.ascii,
652 top_title: self.top_title.clone(),
653 top_right: self.top_right.clone(),
654 hint: self.hint.clone(),
655 quiet_hint: self.quiet_hint.clone(),
656 styles: self.styles,
657 menu: self.menu.clone(),
658 };
659 NativeComposerPlan {
660 area,
661 geometry,
662 cursor,
663 scroll_offset: source.scroll_offset,
664 top_padding: padding,
665 input_rows_budget: budget,
666 source_rows: source.rows,
667 menu_rects,
668 truncated,
669 prompt_position,
670 lines,
671 frame,
672 }
673 }
674 pub fn render(&self, area: Rect, buf: &mut Buffer) -> NativeComposerPlan {
675 let plan = self.plan(area.intersection(buf.area));
676 plan.paint(buf);
677 plan
678 }
679 }
680 impl NativeComposerPlan {
681 pub fn paint(&self, buf: &mut Buffer) {
682 if self.area.is_empty() {
683 return;
684 }
685 let f = &self.frame;
686 let area = self.area;
687 let panel = self.geometry.submit.is_some();
688 let mut block = Block::default().style(f.styles.background);
689 if panel {
690 block = block
691 .borders(Borders::ALL)
692 .border_type(BorderType::Rounded)
693 .border_style(f.styles.border)
694 } else if area.height >= 2 {
695 block = block
696 .borders(Borders::TOP)
697 .border_style(f.styles.quiet_border)
698 }
699 if f.ascii {
700 block = block.border_set(ASCII_BORDER)
701 }
702 block.render(area, buf);
703 if area.height >= 2 {
704 let mut top = Block::default()
705 .borders(Borders::TOP)
706 .border_style(if panel {
707 f.styles.border
708 } else {
709 f.styles.quiet_border
710 })
711 .style(f.styles.background);
712 if f.ascii {
713 top = top.border_set(ASCII_BORDER);
714 }
715 if panel && let Some(title) = &f.top_title {
716 top = top.title(safe_line(title))
717 }
718 if let Some(right) = &f.top_right {
719 top = top.title_top(safe_line(right).right_aligned())
720 }
721 if !panel && let Some(hint) = &f.quiet_hint {
722 top = top.title(safe_line(hint))
723 }
724 top.render(area, buf);
725 if panel {
726 let mut bottom = Block::default()
727 .borders(Borders::BOTTOM)
728 .border_style(f.styles.border)
729 .style(f.styles.background);
730 if f.ascii {
731 bottom = bottom.border_set(ASCII_BORDER);
732 }
733 if let Some(hint) = &f.hint {
734 bottom = bottom.title_bottom(safe_line(hint))
735 }
736 bottom.render(area, buf);
737 for (x, y, mark) in [
738 (area.x, area.y, "╭"),
739 (area.right() - 1, area.y, "╮"),
740 (area.x, area.bottom() - 1, "╰"),
741 (area.right() - 1, area.bottom() - 1, "╯"),
742 ] {
743 buf[(x, y)]
744 .set_symbol(if f.ascii { "+" } else { mark })
745 .set_style(f.styles.border.patch(f.styles.background));
746 }
747 }
748 }
749 Paragraph::new(self.lines.clone())
750 .style(f.styles.background)
751 .wrap(Wrap { trim: false })
752 .render(self.geometry.inner, buf);
753 if let (Some(x), Some(cursor)) = (self.geometry.prompt_x, self.prompt_position) {
754 buf[(x, cursor.y)]
755 .set_symbol(if f.ascii { ">" } else { "❯" })
756 .set_style(f.styles.prompt);
757 }
758 if let Some(rect) = self.geometry.submit {
759 let mark = match (f.can_submit, f.ascii) {
760 (true, false) => "[↵]",
761 (true, true) => "[>]",
762 (false, false) => "[·]",
763 (false, true) => "[.]",
764 };
765 buf.set_stringn(rect.x, rect.y, mark, 3, f.styles.submit);
766 }
767 }
768 }
769 impl Paint for NativeComposerFrame<'_> {
770 fn paint(&self, area: Rect, buf: &mut Buffer, _theme: &Theme) {
771 self.render(area, buf);
772 }
773 fn height(&self, width: u16, _theme: &Theme) -> u16 {
774 self.desired_height(width, self.density.max_rows())
775 }
776 }
777
778 const ASCII_BORDER: ratatui::symbols::border::Set<'static> = ratatui::symbols::border::Set {
779 top_left: "+",
780 top_right: "+",
781 bottom_left: "+",
782 bottom_right: "+",
783 vertical_left: "|",
784 vertical_right: "|",
785 horizontal_top: "-",
786 horizontal_bottom: "-",
787 };
788
789 pub const NATIVE_COMPOSER_PANEL_MIN_WIDTH: u16 = 12;
790
791 /// Format a pasted-text attachment chip (`Pasted text · N lines` / `1 line`),
792 /// projecting the middot separator to `.` when `ascii` is true.
793 #[must_use]
794 pub fn native_composer_paste_chip(lines: usize, ascii: bool) -> String {
795 let sep = if ascii { "." } else { "·" };
796 if lines == 1 {
797 format!("Pasted text {sep} 1 line")
798 } else {
799 format!("Pasted text {sep} {lines} lines")
800 }
801 }
802 fn composer_wrapped_rows(lines: &[Line<'static>], width: u16) -> u16 {
803 if width == 0 {
804 return 0;
805 }
806 u16::try_from(
807 Paragraph::new(lines.to_vec())
808 .wrap(Wrap { trim: false })
809 .line_count(width),
810 )
811 .unwrap_or(u16::MAX)
812 }
813 #[derive(Clone, Copy, Debug)]
814 pub enum NativeComposerRowColumn {
815 DisplayCells,
816 SourceScalars,
817 }
818 /// Pure projection for an existing editor's visual-row command. The host
819 /// decides whether keys/wheel claim that command and applies the result.
820 pub fn native_composer_step_row(
821 input: &str,
822 cursor: usize,
823 width: usize,
824 delta: isize,
825 column: NativeComposerRowColumn,
826 ) -> Option<usize> {
827 if input.is_empty() || delta == 0 {
828 return None;
829 }
830 let rows = native_composer_source_rows(input, width.max(1));
831 if rows.len() < 2 {
832 return None;
833 }
834 let cursor = cursor.min(input.chars().count());
835 let (row, cells) = native_composer_source_cursor(&rows, cursor);
836 let target = if delta < 0 {
837 row.saturating_sub(delta.unsigned_abs())
838 } else {
839 row.saturating_add(delta as usize).min(rows.len() - 1)
840 };
841 if row == target {
842 return None;
843 }
844 let (start, text) = &rows[target];
845 let offset = match column {
846 NativeComposerRowColumn::SourceScalars => {
847 cursor.saturating_sub(rows[row].0).min(text.chars().count())
848 }
849 NativeComposerRowColumn::DisplayCells => {
850 let mut count = 0;
851 let mut used = 0;
852 for g in text.graphemes(true) {
853 let width = native_composer_grapheme_width(g);
854 if used + width > cells {
855 break;
856 }
857 used += width;
858 count += g.chars().count();
859 }
860 count
861 }
862 };
863 Some(start.saturating_add(offset).min(input.chars().count()))
864 }
865 #[cfg(test)]
866 mod tests {
867 use super::{
868 NativeComposerDensity, NativeComposerFrame, NativeComposerMenu, NativeComposerStyles,
869 native_composer_height, native_composer_source_row_count, native_composer_source_rows,
870 };
871 use ratatui::text::Line;
872 use std::borrow::Cow;
873
874 fn frame<'a>(text: &'a str, reserved_rows: usize) -> NativeComposerFrame<'a> {
875 NativeComposerFrame {
876 text: Cow::Borrowed(text),
877 cursor: text.chars().count(),
878 selection: None,
879 placeholder: Line::default(),
880 enclosed: false,
881 density: NativeComposerDensity::Comfortable,
882 history_search: false,
883 focused: true,
884 can_submit: true,
885 ascii: false,
886 top_title: None,
887 top_right: None,
888 hint: None,
889 quiet_hint: None,
890 styles: NativeComposerStyles::default(),
891 menu: NativeComposerMenu {
892 reserved_rows,
893 ..Default::default()
894 },
895 }
896 }
897
898 #[test]
899 fn bounded_count_equals_full_count_until_the_limit() {
900 let cjk = "你好世界".repeat(40);
901 for input in [
902 "",
903 "short",
904 "one\ntwo\nthree",
905 cjk.as_str(),
906 "a very long line of words that wraps across several display rows",
907 "tail\n",
908 ] {
909 for width in [1usize, 7, 40] {
910 let full = native_composer_source_rows(input, width).len();
911 for limit in [1usize, 2, 5, usize::MAX] {
912 assert_eq!(
913 native_composer_source_row_count(input, width, limit),
914 full.min(limit),
915 "input={input:?} width={width} limit={limit}"
916 );
917 }
918 }
919 }
920 }
921
922 #[test]
923 fn desired_height_matches_the_full_wrap_for_large_drafts() {
924 let huge = "你好世界 paste payload ".repeat(400);
925 for (reserved, available) in [(0usize, 9u16), (4, 9), (0, 1)] {
926 let frame = frame(&huge, reserved);
927 let full_rows = native_composer_source_rows(&huge, 38).len();
928 assert_eq!(
929 frame.desired_height(40, available),
930 native_composer_height(full_rows, reserved, available.max(1), frame.density, false,),
931 "reserved={reserved} available={available}"
932 );
933 }
934 }
935 }
936
936 lines RUST