RegularEditingEngine.cpp 1.5 KB

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