selection_model.cc 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "ui/gfx/selection_model.h"
  5. #include <ostream>
  6. #include "base/check.h"
  7. #include "base/format_macros.h"
  8. #include "base/strings/stringprintf.h"
  9. namespace gfx {
  10. SelectionModel::SelectionModel()
  11. : selection_(0),
  12. caret_affinity_(CURSOR_BACKWARD) {}
  13. SelectionModel::SelectionModel(size_t position, LogicalCursorDirection affinity)
  14. : selection_(position),
  15. caret_affinity_(affinity) {}
  16. SelectionModel::SelectionModel(const Range& selection,
  17. LogicalCursorDirection affinity)
  18. : selection_(selection),
  19. caret_affinity_(affinity) {}
  20. SelectionModel::SelectionModel(const std::vector<Range>& selections,
  21. LogicalCursorDirection affinity)
  22. : selection_(selections[0]), caret_affinity_(affinity) {
  23. for (size_t i = 1; i < selections.size(); ++i)
  24. AddSecondarySelection(selections[i]);
  25. }
  26. SelectionModel::SelectionModel(const SelectionModel& selection_model) = default;
  27. SelectionModel::~SelectionModel() = default;
  28. void SelectionModel::AddSecondarySelection(const Range& selection) {
  29. for (auto s : GetAllSelections())
  30. DCHECK(!selection.Intersects(s));
  31. secondary_selections_.push_back(selection);
  32. }
  33. std::vector<Range> SelectionModel::GetAllSelections() const {
  34. std::vector<Range> selections = {selection()};
  35. selections.insert(selections.end(), secondary_selections_.begin(),
  36. secondary_selections_.end());
  37. return selections;
  38. }
  39. bool SelectionModel::operator==(const SelectionModel& sel) const {
  40. return selection() == sel.selection() &&
  41. caret_affinity() == sel.caret_affinity() &&
  42. secondary_selections() == sel.secondary_selections();
  43. }
  44. std::string SelectionModel::ToString() const {
  45. std::string str = "{";
  46. if (selection().is_empty())
  47. base::StringAppendF(&str, "%" PRIuS, caret_pos());
  48. else
  49. str += selection().ToString();
  50. const bool backward = caret_affinity() == CURSOR_BACKWARD;
  51. str += (backward ? ",BACKWARD" : ",FORWARD");
  52. for (auto selection : secondary_selections()) {
  53. str += ",";
  54. if (selection.is_empty())
  55. base::StringAppendF(&str, "%" PRIuS, selection.end());
  56. else
  57. str += selection.ToString();
  58. }
  59. return str + "}";
  60. }
  61. std::ostream& operator<<(std::ostream& out, const SelectionModel& model) {
  62. out << model.ToString();
  63. return out;
  64. }
  65. } // namespace gfx