-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
868 lines (758 loc) · 35.7 KB
/
Copy pathmain.cpp
File metadata and controls
868 lines (758 loc) · 35.7 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
#include <nfd.h>
#include <SFML/Graphics.hpp>
#include "src/GapBuffer.h"
#include "src/UI.h"
#include "src/Scrollbar.h"
#include "src/TextRenderer.h"
#include "src/FileOperations.h"
#include "src/InputHandler.h"
#include "src/SearchDialog.h"
#include "src/StatusBar.h"
#include <iostream>
#include <cmath>
int main() {
const float TOP_MARGIN = 50.0f;
const float SCROLL_PADDING = 10.f;
const float DRAG_THRESHOLD = 5.0f;
const sf::Time CURSOR_BLINK_INTERVAL = sf::milliseconds(500);
sf::RenderWindow window(sf::VideoMode({800, 1000}), "Text Editor");
std::string currentFileName = "Untitled";
bool unsavedChanges = false;
bool showCloseConfirm = false;
auto updateWindowTitle = [&]() {
if (unsavedChanges) {
window.setTitle("Text Editor - " + currentFileName + " *");
} else {
window.setTitle("Text Editor - " + currentFileName);
}
};
updateWindowTitle();
sf::View uiView = window.getDefaultView();
sf::View textView = window.getDefaultView();
window.setFramerateLimit(60);
sf::Font font;
if (!font.openFromFile("fonts/Roboto.ttf")) return 1;
// ── Theme ────────────────────────────────────────────────────────────────
Theme theme; // starts dark
sf::Text text(font);
text.setCharacterSize(24);
text.setFillColor(sf::Color::White);
text.setPosition({0, TOP_MARGIN});
sf::RectangleShape cursor(sf::Vector2f(2, 24));
cursor.setFillColor(sf::Color::White);
GapBuffer gapBuffer;
Scrollbar scrollbar(SCROLL_PADDING);
SearchDialog searchDialog(font);
StatusBar statusBar(font, static_cast<float>(window.getSize().x));
DropdownMenu fileMenu(font, "File", sf::Vector2f(10, 10), {
{"New", "Ctrl+N"},
{"Open", "Ctrl+O"},
{"Save", "Ctrl+S"},
{"Save As", ""},
{"Exit", ""},
});
// Search button (next to the File dropdown)
Button searchBtn(font);
searchBtn.shape.setSize(sf::Vector2f(80.f, 30.f));
searchBtn.shape.setFillColor(sf::Color(50, 50, 50));
searchBtn.shape.setPosition(sf::Vector2f(75.f, 10.f));
searchBtn.text.setString("Search");
searchBtn.text.setCharacterSize(15);
searchBtn.text.setFillColor(sf::Color::White);
{
sf::FloatRect tb = searchBtn.text.getLocalBounds();
searchBtn.text.setPosition(sf::Vector2f(
75.f + (80.f - tb.size.x) / 2.f - tb.position.x,
10.f + (30.f - tb.size.y) / 2.f - tb.position.y
));
}
// Theme toggle button
Button themeToggle(font);
themeToggle.shape.setSize(sf::Vector2f(90.f, 30.f));
themeToggle.shape.setFillColor(sf::Color(50, 50, 50));
themeToggle.shape.setPosition(sf::Vector2f(160.f, 10.f));
themeToggle.text.setString("Light");
themeToggle.text.setCharacterSize(15);
themeToggle.text.setFillColor(sf::Color::White);
{
sf::FloatRect tb = themeToggle.text.getLocalBounds();
themeToggle.text.setPosition(sf::Vector2f(
160.f + (90.f - tb.size.x) / 2.f - tb.position.x,
10.f + (30.f - tb.size.y) / 2.f - tb.position.y
));
}
// applyTheme must be defined after text, cursor, fileMenu, scrollbar are all declared
auto applyTheme = [&]() {
text.setFillColor(theme.textColor());
cursor.setFillColor(theme.cursorColor());
fileMenu.applyTheme(theme);
scrollbar.applyTheme(theme.isDark);
};
auto updateThemeToggleAppearance = [&]() {
themeToggle.text.setString(theme.isDark ? "Light" : "Dark");
themeToggle.shape.setFillColor(theme.btnNormal());
themeToggle.text.setFillColor(theme.textColor());
// Re-center text after string change
sf::FloatRect tb = themeToggle.text.getLocalBounds();
themeToggle.text.setPosition(sf::Vector2f(
160.f + (90.f - tb.size.x) / 2.f - tb.position.x,
10.f + (30.f - tb.size.y) / 2.f - tb.position.y
));
};
updateThemeToggleAppearance();
// Apply initial theme
applyTheme();
// Sync button colors with initial theme
searchBtn.shape.setFillColor(theme.btnNormal());
searchBtn.text.setFillColor(theme.textColor());
Button textSize(font);
textSize.shape.setFillColor(theme.btnNormal());
textSize.text.setFillColor(theme.textColor());
textSize.shape.setSize(sf::Vector2f(140, 30));
textSize.shape.setFillColor(sf::Color(50, 50, 50));
textSize.text.setFont(font);
textSize.text.setCharacterSize(18);
textSize.text.setFillColor(sf::Color::White);
// Helper function to update text size button position
auto updateTextSizeButtonPosition = [&]() {
float xPos = static_cast<float>(window.getSize().x) - 152.f; // 140 width + 12 scrollbar
textSize.shape.setPosition(sf::Vector2f(xPos, 10));
textSize.text.setPosition(sf::Vector2f(xPos + 10, 12));
};
updateTextSizeButtonPosition();
auto performSave = [&]() {
std::string savedFile;
//Save as
if (currentFileName == "Untitled") {
savedFile = saveToFile(gapBuffer, "");
}
else {
savedFile = saveToFile(gapBuffer, currentFileName);
}
if (!savedFile.empty()) {
currentFileName = savedFile;
unsavedChanges = false;
updateWindowTitle();
}
};
bool cursorVisible = true;
sf::Clock cursorBlinkClock;
MouseState mouseState = MouseState::Idle;
sf::Vector2i mousePressPos;
int selectionAnchor = -1;
std::string clipboard = ""; // Internal clipboard storage
// --- File operation helpers ---
auto performNew = [&]() {
gapBuffer.clear();
currentFileName = "Untitled";
unsavedChanges = false;
selectionAnchor = -1;
scrollbar.setScrollOffset(0.f);
updateWindowTitle();
};
auto performSaveAs = [&]() {
std::string savedFile = saveToFile(gapBuffer, "");
if (!savedFile.empty()) {
currentFileName = savedFile;
unsavedChanges = false;
updateWindowTitle();
}
};
auto performOpen = [&]() {
std::string loadedFile = loadFromFile(gapBuffer);
if (!loadedFile.empty()) {
currentFileName = loadedFile;
unsavedChanges = false;
updateWindowTitle();
}
};
// Search highlight
sf::RectangleShape searchHighlight;
searchHighlight.setFillColor(sf::Color(255, 255, 0, 100)); // Yellow highlight
while (window.isOpen()) {
bool cursorMovedThisFrame = false;
while (const std::optional<sf::Event> event = window.pollEvent()) {
// Block input when the modal is open
if (showCloseConfirm) {
if (const auto* mouseEvent = event->getIf<sf::Event::MouseButtonPressed>()) {
sf::Vector2f mousePos(
static_cast<float>(mouseEvent->position.x),
static_cast<float>(mouseEvent->position.y)
);
sf::FloatRect yesBounds(
sf::Vector2f(window.getSize().x / 2.f - 110.f,
window.getSize().y / 2.f + 30.f),
sf::Vector2f(80.f, 35.f)
);
sf::FloatRect noBounds(
sf::Vector2f(window.getSize().x / 2.f + 30.f,
window.getSize().y / 2.f + 30.f),
sf::Vector2f(80.f, 35.f)
);
if (yesBounds.contains(mousePos)) {
window.close();
}
if (noBounds.contains(mousePos)) {
showCloseConfirm = false;
}
}
continue;
}
if (event->is<sf::Event::Closed>()) {
if (unsavedChanges) {
showCloseConfirm = true;
} else {
window.close();
}
}
if (const auto* resizeEvent = event->getIf<sf::Event::Resized>()) {
// Resize both views
sf::Vector2f newSize(static_cast<float>(resizeEvent->size.x),
static_cast<float>(resizeEvent->size.y));
uiView.setSize(newSize);
uiView.setCenter(newSize / 2.f);
textView.setSize(newSize);
textView.setCenter(newSize / 2.f);
// Update text size button position to stay anchored to right
updateTextSizeButtonPosition();
// Update status bar width
statusBar.setWidth(newSize.x);
// Update search dialog position
searchDialog.setPosition(newSize);
}
// Handle search dialog input when it's visible
if (searchDialog.getIsVisible()) {
if (const auto* textEvent = event->getIf<sf::Event::TextEntered>()) {
if (textEvent->unicode < 128 && textEvent->unicode != '\b' &&
textEvent->unicode != 127 && textEvent->unicode != 27) {
searchDialog.handleTextInput(static_cast<char>(textEvent->unicode));
searchDialog.updateSearch(gapBuffer.getString());
cursorMovedThisFrame = true;
}
}
if (const auto* keyEvent = event->getIf<sf::Event::KeyPressed>()) {
if (keyEvent->code == sf::Keyboard::Key::Backspace) {
searchDialog.handleBackspace();
searchDialog.updateSearch(gapBuffer.getString());
}
else if (keyEvent->code == sf::Keyboard::Key::Enter) {
// Treat Enter the same as F3 (next match)
searchDialog.handleKeyPress(sf::Keyboard::Key::F3);
}
else {
searchDialog.handleKeyPress(keyEvent->code);
}
// Move cursor to current match
if (searchDialog.hasMatches()) {
gapBuffer.moveTo(searchDialog.getCurrentMatchPosition());
cursorMovedThisFrame = true;
}
}
// Skip normal text input handling when search is open
continue;
}
if (const auto* textEvent = event->getIf<sf::Event::TextEntered>()) {
if (textEvent->unicode < 128 && textEvent->unicode != '\b' &&
textEvent->unicode != 127) {
// If there's a selection, delete it first before inserting
if (selectionAnchor != -1) {
int cursorPos = static_cast<int>(gapBuffer.getGapStart());
int start = std::min(selectionAnchor, cursorPos);
int end = std::max(selectionAnchor, cursorPos);
gapBuffer.deleteRange(start, end);
unsavedChanges = true;
updateWindowTitle();
selectionAnchor = -1;
}
gapBuffer.insert(static_cast<char>(textEvent->unicode));
unsavedChanges = true;
updateWindowTitle();
cursorMovedThisFrame = true;
}
}
if (const auto* keyEvent = event->getIf<sf::Event::KeyPressed>()) {
bool ctrlOrCmd = sf::Keyboard::isKeyPressed(sf::Keyboard::Key::LControl) ||
sf::Keyboard::isKeyPressed(sf::Keyboard::Key::RControl) ||
sf::Keyboard::isKeyPressed(sf::Keyboard::Key::LSystem);
bool shiftPressed = sf::Keyboard::isKeyPressed(sf::Keyboard::Key::LShift) ||
sf::Keyboard::isKeyPressed(sf::Keyboard::Key::RShift);
if (keyEvent->code == sf::Keyboard::Key::Left) {
if (shiftPressed) {
// Start selection if not already active
if (selectionAnchor == -1) {
selectionAnchor = gapBuffer.getGapStart();
}
} else {
// Clear selection if not holding shift
selectionAnchor = -1;
}
gapBuffer.moveLeft();
cursorMovedThisFrame = true;
}
if (keyEvent->code == sf::Keyboard::Key::Right) {
if (shiftPressed) {
// Start selection if not already active
if (selectionAnchor == -1) {
selectionAnchor = gapBuffer.getGapStart();
}
} else {
// Clear selection if not holding shift
selectionAnchor = -1;
}
gapBuffer.moveRight();
cursorMovedThisFrame = true;
}
if (keyEvent->code == sf::Keyboard::Key::Backspace) {
if (selectionAnchor != -1) {
// Delete the selection
int cursorPos = static_cast<int>(gapBuffer.getGapStart());
int start = std::min(selectionAnchor, cursorPos);
int end = std::max(selectionAnchor, cursorPos);
gapBuffer.deleteRange(start, end);
unsavedChanges = true;
updateWindowTitle();
selectionAnchor = -1;
} else {
// Normal backspace
gapBuffer.backspace();
unsavedChanges = true;
updateWindowTitle();
}
cursorMovedThisFrame = true;
}
if (keyEvent->code == sf::Keyboard::Key::Delete) {
if (selectionAnchor != -1) {
// Delete the selection
int cursorPos = static_cast<int>(gapBuffer.getGapStart());
int start = std::min(selectionAnchor, cursorPos);
int end = std::max(selectionAnchor, cursorPos);
gapBuffer.deleteRange(start, end);
unsavedChanges = true;
updateWindowTitle();
selectionAnchor = -1;
} else {
// Delete character at cursor position
int cursorPos = gapBuffer.getGapStart();
std::string currentText = gapBuffer.getString();
if (cursorPos < static_cast<int>(currentText.length())) {
gapBuffer.deleteRange(cursorPos, cursorPos + 1);
unsavedChanges = true;
updateWindowTitle();
}
}
cursorMovedThisFrame = true;
}
if (keyEvent->code == sf::Keyboard::Key::S && ctrlOrCmd) {
bool shiftPressed = sf::Keyboard::isKeyPressed(sf::Keyboard::Key::LShift) ||
sf::Keyboard::isKeyPressed(sf::Keyboard::Key::RShift);
if (shiftPressed) {
// Force Save As regardless of current file
performSaveAs();
} else {
performSave();
}
}
if (keyEvent->code == sf::Keyboard::Key::N && ctrlOrCmd) {
performNew();
}
if (keyEvent->code == sf::Keyboard::Key::O && ctrlOrCmd) {
performOpen();
}
if (keyEvent->code == sf::Keyboard::Key::Equal && ctrlOrCmd) {
text.setCharacterSize(text.getCharacterSize() + 1);
updateCursorSize(cursor, font, text.getCharacterSize());
}
if (keyEvent->code == sf::Keyboard::Key::Hyphen && ctrlOrCmd) {
if (text.getCharacterSize() >= 6) {
text.setCharacterSize(text.getCharacterSize() - 1);
updateCursorSize(cursor, font, text.getCharacterSize());
}
}
// Search
if (keyEvent->code == sf::Keyboard::Key::F && ctrlOrCmd) {
searchDialog.show();
searchDialog.setPosition(sf::Vector2f(window.getSize().x, window.getSize().y));
// Update search with current text to restore previous matches
searchDialog.updateSearch(gapBuffer.getString());
}
// Clipboard operations
if (keyEvent->code == sf::Keyboard::Key::A && ctrlOrCmd) {
// Select All
selectionAnchor = 0;
gapBuffer.moveTo(gapBuffer.getString().length());
cursorMovedThisFrame = true;
}
if (keyEvent->code == sf::Keyboard::Key::C && ctrlOrCmd) {
// Copy
if (selectionAnchor != -1) {
int cursorPos = static_cast<int>(gapBuffer.getGapStart());
int start = std::min(selectionAnchor, cursorPos);
int end = std::max(selectionAnchor, cursorPos);
clipboard = gapBuffer.getRange(start, end);
sf::Clipboard::setString(clipboard); // Also set system clipboard
}
}
if (keyEvent->code == sf::Keyboard::Key::X && ctrlOrCmd) {
// Cut
if (selectionAnchor != -1) {
int cursorPos = static_cast<int>(gapBuffer.getGapStart());
int start = std::min(selectionAnchor, cursorPos);
int end = std::max(selectionAnchor, cursorPos);
clipboard = gapBuffer.getRange(start, end);
sf::Clipboard::setString(clipboard); // Also set system clipboard
gapBuffer.deleteRange(start, end);
unsavedChanges = true;
updateWindowTitle();
selectionAnchor = -1;
cursorMovedThisFrame = true;
}
}
if (keyEvent->code == sf::Keyboard::Key::V && ctrlOrCmd) {
// Paste
// Try system clipboard first, fall back to internal clipboard
std::string textToPaste = sf::Clipboard::getString().toAnsiString();
if (textToPaste.empty()) {
textToPaste = clipboard;
}
if (!textToPaste.empty()) {
// If there's a selection, delete it first
if (selectionAnchor != -1) {
int cursorPos = static_cast<int>(gapBuffer.getGapStart());
int start = std::min(selectionAnchor, cursorPos);
int end = std::max(selectionAnchor, cursorPos);
gapBuffer.deleteRange(start, end);
unsavedChanges = true;
updateWindowTitle();
selectionAnchor = -1;
}
gapBuffer.insertString(textToPaste);
unsavedChanges = true;
updateWindowTitle();
cursorMovedThisFrame = true;
}
}
}
if (const auto* mouseEvent = event->getIf<sf::Event::MouseButtonPressed>()) {
if (mouseEvent->button == sf::Mouse::Button::Left) {
float windowWidth = static_cast<float>(window.getSize().x);
sf::Vector2f uiPos(static_cast<float>(mouseEvent->position.x),
static_cast<float>(mouseEvent->position.y));
// Check if clicking on the scrollbar area
if (mouseEvent->position.x >= windowWidth - 12) {
sf::FloatRect textBounds = text.getGlobalBounds();
scrollbar.handleMousePress(mouseEvent->position, window.getSize(),
textBounds, TOP_MARGIN);
mouseState = MouseState::ScrollbarDragging;
}
// Check if theme toggle was clicked
else if (themeToggle.shape.getGlobalBounds().contains(uiPos)) {
theme.isDark = !theme.isDark;
applyTheme();
updateThemeToggleAppearance();
// Update search/text buttons too
searchBtn.shape.setFillColor(theme.btnNormal());
searchBtn.text.setFillColor(theme.textColor());
textSize.shape.setFillColor(theme.btnNormal());
textSize.text.setFillColor(theme.textColor());
}
// Check if the search button was clicked
else if (searchBtn.shape.getGlobalBounds().contains(uiPos)) {
searchDialog.show();
searchDialog.setPosition(sf::Vector2f(window.getSize().x, window.getSize().y));
searchDialog.updateSearch(gapBuffer.getString());
}
// Check if the file menu (button or open panel) was clicked
else if (fileMenu.containsPoint(uiPos)) {
// 0=New 1=Open 2=Save 3=Save As 4=Exit
int item = fileMenu.handleClick(uiPos);
if (item == 0) { performNew(); }
else if (item == 1) { performOpen(); }
else if (item == 2) { performSave(); }
else if (item == 3) { performSaveAs(); }
else if (item == 4) {
if (unsavedChanges) { showCloseConfirm = true; }
else { window.close(); }
}
}
// Close an open dropdown when clicking anywhere else
else {
if (fileMenu.isOpen()) {
fileMenu.close();
}
mouseState = MouseState::Pressed;
mousePressPos = mouseEvent->position;
// Clicking in text area
handleMouseClick(sf::Vector2i(mouseEvent->position.x,mouseEvent->position.y), gapBuffer, text,
window, textView);
selectionAnchor = gapBuffer.getGapStart();
}
}
}
if (const auto* moveEvent = event->getIf<sf::Event::MouseMoved>()) {
// Always update dropdown hover state
fileMenu.handleHover(sf::Vector2f(
static_cast<float>(moveEvent->position.x),
static_cast<float>(moveEvent->position.y)));
// Hover tint for search button
sf::Vector2f mp(static_cast<float>(moveEvent->position.x),
static_cast<float>(moveEvent->position.y));
searchBtn.shape.setFillColor(
searchBtn.shape.getGlobalBounds().contains(mp)
? theme.btnHover()
: theme.btnNormal());
searchBtn.text.setFillColor(theme.textColor());
themeToggle.shape.setFillColor(
themeToggle.shape.getGlobalBounds().contains(mp)
? theme.btnHover()
: theme.btnNormal());
if (mouseState == MouseState::ScrollbarDragging) {
sf::FloatRect textBounds = text.getGlobalBounds();
scrollbar.handleMouseMove(moveEvent->position, window.getSize(), textBounds);
}
else if (mouseState == MouseState::Pressed) {
sf::Vector2f delta(
moveEvent->position.x - mousePressPos.x,
moveEvent->position.y - mousePressPos.y
);
if (std::hypot(delta.x, delta.y) > DRAG_THRESHOLD) {
mouseState = MouseState::Dragging;
}
}
else if (mouseState == MouseState::Dragging) {
// Convert mouse → text coords
sf::Vector2f worldPos = window.mapPixelToCoords(moveEvent->position, textView);
int bestIndex = -1;
float bestDistance = std::numeric_limits<float>::max();
for (size_t i = 0; i <= text.getString().getSize(); i++) {
sf::Vector2f charPos = text.findCharacterPos(i);
float charHeight = text.getCharacterSize();
if (worldPos.y >= charPos.y && worldPos.y < charPos.y + charHeight) {
float dist = std::abs(worldPos.x - charPos.x);
if (dist < bestDistance) {
bestDistance = dist;
bestIndex = static_cast<int>(i);
}
}
}
if (bestIndex != -1) {
gapBuffer.moveTo(bestIndex);
}
cursorMovedThisFrame = true;
}
}
if (const auto* mouseEvent = event->getIf<sf::Event::MouseButtonReleased>()) {
if (mouseEvent->button == sf::Mouse::Button::Left) {
if (mouseState == MouseState::Pressed) {
selectionAnchor = -1;
}
if (mouseState == MouseState::ScrollbarDragging) {
scrollbar.handleMouseRelease();
}
mouseState = MouseState::Idle;
}
}
if (const auto* scrollEvent = event->getIf<sf::Event::MouseWheelScrolled>()) {
if (scrollEvent->wheel == sf::Mouse::Wheel::Vertical) {
float delta = scrollEvent->delta * 30.f;
scrollbar.setScrollOffset(scrollbar.getScrollOffset() - delta);
}
}
}
// Vertical arrow key handling with repeat
static sf::Clock verticalMoveClock;
static bool verticalKeyHeld = false;
const sf::Time initialDelay = sf::milliseconds(250);
const sf::Time repeatDelay = sf::milliseconds(60);
bool upHeld = sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Up);
bool downHeld = sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Down);
if (upHeld || downHeld) {
if (!verticalKeyHeld) {
moveCursorVertical(gapBuffer, text, font, downHeld);
cursorMovedThisFrame = true;
verticalMoveClock.restart();
verticalKeyHeld = true;
} else {
sf::Time elapsed = verticalMoveClock.getElapsedTime();
sf::Time needed = (elapsed < initialDelay) ? initialDelay : repeatDelay;
if (elapsed >= needed) {
moveCursorVertical(gapBuffer, text, font, downHeld);
cursorMovedThisFrame = true;
verticalMoveClock.restart();
}
}
} else {
verticalKeyHeld = false;
}
// Update search dialog
searchDialog.update();
// Cursor blinking logic
if (cursorMovedThisFrame) {
cursorVisible = true;
cursorBlinkClock.restart();
}
if (cursorBlinkClock.getElapsedTime() >= CURSOR_BLINK_INTERVAL) {
cursorVisible = !cursorVisible;
cursorBlinkClock.restart();
}
// Update text display with word wrapping
float textAreaWidth = static_cast<float>(window.getSize().x) - 25.f;
DisplayState state = wrapText(gapBuffer, text, textAreaWidth);
text.setString(state.content);
// Update cursor position
cursor.setPosition(text.findCharacterPos(state.cursorIndex));
sf::Vector2f cursorPos = cursor.getPosition();
float cursorHeight = cursor.getSize().y;
// Draw search highlight (must be after wrapText + textView)
if (searchDialog.getIsVisible() && searchDialog.hasMatches()) {
int matchPos = static_cast<int>(searchDialog.getCurrentMatchPosition());
int matchLen = static_cast<int>(searchDialog.getMatchLength());
sf::Vector2f startPos = text.findCharacterPos(matchPos);
sf::Vector2f endPos = text.findCharacterPos(matchPos + matchLen);
searchHighlight.setPosition(startPos);
searchHighlight.setSize(sf::Vector2f(
std::max(2.f, endPos.x - startPos.x),
static_cast<float>(text.getCharacterSize())
));
window.draw(searchHighlight);
}
// Auto-scroll to cursor
if (cursorMovedThisFrame) {
float windowHeight = static_cast<float>(window.getSize().y);
float topVisible = scrollbar.getScrollOffset() + TOP_MARGIN;
float bottomVisible = scrollbar.getScrollOffset() + windowHeight - SCROLL_PADDING;
if (cursorPos.y < topVisible) {
scrollbar.setScrollOffset(cursorPos.y - TOP_MARGIN);
} else if (cursorPos.y + cursorHeight > bottomVisible) {
scrollbar.setScrollOffset((cursorPos.y + cursorHeight) - windowHeight + SCROLL_PADDING);
}
}
// Clamp scroll to valid range
sf::FloatRect textBounds = text.getGlobalBounds();
scrollbar.clampScroll(window.getSize(), textBounds);
// Update UI
statusBar.update(gapBuffer, unsavedChanges, selectionAnchor, text.getCharacterSize());
window.clear(theme.windowBg());
// Set text view with scroll offset
textView.setCenter(
sf::Vector2f(
static_cast<float>(window.getSize().x) / 2.f,
(static_cast<float>(window.getSize().y) / 2.f) + scrollbar.getScrollOffset()
)
);
window.setView(textView);
// Draw selection highlighting
drawSelection(window, text, font, selectionAnchor, gapBuffer.getGapStart());
// Draw search result highlighting
if (searchDialog.hasMatches() && searchDialog.getIsVisible()) {
size_t rawMatchPos = searchDialog.getCurrentMatchPosition();
size_t rawMatchLen = searchDialog.getMatchLength();
// Convert raw buffer positions to display positions (accounting for word wrap)
size_t displayMatchPos = mapRawToDisplay(gapBuffer.getString(), rawMatchPos, text, textAreaWidth);
size_t displayMatchEnd = mapRawToDisplay(gapBuffer.getString(), rawMatchPos + rawMatchLen, text, textAreaWidth);
// Draw highlight for each character in the match
for (size_t i = displayMatchPos; i < displayMatchEnd; i++) {
sf::Vector2f charPos = text.findCharacterPos(i);
sf::Vector2f nextCharPos = text.findCharacterPos(i + 1);
float width = nextCharPos.x - charPos.x;
float height = text.getCharacterSize();
if (nextCharPos.y != charPos.y || width <= 0) {
width = 10.f; // Fallback width for newlines
}
searchHighlight.setPosition(charPos);
searchHighlight.setSize(sf::Vector2f(width, height));
window.draw(searchHighlight);
}
}
// Draw text and cursor
window.draw(text);
if (cursorVisible && !searchDialog.getIsVisible()) {
window.draw(cursor);
}
// Switch to UI view for drawing UI elements
window.setView(uiView);
// Draw scrollbar
scrollbar.draw(window, textBounds, TOP_MARGIN);
// Draw header background
sf::RectangleShape headerBg(sf::Vector2f(static_cast<float>(window.getSize().x), TOP_MARGIN));
headerBg.setFillColor(theme.headerBg());
window.draw(headerBg);
// Draw file dropdown menu (drawn last so it appears on top of the header)
fileMenu.draw(window);
// Draw search button
window.draw(searchBtn.shape);
window.draw(searchBtn.text);
// Draw theme toggle button
window.draw(themeToggle.shape);
window.draw(themeToggle.text);
// Draw search dialog on top of everything
searchDialog.draw(window);
// Draw the modal panel if needed
if (showCloseConfirm) {
// Dark overlay
sf::RectangleShape overlay(
sf::Vector2f(window.getSize().x, window.getSize().y)
);
overlay.setFillColor(sf::Color(0, 0, 0, 150));
window.draw(overlay);
// Dialog box
sf::RectangleShape dialog(sf::Vector2f(360.f, 160.f));
dialog.setFillColor(theme.panelBg());
dialog.setOutlineThickness(2.f);
dialog.setOutlineColor(theme.textColor());
dialog.setPosition(
sf::Vector2f(window.getSize().x / 2.f - 180.f,
window.getSize().y / 2.f - 80.f)
);
window.draw(dialog);
// Message
sf::Text msg(font);
msg.setString("You have unsaved changes.\nQuit anyway?");
msg.setCharacterSize(18);
msg.setFillColor(theme.textColor());
msg.setPosition(
sf::Vector2f(dialog.getPosition().x + 20.f,
dialog.getPosition().y + 20.f)
);
window.draw(msg);
// Yes button
sf::RectangleShape yesBtn(sf::Vector2f(80.f, 35.f));
yesBtn.setFillColor(theme.btnNormal());
yesBtn.setPosition(
sf::Vector2f(dialog.getPosition().x + 70.f,
dialog.getPosition().y + 100.f)
);
window.draw(yesBtn);
sf::Text yesText(font);
yesText.setString("Yes");
yesText.setCharacterSize(16);
yesText.setFillColor(theme.textColor());
yesText.setPosition(
sf::Vector2f(yesBtn.getPosition().x + 25.f,
yesBtn.getPosition().y + 7.f)
);
window.draw(yesText);
// No button
sf::RectangleShape noBtn(sf::Vector2f(80.f, 35.f));
noBtn.setFillColor(theme.btnNormal());
noBtn.setPosition(
sf::Vector2f(dialog.getPosition().x + 210.f,
dialog.getPosition().y + 100.f)
);
window.draw(noBtn);
sf::Text noText(font);
noText.setString("No");
noText.setCharacterSize(16);
noText.setFillColor(theme.textColor());
noText.setPosition(
sf::Vector2f(noBtn.getPosition().x + 28.f,
noBtn.getPosition().y + 7.f)
);
window.draw(noText);
}
// Draw status bar at the bottom
statusBar.draw(window, theme);
window.display();
cursorMovedThisFrame = false;
}
return 0;
}