WidgetTreeModel.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include "WidgetTreeModel.h"
  2. #include <AK/StringBuilder.h>
  3. #include <LibGUI/GWidget.h>
  4. #include <stdio.h>
  5. WidgetTreeModel::WidgetTreeModel(GWidget& root)
  6. : m_root(root)
  7. {
  8. m_widget_icon.set_bitmap_for_size(16, GraphicsBitmap::load_from_file("/res/icons/16x16/inspector-object.png"));
  9. }
  10. WidgetTreeModel::~WidgetTreeModel()
  11. {
  12. }
  13. GModelIndex WidgetTreeModel::index(int row, int column, const GModelIndex& parent) const
  14. {
  15. if (!parent.is_valid()) {
  16. return create_index(row, column, m_root.ptr());
  17. }
  18. auto& parent_node = *static_cast<GWidget*>(parent.internal_data());
  19. return create_index(row, column, parent_node.child_widgets().at(row));
  20. }
  21. GModelIndex WidgetTreeModel::parent_index(const GModelIndex& index) const
  22. {
  23. if (!index.is_valid())
  24. return {};
  25. auto& widget = *static_cast<GWidget*>(index.internal_data());
  26. if (&widget == m_root.ptr())
  27. return {};
  28. if (widget.parent_widget() == m_root.ptr())
  29. return create_index(0, 0, m_root.ptr());
  30. // Walk the grandparent's children to find the index of widget's parent in its parent.
  31. // (This is needed to produce the row number of the GModelIndex corresponding to widget's parent.)
  32. int grandparent_child_index = 0;
  33. for (auto& grandparent_child : widget.parent_widget()->parent_widget()->child_widgets()) {
  34. if (grandparent_child == widget.parent_widget())
  35. return create_index(grandparent_child_index, 0, widget.parent_widget());
  36. ++grandparent_child_index;
  37. }
  38. ASSERT_NOT_REACHED();
  39. return {};
  40. }
  41. int WidgetTreeModel::row_count(const GModelIndex& index) const
  42. {
  43. if (!index.is_valid())
  44. return 1;
  45. auto& widget = *static_cast<GWidget*>(index.internal_data());
  46. return widget.child_widgets().size();
  47. }
  48. int WidgetTreeModel::column_count(const GModelIndex&) const
  49. {
  50. return 1;
  51. }
  52. GVariant WidgetTreeModel::data(const GModelIndex& index, Role role) const
  53. {
  54. auto* widget = static_cast<GWidget*>(index.internal_data());
  55. if (role == Role::Icon) {
  56. return m_widget_icon;
  57. }
  58. if (role == Role::Display) {
  59. return String::format("%s (%s)", widget->class_name(), widget->relative_rect().to_string().characters());
  60. }
  61. return {};
  62. }
  63. void WidgetTreeModel::update()
  64. {
  65. did_update();
  66. }