Widget.cpp 36 KB

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