Model.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibGUI/AbstractView.h>
  7. #include <LibGUI/Model.h>
  8. namespace GUI {
  9. Model::Model()
  10. {
  11. }
  12. Model::~Model()
  13. {
  14. }
  15. void Model::register_view(Badge<AbstractView>, AbstractView& view)
  16. {
  17. m_views.set(&view);
  18. m_clients.set(&view);
  19. }
  20. void Model::unregister_view(Badge<AbstractView>, AbstractView& view)
  21. {
  22. m_views.remove(&view);
  23. m_clients.remove(&view);
  24. }
  25. void Model::for_each_view(Function<void(AbstractView&)> callback)
  26. {
  27. for (auto* view : m_views)
  28. callback(*view);
  29. }
  30. void Model::did_update(unsigned flags)
  31. {
  32. for (auto* client : m_clients)
  33. client->model_did_update(flags);
  34. }
  35. ModelIndex Model::create_index(int row, int column, const void* data) const
  36. {
  37. return ModelIndex(*this, row, column, const_cast<void*>(data));
  38. }
  39. ModelIndex Model::index(int row, int column, const ModelIndex&) const
  40. {
  41. return create_index(row, column);
  42. }
  43. bool Model::accepts_drag(const ModelIndex&, const Vector<String>&) const
  44. {
  45. return false;
  46. }
  47. void Model::register_client(ModelClient& client)
  48. {
  49. m_clients.set(&client);
  50. }
  51. void Model::unregister_client(ModelClient& client)
  52. {
  53. m_clients.remove(&client);
  54. }
  55. RefPtr<Core::MimeData> Model::mime_data(const ModelSelection& selection) const
  56. {
  57. auto mime_data = Core::MimeData::construct();
  58. RefPtr<Gfx::Bitmap> bitmap;
  59. StringBuilder text_builder;
  60. StringBuilder data_builder;
  61. bool first = true;
  62. selection.for_each_index([&](auto& index) {
  63. auto text_data = index.data();
  64. if (!first)
  65. text_builder.append(", ");
  66. text_builder.append(text_data.to_string());
  67. if (!first)
  68. data_builder.append('\n');
  69. auto data = index.data(ModelRole::MimeData);
  70. data_builder.append(data.to_string());
  71. first = false;
  72. if (!bitmap) {
  73. Variant icon_data = index.data(ModelRole::Icon);
  74. if (icon_data.is_icon())
  75. bitmap = icon_data.as_icon().bitmap_for_size(32);
  76. }
  77. });
  78. mime_data->set_data(drag_data_type(), data_builder.to_byte_buffer());
  79. mime_data->set_text(text_builder.to_string());
  80. if (bitmap)
  81. mime_data->set_data("image/x-raw-bitmap", bitmap->serialize_to_byte_buffer());
  82. return mime_data;
  83. }
  84. }