URLBox.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * Copyright (c) 2023, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <Applications/Browser/URLBox.h>
  7. #include <LibGfx/Palette.h>
  8. #include <LibGfx/TextAttributes.h>
  9. #include <LibURL/URL.h>
  10. #include <LibWebView/URL.h>
  11. namespace Browser {
  12. URLBox::URLBox()
  13. {
  14. set_auto_focusable(false);
  15. on_change = [this] {
  16. highlight_url();
  17. };
  18. }
  19. void URLBox::focusout_event(GUI::FocusEvent& event)
  20. {
  21. set_focus_transition(true);
  22. highlight_url();
  23. GUI::TextBox::focusout_event(event);
  24. }
  25. void URLBox::focusin_event(GUI::FocusEvent& event)
  26. {
  27. highlight_url();
  28. GUI::TextBox::focusin_event(event);
  29. }
  30. void URLBox::mousedown_event(GUI::MouseEvent& event)
  31. {
  32. if (is_displayonly())
  33. return;
  34. if (event.button() != GUI::MouseButton::Primary)
  35. return;
  36. if (is_focus_transition()) {
  37. GUI::TextBox::select_current_line();
  38. set_focus_transition(false);
  39. } else {
  40. GUI::TextBox::mousedown_event(event);
  41. }
  42. }
  43. void URLBox::highlight_url()
  44. {
  45. Vector<GUI::TextDocumentSpan> spans;
  46. if (auto url_parts = WebView::break_url_into_parts(text()); url_parts.has_value()) {
  47. Gfx::TextAttributes dark_attributes;
  48. dark_attributes.color = palette().color(Gfx::ColorRole::PlaceholderText);
  49. Gfx::TextAttributes highlight_attributes;
  50. highlight_attributes.color = palette().color(Gfx::ColorRole::BaseText);
  51. spans.append({
  52. { { 0, 0 }, { 0, url_parts->scheme_and_subdomain.length() } },
  53. dark_attributes,
  54. });
  55. spans.append({
  56. { { 0, url_parts->scheme_and_subdomain.length() }, { 0, url_parts->scheme_and_subdomain.length() + url_parts->effective_tld_plus_one.length() } },
  57. highlight_attributes,
  58. });
  59. spans.append({
  60. {
  61. { 0, url_parts->scheme_and_subdomain.length() + url_parts->effective_tld_plus_one.length() },
  62. { 0, url_parts->scheme_and_subdomain.length() + url_parts->effective_tld_plus_one.length() + url_parts->remainder.length() },
  63. },
  64. dark_attributes,
  65. });
  66. }
  67. document().set_spans(0, move(spans));
  68. update();
  69. }
  70. }