-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcpptui.hpp
More file actions
19324 lines (17179 loc) · 676 KB
/
cpptui.hpp
File metadata and controls
19324 lines (17179 loc) · 676 KB
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
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#pragma once
#ifdef _WIN32
#define NOMINMAX
#include <windows.h>
#include <conio.h>
#else
#include <termios.h>
#include <unistd.h>
#include <sys/ioctl.h>
#endif
#include <iostream>
#include <string>
#include <vector>
#include <functional>
#include <chrono>
#include <thread>
#include <memory>
#include <sstream>
#include <csignal>
#include <deque>
#include <regex>
#include <fstream>
#include <cstdlib>
#include <cmath>
#include <iomanip>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <filesystem>
#include <atomic>
#include <optional>
namespace cpptui
{
class App;
class Dialog;
/// @brief Unique identifier for scheduled timer callbacks
struct TimerId
{
int id; ///< The unique ID of the timer
/// @brief Compare two TimerIds for equality
bool operator==(const TimerId &other) const { return id == other.id; }
/// @brief Compare two TimerIds for inequality
bool operator!=(const TimerId &other) const { return id != other.id; }
};
/// @brief Rectangle geometry used for layout, bounds checking, and clipping
struct Rect
{
int x; ///< X coordinate of the top-left corner
int y; ///< Y coordinate of the top-left corner
int width; ///< Width of the rectangle
int height; ///< Height of the rectangle
/// @brief Check if a point is contained within the rectangle
/// @param px X coordinate of the point
/// @param py Y coordinate of the point
/// @return true if the point is inside, false otherwise
bool contains(int px, int py) const
{
return px >= x && px < x + width && py >= y && py < y + height;
}
/// @brief Calculate the intersection with another rectangle
/// @param other The other rectangle
/// @return A new Rect representing the intersection area
Rect intersect(const Rect &other) const
{
int nx = std::max(x, other.x);
int ny = std::max(y, other.y);
int nw = std::min(x + width, other.x + other.width) - nx;
int nh = std::min(y + height, other.y + other.height) - ny;
if (nw < 0)
nw = 0;
if (nh < 0)
nh = 0;
return {nx, ny, nw, nh};
}
};
constexpr int VERSION_MAJOR = 1;
constexpr int VERSION_MINOR = 3;
constexpr int VERSION_PATCH = 1;
inline std::string version()
{
return std::to_string(VERSION_MAJOR) + "." +
std::to_string(VERSION_MINOR) + "." +
std::to_string(VERSION_PATCH);
}
inline volatile std::sig_atomic_t g_resize_pending = 0;
inline void handle_winch(int sig)
{
g_resize_pending = 1;
}
inline std::function<void()> quit_app;
// ========================================================================
// UTF-8 and Wide Character Utilities
// ========================================================================
/// @brief Helper structure containing pre-processed character information
struct CharInfo
{
std::string content; ///< The UTF-8 string content of the character
int display_width; ///< The display width (0, 1, or 2)
};
/// @brief Centralized helper for text manipulation, UTF-8 processing, and selection logic
struct TextHelper
{
/// @brief Decode a UTF-8 character from a string
static bool utf8_decode_codepoint(const std::string &s, size_t pos, uint32_t &out_codepoint, int &out_len)
{
if (pos >= s.size())
return false;
unsigned char c = static_cast<unsigned char>(s[pos]);
if ((c & 0x80) == 0)
{
out_codepoint = c;
out_len = 1;
}
else if ((c & 0xE0) == 0xC0)
{
if (pos + 1 >= s.size())
return false;
out_codepoint = (c & 0x1F) << 6;
out_codepoint |= (static_cast<unsigned char>(s[pos + 1]) & 0x3F);
out_len = 2;
}
else if ((c & 0xF0) == 0xE0)
{
if (pos + 2 >= s.size())
return false;
out_codepoint = (c & 0x0F) << 12;
out_codepoint |= (static_cast<unsigned char>(s[pos + 1]) & 0x3F) << 6;
out_codepoint |= (static_cast<unsigned char>(s[pos + 2]) & 0x3F);
out_len = 3;
}
else if ((c & 0xF8) == 0xF0)
{
if (pos + 3 >= s.size())
return false;
out_codepoint = (c & 0x07) << 18;
out_codepoint |= (static_cast<unsigned char>(s[pos + 1]) & 0x3F) << 12;
out_codepoint |= (static_cast<unsigned char>(s[pos + 2]) & 0x3F) << 6;
out_codepoint |= (static_cast<unsigned char>(s[pos + 3]) & 0x3F);
out_len = 4;
}
else
{
out_codepoint = c;
out_len = 1;
}
return true;
}
/// @brief Get display width of a codepoint
static int char_display_width(uint32_t codepoint)
{
if (codepoint == 0 || codepoint < 0x20 || codepoint == 0x7F || (codepoint >= 0x80 && codepoint < 0xA0))
return 0;
if (codepoint == 0x00AD)
return 0; // Soft hyphen
// Combining marks
if ((codepoint >= 0x0300 && codepoint <= 0x036F) || (codepoint >= 0x1AB0 && codepoint <= 0x1AFF) ||
(codepoint >= 0x1DC0 && codepoint <= 0x1DFF) || (codepoint >= 0x20D0 && codepoint <= 0x20FF) ||
(codepoint >= 0xFE20 && codepoint <= 0xFE2F))
return 0;
// Explicit Narrow Overrides for ambiguous symbols often used as icons
// Checkmark (2713), Ballot X (2717), Warning Sign (26A0)
if (codepoint == 0x2713 || codepoint == 0x2717 || codepoint == 0x26A0)
return 1;
// Zero-width
if ((codepoint >= 0x200B && codepoint <= 0x200F) || (codepoint >= 0x2028 && codepoint <= 0x202F) ||
(codepoint >= 0x2060 && codepoint <= 0x206F) || codepoint == 0xFEFF)
return 0;
if ((codepoint >= 0xFE00 && codepoint <= 0xFE0F) || (codepoint >= 0xE0100 && codepoint <= 0xE01EF))
return 0;
// Wide characters
if ((codepoint >= 0x4E00 && codepoint <= 0x9FFF) || (codepoint >= 0x3400 && codepoint <= 0x4DBF) ||
(codepoint >= 0x20000 && codepoint <= 0x2A6DF) || (codepoint >= 0x2A700 && codepoint <= 0x2B73F) ||
(codepoint >= 0x2B740 && codepoint <= 0x2B81F) || (codepoint >= 0x2B820 && codepoint <= 0x2CEAF) ||
(codepoint >= 0x2CEB0 && codepoint <= 0x2EBEF) || (codepoint >= 0x30000 && codepoint <= 0x3134F) ||
(codepoint >= 0xF900 && codepoint <= 0xFAFF) || (codepoint >= 0x2F800 && codepoint <= 0x2FA1F) ||
(codepoint >= 0xFF01 && codepoint <= 0xFF60) || (codepoint >= 0xFFE0 && codepoint <= 0xFFE6) ||
(codepoint >= 0xAC00 && codepoint <= 0xD7AF) || (codepoint >= 0x1100 && codepoint <= 0x11FF) ||
(codepoint >= 0x3130 && codepoint <= 0x318F) || (codepoint >= 0xA960 && codepoint <= 0xA97F) ||
(codepoint >= 0xD7B0 && codepoint <= 0xD7FF) || (codepoint >= 0x3040 && codepoint <= 0x309F) ||
(codepoint >= 0x30A0 && codepoint <= 0x30FF) || (codepoint >= 0x31F0 && codepoint <= 0x31FF) ||
(codepoint >= 0x3000 && codepoint <= 0x303F) || (codepoint >= 0x3200 && codepoint <= 0x32FF) ||
(codepoint >= 0x3300 && codepoint <= 0x33FF) || (codepoint >= 0xFE30 && codepoint <= 0xFE4F) ||
(codepoint >= 0x1F300 && codepoint <= 0x1F9FF) || (codepoint >= 0x1FA00 && codepoint <= 0x1FAFF) ||
(codepoint >= 0x2600 && codepoint <= 0x26FF) || (codepoint >= 0x2700 && codepoint <= 0x27BF))
{
return 2;
}
return 1;
}
/// @brief Calculate total display width of a string
static int utf8_display_width(const std::string &s)
{
int width = 0;
size_t pos = 0;
while (pos < s.size())
{
uint32_t codepoint;
int len;
if (utf8_decode_codepoint(s, pos, codepoint, len))
{
width += char_display_width(codepoint);
pos += len;
}
else
{
pos++;
}
}
return width;
}
/// @brief Check if a codepoint is a word character
static bool is_word_char(uint32_t cp)
{
if (cp == '_')
return true;
if (cp >= 'a' && cp <= 'z')
return true;
if (cp >= 'A' && cp <= 'Z')
return true;
if (cp >= '0' && cp <= '9')
return true;
if (cp >= 0x4E00 && cp <= 0x9FFF)
return true;
return false;
}
/// @brief Pre-process text into characters for rendering
static std::vector<CharInfo> prepare_text_for_render(const std::string &text)
{
std::vector<CharInfo> chars;
size_t pos = 0;
while (pos < text.size())
{
uint32_t codepoint;
int byte_len;
if (utf8_decode_codepoint(text, pos, codepoint, byte_len))
{
CharInfo ci;
ci.content = text.substr(pos, byte_len);
ci.display_width = char_display_width(codepoint);
if (ci.display_width < 0)
ci.display_width = 0;
chars.push_back(ci);
pos += byte_len;
}
else
{
pos++;
}
}
return chars;
}
/// @brief Convert visual X to character index
static int visual_to_char_pos(const std::vector<CharInfo> &chars, int visual_x)
{
int current_vx = 0;
for (size_t i = 0; i < chars.size(); ++i)
{
int cw = chars[i].display_width;
if (current_vx + cw / 2 >= visual_x)
return (int)i;
current_vx += cw;
}
return (int)chars.size();
}
/// @brief Convert character index to byte offset
static size_t char_to_byte_pos(const std::string &text, size_t char_idx)
{
size_t pos = 0;
size_t count = 0;
while (pos < text.size() && count < char_idx)
{
uint32_t cp;
int len;
if (utf8_decode_codepoint(text, pos, cp, len))
{
pos += len;
count++;
}
else
{
pos++;
}
}
return pos;
}
/// @brief Find word boundaries at a given character position
static void select_word_at(const std::vector<CharInfo> &chars, int pos, int &start, int &end)
{
if (pos < 0 || pos >= (int)chars.size())
{
if (pos < 0)
pos = 0;
if (pos > (int)chars.size())
pos = (int)chars.size();
start = pos;
end = pos;
return;
}
std::vector<uint32_t> codepoints;
codepoints.reserve(chars.size());
for (const auto &c : chars)
{
uint32_t cp;
int len;
utf8_decode_codepoint(c.content, 0, cp, len);
codepoints.push_back(cp);
}
if (!is_word_char(codepoints[pos]))
{
start = pos;
end = pos + 1;
return;
}
start = pos;
while (start > 0 && is_word_char(codepoints[start - 1]))
start--;
end = pos;
while (end < (int)codepoints.size() && is_word_char(codepoints[end]))
end++;
}
// --- New Helper Methods ---
/// @brief Count number of UTF-8 codepoints in a string
static size_t count_codepoints(const std::string &text)
{
size_t count = 0;
size_t pos = 0;
while (pos < text.size())
{
uint32_t cp;
int len;
if (utf8_decode_codepoint(text, pos, cp, len))
{
count++;
pos += len;
}
else
{
pos++;
}
}
return count;
}
/// @brief Safe UTF-8 substring
static std::string utf8_substr(const std::string &text, size_t start_char_idx, size_t count = std::string::npos)
{
size_t byte_start = char_to_byte_pos(text, start_char_idx);
if (count == std::string::npos)
{
return text.substr(byte_start);
}
size_t byte_end = char_to_byte_pos(text, start_char_idx + count);
return text.substr(byte_start, byte_end - byte_start);
}
/// @brief Find word boundaries (generic string version)
static void find_word_boundaries(const std::string &text, int char_idx, int &start, int &end)
{
auto chars = prepare_text_for_render(text);
select_word_at(chars, char_idx, start, end);
}
};
/// @brief Reusable helper for managing text selection state
struct SelectionState
{
int start = -1;
int end = -1;
bool mouse_down = false;
int drag_start_idx = -1;
bool inclusive_drag = true; // Default to inclusive (Border/Label style)
int click_count = 0;
std::chrono::steady_clock::time_point last_click_time;
int last_click_idx = -1;
/// @brief reset selection
void clear()
{
start = -1;
end = -1;
mouse_down = false;
drag_start_idx = -1;
}
/// @brief check if selection is active and valid
bool has_selection() const
{
return start != -1 && end != -1 && start < end;
}
/// @brief check if a specific character index is selected
bool is_selected(int idx) const
{
return has_selection() && idx >= start && idx < end;
}
/// @brief Handle mouse press event
/// @return true if event handled (selection started)
bool handle_mouse_press(const std::vector<CharInfo> &chars, int char_idx)
{
auto now = std::chrono::steady_clock::now();
auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(now - last_click_time).count();
if (diff < 500 && last_click_idx == char_idx)
{
click_count++;
if (click_count == 2)
{
// Double click - Select word
int s = 0, e = 0;
TextHelper::select_word_at(chars, char_idx, s, e);
start = s;
end = e;
drag_start_idx = end; // Anchor for drag extension
mouse_down = true;
}
else if (click_count == 3)
{
// Triple click - Select All
start = 0;
end = (int)chars.size();
drag_start_idx = end;
mouse_down = true;
}
else
{
// Reset to single click behavior if > 3
click_count = 1;
mouse_down = true;
drag_start_idx = char_idx;
start = char_idx;
end = char_idx;
}
}
else
{
click_count = 1;
mouse_down = true;
drag_start_idx = char_idx;
start = char_idx;
end = char_idx;
}
last_click_time = now;
last_click_idx = char_idx;
return true;
}
/// @brief Handle mouse drag event
bool handle_mouse_drag(int char_idx)
{
if (mouse_down)
{
start = std::min(drag_start_idx, char_idx);
end = std::max(drag_start_idx, char_idx);
if (inclusive_drag)
end += 1; // Inclusive of currently dragged-over char
return true;
}
return false;
}
/// @brief Handle mouse release
bool handle_mouse_release()
{
if (mouse_down)
{
mouse_down = false;
return true;
}
return false;
}
/// @brief Get selected text
std::string get_selected_text(const std::vector<CharInfo> &chars) const
{
if (!has_selection())
return "";
std::string res;
for (int i = start; i < end && i < (int)chars.size(); ++i)
{
res += chars[i].content;
}
return res;
}
};
// Backward compatibility wrappers
inline bool utf8_decode_codepoint(const std::string &s, size_t pos, uint32_t &out_codepoint, int &out_len)
{
return TextHelper::utf8_decode_codepoint(s, pos, out_codepoint, out_len);
}
inline int char_display_width(uint32_t codepoint)
{
return TextHelper::char_display_width(codepoint);
}
inline int utf8_display_width(const std::string &s)
{
return TextHelper::utf8_display_width(s);
}
inline bool is_word_char(uint32_t cp)
{
return TextHelper::is_word_char(cp);
}
inline int utf8_char_byte_length(const std::string &s, size_t pos)
{
// Helper to determine char byte length
unsigned char c = static_cast<unsigned char>(s[pos]);
if ((c & 0x80) == 0)
return 1;
if ((c & 0xE0) == 0xC0)
return 2;
if ((c & 0xF0) == 0xE0)
return 3;
if ((c & 0xF8) == 0xF0)
return 4;
return 1;
}
inline std::vector<CharInfo> prepare_text_for_render(const std::string &text)
{
return TextHelper::prepare_text_for_render(text);
}
/// @brief Base64 encoding for clipboard operations (OSC 52)
/// @param input The string to encode
/// @return Base64 encoded string
inline std::string base64_encode(const std::string &input)
{
static const char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string output;
output.reserve(((input.size() + 2) / 3) * 4);
size_t i = 0;
while (i < input.size())
{
uint32_t octet_a = i < input.size() ? (unsigned char)input[i++] : 0;
uint32_t octet_b = i < input.size() ? (unsigned char)input[i++] : 0;
uint32_t octet_c = i < input.size() ? (unsigned char)input[i++] : 0;
uint32_t triple = (octet_a << 16) + (octet_b << 8) + octet_c;
output.push_back(table[(triple >> 18) & 0x3F]);
output.push_back(table[(triple >> 12) & 0x3F]);
output.push_back((i > input.size() + 1) ? '=' : table[(triple >> 6) & 0x3F]);
output.push_back((i > input.size()) ? '=' : table[triple & 0x3F]);
}
return output;
}
/// @brief Internal clipboard buffer for fallback operation
inline std::string g_internal_clipboard = "";
/// @brief Copy text to system clipboard using native methods and OSC 52 fallback
inline void copy_to_clipboard(const std::string &text)
{
if (text.empty())
return;
// Always save to internal clipboard first
g_internal_clipboard = text;
bool success = false;
#ifdef _WIN32
// Windows: clip command
FILE *pipe = _popen("clip", "w");
if (pipe)
{
fwrite(text.c_str(), 1, text.size(), pipe);
_pclose(pipe);
success = true;
}
#else
// Linux: Try common clipboard utilities
// 1. wl-copy (Wayland)
if (std::getenv("WAYLAND_DISPLAY"))
{
FILE *pipe = popen("wl-copy", "w");
if (pipe)
{
fwrite(text.c_str(), 1, text.size(), pipe);
pclose(pipe);
success = true;
}
}
// 2. xclip (X11)
if (!success)
{
FILE *pipe = popen("xclip -selection clipboard -i 2>/dev/null", "w");
if (pipe)
{
fwrite(text.c_str(), 1, text.size(), pipe);
if (pclose(pipe) == 0)
success = true;
}
}
// 3. xsel (X11 fallback)
if (!success)
{
FILE *pipe = popen("xsel -b -i 2>/dev/null", "w");
if (pipe)
{
fwrite(text.c_str(), 1, text.size(), pipe);
if (pclose(pipe) == 0)
success = true;
}
}
#endif
// Always use OSC 52 as a reliable fallback for remote terminals / SSH
std::string encoded = base64_encode(text);
// OSC 52 ; c ; <base64> BEL
std::cout << "\033]52;c;" << encoded << "\x07" << std::flush;
}
/// @brief Retrieve text from system clipboard using native tools
/// @return The string content of the clipboard, or empty if failed
inline std::string paste_from_clipboard()
{
std::string result;
bool success = false;
char buffer[128];
#ifdef _WIN32
// Windows: clip is write-only. Use powershell as a fallback for standard windows terminals.
// Try powershell as fallback for standard windows terminals
FILE *pipe = _popen("powershell.exe -NoProfile -Command Get-Clipboard", "r");
if (pipe)
{
while (fgets(buffer, sizeof(buffer), pipe) != NULL)
{
result += buffer;
}
_pclose(pipe);
// Remove trailing newline often added by powershell
if (!result.empty() && result.back() == '\n')
result.pop_back();
if (!result.empty() && result.back() == '\r')
result.pop_back();
success = true;
}
#else
// Linux: Try common clipboard utilities
// 1. wl-paste (Wayland)
if (!success && std::getenv("WAYLAND_DISPLAY"))
{
FILE *pipe = popen("wl-paste --no-newline 2>/dev/null", "r");
if (pipe)
{
while (fgets(buffer, sizeof(buffer), pipe) != NULL)
{
result += buffer;
success = true;
}
pclose(pipe);
}
}
// 2. xclip (X11)
if (!success)
{
FILE *pipe = popen("xclip -selection clipboard -o 2>/dev/null", "r");
if (pipe)
{
while (fgets(buffer, sizeof(buffer), pipe) != NULL)
{
result += buffer;
success = true;
}
if (pclose(pipe) == 0)
success = true; // Only mark success if exit code 0
else
result.clear(); // Clear if command failed
}
}
// 3. xsel (X11 fallback)
if (!success)
{
FILE *pipe = popen("xsel -b -o 2>/dev/null", "r");
if (pipe)
{
while (fgets(buffer, sizeof(buffer), pipe) != NULL)
{
result += buffer;
success = true;
}
if (pclose(pipe) == 0)
success = true;
else
result.clear();
}
}
#endif
// Fallback to internal clipboard if system clipboard failed or returned nothing
if (!success || result.empty())
{
return g_internal_clipboard;
}
return result;
}
/// @brief alignment options for text and widgets
enum class Alignment
{
Left, ///< Align to the left
Center, ///< Align to the center
Right ///< Align to the right
};
/// @brief Types of events that can occur
enum class EventType
{
None, ///< No event
Key, ///< Keyboard key press
Mouse, ///< Mouse movement or click
Resize, ///< Terminal resize
Quit, ///< Application quit request
Paste ///< Paste from clipboard (bracketed paste)
};
/// @brief Represents an input event (keyboard, mouse, or system)
struct Event
{
EventType type = EventType::None; ///< The type of event
int key = 0; ///< ASCII or Key code for Key events
int x = 0; ///< X coordinate for Mouse events
int y = 0; ///< Y coordinate for Mouse events
int button = -1; ///< Raw button code for Mouse events
std::string paste_text; ///< Text content for Paste events
// Helpers for standard 1003 mouse tracking encoding
bool mouse_left() const { return (button & 3) == 0 && (button & 64) == 0; }
bool mouse_middle() const { return (button & 3) == 1 && (button & 64) == 0; }
bool mouse_right() const { return (button & 3) == 2 && (button & 64) == 0; }
bool mouse_release() const { return (button & 3) == 3; }
bool mouse_motion() const { return (button & 32) != 0; }
bool mouse_drag() const { return mouse_motion() && !mouse_release(); }
bool mouse_move() const { return mouse_motion() && mouse_release(); }
bool mouse_wheel() const { return (button & 64) != 0; } // Bit 6 typically indicates mouse wheel events
bool shift = false; ///< True if Shift modifier is active
bool ctrl = false; ///< True if Ctrl modifier is active
bool alt = false; ///< True if Alt modifier is active
/// @brief Check if the event is a copy command
bool is_copy() const
{
return (ctrl && shift && (key == 'c' || key == 'C')) ||
(ctrl && (key == 'c' || key == 'C' || key == 3));
}
bool is_cut() const
{
return (ctrl && shift && (key == 'x' || key == 'X')) ||
(ctrl && (key == 'x' || key == 'X' || key == 24));
}
bool is_paste() const
{
return (ctrl && shift && (key == 'v' || key == 'V')) ||
(ctrl && (key == 'v' || key == 'V' || key == 22));
}
bool is_select_all() const { return ctrl && (key == 'a' || key == 1); }
bool is_undo() const
{
return (ctrl && !shift && (key == 'z' || key == 'Z' || key == 26));
}
bool is_redo() const
{
return (ctrl && shift && (key == 'z' || key == 'Z')) ||
(ctrl && !shift && (key == 'y' || key == 'Y' || key == 25));
}
bool is_enter() const { return key == 10 || key == 13; }
bool is_tab() const { return key == 9; }
bool is_backspace() const { return key == 8 || key == 127; }
bool is_delete() const { return key == 1005; }
bool is_nav_up() const { return key == 1065; }
bool is_nav_down() const { return key == 1066; }
bool is_nav_left() const { return key == 1068; }
bool is_nav_right() const { return key == 1067; }
bool is_nav_home() const { return key == 1003; }
bool is_nav_end() const { return key == 1004; }
bool is_nav_pgup() const { return key == 1001; }
bool is_nav_pgdn() const { return key == 1002; }
bool is_insert() const { return key == 1006; }
// Helpers for read-only view scrolling (includes '5', '6', Delete, Insert)
bool is_view_scroll_up() const { return is_nav_pgup() || is_delete() || key == 53; }
bool is_view_scroll_down() const { return is_nav_pgdn() || is_insert() || key == 54; }
// Type checking helpers
bool is_key_event() const { return type == EventType::Key; }
bool is_mouse_event() const { return type == EventType::Mouse; }
// Additional key helpers
bool is_space() const { return key == ' ' || key == 32; }
bool is_escape() const { return key == 27; }
bool is_activate() const { return is_enter() || is_space(); }
bool is_printable() const { return (unsigned char)key >= 32 && key != 127 && key < 1000; }
// Mouse wheel direction helpers
bool mouse_wheel_up() const { return button == 64; }
bool mouse_wheel_down() const { return button == 65; }
// Navigation combo helpers (for list/grid navigation)
bool is_nav_prev() const { return is_nav_up() || is_nav_left(); }
bool is_nav_next() const { return is_nav_down() || is_nav_right(); }
};
/// @brief Represents an RGB color
struct Color
{
uint8_t r = 255, g = 255, b = 255;
bool is_default = true; ///< If true, uses the terminal's default color
Color() = default;
Color(uint8_t r, uint8_t g, uint8_t b, bool is_default = false)
: r(r), g(g), b(b), is_default(is_default) {}
static Color White() { return {255, 255, 255, false}; }
static Color Black() { return {0, 0, 0, false}; }
static Color Red() { return {255, 0, 0, false}; }
static Color Green() { return {0, 255, 0, false}; }
static Color Blue() { return {0, 0, 255, false}; }
static Color Yellow() { return {255, 255, 0, false}; }
static Color Cyan() { return {0, 255, 255, false}; }
static Color Magenta() { return {255, 0, 255, false}; }
bool operator==(const Color &other) const
{
if (is_default && other.is_default)
return true;
return r == other.r && g == other.g && b == other.b && is_default == other.is_default;
}
bool operator!=(const Color &other) const { return !(*this == other); }
/// @brief Returns this color if not default, otherwise returns the fallback
/// @param fallback The color to use if this color is_default
/// @return This color or fallback
Color resolve(const Color &fallback) const
{
return is_default ? fallback : *this;
}
/// @brief Calculate optimal contrasting text color (black or white) for a background
/// Uses relative luminance formula for accessibility
/// @param bg The background color
/// @return Black or White, whichever provides better contrast
static Color contrast_color(const Color &bg)
{
// Proper sRGB to linear conversion with gamma correction
auto srgb_to_linear = [](double c) -> double
{
if (c <= 0.04045)
return c / 12.92;
return std::pow((c + 0.055) / 1.055, 2.4);
};
double r_lin = srgb_to_linear(bg.r / 255.0);
double g_lin = srgb_to_linear(bg.g / 255.0);
double b_lin = srgb_to_linear(bg.b / 255.0);
// Relative luminance formula (ITU-R BT.709)
double luminance = 0.2126 * r_lin + 0.7152 * g_lin + 0.0722 * b_lin;
// Return black for light backgrounds, white for dark backgrounds
// Threshold of 0.4 provides better contrast for mid-tone colors
return luminance > 0.4 ? Black() : White();
}
/// @brief Convert HSV to RGB color
/// @param h Hue (0.0 - 1.0)
/// @param s Saturation (0.0 - 1.0)
/// @param v Value/brightness (0.0 - 1.0)
/// @return RGB Color
static Color hsv_to_rgb(float h, float s, float v)
{
int i = (int)(h * 6);
float f = h * 6 - i;
float p = v * (1 - s);
float q = v * (1 - f * s);
float t = v * (1 - (1 - f) * s);
float r = 0, g = 0, b = 0;
switch (i % 6)
{
case 0:
r = v;
g = t;
b = p;
break;
case 1:
r = q;
g = v;
b = p;
break;
case 2:
r = p;
g = v;
b = t;
break;
case 3:
r = p;
g = q;
b = v;
break;
case 4:
r = t;
g = p;
b = v;
break;
case 5:
r = v;
g = p;
b = q;
break;
}
return Color{(uint8_t)(r * 255), (uint8_t)(g * 255), (uint8_t)(b * 255)};
}
/// @brief Convert RGB to HSV
/// @param c The RGB color
/// @param h Output: Hue (0.0 - 1.0)
/// @param s Output: Saturation (0.0 - 1.0)
/// @param v Output: Value/brightness (0.0 - 1.0)
static void rgb_to_hsv(const Color &c, float &h, float &s, float &v)
{
float r = c.r / 255.0f;
float g = c.g / 255.0f;
float b = c.b / 255.0f;
float max_c = std::max({r, g, b});
float min_c = std::min({r, g, b});
float delta = max_c - min_c;
v = max_c;
if (delta < 0.00001f)
{
s = 0;
h = 0;
return;
}
s = (max_c > 0.0f) ? (delta / max_c) : 0.0f;
if (r >= max_c)
{
h = (g - b) / delta;
}
else if (g >= max_c)