Widget.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  1. /*
  2. * Copyright (c) 2018-2023, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Assertions.h>
  8. #include <AK/Debug.h>
  9. #include <AK/IterationDecision.h>
  10. #include <AK/JsonObject.h>
  11. #include <AK/NonnullRefPtr.h>
  12. #include <AK/RefPtr.h>
  13. #include <LibGUI/Action.h>
  14. #include <LibGUI/Application.h>
  15. #include <LibGUI/BoxLayout.h>
  16. #include <LibGUI/ConnectionToWindowServer.h>
  17. #include <LibGUI/Event.h>
  18. #include <LibGUI/GML/AST.h>
  19. #include <LibGUI/GML/Parser.h>
  20. #include <LibGUI/Layout.h>
  21. #include <LibGUI/Menu.h>
  22. #include <LibGUI/Painter.h>
  23. #include <LibGUI/TabWidget.h>
  24. #include <LibGUI/Widget.h>
  25. #include <LibGUI/Window.h>
  26. #include <LibGfx/Bitmap.h>
  27. #include <LibGfx/Font/Font.h>
  28. #include <LibGfx/Font/FontDatabase.h>
  29. #include <LibGfx/Palette.h>
  30. #include <LibGfx/SystemTheme.h>
  31. #include <unistd.h>
  32. REGISTER_GUI_OBJECT(GUI, Widget)
  33. namespace GUI {
  34. Widget::Widget()
  35. : m_background_role(Gfx::ColorRole::Window)
  36. , m_foreground_role(Gfx::ColorRole::WindowText)
  37. , m_font(Gfx::FontDatabase::default_font())
  38. , m_palette(Application::the()->palette().impl())
  39. {
  40. REGISTER_READONLY_STRING_PROPERTY("class_name", class_name);
  41. REGISTER_DEPRECATED_STRING_PROPERTY("name", name, set_name);
  42. register_property(
  43. "address"sv, [this] { return FlatPtr(this); },
  44. nullptr, nullptr);
  45. register_property(
  46. "parent"sv, [this] { return FlatPtr(this->parent()); },
  47. nullptr, nullptr);
  48. REGISTER_RECT_PROPERTY("relative_rect", relative_rect, set_relative_rect);
  49. REGISTER_BOOL_PROPERTY("fill_with_background_color", fill_with_background_color, set_fill_with_background_color);
  50. REGISTER_BOOL_PROPERTY("visible", is_visible, set_visible);
  51. REGISTER_BOOL_PROPERTY("focused", is_focused, set_focus);
  52. REGISTER_BOOL_PROPERTY("enabled", is_enabled, set_enabled);
  53. REGISTER_STRING_PROPERTY("tooltip", tooltip, set_tooltip);
  54. REGISTER_UI_SIZE_PROPERTY("min_size", min_size, set_min_size);
  55. REGISTER_READONLY_UI_SIZE_PROPERTY("effective_min_size", effective_min_size);
  56. REGISTER_UI_SIZE_PROPERTY("max_size", max_size, set_max_size);
  57. REGISTER_UI_SIZE_PROPERTY("preferred_size", preferred_size, set_preferred_size);
  58. REGISTER_READONLY_UI_SIZE_PROPERTY("effective_preferred_size", effective_preferred_size);
  59. REGISTER_INT_PROPERTY("width", width, set_width);
  60. REGISTER_UI_DIMENSION_PROPERTY("min_width", min_width, set_min_width);
  61. REGISTER_UI_DIMENSION_PROPERTY("max_width", max_width, set_max_width);
  62. REGISTER_UI_DIMENSION_PROPERTY("preferred_width", preferred_width, set_preferred_width);
  63. REGISTER_INT_PROPERTY("height", height, set_height);
  64. REGISTER_UI_DIMENSION_PROPERTY("min_height", min_height, set_min_height);
  65. REGISTER_UI_DIMENSION_PROPERTY("max_height", max_height, set_max_height);
  66. REGISTER_UI_DIMENSION_PROPERTY("preferred_height", preferred_height, set_preferred_height);
  67. REGISTER_INT_PROPERTY("fixed_width", dummy_fixed_width, set_fixed_width);
  68. REGISTER_INT_PROPERTY("fixed_height", dummy_fixed_height, set_fixed_height);
  69. REGISTER_SIZE_PROPERTY("fixed_size", dummy_fixed_size, set_fixed_size);
  70. REGISTER_BOOL_PROPERTY("shrink_to_fit", is_shrink_to_fit, set_shrink_to_fit);
  71. REGISTER_INT_PROPERTY("x", x, set_x);
  72. REGISTER_INT_PROPERTY("y", y, set_y);
  73. REGISTER_STRING_PROPERTY("font", font_family, set_font_family);
  74. REGISTER_INT_PROPERTY("font_size", m_font->presentation_size, set_font_size);
  75. REGISTER_FONT_WEIGHT_PROPERTY("font_weight", m_font->weight, set_font_weight);
  76. REGISTER_STRING_PROPERTY("title", title, set_title);
  77. REGISTER_BOOL_PROPERTY("font_fixed_width", is_font_fixed_width, set_font_fixed_width)
  78. register_property(
  79. "font_type"sv, [this] { return m_font->is_fixed_width() ? "FixedWidth" : "Normal"; },
  80. [](JsonValue const& value) -> ErrorOr<bool> {
  81. if (value.is_string()) {
  82. auto string = value.as_string();
  83. if (string == "FixedWidth")
  84. return true;
  85. if (string == "Normal")
  86. return false;
  87. }
  88. return Error::from_string_literal("\"FixedWidth\" or \"Normal\" is expected");
  89. },
  90. [this](auto const& value) { return set_font_fixed_width(value); });
  91. REGISTER_ENUM_PROPERTY("focus_policy", focus_policy, set_focus_policy, GUI::FocusPolicy,
  92. { GUI::FocusPolicy::ClickFocus, "ClickFocus" },
  93. { GUI::FocusPolicy::NoFocus, "NoFocus" },
  94. { GUI::FocusPolicy::TabFocus, "TabFocus" },
  95. { GUI::FocusPolicy::StrongFocus, "StrongFocus" });
  96. register_property(
  97. "foreground_color"sv,
  98. [this]() { return palette().color(foreground_role()).to_byte_string(); },
  99. ::GUI::PropertyDeserializer<Color> {},
  100. [this](Gfx::Color const& color) {
  101. auto _palette = palette();
  102. _palette.set_color(foreground_role(), color);
  103. set_palette(_palette);
  104. });
  105. register_property(
  106. "background_color"sv,
  107. [this]() { return palette().color(background_role()).to_byte_string(); },
  108. ::GUI::PropertyDeserializer<Color> {},
  109. [this](Gfx::Color const& color) {
  110. set_background_color(color);
  111. });
  112. #define __ENUMERATE_COLOR_ROLE(role) \
  113. { Gfx::ColorRole::role, #role },
  114. REGISTER_ENUM_PROPERTY("foreground_role", foreground_role, set_foreground_role, Gfx::ColorRole,
  115. { Gfx::ColorRole::NoRole, "NoRole" },
  116. ENUMERATE_COLOR_ROLES(__ENUMERATE_COLOR_ROLE));
  117. REGISTER_ENUM_PROPERTY("background_role", background_role, set_background_role, Gfx::ColorRole,
  118. { Gfx::ColorRole::NoRole, "NoRole" },
  119. ENUMERATE_COLOR_ROLES(__ENUMERATE_COLOR_ROLE));
  120. #undef __ENUMERATE_COLOR_ROLE
  121. }
  122. Widget::~Widget() = default;
  123. void Widget::layout_relevant_change_occurred()
  124. {
  125. if (auto* parent = parent_widget())
  126. parent->layout_relevant_change_occurred();
  127. else if (window())
  128. window()->schedule_relayout();
  129. }
  130. void Widget::child_event(Core::ChildEvent& event)
  131. {
  132. if (event.type() == Event::ChildAdded) {
  133. if (event.child() && is<Widget>(*event.child()) && layout()) {
  134. if (event.insertion_before_child() && is<Widget>(event.insertion_before_child()))
  135. layout()->insert_widget_before(verify_cast<Widget>(*event.child()), verify_cast<Widget>(*event.insertion_before_child()));
  136. else
  137. layout()->add_widget(verify_cast<Widget>(*event.child()));
  138. layout_relevant_change_occurred();
  139. }
  140. if (window() && event.child() && is<Widget>(*event.child()))
  141. window()->did_add_widget({}, verify_cast<Widget>(*event.child()));
  142. if (event.child() && is<Widget>(*event.child()) && static_cast<Widget const&>(*event.child()).is_visible()) {
  143. ShowEvent show_event;
  144. event.child()->dispatch_event(show_event);
  145. }
  146. }
  147. if (event.type() == Event::ChildRemoved) {
  148. if (layout()) {
  149. if (event.child() && is<Widget>(*event.child()))
  150. layout()->remove_widget(verify_cast<Widget>(*event.child()));
  151. layout_relevant_change_occurred();
  152. }
  153. if (window() && event.child() && is<Widget>(*event.child()))
  154. window()->did_remove_widget({}, verify_cast<Widget>(*event.child()));
  155. if (event.child() && is<Widget>(*event.child())) {
  156. HideEvent hide_event;
  157. event.child()->dispatch_event(hide_event);
  158. }
  159. update();
  160. }
  161. return Core::EventReceiver::child_event(event);
  162. }
  163. void Widget::set_relative_rect(Gfx::IntRect const& a_rect)
  164. {
  165. // Get rid of negative width/height values.
  166. Gfx::IntRect rect = {
  167. a_rect.x(),
  168. a_rect.y(),
  169. max(a_rect.width(), 0),
  170. max(a_rect.height(), 0)
  171. };
  172. if (rect == m_relative_rect)
  173. return;
  174. auto old_rect = m_relative_rect;
  175. bool size_changed = m_relative_rect.size() != rect.size();
  176. m_relative_rect = rect;
  177. if (size_changed) {
  178. ResizeEvent resize_event(rect.size());
  179. event(resize_event);
  180. }
  181. if (auto* parent = parent_widget())
  182. parent->update(old_rect);
  183. update();
  184. }
  185. void Widget::event(Core::Event& event)
  186. {
  187. if (!is_enabled()) {
  188. switch (event.type()) {
  189. case Event::MouseUp:
  190. case Event::MouseDown:
  191. case Event::MouseMove:
  192. case Event::MouseWheel:
  193. case Event::MouseDoubleClick:
  194. case Event::KeyUp:
  195. case Event::KeyDown:
  196. return;
  197. default:
  198. break;
  199. }
  200. }
  201. switch (event.type()) {
  202. case Event::Paint:
  203. return handle_paint_event(static_cast<PaintEvent&>(event));
  204. case Event::Resize:
  205. return handle_resize_event(static_cast<ResizeEvent&>(event));
  206. case Event::FocusIn:
  207. return focusin_event(static_cast<FocusEvent&>(event));
  208. case Event::FocusOut:
  209. return focusout_event(static_cast<FocusEvent&>(event));
  210. case Event::Show:
  211. return show_event(static_cast<ShowEvent&>(event));
  212. case Event::Hide:
  213. return hide_event(static_cast<HideEvent&>(event));
  214. case Event::KeyDown:
  215. return handle_keydown_event(static_cast<KeyEvent&>(event));
  216. case Event::KeyUp:
  217. return keyup_event(static_cast<KeyEvent&>(event));
  218. case Event::MouseMove:
  219. return mousemove_event(static_cast<MouseEvent&>(event));
  220. case Event::MouseDown:
  221. return handle_mousedown_event(static_cast<MouseEvent&>(event));
  222. case Event::MouseDoubleClick:
  223. return handle_mousedoubleclick_event(static_cast<MouseEvent&>(event));
  224. case Event::MouseUp:
  225. return handle_mouseup_event(static_cast<MouseEvent&>(event));
  226. case Event::MouseWheel:
  227. return mousewheel_event(static_cast<MouseEvent&>(event));
  228. case Event::DragEnter:
  229. return drag_enter_event(static_cast<DragEvent&>(event));
  230. case Event::DragMove:
  231. return drag_move_event(static_cast<DragEvent&>(event));
  232. case Event::DragLeave:
  233. return drag_leave_event(static_cast<Event&>(event));
  234. case Event::Drop:
  235. return drop_event(static_cast<DropEvent&>(event));
  236. case Event::ThemeChange:
  237. return theme_change_event(static_cast<ThemeChangeEvent&>(event));
  238. case Event::FontsChange:
  239. return fonts_change_event(static_cast<FontsChangeEvent&>(event));
  240. case Event::Enter:
  241. return handle_enter_event(event);
  242. case Event::Leave:
  243. return handle_leave_event(event);
  244. case Event::EnabledChange:
  245. return change_event(static_cast<Event&>(event));
  246. case Event::ContextMenu:
  247. return context_menu_event(static_cast<ContextMenuEvent&>(event));
  248. case Event::AppletAreaRectChange:
  249. return applet_area_rect_change_event(static_cast<AppletAreaRectChangeEvent&>(event));
  250. default:
  251. return Core::EventReceiver::event(event);
  252. }
  253. }
  254. void Widget::handle_keydown_event(KeyEvent& event)
  255. {
  256. keydown_event(event);
  257. if (event.is_accepted())
  258. return;
  259. if (auto action = Action::find_action_for_shortcut(*this, Shortcut(event.modifiers(), event.key()))) {
  260. action->process_event(*window(), event);
  261. if (event.is_accepted())
  262. return;
  263. }
  264. if (event.key() == KeyCode::Key_Menu) {
  265. ContextMenuEvent c_event(window_relative_rect().bottom_right().translated(-1), screen_relative_rect().bottom_right().translated(-1));
  266. dispatch_event(c_event);
  267. return;
  268. }
  269. event.ignore();
  270. }
  271. void Widget::handle_paint_event(PaintEvent& event)
  272. {
  273. VERIFY(is_visible());
  274. if (!rect().intersects(event.rect())) {
  275. // This widget is not inside the paint event rect.
  276. // Since widgets fully contain their children, we don't need to recurse further.
  277. return;
  278. }
  279. if (fill_with_background_color()) {
  280. Painter painter(*this);
  281. painter.fill_rect(event.rect(), palette().color(background_role()));
  282. }
  283. paint_event(event);
  284. auto children_clip_rect = this->children_clip_rect();
  285. for_each_child_widget([&](auto& child) {
  286. if (!child.is_visible())
  287. return IterationDecision::Continue;
  288. if (child.relative_rect().intersects(event.rect())) {
  289. PaintEvent local_event(event.rect().intersected(children_clip_rect).intersected(child.relative_rect()).translated(-child.relative_position()));
  290. child.dispatch_event(local_event, this);
  291. }
  292. return IterationDecision::Continue;
  293. });
  294. second_paint_event(event);
  295. auto* app = Application::the();
  296. if (app && app->dnd_debugging_enabled() && has_pending_drop()) {
  297. Painter painter(*this);
  298. painter.draw_rect(rect(), Color::Blue);
  299. }
  300. if (app && app->focus_debugging_enabled() && is_focused()) {
  301. Painter painter(*this);
  302. painter.draw_rect(rect(), Color::Cyan);
  303. }
  304. if (app && app->hover_debugging_enabled() && this == window()->hovered_widget()) {
  305. Painter painter(*this);
  306. painter.draw_rect(rect(), Color::Red);
  307. }
  308. }
  309. void Widget::set_layout(NonnullRefPtr<Layout> layout)
  310. {
  311. if (m_layout) {
  312. m_layout->notify_disowned({}, *this);
  313. m_layout->remove_from_parent();
  314. }
  315. m_layout = move(layout);
  316. if (m_layout) {
  317. add_child(*m_layout);
  318. m_layout->notify_adopted({}, *this);
  319. do_layout();
  320. } else {
  321. update();
  322. }
  323. layout_relevant_change_occurred();
  324. }
  325. void Widget::do_layout()
  326. {
  327. for_each_child_widget([&](auto& child) {
  328. child.do_layout();
  329. return IterationDecision::Continue;
  330. });
  331. custom_layout();
  332. if (!m_layout)
  333. return;
  334. m_layout->run(*this);
  335. did_layout();
  336. update();
  337. }
  338. void Widget::notify_layout_changed(Badge<Layout>)
  339. {
  340. invalidate_layout();
  341. }
  342. void Widget::handle_resize_event(ResizeEvent& event)
  343. {
  344. resize_event(event);
  345. do_layout();
  346. }
  347. void Widget::handle_mouseup_event(MouseEvent& event)
  348. {
  349. mouseup_event(event);
  350. }
  351. void Widget::handle_mousedown_event(MouseEvent& event)
  352. {
  353. if (has_flag(focus_policy(), FocusPolicy::ClickFocus))
  354. set_focus(true, FocusSource::Mouse);
  355. mousedown_event(event);
  356. if (event.button() == MouseButton::Secondary) {
  357. ContextMenuEvent c_event(event.position(), screen_relative_rect().location().translated(event.position()));
  358. dispatch_event(c_event);
  359. }
  360. }
  361. void Widget::handle_mousedoubleclick_event(MouseEvent& event)
  362. {
  363. doubleclick_event(event);
  364. }
  365. void Widget::handle_enter_event(Core::Event& event)
  366. {
  367. if (auto* window = this->window())
  368. window->update_cursor({});
  369. show_or_hide_tooltip();
  370. enter_event(event);
  371. }
  372. void Widget::handle_leave_event(Core::Event& event)
  373. {
  374. if (auto* window = this->window())
  375. window->update_cursor({});
  376. if (Application::the()->tooltip_source_widget() == this)
  377. Application::the()->hide_tooltip();
  378. leave_event(event);
  379. }
  380. void Widget::doubleclick_event(MouseEvent&)
  381. {
  382. }
  383. void Widget::resize_event(ResizeEvent&)
  384. {
  385. }
  386. void Widget::paint_event(PaintEvent&)
  387. {
  388. }
  389. void Widget::second_paint_event(PaintEvent&)
  390. {
  391. }
  392. void Widget::show_event(ShowEvent&)
  393. {
  394. }
  395. void Widget::hide_event(HideEvent&)
  396. {
  397. }
  398. void Widget::keydown_event(KeyEvent& event)
  399. {
  400. if (!event.alt() && !event.ctrl() && !event.super()) {
  401. if (event.key() == KeyCode::Key_Tab) {
  402. if (event.shift())
  403. focus_previous_widget(FocusSource::Keyboard, false);
  404. else
  405. focus_next_widget(FocusSource::Keyboard, false);
  406. event.accept();
  407. return;
  408. }
  409. if (!event.shift() && (event.key() == KeyCode::Key_Left || event.key() == KeyCode::Key_Up)) {
  410. focus_previous_widget(FocusSource::Keyboard, true);
  411. event.accept();
  412. return;
  413. }
  414. if (!event.shift() && (event.key() == KeyCode::Key_Right || event.key() == KeyCode::Key_Down)) {
  415. focus_next_widget(FocusSource::Keyboard, true);
  416. event.accept();
  417. return;
  418. }
  419. }
  420. event.ignore();
  421. }
  422. void Widget::keyup_event(KeyEvent& event)
  423. {
  424. event.ignore();
  425. }
  426. void Widget::mousedown_event(MouseEvent&)
  427. {
  428. }
  429. void Widget::mouseup_event(MouseEvent&)
  430. {
  431. }
  432. void Widget::mousemove_event(MouseEvent&)
  433. {
  434. }
  435. void Widget::mousewheel_event(MouseEvent& event)
  436. {
  437. event.ignore();
  438. }
  439. void Widget::context_menu_event(ContextMenuEvent& event)
  440. {
  441. event.ignore();
  442. }
  443. void Widget::focusin_event(FocusEvent&)
  444. {
  445. }
  446. void Widget::focusout_event(FocusEvent&)
  447. {
  448. }
  449. void Widget::enter_event(Core::Event&)
  450. {
  451. }
  452. void Widget::leave_event(Core::Event&)
  453. {
  454. }
  455. void Widget::change_event(Event&)
  456. {
  457. }
  458. void Widget::drag_move_event(DragEvent&)
  459. {
  460. }
  461. void Widget::drag_enter_event(DragEvent& event)
  462. {
  463. StringBuilder builder;
  464. builder.join(',', event.mime_types());
  465. dbgln_if(DRAG_DEBUG, "{} {:p} DRAG ENTER @ {}, {}", class_name(), this, event.position(), builder.string_view());
  466. }
  467. void Widget::drag_leave_event(Event&)
  468. {
  469. dbgln_if(DRAG_DEBUG, "{} {:p} DRAG LEAVE", class_name(), this);
  470. }
  471. void Widget::drop_event(DropEvent& event)
  472. {
  473. dbgln_if(DRAG_DEBUG, "{} {:p} DROP @ {}, '{}'", class_name(), this, event.position(), event.text());
  474. event.ignore();
  475. }
  476. void Widget::theme_change_event(ThemeChangeEvent&)
  477. {
  478. }
  479. void Widget::fonts_change_event(FontsChangeEvent&)
  480. {
  481. if (m_default_font)
  482. set_font(nullptr);
  483. }
  484. void Widget::screen_rects_change_event(ScreenRectsChangeEvent&)
  485. {
  486. }
  487. void Widget::applet_area_rect_change_event(AppletAreaRectChangeEvent&)
  488. {
  489. }
  490. void Widget::update()
  491. {
  492. if (rect().is_empty())
  493. return;
  494. update(rect());
  495. for (auto& it : m_focus_delegators) {
  496. if (!it.is_null() && !it->rect().is_empty())
  497. it->update(it->rect());
  498. }
  499. }
  500. void Widget::update(Gfx::IntRect const& rect)
  501. {
  502. if (!is_visible())
  503. return;
  504. if (!updates_enabled())
  505. return;
  506. auto bound_by_widget = rect.intersected(this->rect());
  507. if (bound_by_widget.is_empty())
  508. return;
  509. Window* window = m_window;
  510. Widget* parent = parent_widget();
  511. while (parent) {
  512. if (!parent->updates_enabled())
  513. return;
  514. window = parent->m_window;
  515. parent = parent->parent_widget();
  516. }
  517. if (window)
  518. window->update(bound_by_widget.translated(window_relative_rect().location()));
  519. }
  520. void Widget::repaint()
  521. {
  522. if (rect().is_empty())
  523. return;
  524. repaint(rect());
  525. }
  526. void Widget::repaint(Gfx::IntRect const& rect)
  527. {
  528. auto* window = this->window();
  529. if (!window)
  530. return;
  531. update(rect);
  532. window->flush_pending_paints_immediately();
  533. }
  534. Gfx::IntRect Widget::window_relative_rect() const
  535. {
  536. auto rect = relative_rect();
  537. for (auto* parent = parent_widget(); parent; parent = parent->parent_widget()) {
  538. rect.translate_by(parent->relative_position());
  539. }
  540. return rect;
  541. }
  542. Gfx::IntRect Widget::screen_relative_rect() const
  543. {
  544. auto window_position = window()->window_type() == WindowType::Applet
  545. ? window()->applet_rect_on_screen().location()
  546. : window()->rect().location();
  547. return window_relative_rect().translated(window_position);
  548. }
  549. Widget* Widget::child_at(Gfx::IntPoint point) const
  550. {
  551. for (int i = children().size() - 1; i >= 0; --i) {
  552. if (!is<Widget>(children()[i]))
  553. continue;
  554. auto& child = verify_cast<Widget>(*children()[i]);
  555. if (!child.is_visible())
  556. continue;
  557. if (child.relative_non_grabbable_rect().contains(point))
  558. return const_cast<Widget*>(&child);
  559. }
  560. return nullptr;
  561. }
  562. Widget::HitTestResult Widget::hit_test(Gfx::IntPoint position, ShouldRespectGreediness should_respect_greediness)
  563. {
  564. if (should_respect_greediness == ShouldRespectGreediness::Yes && is_greedy_for_hits())
  565. return { this, position };
  566. if (auto* child = child_at(position))
  567. return child->hit_test(position - child->relative_position());
  568. return { this, position };
  569. }
  570. void Widget::set_window(Window* window)
  571. {
  572. if (m_window == window)
  573. return;
  574. m_window = window;
  575. }
  576. void Widget::set_focus_proxy(Widget* proxy)
  577. {
  578. if (m_focus_proxy == proxy)
  579. return;
  580. if (proxy)
  581. proxy->add_focus_delegator(this);
  582. else if (m_focus_proxy)
  583. m_focus_proxy->remove_focus_delegator(this);
  584. m_focus_proxy = proxy;
  585. }
  586. void Widget::add_focus_delegator(Widget* delegator)
  587. {
  588. m_focus_delegators.remove_all_matching([&](auto& entry) {
  589. return entry.is_null() || entry == delegator;
  590. });
  591. m_focus_delegators.append(delegator);
  592. }
  593. void Widget::remove_focus_delegator(Widget* delegator)
  594. {
  595. m_focus_delegators.remove_first_matching([&](auto& entry) {
  596. return entry == delegator;
  597. });
  598. }
  599. FocusPolicy Widget::focus_policy() const
  600. {
  601. if (m_focus_proxy)
  602. return m_focus_proxy->focus_policy();
  603. return m_focus_policy;
  604. }
  605. void Widget::set_focus_policy(FocusPolicy policy)
  606. {
  607. if (m_focus_proxy)
  608. return m_focus_proxy->set_focus_policy(policy);
  609. m_focus_policy = policy;
  610. }
  611. bool Widget::is_focused() const
  612. {
  613. if (m_focus_proxy)
  614. return m_focus_proxy->is_focused();
  615. auto* win = window();
  616. if (!win)
  617. return false;
  618. if (win->is_focusable())
  619. return win->focused_widget() == this;
  620. return false;
  621. }
  622. void Widget::set_focus(bool focus, FocusSource source)
  623. {
  624. if (m_focus_proxy)
  625. return m_focus_proxy->set_focus(focus, source);
  626. auto* win = window();
  627. if (!win)
  628. return;
  629. if (focus) {
  630. win->set_focused_widget(this, source);
  631. } else {
  632. if (win->focused_widget() == this)
  633. win->set_focused_widget(nullptr, source);
  634. }
  635. }
  636. void Widget::set_font(Gfx::Font const* font)
  637. {
  638. if (m_font.ptr() == font)
  639. return;
  640. if (!font) {
  641. m_font = Gfx::FontDatabase::default_font();
  642. m_default_font = true;
  643. } else {
  644. m_font = *font;
  645. m_default_font = false;
  646. }
  647. did_change_font();
  648. update();
  649. }
  650. void Widget::set_font_family(String const& family)
  651. {
  652. set_font(Gfx::FontDatabase::the().get(family, m_font->presentation_size(), m_font->weight(), m_font->width(), m_font->slope()));
  653. }
  654. void Widget::set_font_size(unsigned size)
  655. {
  656. set_font(Gfx::FontDatabase::the().get(m_font->family(), size, m_font->weight(), m_font->width(), m_font->slope()));
  657. }
  658. void Widget::set_font_weight(unsigned weight)
  659. {
  660. set_font(Gfx::FontDatabase::the().get(m_font->family(), m_font->presentation_size(), weight, m_font->width(), m_font->slope()));
  661. }
  662. void Widget::set_font_fixed_width(bool fixed_width)
  663. {
  664. if (fixed_width)
  665. set_font(Gfx::FontDatabase::the().get(Gfx::FontDatabase::the().default_fixed_width_font().family(), m_font->presentation_size(), m_font->weight(), m_font->width(), m_font->slope()));
  666. else
  667. set_font(Gfx::FontDatabase::the().get(Gfx::FontDatabase::the().default_font().family(), m_font->presentation_size(), m_font->weight(), m_font->width(), m_font->slope()));
  668. }
  669. bool Widget::is_font_fixed_width()
  670. {
  671. return font().is_fixed_width();
  672. }
  673. void Widget::set_min_size(UISize const& size)
  674. {
  675. VERIFY(size.width().is_one_of(SpecialDimension::Regular, SpecialDimension::Shrink));
  676. if (m_min_size == size)
  677. return;
  678. m_min_size = size;
  679. layout_relevant_change_occurred();
  680. }
  681. void Widget::set_max_size(UISize const& size)
  682. {
  683. VERIFY(size.width().is_one_of(SpecialDimension::Regular, SpecialDimension::Grow));
  684. if (m_max_size == size)
  685. return;
  686. m_max_size = size;
  687. layout_relevant_change_occurred();
  688. }
  689. void Widget::set_preferred_size(UISize const& size)
  690. {
  691. if (m_preferred_size == size)
  692. return;
  693. m_preferred_size = size;
  694. layout_relevant_change_occurred();
  695. }
  696. Optional<UISize> Widget::calculated_preferred_size() const
  697. {
  698. if (layout())
  699. return { layout()->preferred_size() };
  700. return {};
  701. }
  702. Optional<UISize> Widget::calculated_min_size() const
  703. {
  704. if (layout())
  705. return { layout()->min_size() };
  706. // Fall back to at least displaying the margins, so the Widget is not 0 size.
  707. auto m = content_margins();
  708. if (!m.is_null())
  709. return UISize { m.left() + m.right(), m.top() + m.bottom() };
  710. return {};
  711. }
  712. void Widget::invalidate_layout()
  713. {
  714. if (window())
  715. window()->schedule_relayout();
  716. }
  717. void Widget::set_visible(bool visible)
  718. {
  719. if (visible == m_visible)
  720. return;
  721. m_visible = visible;
  722. layout_relevant_change_occurred();
  723. if (m_visible)
  724. update();
  725. if (!m_visible && is_focused())
  726. set_focus(false);
  727. if (m_visible) {
  728. ShowEvent e;
  729. event(e);
  730. } else {
  731. HideEvent e;
  732. event(e);
  733. }
  734. }
  735. bool Widget::spans_entire_window_horizontally() const
  736. {
  737. auto* w = window();
  738. if (!w)
  739. return false;
  740. auto* main_widget = w->main_widget();
  741. if (!main_widget)
  742. return false;
  743. if (main_widget == this)
  744. return true;
  745. auto wrr = window_relative_rect();
  746. return wrr.left() == main_widget->rect().left() && wrr.right() == main_widget->rect().right();
  747. }
  748. void Widget::set_enabled(bool enabled)
  749. {
  750. if (m_enabled == enabled)
  751. return;
  752. m_enabled = enabled;
  753. for_each_child_widget([enabled](auto& child) {
  754. child.set_enabled(enabled);
  755. return IterationDecision::Continue;
  756. });
  757. if (!m_enabled && window() && window()->focused_widget() == this) {
  758. window()->did_disable_focused_widget({});
  759. }
  760. if (!m_enabled)
  761. set_override_cursor(Gfx::StandardCursor::None);
  762. Event e(Event::EnabledChange);
  763. event(e);
  764. update();
  765. }
  766. void Widget::move_to_front()
  767. {
  768. auto* parent = parent_widget();
  769. if (!parent)
  770. return;
  771. if (parent->children().size() == 1)
  772. return;
  773. parent->children().remove_first_matching([this](auto& entry) {
  774. return entry == this;
  775. });
  776. parent->children().append(*this);
  777. parent->update();
  778. }
  779. void Widget::move_to_back()
  780. {
  781. auto* parent = parent_widget();
  782. if (!parent)
  783. return;
  784. if (parent->children().size() == 1)
  785. return;
  786. parent->children().remove_first_matching([this](auto& entry) {
  787. return entry == this;
  788. });
  789. parent->children().prepend(*this);
  790. parent->update();
  791. }
  792. bool Widget::is_frontmost() const
  793. {
  794. auto* parent = parent_widget();
  795. if (!parent)
  796. return true;
  797. return parent->children().last() == this;
  798. }
  799. bool Widget::is_backmost() const
  800. {
  801. auto* parent = parent_widget();
  802. if (!parent)
  803. return true;
  804. return parent->children().first() == this;
  805. }
  806. Action* Widget::action_for_shortcut(Shortcut const& shortcut)
  807. {
  808. return Action::find_action_for_shortcut(*this, shortcut);
  809. }
  810. void Widget::set_updates_enabled(bool enabled)
  811. {
  812. if (m_updates_enabled == enabled)
  813. return;
  814. m_updates_enabled = enabled;
  815. if (enabled)
  816. update();
  817. }
  818. void Widget::focus_previous_widget(FocusSource source, bool siblings_only)
  819. {
  820. auto focusable_widgets = window()->focusable_widgets(source);
  821. if (siblings_only)
  822. focusable_widgets.remove_all_matching([this](auto& entry) { return entry.parent() != parent(); });
  823. for (int i = focusable_widgets.size() - 1; i >= 0; --i) {
  824. if (&focusable_widgets[i] != this)
  825. continue;
  826. if (i > 0)
  827. focusable_widgets[i - 1].set_focus(true, source);
  828. else
  829. focusable_widgets.last().set_focus(true, source);
  830. }
  831. }
  832. void Widget::focus_next_widget(FocusSource source, bool siblings_only)
  833. {
  834. auto focusable_widgets = window()->focusable_widgets(source);
  835. if (siblings_only)
  836. focusable_widgets.remove_all_matching([this](auto& entry) { return entry.parent() != parent(); });
  837. for (size_t i = 0; i < focusable_widgets.size(); ++i) {
  838. if (&focusable_widgets[i] != this)
  839. continue;
  840. if (i < focusable_widgets.size() - 1)
  841. focusable_widgets[i + 1].set_focus(true, source);
  842. else
  843. focusable_widgets.first().set_focus(true, source);
  844. }
  845. }
  846. Vector<Widget&> Widget::child_widgets() const
  847. {
  848. Vector<Widget&> widgets;
  849. widgets.ensure_capacity(children().size());
  850. for (auto& child : const_cast<Widget*>(this)->children()) {
  851. if (is<Widget>(*child))
  852. widgets.append(static_cast<Widget&>(*child));
  853. }
  854. return widgets;
  855. }
  856. void Widget::set_palette(Palette& palette)
  857. {
  858. m_palette = palette.impl();
  859. update();
  860. }
  861. void Widget::set_title(String title)
  862. {
  863. m_title = move(title);
  864. layout_relevant_change_occurred();
  865. // For tab widget children, our change in title also affects the parent.
  866. if (parent_widget())
  867. parent_widget()->update();
  868. }
  869. String Widget::title() const
  870. {
  871. return m_title;
  872. }
  873. void Widget::set_background_role(ColorRole role)
  874. {
  875. m_background_role = role;
  876. update();
  877. }
  878. void Widget::set_foreground_role(ColorRole role)
  879. {
  880. m_foreground_role = role;
  881. update();
  882. }
  883. void Widget::set_background_color(Gfx::Color color)
  884. {
  885. auto _palette = palette();
  886. _palette.set_color(background_role(), color);
  887. set_palette(_palette);
  888. }
  889. Gfx::Palette Widget::palette() const
  890. {
  891. return Gfx::Palette(*m_palette);
  892. }
  893. void Widget::set_grabbable_margins(Margins const& margins)
  894. {
  895. if (m_grabbable_margins == margins)
  896. return;
  897. m_grabbable_margins = margins;
  898. layout_relevant_change_occurred();
  899. }
  900. Gfx::IntRect Widget::relative_non_grabbable_rect() const
  901. {
  902. auto rect = relative_rect();
  903. rect.translate_by(m_grabbable_margins.left(), m_grabbable_margins.top());
  904. rect.set_width(rect.width() - (m_grabbable_margins.left() + m_grabbable_margins.right()));
  905. rect.set_height(rect.height() - (m_grabbable_margins.top() + m_grabbable_margins.bottom()));
  906. return rect;
  907. }
  908. void Widget::set_tooltip(String tooltip)
  909. {
  910. m_tooltip = move(tooltip);
  911. if (Application::the()->tooltip_source_widget() == this)
  912. show_or_hide_tooltip();
  913. }
  914. void Widget::show_or_hide_tooltip()
  915. {
  916. if (has_tooltip())
  917. Application::the()->show_tooltip(m_tooltip, this);
  918. else
  919. Application::the()->hide_tooltip();
  920. }
  921. Gfx::IntRect Widget::children_clip_rect() const
  922. {
  923. return rect();
  924. }
  925. void Widget::set_override_cursor(AK::Variant<Gfx::StandardCursor, NonnullRefPtr<Gfx::Bitmap const>> cursor)
  926. {
  927. if (m_override_cursor == cursor)
  928. return;
  929. m_override_cursor = move(cursor);
  930. if (auto* window = this->window()) {
  931. window->update_cursor({});
  932. }
  933. }
  934. ErrorOr<void> Widget::load_from_gml(StringView gml_string)
  935. {
  936. return load_from_gml(gml_string, [](StringView class_name) -> ErrorOr<NonnullRefPtr<Core::EventReceiver>> {
  937. dbgln("Class '{}' not registered", class_name);
  938. return Error::from_string_literal("Class not registered");
  939. });
  940. }
  941. ErrorOr<void> Widget::load_from_gml(StringView gml_string, UnregisteredChildHandler unregistered_child_handler)
  942. {
  943. auto value = TRY(GML::parse_gml(gml_string));
  944. return load_from_gml_ast(value, unregistered_child_handler);
  945. }
  946. ErrorOr<void> Widget::load_from_gml_ast(NonnullRefPtr<GUI::GML::Node const> ast, UnregisteredChildHandler unregistered_child_handler)
  947. {
  948. if (is<GUI::GML::GMLFile>(ast.ptr()))
  949. return load_from_gml_ast(static_cast<GUI::GML::GMLFile const&>(*ast).main_class(), unregistered_child_handler);
  950. VERIFY(is<GUI::GML::Object>(ast.ptr()));
  951. auto const& object = static_cast<GUI::GML::Object const&>(*ast);
  952. object.for_each_property([&](auto key, auto value) {
  953. set_property(key, value);
  954. });
  955. auto layout = object.layout_object();
  956. if (!layout.is_null()) {
  957. auto class_name = layout->name();
  958. if (class_name.is_null()) {
  959. return Error::from_string_literal("Invalid layout class name");
  960. }
  961. auto& layout_class = *GUI::ObjectClassRegistration::find("GUI::Layout"sv);
  962. if (auto* registration = GUI::ObjectClassRegistration::find(class_name)) {
  963. auto layout = TRY(registration->construct());
  964. if (!registration->is_derived_from(layout_class)) {
  965. dbgln("Invalid layout class: '{}'", class_name.to_byte_string());
  966. return Error::from_string_literal("Invalid layout class");
  967. }
  968. set_layout(static_ptr_cast<Layout>(layout));
  969. } else {
  970. dbgln("Unknown layout class: '{}'", class_name.to_byte_string());
  971. return Error::from_string_literal("Unknown layout class");
  972. }
  973. layout->for_each_property([&](auto key, auto value) {
  974. this->layout()->set_property(key, value);
  975. });
  976. }
  977. auto& widget_class = *GUI::ObjectClassRegistration::find("GUI::Widget"sv);
  978. bool is_tab_widget = is<TabWidget>(*this);
  979. TRY(object.try_for_each_child_object([&](auto const& child_data) -> ErrorOr<void> {
  980. auto class_name = child_data.name();
  981. // It is very questionable if this pseudo object should exist, but it works fine like this for now.
  982. if (class_name == "GUI::Layout::Spacer") {
  983. if (!this->layout()) {
  984. return Error::from_string_literal("Specified GUI::Layout::Spacer in GML, but the parent has no Layout.");
  985. }
  986. add_spacer();
  987. } else {
  988. RefPtr<Core::EventReceiver> child;
  989. if (auto* registration = GUI::ObjectClassRegistration::find(class_name)) {
  990. child = TRY(registration->construct());
  991. if (!registration->is_derived_from(widget_class)) {
  992. dbgln("Invalid widget class: '{}'", class_name);
  993. return Error::from_string_literal("Invalid widget class");
  994. }
  995. } else {
  996. child = TRY(unregistered_child_handler(class_name));
  997. }
  998. if (!child)
  999. return Error::from_string_literal("Unable to construct a Widget class for child");
  1000. add_child(*child);
  1001. // This is possible as we ensure that Widget is a base class above.
  1002. TRY(static_ptr_cast<Widget>(child)->load_from_gml_ast(child_data, unregistered_child_handler));
  1003. if (is_tab_widget) {
  1004. // FIXME: We need to have the child added before loading it so that it can access us. But the TabWidget logic requires the child to not be present yet.
  1005. remove_child(*child);
  1006. reinterpret_cast<TabWidget*>(this)->add_widget(*static_ptr_cast<Widget>(child));
  1007. }
  1008. }
  1009. return {};
  1010. }));
  1011. return {};
  1012. }
  1013. bool Widget::has_focus_within() const
  1014. {
  1015. auto* window = this->window();
  1016. if (!window)
  1017. return false;
  1018. if (!window->focused_widget())
  1019. return false;
  1020. auto& effective_focus_widget = focus_proxy() ? *focus_proxy() : *this;
  1021. return window->focused_widget() == &effective_focus_widget || is_ancestor_of(*window->focused_widget());
  1022. }
  1023. void Widget::set_shrink_to_fit(bool shrink_to_fit)
  1024. {
  1025. // This function is deprecated, and soon to be removed, it is only still here to ease the transition to UIDimensions
  1026. if (shrink_to_fit)
  1027. set_preferred_size(SpecialDimension::Fit);
  1028. }
  1029. bool Widget::has_pending_drop() const
  1030. {
  1031. return Application::the()->pending_drop_widget() == this;
  1032. }
  1033. bool Widget::is_visible_for_timer_purposes() const
  1034. {
  1035. return is_visible() && Object::is_visible_for_timer_purposes();
  1036. }
  1037. void Widget::add_spacer()
  1038. {
  1039. VERIFY(layout());
  1040. return layout()->add_spacer();
  1041. }
  1042. String Widget::font_family() const
  1043. {
  1044. return m_font->family();
  1045. }
  1046. }