Widget.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203
  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_INT_PROPERTY("width", width, set_width);
  50. REGISTER_UI_DIMENSION_PROPERTY("min_width", min_width, set_min_width);
  51. REGISTER_UI_DIMENSION_PROPERTY("max_width", max_width, set_max_width);
  52. REGISTER_INT_PROPERTY("height", height, set_height);
  53. REGISTER_UI_DIMENSION_PROPERTY("min_height", min_height, set_min_height);
  54. REGISTER_UI_DIMENSION_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(UISize const& size)
  686. {
  687. VERIFY(size.width().is_one_of(SpecialDimension::Regular, SpecialDimension::Shrink));
  688. if (m_min_size == size)
  689. return;
  690. m_min_size = size;
  691. invalidate_layout();
  692. }
  693. void Widget::set_max_size(UISize const& size)
  694. {
  695. VERIFY(size.width().is_one_of(SpecialDimension::Regular, SpecialDimension::Grow));
  696. if (m_max_size == size)
  697. return;
  698. m_max_size = size;
  699. invalidate_layout();
  700. }
  701. void Widget::invalidate_layout()
  702. {
  703. if (window())
  704. window()->schedule_relayout();
  705. }
  706. void Widget::set_visible(bool visible)
  707. {
  708. if (visible == m_visible)
  709. return;
  710. m_visible = visible;
  711. if (auto* parent = parent_widget())
  712. parent->invalidate_layout();
  713. if (m_visible)
  714. update();
  715. if (!m_visible && is_focused())
  716. set_focus(false);
  717. if (m_visible) {
  718. ShowEvent e;
  719. event(e);
  720. } else {
  721. HideEvent e;
  722. event(e);
  723. }
  724. }
  725. bool Widget::spans_entire_window_horizontally() const
  726. {
  727. auto* w = window();
  728. if (!w)
  729. return false;
  730. auto* main_widget = w->main_widget();
  731. if (!main_widget)
  732. return false;
  733. if (main_widget == this)
  734. return true;
  735. auto wrr = window_relative_rect();
  736. return wrr.left() == main_widget->rect().left() && wrr.right() == main_widget->rect().right();
  737. }
  738. void Widget::set_enabled(bool enabled)
  739. {
  740. if (m_enabled == enabled)
  741. return;
  742. m_enabled = enabled;
  743. for_each_child_widget([enabled](auto& child) {
  744. child.set_enabled(enabled);
  745. return IterationDecision::Continue;
  746. });
  747. if (!m_enabled && window() && window()->focused_widget() == this) {
  748. window()->did_disable_focused_widget({});
  749. }
  750. if (!m_enabled)
  751. set_override_cursor(Gfx::StandardCursor::None);
  752. Event e(Event::EnabledChange);
  753. event(e);
  754. update();
  755. }
  756. void Widget::move_to_front()
  757. {
  758. auto* parent = parent_widget();
  759. if (!parent)
  760. return;
  761. if (parent->children().size() == 1)
  762. return;
  763. parent->children().remove_first_matching([this](auto& entry) {
  764. return entry == this;
  765. });
  766. parent->children().append(*this);
  767. parent->update();
  768. }
  769. void Widget::move_to_back()
  770. {
  771. auto* parent = parent_widget();
  772. if (!parent)
  773. return;
  774. if (parent->children().size() == 1)
  775. return;
  776. parent->children().remove_first_matching([this](auto& entry) {
  777. return entry == this;
  778. });
  779. parent->children().prepend(*this);
  780. parent->update();
  781. }
  782. bool Widget::is_frontmost() const
  783. {
  784. auto* parent = parent_widget();
  785. if (!parent)
  786. return true;
  787. return &parent->children().last() == this;
  788. }
  789. bool Widget::is_backmost() const
  790. {
  791. auto* parent = parent_widget();
  792. if (!parent)
  793. return true;
  794. return &parent->children().first() == this;
  795. }
  796. Action* Widget::action_for_shortcut(Shortcut const& shortcut)
  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(Palette const& palette)
  855. {
  856. m_palette = palette.impl();
  857. update();
  858. }
  859. void Widget::set_title(String title)
  860. {
  861. m_title = move(title);
  862. // For tab widget children, our change in title also affects the parent.
  863. if (parent_widget())
  864. parent_widget()->update();
  865. }
  866. String Widget::title() const
  867. {
  868. return m_title;
  869. }
  870. void Widget::set_background_role(ColorRole role)
  871. {
  872. m_background_role = role;
  873. update();
  874. }
  875. void Widget::set_foreground_role(ColorRole role)
  876. {
  877. m_foreground_role = role;
  878. update();
  879. }
  880. Gfx::Palette Widget::palette() const
  881. {
  882. return Gfx::Palette(*m_palette);
  883. }
  884. void Widget::did_begin_inspection()
  885. {
  886. update();
  887. }
  888. void Widget::did_end_inspection()
  889. {
  890. update();
  891. }
  892. void Widget::set_grabbable_margins(Margins const& margins)
  893. {
  894. if (m_grabbable_margins == margins)
  895. return;
  896. m_grabbable_margins = margins;
  897. invalidate_layout();
  898. }
  899. Gfx::IntRect Widget::relative_non_grabbable_rect() const
  900. {
  901. auto rect = relative_rect();
  902. rect.translate_by(m_grabbable_margins.left(), m_grabbable_margins.top());
  903. rect.set_width(rect.width() - (m_grabbable_margins.left() + m_grabbable_margins.right()));
  904. rect.set_height(rect.height() - (m_grabbable_margins.top() + m_grabbable_margins.bottom()));
  905. return rect;
  906. }
  907. void Widget::set_tooltip(String tooltip)
  908. {
  909. m_tooltip = move(tooltip);
  910. if (Application::the()->tooltip_source_widget() == this)
  911. show_or_hide_tooltip();
  912. }
  913. void Widget::show_or_hide_tooltip()
  914. {
  915. if (has_tooltip())
  916. Application::the()->show_tooltip(m_tooltip, this);
  917. else
  918. Application::the()->hide_tooltip();
  919. }
  920. Gfx::IntRect Widget::children_clip_rect() const
  921. {
  922. return rect();
  923. }
  924. void Widget::set_override_cursor(AK::Variant<Gfx::StandardCursor, NonnullRefPtr<Gfx::Bitmap>> cursor)
  925. {
  926. auto const& are_cursors_the_same = [](AK::Variant<Gfx::StandardCursor, NonnullRefPtr<Gfx::Bitmap>> const& a, AK::Variant<Gfx::StandardCursor, NonnullRefPtr<Gfx::Bitmap>> const& b) {
  927. if (a.has<Gfx::StandardCursor>() != b.has<Gfx::StandardCursor>())
  928. return false;
  929. if (a.has<Gfx::StandardCursor>())
  930. return a.get<Gfx::StandardCursor>() == b.get<Gfx::StandardCursor>();
  931. return a.get<NonnullRefPtr<Gfx::Bitmap>>().ptr() == b.get<NonnullRefPtr<Gfx::Bitmap>>().ptr();
  932. };
  933. if (are_cursors_the_same(m_override_cursor, cursor))
  934. return;
  935. m_override_cursor = move(cursor);
  936. if (auto* window = this->window()) {
  937. window->update_cursor({});
  938. }
  939. }
  940. bool Widget::load_from_gml(StringView gml_string)
  941. {
  942. return load_from_gml(gml_string, [](String const& class_name) -> RefPtr<Core::Object> {
  943. dbgln("Class '{}' not registered", class_name);
  944. return nullptr;
  945. });
  946. }
  947. bool Widget::load_from_gml(StringView gml_string, RefPtr<Core::Object> (*unregistered_child_handler)(String const&))
  948. {
  949. auto value = GML::parse_gml(gml_string);
  950. if (value.is_error()) {
  951. // FIXME: We don't report the error, so at least print it.
  952. dbgln("Error while parsing GML: {}", value.error());
  953. return false;
  954. }
  955. return load_from_gml_ast(value.release_value(), unregistered_child_handler);
  956. }
  957. bool Widget::load_from_gml_ast(NonnullRefPtr<GUI::GML::Node> ast, RefPtr<Core::Object> (*unregistered_child_handler)(String const&))
  958. {
  959. if (is<GUI::GML::GMLFile>(ast.ptr()))
  960. return load_from_gml_ast(static_ptr_cast<GUI::GML::GMLFile>(ast)->main_class(), unregistered_child_handler);
  961. VERIFY(is<GUI::GML::Object>(ast.ptr()));
  962. auto object = static_ptr_cast<GUI::GML::Object>(ast);
  963. object->for_each_property([&](auto key, auto value) {
  964. set_property(key, value);
  965. });
  966. auto layout = object->layout_object();
  967. if (!layout.is_null()) {
  968. auto class_name = layout->name();
  969. if (class_name.is_null()) {
  970. dbgln("Invalid layout class name");
  971. return false;
  972. }
  973. auto& layout_class = *Core::ObjectClassRegistration::find("GUI::Layout");
  974. if (auto* registration = Core::ObjectClassRegistration::find(class_name)) {
  975. auto layout = registration->construct();
  976. if (!layout || !registration->is_derived_from(layout_class)) {
  977. dbgln("Invalid layout class: '{}'", class_name.to_string());
  978. return false;
  979. }
  980. set_layout(static_ptr_cast<Layout>(layout).release_nonnull());
  981. } else {
  982. dbgln("Unknown layout class: '{}'", class_name.to_string());
  983. return false;
  984. }
  985. layout->for_each_property([&](auto key, auto value) {
  986. this->layout()->set_property(key, value);
  987. });
  988. }
  989. auto& widget_class = *Core::ObjectClassRegistration::find("GUI::Widget");
  990. bool is_tab_widget = is<TabWidget>(*this);
  991. object->for_each_child_object_interruptible([&](auto child_data) {
  992. auto class_name = child_data->name();
  993. // It is very questionable if this pseudo object should exist, but it works fine like this for now.
  994. if (class_name == "GUI::Layout::Spacer") {
  995. if (!this->layout()) {
  996. dbgln("Specified GUI::Layout::Spacer in GML, but the parent has no Layout.");
  997. return IterationDecision::Break;
  998. }
  999. this->layout()->add_spacer();
  1000. } else {
  1001. RefPtr<Core::Object> child;
  1002. if (auto* registration = Core::ObjectClassRegistration::find(class_name)) {
  1003. child = registration->construct();
  1004. if (!child || !registration->is_derived_from(widget_class)) {
  1005. dbgln("Invalid widget class: '{}'", class_name);
  1006. return IterationDecision::Break;
  1007. }
  1008. } else {
  1009. child = unregistered_child_handler(class_name);
  1010. }
  1011. if (!child)
  1012. return IterationDecision::Break;
  1013. add_child(*child);
  1014. // This is possible as we ensure that Widget is a base class above.
  1015. static_ptr_cast<Widget>(child)->load_from_gml_ast(child_data, unregistered_child_handler);
  1016. if (is_tab_widget) {
  1017. // 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.
  1018. remove_child(*child);
  1019. reinterpret_cast<TabWidget*>(this)->add_widget(*static_ptr_cast<Widget>(child));
  1020. }
  1021. }
  1022. return IterationDecision::Continue;
  1023. });
  1024. return true;
  1025. }
  1026. bool Widget::has_focus_within() const
  1027. {
  1028. auto* window = this->window();
  1029. if (!window)
  1030. return false;
  1031. if (!window->focused_widget())
  1032. return false;
  1033. auto& effective_focus_widget = focus_proxy() ? *focus_proxy() : *this;
  1034. return window->focused_widget() == &effective_focus_widget || is_ancestor_of(*window->focused_widget());
  1035. }
  1036. void Widget::set_shrink_to_fit(bool b)
  1037. {
  1038. if (m_shrink_to_fit == b)
  1039. return;
  1040. m_shrink_to_fit = b;
  1041. invalidate_layout();
  1042. }
  1043. bool Widget::has_pending_drop() const
  1044. {
  1045. return Application::the()->pending_drop_widget() == this;
  1046. }
  1047. bool Widget::is_visible_for_timer_purposes() const
  1048. {
  1049. return is_visible() && Object::is_visible_for_timer_purposes();
  1050. }
  1051. }