aboutsummaryrefslogtreecommitdiff
path: root/src/tui/layout.cc
blob: e12c8d018346fbbf329aefc59940b22254543cdc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
/*
 * Ricochet - A minimalist CLI web browser for fast, distraction-free navigation.
 * Copyright (C) 2026  Richard Qin
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#include "layout.hh"
#include "document_text.hh"

#include <algorithm>
#include <limits>
#include <map>
#include <numeric>
#include <stdexcept>
#include <string>
#include <string_view>
#include <tuple>
#include <type_traits>
#include <utility>

namespace ricochet::tui::detail {
namespace {

constexpr int tab_columns = 8;
constexpr std::int64_t cell_gap = 3;
constexpr std::int64_t minimum_cell_columns = 4;

TextStyle overlay( TextStyle base, TextStyle extra )
{
  return { base.emphasis || extra.emphasis,
           base.strong || extra.strong,
           base.code || extra.code,
           base.subdued || extra.subdued,
           base.warning || extra.warning };
}

struct Atom
{
  Grapheme glyph {};
  DocumentRange source {};
  TextStyle style {};
  std::optional<HitTarget> target {};
  bool decoration { false };
};

struct TextSpan
{
  const Text* leaf;
  ByteRange bytes;
};

DocumentPoint text_point( std::span<const TextSpan> spans, std::size_t offset, bool end )
{
  for ( const auto& span : spans ) {
    // At an inline seam an end belongs to the preceding leaf, a start to the next.
    if ( offset < span.bytes.end || ( end && offset == span.bytes.end ) ) {
      return TextPosition { span.leaf->id, offset - span.bytes.start };
    }
  }
  const auto& last = spans.back();
  return TextPosition { last.leaf->id, last.leaf->utf8.size() };
}

LayoutGlyph anchor( DocumentPoint point, LayoutPoint location, std::int64_t width )
{ return { .position = location, .source = { point, point }, .clip_right = width }; }

void append_box( LayoutData& destination, LayoutData source, std::size_t row, std::int64_t column )
{
  destination.rows = std::max( destination.rows, row + source.rows );
  destination.extent = std::max( destination.extent, column + source.extent );
  for ( auto& glyph : source.glyphs ) {
    glyph.position.row += row;
    glyph.position.column += column;
    glyph.line_start += column;
    for ( auto& window : glyph.scrolls ) {
      window.left += column;
    }
    glyph.clip_left += column;
    glyph.clip_right += column;
    destination.glyphs.push_back( std::move( glyph ) );
  }
}

class LayoutBuilder
{
public:
  LayoutBuilder( const DocumentData& document, const TextService& text, std::span<const HorizontalScroll> scrolls )
    : document_( document ), text_( text ), scrolls_( scrolls )
  {
    for ( const auto& control : document.controls ) {
      controls_.emplace( control.id, &control );
    }
  }

  LayoutData blocks( std::span<const Block> content, std::int64_t width, TextStyle style = {} ) const
  {
    LayoutData result;
    std::size_t row = 0;
    for ( const auto& block : content ) {
      auto box = block_box( block, width, style );
      const auto height = box.rows;
      append_box( result, std::move( box ), row, 0 );
      row += height;
    }
    return result;
  }

private:
  void text_run( std::vector<Atom>& atoms,
                 std::span<const TextSpan> spans,
                 const std::string& utf8,
                 bool tabs,
                 TextStyle base ) const
  {
    const auto analysis = text_.analyze( utf8, true, tabs );
    for ( const auto& glyph : analysis.graphemes ) {
      Atom atom { .glyph = glyph,
                  .source
                  = { text_point( spans, glyph.bytes.start, false ), text_point( spans, glyph.bytes.end, true ) },
                  .style = base };
      for ( const auto& span : spans ) {
        // Only source portions intersecting this grapheme can contribute style/link.
        if ( span.bytes.start >= glyph.bytes.end || span.bytes.end <= glyph.bytes.start ) {
          continue;
        }
        const ByteRange local { std::max( span.bytes.start, glyph.bytes.start ) - span.bytes.start,
                                std::min( span.bytes.end, glyph.bytes.end ) - span.bytes.start };
        for ( const auto& styled : span.leaf->styles ) {
          if ( styled.bytes.start < local.end && local.start < styled.bytes.end ) {
            atom.style = overlay( atom.style, styled.style );
          }
        }
        for ( const auto& link : document_.links ) {
          for ( const auto& range : link.ranges ) {
            if ( range.block == span.leaf->id && range.bytes.start < local.end && local.start < range.bytes.end ) {
              const HitTarget target = link.id;
              // One grapheme cannot activate two links, including across leaf seams.
              if ( atom.target && atom.target != target ) {
                throw std::invalid_argument( "Overlapping links address the same grapheme" );
              }
              atom.target = target;
              atom.style.emphasis = true;
            }
          }
        }
      }
      atoms.push_back( std::move( atom ) );
    }
    // Empty text still has a real byte boundary; no fabricated display character.
    if ( utf8.empty() ) {
      const auto point = text_point( spans, 0, false );
      atoms.push_back( { .glyph = { .columns = 0 }, .source = { point, point }, .style = base } );
    }
  }

  void control_atoms( std::vector<Atom>& atoms, ControlId id, TextStyle base ) const
  {
    // A missing ID is a malformed document reference; map::at reports it directly.
    const auto& control = *controls_.at( id );
    const auto* input = std::get_if<TextControl>( &control.content );
    const bool multiline = input && input->kind == TextControlKind::MultiLine;
    const auto before = ObjectPosition { id, BoundarySide::Before };
    const auto after = ObjectPosition { id, BoundarySide::After };
    const auto style = overlay( base, { .subdued = control.disabled, .warning = control.error.has_value() } );
    std::wstring_view opening = L"[";
    std::wstring_view closing = L"]";
    if ( const auto* checkbox = std::get_if<Checkbox>( &control.content ) ) {
      opening = checkbox->checked ? L"[x] " : L"[ ] ";
      closing = L"";
    } else if ( const auto* radio = std::get_if<RadioButton>( &control.content ) ) {
      opening = radio->checked ? L"(*) " : L"( ) ";
      closing = L"";
    }
    for ( const auto character : opening ) {
      atoms.push_back( { .glyph = { .display = std::wstring( 1, character ) },
                         .source = { before, before },
                         .style = style,
                         .target = id } );
    }
    const auto display = control_display_text( control, text_ );
    const auto analysis = text_.analyze( display, multiline, false );
    for ( const auto& glyph : analysis.graphemes ) {
      atoms.push_back( { .glyph = glyph,
                         .source = { ControlTextPosition { id, {}, glyph.bytes.start },
                                     ControlTextPosition { id, {}, glyph.bytes.end } },
                         .style = style,
                         .target = id } );
    }
    if ( display.empty() ) {
      const auto point = ControlTextPosition { id, {}, 0 };
      atoms.push_back( { .glyph = { .display = L" " }, .source = { point, point }, .style = style, .target = id } );
    }
    for ( const auto character : closing ) {
      atoms.push_back( { .glyph = { .display = std::wstring( 1, character ), .break_after = true },
                         .source = { after, after },
                         .style = style,
                         .target = id } );
    }
    // Checkbox/radio controls have no closing bracket but still have an after boundary.
    atoms.push_back( { .glyph = { .columns = 0, .break_after = true },
                       .source = { after, after },
                       .style = style,
                       .target = id } );
  }

  std::vector<Atom> inline_atoms( std::span<const Inline> content, TextStyle style ) const
  {
    std::vector<Atom> result;
    std::vector<TextSpan> spans;
    std::string utf8;
    const auto flush = [&] {
      if ( !spans.empty() ) {
        text_run( result, spans, utf8, false, style );
        spans.clear();
        utf8.clear();
      }
    };
    for ( const auto& item : content ) {
      if ( const auto* text = std::get_if<Text>( &item ) ) {
        const auto start = utf8.size();
        utf8 += text->utf8;
        spans.push_back( { text, { start, utf8.size() } } );
      } else {
        flush();
        control_atoms( result, std::get<ControlPlaceholder>( item ).control, style );
      }
    }
    flush();
    return result;
  }

  LayoutData flow( std::span<const Atom> atoms, std::int64_t width, bool wrap ) const
  {
    LayoutData result;
    std::size_t start = 0;
    std::size_t row = 0;
    while ( start < atoms.size() ) {
      std::size_t end = start;
      std::size_t opportunity = start;
      std::int64_t column = 0;
      while ( end < atoms.size() && atoms[end].glyph.kind != TextUnitKind::LineBreak ) {
        const auto& glyph = atoms[end].glyph;
        const int cells = glyph.kind == TextUnitKind::Tab ? tab_columns - column % tab_columns : glyph.columns;
        if ( wrap && column + cells > width && end > start ) {
          break;
        }
        column += cells;
        ++end;
        if ( glyph.break_after ) {
          opportunity = end;
        }
      }
      // Prefer a Unicode line boundary; an overlong word breaks at a grapheme.
      if ( end < atoms.size() && atoms[end].glyph.kind != TextUnitKind::LineBreak && opportunity > start ) {
        end = opportunity;
      }
      column = 0;
      for ( auto index = start; index < end; ++index ) {
        const auto& atom = atoms[index];
        const bool tab = atom.glyph.kind == TextUnitKind::Tab;
        const int cells = tab ? tab_columns - column % tab_columns : atom.glyph.columns;
        result.glyphs.push_back( { .position = { row, column },
                                   .columns = cells,
                                   .text = atom.glyph.display,
                                   .style = atom.style,
                                   .source = atom.source,
                                   .target = atom.target,
                                   .clip_right = wrap ? width : std::numeric_limits<std::int64_t>::max(),
                                   .decoration = atom.decoration,
                                   .fill = tab,
                                   .word_start = atom.glyph.word_start,
                                   .word_end = atom.glyph.word_end } );
        column += cells;
      }
      result.extent = std::max( result.extent, column );
      if ( end < atoms.size() && atoms[end].glyph.kind == TextUnitKind::LineBreak ) {
        const auto& atom = atoms[end++];
        result.glyphs.push_back( { .position = { row, column },
                                   .source = atom.source,
                                   .target = atom.target,
                                   .clip_right = width,
                                   .line_break = true } );
        // The endpoint of a hard LF belongs to the next line, including a
        // trailing empty line; it must also be reachable by hit testing.
        auto boundary = anchor( atom.source.end, { row + 1, 0 }, width );
        boundary.target = atom.target;
        result.glyphs.push_back( std::move( boundary ) );
        result.rows = row + 2;
      } else {
        result.rows = row + 1;
      }
      start = end;
      ++row;
    }
    return result;
  }

  void horizontal( LayoutData& box, BlockId block, std::int64_t width ) const
  {
    const auto scroll = std::ranges::find( scrolls_, block, &HorizontalScroll::block );
    const auto requested = scroll == scrolls_.end() ? 0 : scroll->columns;
    const auto maximum = std::max<std::int64_t>( 0, box.extent - width );
    const auto shift = static_cast<std::int64_t>( std::min<std::uint64_t>( requested, maximum ) );
    for ( auto& glyph : box.glyphs ) {
      for ( auto& window : glyph.scrolls ) {
        window.left -= shift;
      }
      glyph.scrolls.push_back( { block, 0, width, shift, maximum } );
      glyph.position.column -= shift;
      glyph.line_start -= shift;
      glyph.clip_left = std::max<std::int64_t>( 0, glyph.clip_left - shift );
      glyph.clip_right = std::min( width, glyph.clip_right - shift );
    }
  }

  LayoutData list_box( const List& list, std::int64_t width, TextStyle style ) const
  {
    LayoutData result;
    std::size_t row = 0;
    auto number = list.first_number;
    for ( const auto& item : list.items ) {
      const auto marker
        = item.marker.value_or( list.kind == ListKind::Ordered ? std::to_string( number ) + "." : "-" );
      const auto analysis = text_.analyze( marker, false, false );
      const auto marker_width
        = std::accumulate( analysis.graphemes.begin(),
                           analysis.graphemes.end(),
                           std::int64_t { 0 },
                           []( auto total, const auto& glyph ) { return total + glyph.columns; } );
      // Deep nesting must leave at least one body cell; clipped markers stay decoration.
      const auto indent = std::min( marker_width + 1, width - 1 );
      auto body = blocks( item.content, width - indent, style );
      const auto height = body.rows;
      append_box( result, std::move( body ), row, indent );
      std::int64_t column = 0;
      for ( const auto& glyph : analysis.graphemes ) {
        result.glyphs.push_back( { .position = { row, column },
                                   .columns = glyph.columns,
                                   .text = glyph.display,
                                   .style = style,
                                   .clip_right = indent,
                                   .decoration = true } );
        column += glyph.columns;
      }
      row += height;
      // Ordered counters can start at the model's largest int64 value.
      if ( number < std::numeric_limits<std::int64_t>::max() ) {
        ++number;
      }
    }
    return result;
  }

  LayoutData table_box( const Table& table, BlockId id, std::int64_t width, TextStyle style ) const
  {
    if ( table.columns == 0 ) {
      return {};
    }
    std::vector<std::int64_t> widths( table.columns, 1 );
    std::vector<std::int64_t> desired( table.columns, 1 );
    for ( std::size_t row = 0; row < table.rows.size(); ++row ) {
      for ( const auto& cell : table.rows[row].cells ) {
        // Spans index the supplied grid. Reject zero/out-of-grid spans before indexing.
        if ( cell.column >= table.columns || cell.column_span == 0 || cell.row_span == 0
             || cell.column_span > table.columns - cell.column || cell.row_span > table.rows.size() - row ) {
          throw std::invalid_argument( "Table cell span lies outside its resolved grid" );
        }
        const auto measure = blocks( cell.content, width, style );
        const auto span = static_cast<std::int64_t>( cell.column_span );
        const auto preferred = std::max<std::int64_t>( 1, ( measure.extent + span - 1 ) / span );
        for ( auto column = cell.column; column < cell.column + cell.column_span; ++column ) {
          desired[column] = std::max( desired[column], preferred );
          widths[column] = std::max( widths[column], std::min( preferred, minimum_cell_columns ) );
        }
      }
    }
    const auto gaps = cell_gap * static_cast<std::int64_t>( table.columns - 1 );
    auto remaining = width - gaps - std::accumulate( widths.begin(), widths.end(), std::int64_t { 0 } );
    // Grow content-bearing columns toward their preferred width, within the viewport.
    while ( remaining > 0 ) {
      bool grew = false;
      for ( std::size_t column = 0; column < widths.size() && remaining > 0; ++column ) {
        if ( widths[column] < desired[column] ) {
          ++widths[column];
          --remaining;
          grew = true;
        }
      }
      if ( !grew ) {
        break;
      }
    }
    struct CellBox
    {
      const TableCell* cell;
      std::size_t row;
      LayoutData box;
    };
    std::vector<CellBox> cells;
    std::vector<std::size_t> heights( table.rows.size(), 1 );
    for ( std::size_t row = 0; row < table.rows.size(); ++row ) {
      for ( const auto& cell : table.rows[row].cells ) {
        const auto first = widths.begin() + static_cast<std::ptrdiff_t>( cell.column );
        const auto last = first + static_cast<std::ptrdiff_t>( cell.column_span );
        const auto cell_width = std::accumulate( first, last, std::int64_t { 0 } )
                                + cell_gap * static_cast<std::int64_t>( cell.column_span - 1 );
        auto box = blocks( cell.content, cell_width, overlay( style, { .strong = cell.header } ) );
        const auto begin = heights.begin() + static_cast<std::ptrdiff_t>( row );
        const auto end = begin + static_cast<std::ptrdiff_t>( cell.row_span );
        const auto height = std::accumulate( begin, end, std::size_t { 0 } );
        if ( box.rows > height ) {
          heights[row + cell.row_span - 1] += box.rows - height;
        }
        cells.push_back( { &cell, row, std::move( box ) } );
      }
    }
    std::vector<std::size_t> row_offsets( heights.size() + 1, 0 );
    std::partial_sum( heights.begin(), heights.end(), row_offsets.begin() + 1 );
    std::vector<std::int64_t> column_offsets( widths.size(), 0 );
    for ( std::size_t column = 1; column < widths.size(); ++column ) {
      column_offsets[column] = column_offsets[column - 1] + widths[column - 1] + cell_gap;
    }
    LayoutData result;
    result.extent = std::accumulate( widths.begin(), widths.end(), gaps );
    result.rows = std::max<std::size_t>( 1, row_offsets.back() );
    for ( auto& cell : cells ) {
      const auto column = column_offsets[cell.cell->column];
      append_box( result, std::move( cell.box ), row_offsets[cell.row], column );
      if ( cell.cell->column != 0 ) {
        for ( auto row = row_offsets[cell.row]; row < row_offsets[cell.row + cell.cell->row_span]; ++row ) {
          result.glyphs.push_back( { .position = { row, column - 2 },
                                     .columns = 1,
                                     .text = L"|",
                                     .style = { .subdued = true },
                                     .clip_right = result.extent,
                                     .decoration = true } );
        }
      }
    }
    // A nested preformatted block scrolls inside its cell; its natural extent
    // must not enlarge the enclosing table's horizontal scroll range.
    result.extent = std::accumulate( widths.begin(), widths.end(), gaps );
    horizontal( result, id, width );
    return result;
  }

  LayoutData block_box( const Block& block, std::int64_t width, TextStyle style ) const
  {
    auto result = std::visit(
      [this, &block, width, style]( const auto& value ) -> LayoutData {
        using Value = std::decay_t<decltype( value )>;
        if constexpr ( std::is_same_v<Value, Paragraph> ) {
          return flow( inline_atoms( value.content, style ), width, true );
        } else if constexpr ( std::is_same_v<Value, Heading> ) {
          return flow( inline_atoms( value.content, overlay( style, { .strong = true } ) ), width, true );
        } else if constexpr ( std::is_same_v<Value, Preformatted> || std::is_same_v<Value, Alternative> ) {
          const Text& leaf = [&]() -> const Text& {
            if constexpr ( std::is_same_v<Value, Preformatted> ) {
              return value.content;
            } else {
              return value.description;
            }
          }();
          const TextSpan span { &leaf, { 0, leaf.utf8.size() } };
          std::vector<Atom> atoms;
          constexpr bool preformatted = std::is_same_v<Value, Preformatted>;
          text_run(
            atoms, std::span( &span, 1 ), leaf.utf8, preformatted, overlay( style, { .code = preformatted } ) );
          auto box = flow( atoms, width, !preformatted );
          if constexpr ( preformatted ) {
            horizontal( box, block.id, width );
          }
          return box;
        } else if constexpr ( std::is_same_v<Value, List> ) {
          return list_box( value, width, style );
        } else if constexpr ( std::is_same_v<Value, Table> ) {
          return table_box( value, block.id, width, style );
        } else if constexpr ( std::is_same_v<Value, ControlPlaceholder> ) {
          std::vector<Atom> atoms;
          control_atoms( atoms, value.control, style );
          return flow( atoms, width, true );
        } else {
          LayoutData box;
          box.extent = width;
          for ( std::int64_t column = 0; column < width; ++column ) {
            box.glyphs.push_back( { .position = { 0, column },
                                    .columns = 1,
                                    .text = L"-",
                                    .style = { .subdued = true },
                                    .clip_right = width,
                                    .decoration = true } );
          }
          return box;
        }
      },
      block.content );
    const bool has_text
      = std::ranges::any_of( result.glyphs, []( const auto& glyph ) { return !glyph.decoration; } );
    auto before = anchor( ObjectPosition { block.id, BoundarySide::Before }, {}, width );
    auto after = anchor( ObjectPosition { block.id, BoundarySide::After },
                         { result.rows - 1, std::min( result.extent, width ) },
                         width );
    before.boundary_only = has_text;
    after.boundary_only = true;
    result.glyphs.push_back( std::move( before ) );
    result.glyphs.push_back( std::move( after ) );
    return result;
  }

  const DocumentData& document_;
  const TextService& text_;
  std::span<const HorizontalScroll> scrolls_;
  std::map<ControlId, const Control*> controls_ {};
};

LayoutPoint end_point( const LayoutGlyph& glyph )
{
  // Object decorations and empty fields do not create a second text boundary.
  if ( glyph.source.start == glyph.source.end ) {
    return glyph.position;
  }
  if ( glyph.line_break ) {
    return { glyph.position.row + 1, glyph.line_start };
  }
  return { glyph.position.row, glyph.position.column + glyph.columns };
}

} // namespace

DocumentLayout::DocumentLayout( const Document& document,
                                const TextService& text,
                                int columns,
                                std::span<const HorizontalScroll> scrolls )
  : columns_( std::max( 1, columns ) )
  , data_( LayoutBuilder( document.data(), text, scrolls ).blocks( document.data().blocks, columns_ ) )
{
  // An empty document still has a location for its cursor/viewport anchor.
  if ( data_.glyphs.empty() ) {
    data_.glyphs.push_back( anchor( DocumentStart {}, {}, columns_ ) );
  }
  for ( std::size_t index = 0; index < data_.glyphs.size(); ++index ) {
    const auto& glyph = data_.glyphs[index];
    if ( glyph.decoration || glyph.boundary_only ) {
      continue;
    }
    // Wrapped object borders and hard-break anchors can repeat a logical point.
    // Keep one reading stop, preferring actual text over its zero-width anchor.
    if ( !stops_.empty() && data_.glyphs[stops_.back()].source.start == glyph.source.start ) {
      if ( data_.glyphs[stops_.back()].columns == 0 ) {
        stops_.back() = index;
      }
    } else {
      stops_.push_back( index );
    }
  }
}

int DocumentLayout::columns() const
{ return columns_; }
std::size_t DocumentLayout::rows() const
{ return data_.rows; }

std::optional<LayoutPoint> DocumentLayout::locate( const DisplayPosition& position ) const
{
  if ( std::holds_alternative<DocumentStart>( position.point ) ) {
    return data_.glyphs[stops_.front()].position;
  }
  std::optional<LayoutPoint> fallback;
  for ( const auto& glyph : data_.glyphs ) {
    if ( glyph.decoration ) {
      continue;
    }
    if ( position.point == glyph.source.start ) {
      if ( position.affinity == WrapAffinity::NextLine ) {
        return glyph.position;
      }
      fallback = glyph.position;
    }
    if ( position.point == glyph.source.end ) {
      if ( position.affinity == WrapAffinity::PreviousLine ) {
        return end_point( glyph );
      }
      fallback = end_point( glyph );
    }
  }
  return fallback;
}

std::optional<LayoutHit> DocumentLayout::hit( LayoutPoint point ) const
{
  // Blank space below the document means its last reading position, independent
  // of the mouse column (especially when the final block is a table).
  if ( point.row >= data_.rows ) {
    const auto& glyph = data_.glyphs[stops_.back()];
    return LayoutHit { last(), glyph.source, glyph.target };
  }
  const LayoutGlyph* nearest = nullptr;
  auto distance
    = std::tuple { std::numeric_limits<std::size_t>::max(), std::numeric_limits<std::int64_t>::max(), true };
  for ( const auto& glyph : data_.glyphs ) {
    // Decorations and partially clipped wide glyphs have no independent text hit.
    if ( glyph.decoration || glyph.boundary_only ) {
      continue;
    }
    const auto left = std::max( glyph.position.column, glyph.clip_left );
    const auto edge = std::min( glyph.position.column + glyph.columns, glyph.clip_right );
    // Tab blanks may be clipped individually; a wide glyph remains indivisible.
    if ( ( glyph.fill && left >= edge )
         || ( !glyph.fill
              && ( glyph.position.column < glyph.clip_left
                   || glyph.position.column + glyph.columns > glyph.clip_right ) ) ) {
      continue;
    }
    const auto row_distance
      = glyph.position.row > point.row ? glyph.position.row - point.row : point.row - glyph.position.row;
    const auto right = std::max( left, edge - 1 );
    const auto column_distance = std::max( { left - point.column, point.column - right, std::int64_t { 0 } } );
    const auto candidate = std::tuple { row_distance, column_distance, glyph.columns == 0 };
    if ( candidate < distance ) {
      nearest = &glyph;
      distance = candidate;
    }
  }
  if ( !nearest ) {
    return std::nullopt;
  }
  const bool after = !nearest->line_break && point.column >= nearest->position.column + nearest->columns;
  return LayoutHit { .position = { after ? nearest->source.end : nearest->source.start,
                                   after ? WrapAffinity::PreviousLine : WrapAffinity::NextLine },
                     .unit = nearest->source,
                     .target = nearest->target };
}

DisplayPosition DocumentLayout::stop( std::size_t index ) const
{ return { data_.glyphs[stops_[index]].source.start, WrapAffinity::NextLine }; }

DisplayPosition DocumentLayout::first() const
{ return stop( 0 ); }
DisplayPosition DocumentLayout::last() const
{ return stop( stops_.size() - 1 ); }

std::size_t DocumentLayout::nearest_stop( LayoutPoint point ) const
{
  std::size_t nearest = 0;
  auto distance = std::pair { std::numeric_limits<std::size_t>::max(), std::numeric_limits<std::int64_t>::max() };
  for ( std::size_t index = 0; index < stops_.size(); ++index ) {
    const auto& glyph = data_.glyphs[stops_[index]];
    const auto row = glyph.position.row;
    const auto right = glyph.position.column + std::max( 1, glyph.columns ) - 1;
    const auto candidate = std::pair {
      row > point.row ? row - point.row : point.row - row,
      std::max( { glyph.position.column - point.column, point.column - right, std::int64_t { 0 } } ) };
    if ( candidate < distance ) {
      nearest = index;
      distance = candidate;
    }
  }
  return nearest;
}

DocumentLayout::ReadingPosition DocumentLayout::reading_position( const DisplayPosition& position ) const
{
  std::optional<std::size_t> endpoint;
  for ( std::size_t index = 0; index < stops_.size(); ++index ) {
    const auto& glyph = data_.glyphs[stops_[index]];
    if ( glyph.source.start == position.point ) {
      return { index, position.affinity == WrapAffinity::NextLine };
    }
    if ( glyph.source.end == position.point ) {
      endpoint = index + 1;
    }
  }
  if ( endpoint ) {
    return { *endpoint, false };
  }
  // Structural block anchors have coordinates but are not extra character stops.
  return { nearest_stop( locate( position ).value() ), true };
}

DisplayPosition DocumentLayout::adjacent( const DisplayPosition& position, int direction ) const
{
  const auto current = reading_position( position );
  if ( direction < 0 ) {
    return stop( current.index == 0 ? 0 : current.index - 1 );
  }
  return stop( std::min( stops_.size() - 1, current.index + static_cast<std::size_t>( current.at_start ) ) );
}

DisplayPosition DocumentLayout::word( const DisplayPosition& position, WordMotion motion ) const
{
  const auto current = reading_position( position );
  if ( motion == WordMotion::Previous ) {
    for ( auto index = current.index; index > 0; ) {
      --index;
      if ( data_.glyphs[stops_[index]].word_start ) {
        return stop( index );
      }
    }
    return first();
  }
  auto begin = current.index;
  if ( current.at_start && ( motion == WordMotion::Next || data_.glyphs[stops_[begin]].word_end ) ) {
    ++begin;
  }
  for ( auto index = begin; index < stops_.size(); ++index ) {
    const auto& glyph = data_.glyphs[stops_[index]];
    if ( motion == WordMotion::Next ? glyph.word_start : glyph.word_end ) {
      return stop( index );
    }
  }
  return last();
}

DisplayPosition DocumentLayout::on_row( LayoutPoint point ) const
{ return stop( nearest_stop( point ) ); }

DisplayPosition DocumentLayout::line_edge( const DisplayPosition& position, bool end ) const
{
  const auto row = locate( position ).value().row;
  auto chosen = nearest_stop( { row, 0 } );
  for ( std::size_t index = 0; index < stops_.size(); ++index ) {
    const auto& glyph = data_.glyphs[stops_[index]];
    const auto column = data_.glyphs[stops_[chosen]].position.column;
    if ( glyph.position.row == row && ( end ? glyph.position.column > column : glyph.position.column < column ) ) {
      chosen = index;
    }
  }
  return stop( chosen );
}

const LayoutGlyph& DocumentLayout::cursor_glyph( const DisplayPosition& position ) const
{
  const auto current = reading_position( position );
  const auto index = current.at_start || current.index == 0 ? current.index : current.index - 1;
  return data_.glyphs[stops_[std::min( index, stops_.size() - 1 )]];
}

std::optional<HitTarget> DocumentLayout::target( const DisplayPosition& position ) const
{ return cursor_glyph( position ).target; }

std::optional<LayoutPoint> DocumentLayout::cursor_cell( const DisplayPosition& position ) const
{
  const auto& glyph = cursor_glyph( position );
  auto point = locate( position ).value();
  if ( glyph.fill ) {
    // Any visible part of an expanded tab represents the same logical unit.
    const auto left = std::max( glyph.position.column, glyph.clip_left );
    const auto right = std::min( glyph.position.column + glyph.columns, glyph.clip_right );
    if ( left >= right ) {
      return std::nullopt;
    }
    point.column = std::clamp( point.column, left, right - 1 );
    return point;
  }
  if ( point.column == glyph.clip_right && point.row == glyph.position.row ) {
    // An insertion boundary or LF immediately after a full row has no cell.
    // Use the preceding complete glyph; do not reveal a cursor further offscreen.
    auto column = glyph.clip_right - 1;
    for ( const auto index : stops_ ) {
      const auto& candidate = data_.glyphs[index];
      if ( candidate.position.row == point.row && candidate.columns > 0
           && candidate.position.column >= glyph.clip_left
           && candidate.position.column + candidate.columns == glyph.clip_right ) {
        column = candidate.position.column;
      }
    }
    point.column = column;
  }
  // In a one-cell viewport a wide glyph is clipped entirely. Its cursor occupies
  // the blank fallback cell, never paints half of the character.
  const auto width = point.column == glyph.position.column
                       ? std::min<std::int64_t>( std::max( 1, glyph.columns ), glyph.clip_right - glyph.clip_left )
                       : 1;
  if ( point.column < glyph.clip_left || point.column >= glyph.clip_right
       || point.column + width > glyph.clip_right ) {
    return std::nullopt;
  }
  return point;
}

std::vector<HorizontalScroll> DocumentLayout::reveal( const DisplayPosition& position ) const
{
  const auto& glyph = cursor_glyph( position );
  auto column = glyph.position.column;
  const auto width = std::max( 1, glyph.columns );
  std::vector<HorizontalScroll> result;
  for ( const auto& window : glyph.scrolls ) {
    const auto delta
      = column < window.left
          ? column - window.left
          : std::max<std::int64_t>(
              0, column + std::min<std::int64_t>( width, window.width ) - window.left - window.width );
    const auto offset = std::clamp( window.offset + delta, std::int64_t { 0 }, window.maximum );
    if ( offset != window.offset ) {
      result.push_back( { window.block, static_cast<std::size_t>( offset ) } );
      column -= offset - window.offset;
    }
  }
  return result;
}

std::vector<HorizontalScroll> DocumentLayout::pan( const DisplayPosition& position, int direction ) const
{
  for ( const auto& window : cursor_glyph( position ).scrolls ) {
    if ( window.maximum > 0 ) {
      const auto offset = std::clamp( window.offset + direction, std::int64_t { 0 }, window.maximum );
      if ( offset == window.offset ) {
        return {};
      }
      return { { window.block, static_cast<std::size_t>( offset ) } };
    }
  }
  return {};
}

DocumentRange DocumentLayout::unit( const DisplayPosition& position ) const
{
  const auto reading = reading_position( position );
  if ( !reading.at_start ) {
    return { position.point, position.point };
  }
  return data_.glyphs[stops_[reading.index]].source;
}

void DocumentLayout::append_frame( Frame& frame,
                                   std::size_t first_row,
                                   CellPoint origin,
                                   ScreenSize viewport,
                                   const DocumentText& content,
                                   std::optional<DocumentRange> selection,
                                   const DisplayPosition& cursor,
                                   std::optional<HitTarget> focus ) const
{
  const auto selected = selection ? content.offsets( *selection ) : ByteRange {};
  const auto caret = cursor_cell( cursor );
  for ( const auto& glyph : data_.glyphs ) {
    if ( glyph.position.row < first_row
         || glyph.position.row - first_row >= static_cast<std::size_t>( std::max( 0, viewport.rows ) ) ) {
      continue;
    }
    bool highlighted = false;
    if ( selection && !glyph.decoration && !glyph.boundary_only ) {
      const auto bytes = content.offsets( glyph.source );
      highlighted = bytes.start < selected.end && selected.start < bytes.end;
      // A control border has an object position but contributes no decoration to copy.
      if ( bytes.start == bytes.end && std::holds_alternative<ObjectPosition>( glyph.source.start ) ) {
        highlighted = selected.start <= bytes.start && bytes.start < selected.end;
      }
    }
    const bool newline = glyph.line_break && highlighted;
    if ( glyph.text.empty() && !newline ) {
      continue;
    }
    auto style = glyph.style;
    style.strong = style.strong || ( focus && glyph.target == focus );
    const auto left = std::max<std::int64_t>( 0, glyph.clip_left );
    const auto right = std::min<std::int64_t>( viewport.columns, glyph.clip_right );
    const auto row = origin.row + static_cast<int>( glyph.position.row - first_row );
    const bool at_cursor = caret && caret->row == glyph.position.row && caret->column >= glyph.position.column
                           && caret->column < glyph.position.column + std::max( 1, glyph.columns );
    if ( glyph.fill ) {
      // Expanded tabs are many blank cells but keep a single source range/hit unit.
      for ( auto column = std::max( left, glyph.position.column );
            column < std::min( right, glyph.position.column + glyph.columns );
            ++column ) {
        frame.glyphs.push_back( { .position = { row, origin.column + static_cast<int>( column ) },
                                  .text = L" ",
                                  .style = style,
                                  .selected = highlighted,
                                  .cursor = at_cursor && column == caret->column } );
      }
    } else if ( glyph.position.column >= left
                && glyph.position.column + ( newline ? 1 : glyph.columns ) <= right ) {
      frame.glyphs.push_back( { .position = { row, origin.column + static_cast<int>( glyph.position.column ) },
                                .width = newline ? 1 : glyph.columns,
                                .text = newline ? L" " : glyph.text,
                                .style = style,
                                .selected = highlighted,
                                .cursor = at_cursor } );
    }
  }
}

} // namespace ricochet::tui::detail