Widget.cpp 33 KB

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