Widget.cpp 35 KB

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