HistoryModel.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * Copyright (c) 2022, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "HistoryModel.h"
  7. #include <AK/FuzzyMatch.h>
  8. namespace Browser {
  9. void HistoryModel::set_items(Vector<URLTitlePair> items)
  10. {
  11. begin_insert_rows({}, m_entries.size(), m_entries.size());
  12. m_entries = move(items);
  13. end_insert_rows();
  14. did_update(DontInvalidateIndices);
  15. }
  16. void HistoryModel::clear_items()
  17. {
  18. begin_insert_rows({}, m_entries.size(), m_entries.size());
  19. m_entries.clear();
  20. end_insert_rows();
  21. did_update(DontInvalidateIndices);
  22. }
  23. int HistoryModel::row_count(GUI::ModelIndex const& index) const
  24. {
  25. if (!index.is_valid())
  26. return m_entries.size();
  27. return 0;
  28. }
  29. ErrorOr<String> HistoryModel::column_name(int column) const
  30. {
  31. switch (column) {
  32. case Column::Title:
  33. return "Title"_string;
  34. case Column::URL:
  35. return "URL"_string;
  36. default:
  37. VERIFY_NOT_REACHED();
  38. }
  39. return String {};
  40. }
  41. GUI::ModelIndex HistoryModel::index(int row, int column, GUI::ModelIndex const&) const
  42. {
  43. if (static_cast<size_t>(row) < m_entries.size())
  44. return create_index(row, column, &m_entries.at(row));
  45. return {};
  46. }
  47. GUI::Variant HistoryModel::data(GUI::ModelIndex const& index, GUI::ModelRole role) const
  48. {
  49. if (role != GUI::ModelRole::Display)
  50. return {};
  51. auto const& history_entry = m_entries[index.row()];
  52. switch (index.column()) {
  53. case Column::Title:
  54. return history_entry.title;
  55. case Column::URL:
  56. return history_entry.url.serialize();
  57. }
  58. VERIFY_NOT_REACHED();
  59. }
  60. GUI::Model::MatchResult HistoryModel::data_matches(GUI::ModelIndex const& index, GUI::Variant const& term) const
  61. {
  62. auto needle = term.as_string();
  63. if (needle.is_empty())
  64. return { TriState::True };
  65. auto const& history_entry = m_entries[index.row()];
  66. auto haystack = ByteString::formatted("{} {}", history_entry.title, history_entry.url.serialize());
  67. auto match_result = fuzzy_match(needle, haystack);
  68. if (match_result.score > 0)
  69. return { TriState::True, match_result.score };
  70. return { TriState::False };
  71. }
  72. }