Serenity Operating System
1/*
2 * Copyright (c) 2020, the SerenityOS developers.
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7#include <AK/QuickSort.h>
8#include <LibGUI/RegularEditingEngine.h>
9#include <LibGUI/TextEditor.h>
10
11namespace GUI {
12
13CursorWidth RegularEditingEngine::cursor_width() const
14{
15 return CursorWidth::NARROW;
16}
17
18bool RegularEditingEngine::on_key(KeyEvent const& event)
19{
20 if (EditingEngine::on_key(event))
21 return true;
22
23 if (event.key() == KeyCode::Key_Escape) {
24 if (m_editor->on_escape_pressed)
25 m_editor->on_escape_pressed();
26 return true;
27 }
28
29 if (event.alt() && event.shift() && event.key() == KeyCode::Key_S) {
30 sort_selected_lines();
31 return true;
32 }
33
34 return false;
35}
36
37static int strcmp_utf32(u32 const* s1, u32 const* s2, size_t n)
38{
39 while (n-- > 0) {
40 if (*s1++ != *s2++)
41 return s1[-1] < s2[-1] ? -1 : 1;
42 }
43 return 0;
44}
45
46void RegularEditingEngine::sort_selected_lines()
47{
48 if (!m_editor->is_editable())
49 return;
50
51 if (!m_editor->has_selection())
52 return;
53
54 size_t first_line;
55 size_t last_line;
56 get_selection_line_boundaries(first_line, last_line);
57
58 auto& lines = m_editor->document().lines();
59
60 auto start = lines.begin() + (int)first_line;
61 auto end = lines.begin() + (int)last_line + 1;
62
63 quick_sort(start, end, [](auto& a, auto& b) {
64 return strcmp_utf32(a->code_points(), b->code_points(), min(a->length(), b->length())) < 0;
65 });
66
67 m_editor->did_change();
68 m_editor->update();
69}
70
71}