Widget.cpp 34 KB

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