Widget.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Assertions.h>
  27. #include <AK/JsonObject.h>
  28. #include <LibGfx/Bitmap.h>
  29. #include <LibGfx/Palette.h>
  30. #include <LibGUI/Action.h>
  31. #include <LibGUI/Application.h>
  32. #include <LibGUI/Button.h>
  33. #include <LibGUI/CheckBox.h>
  34. #include <LibGUI/Event.h>
  35. #include <LibGUI/GroupBox.h>
  36. #include <LibGUI/Label.h>
  37. #include <LibGUI/Layout.h>
  38. #include <LibGUI/Menu.h>
  39. #include <LibGUI/Painter.h>
  40. #include <LibGUI/RadioButton.h>
  41. #include <LibGUI/ScrollBar.h>
  42. #include <LibGUI/Slider.h>
  43. #include <LibGUI/SpinBox.h>
  44. #include <LibGUI/TextBox.h>
  45. #include <LibGUI/Widget.h>
  46. #include <LibGUI/Window.h>
  47. #include <LibGUI/WindowServerConnection.h>
  48. #include <unistd.h>
  49. namespace GUI {
  50. REGISTER_GWIDGET(Button)
  51. REGISTER_GWIDGET(CheckBox)
  52. REGISTER_GWIDGET(GroupBox)
  53. REGISTER_GWIDGET(Label)
  54. REGISTER_GWIDGET(RadioButton)
  55. REGISTER_GWIDGET(ScrollBar)
  56. REGISTER_GWIDGET(Slider)
  57. REGISTER_GWIDGET(SpinBox)
  58. REGISTER_GWIDGET(TextBox)
  59. REGISTER_GWIDGET(Widget)
  60. static HashMap<String, WidgetClassRegistration*>& widget_classes()
  61. {
  62. static HashMap<String, WidgetClassRegistration*>* map;
  63. if (!map)
  64. map = new HashMap<String, WidgetClassRegistration*>;
  65. return *map;
  66. }
  67. WidgetClassRegistration::WidgetClassRegistration(const String& class_name, Function<NonnullRefPtr<Widget>(Widget*)> factory)
  68. : m_class_name(class_name)
  69. , m_factory(move(factory))
  70. {
  71. widget_classes().set(class_name, this);
  72. }
  73. WidgetClassRegistration::~WidgetClassRegistration()
  74. {
  75. }
  76. void WidgetClassRegistration::for_each(Function<void(const WidgetClassRegistration&)> callback)
  77. {
  78. for (auto& it : widget_classes()) {
  79. callback(*it.value);
  80. }
  81. }
  82. const WidgetClassRegistration* WidgetClassRegistration::find(const String& class_name)
  83. {
  84. return widget_classes().get(class_name).value_or(nullptr);
  85. }
  86. Widget::Widget(Widget* parent)
  87. : Core::Object(parent, true)
  88. , m_font(Gfx::Font::default_font())
  89. , m_palette(Application::the().palette().impl())
  90. {
  91. }
  92. Widget::~Widget()
  93. {
  94. }
  95. void Widget::child_event(Core::ChildEvent& event)
  96. {
  97. if (event.type() == Event::ChildAdded) {
  98. if (event.child() && Core::is<Widget>(*event.child()) && layout()) {
  99. if (event.insertion_before_child() && event.insertion_before_child()->is_widget())
  100. layout()->insert_widget_before(Core::to<Widget>(*event.child()), Core::to<Widget>(*event.insertion_before_child()));
  101. else
  102. layout()->add_widget(Core::to<Widget>(*event.child()));
  103. }
  104. }
  105. if (event.type() == Event::ChildRemoved) {
  106. if (layout()) {
  107. if (event.child() && Core::is<Widget>(*event.child()))
  108. layout()->remove_widget(Core::to<Widget>(*event.child()));
  109. else
  110. invalidate_layout();
  111. }
  112. update();
  113. }
  114. return Core::Object::child_event(event);
  115. }
  116. void Widget::set_relative_rect(const Gfx::Rect& a_rect)
  117. {
  118. // Get rid of negative width/height values.
  119. Gfx::Rect rect = {
  120. a_rect.x(),
  121. a_rect.y(),
  122. max(a_rect.width(), 0),
  123. max(a_rect.height(), 0)
  124. };
  125. if (rect == m_relative_rect)
  126. return;
  127. auto old_rect = m_relative_rect;
  128. bool size_changed = m_relative_rect.size() != rect.size();
  129. m_relative_rect = rect;
  130. if (size_changed) {
  131. ResizeEvent resize_event(m_relative_rect.size(), rect.size());
  132. event(resize_event);
  133. }
  134. if (auto* parent = parent_widget())
  135. parent->update(old_rect);
  136. update();
  137. }
  138. void Widget::event(Core::Event& event)
  139. {
  140. switch (event.type()) {
  141. case Event::Paint:
  142. return handle_paint_event(static_cast<PaintEvent&>(event));
  143. case Event::Resize:
  144. return handle_resize_event(static_cast<ResizeEvent&>(event));
  145. case Event::FocusIn:
  146. return focusin_event(event);
  147. case Event::FocusOut:
  148. return focusout_event(event);
  149. case Event::Show:
  150. return show_event(static_cast<ShowEvent&>(event));
  151. case Event::Hide:
  152. return hide_event(static_cast<HideEvent&>(event));
  153. case Event::KeyDown:
  154. return keydown_event(static_cast<KeyEvent&>(event));
  155. case Event::KeyUp:
  156. return keyup_event(static_cast<KeyEvent&>(event));
  157. case Event::MouseMove:
  158. return mousemove_event(static_cast<MouseEvent&>(event));
  159. case Event::MouseDown:
  160. return handle_mousedown_event(static_cast<MouseEvent&>(event));
  161. case Event::MouseDoubleClick:
  162. return handle_mousedoubleclick_event(static_cast<MouseEvent&>(event));
  163. case Event::MouseUp:
  164. return handle_mouseup_event(static_cast<MouseEvent&>(event));
  165. case Event::MouseWheel:
  166. return mousewheel_event(static_cast<MouseEvent&>(event));
  167. case Event::Drop:
  168. return drop_event(static_cast<DropEvent&>(event));
  169. case Event::Enter:
  170. return handle_enter_event(event);
  171. case Event::Leave:
  172. return handle_leave_event(event);
  173. case Event::EnabledChange:
  174. return change_event(static_cast<Event&>(event));
  175. default:
  176. return Core::Object::event(event);
  177. }
  178. }
  179. void Widget::handle_paint_event(PaintEvent& event)
  180. {
  181. ASSERT(is_visible());
  182. if (fill_with_background_color()) {
  183. Painter painter(*this);
  184. painter.fill_rect(event.rect(), palette().color(background_role()));
  185. } else {
  186. #ifdef DEBUG_WIDGET_UNDERDRAW
  187. // FIXME: This is a bit broken.
  188. // If the widget is not opaque, let's not mess it up with debugging color.
  189. Painter painter(*this);
  190. painter.fill_rect(rect(), Color::Red);
  191. #endif
  192. }
  193. paint_event(event);
  194. for_each_child_widget([&](auto& child) {
  195. if (!child.is_visible())
  196. return IterationDecision::Continue;
  197. if (child.relative_rect().intersects(event.rect())) {
  198. PaintEvent local_event(event.rect().intersected(child.relative_rect()).translated(-child.relative_position()));
  199. child.dispatch_event(local_event, this);
  200. }
  201. return IterationDecision::Continue;
  202. });
  203. second_paint_event(event);
  204. }
  205. void Widget::set_layout(OwnPtr<Layout>&& layout)
  206. {
  207. if (m_layout)
  208. m_layout->notify_disowned({}, *this);
  209. m_layout = move(layout);
  210. if (m_layout) {
  211. m_layout->notify_adopted({}, *this);
  212. do_layout();
  213. } else {
  214. update();
  215. }
  216. }
  217. void Widget::do_layout()
  218. {
  219. for_each_child_widget([&](auto& child) {
  220. child.do_layout();
  221. return IterationDecision::Continue;
  222. });
  223. custom_layout();
  224. if (!m_layout)
  225. return;
  226. m_layout->run(*this);
  227. did_layout();
  228. update();
  229. }
  230. void Widget::notify_layout_changed(Badge<Layout>)
  231. {
  232. invalidate_layout();
  233. }
  234. void Widget::handle_resize_event(ResizeEvent& event)
  235. {
  236. resize_event(event);
  237. do_layout();
  238. }
  239. void Widget::handle_mouseup_event(MouseEvent& event)
  240. {
  241. mouseup_event(event);
  242. }
  243. void Widget::handle_mousedown_event(MouseEvent& event)
  244. {
  245. if (accepts_focus())
  246. set_focus(true);
  247. mousedown_event(event);
  248. if (event.button() == MouseButton::Right) {
  249. ContextMenuEvent c_event(event.position(), screen_relative_rect().location().translated(event.position()));
  250. context_menu_event(c_event);
  251. }
  252. }
  253. void Widget::handle_mousedoubleclick_event(MouseEvent& event)
  254. {
  255. doubleclick_event(event);
  256. }
  257. void Widget::handle_enter_event(Core::Event& event)
  258. {
  259. if (has_tooltip())
  260. Application::the().show_tooltip(m_tooltip, screen_relative_rect().center().translated(0, height() / 2));
  261. enter_event(event);
  262. }
  263. void Widget::handle_leave_event(Core::Event& event)
  264. {
  265. Application::the().hide_tooltip();
  266. leave_event(event);
  267. }
  268. void Widget::click_event(MouseEvent&)
  269. {
  270. }
  271. void Widget::doubleclick_event(MouseEvent&)
  272. {
  273. }
  274. void Widget::resize_event(ResizeEvent&)
  275. {
  276. }
  277. void Widget::paint_event(PaintEvent&)
  278. {
  279. }
  280. void Widget::second_paint_event(PaintEvent&)
  281. {
  282. }
  283. void Widget::show_event(ShowEvent&)
  284. {
  285. }
  286. void Widget::hide_event(HideEvent&)
  287. {
  288. }
  289. void Widget::keydown_event(KeyEvent& event)
  290. {
  291. if (!event.alt() && !event.ctrl() && !event.logo() && event.key() == KeyCode::Key_Tab) {
  292. if (event.shift())
  293. focus_previous_widget();
  294. else
  295. focus_next_widget();
  296. event.accept();
  297. return;
  298. }
  299. event.ignore();
  300. }
  301. void Widget::keyup_event(KeyEvent&)
  302. {
  303. }
  304. void Widget::mousedown_event(MouseEvent&)
  305. {
  306. }
  307. void Widget::mouseup_event(MouseEvent&)
  308. {
  309. }
  310. void Widget::mousemove_event(MouseEvent&)
  311. {
  312. }
  313. void Widget::mousewheel_event(MouseEvent&)
  314. {
  315. }
  316. void Widget::context_menu_event(ContextMenuEvent&)
  317. {
  318. }
  319. void Widget::focusin_event(Core::Event&)
  320. {
  321. }
  322. void Widget::focusout_event(Core::Event&)
  323. {
  324. }
  325. void Widget::enter_event(Core::Event&)
  326. {
  327. }
  328. void Widget::leave_event(Core::Event&)
  329. {
  330. }
  331. void Widget::change_event(Event&)
  332. {
  333. }
  334. void Widget::drop_event(DropEvent& event)
  335. {
  336. dbg() << class_name() << "{" << this << "} DROP position: " << event.position() << ", text: '" << event.text() << "'";
  337. event.ignore();
  338. }
  339. void Widget::update()
  340. {
  341. if (rect().is_empty())
  342. return;
  343. update(rect());
  344. }
  345. void Widget::update(const Gfx::Rect& rect)
  346. {
  347. if (!is_visible())
  348. return;
  349. if (!updates_enabled())
  350. return;
  351. Window* window = m_window;
  352. Widget* parent = parent_widget();
  353. while (parent) {
  354. if (!parent->updates_enabled())
  355. return;
  356. window = parent->m_window;
  357. parent = parent->parent_widget();
  358. }
  359. if (window)
  360. window->update(rect.translated(window_relative_rect().location()));
  361. }
  362. Gfx::Rect Widget::window_relative_rect() const
  363. {
  364. auto rect = relative_rect();
  365. for (auto* parent = parent_widget(); parent; parent = parent->parent_widget()) {
  366. rect.move_by(parent->relative_position());
  367. }
  368. return rect;
  369. }
  370. Gfx::Rect Widget::screen_relative_rect() const
  371. {
  372. return window_relative_rect().translated(window()->position());
  373. }
  374. Widget* Widget::child_at(const Gfx::Point& point) const
  375. {
  376. for (int i = children().size() - 1; i >= 0; --i) {
  377. if (!Core::is<Widget>(children()[i]))
  378. continue;
  379. auto& child = Core::to<Widget>(children()[i]);
  380. if (!child.is_visible())
  381. continue;
  382. if (child.relative_rect().contains(point))
  383. return const_cast<Widget*>(&child);
  384. }
  385. return nullptr;
  386. }
  387. Widget::HitTestResult Widget::hit_test(const Gfx::Point& position, ShouldRespectGreediness should_respect_greediness)
  388. {
  389. if (should_respect_greediness == ShouldRespectGreediness::Yes && is_greedy_for_hits())
  390. return { this, position };
  391. if (auto* child = child_at(position))
  392. return child->hit_test(position - child->relative_position());
  393. return { this, position };
  394. }
  395. void Widget::set_window(Window* window)
  396. {
  397. if (m_window == window)
  398. return;
  399. m_window = window;
  400. }
  401. bool Widget::is_focused() const
  402. {
  403. auto* win = window();
  404. if (!win)
  405. return false;
  406. if (!win->is_active())
  407. return false;
  408. return win->focused_widget() == this;
  409. }
  410. void Widget::set_focus(bool focus)
  411. {
  412. auto* win = window();
  413. if (!win)
  414. return;
  415. if (focus) {
  416. win->set_focused_widget(this);
  417. } else {
  418. if (win->focused_widget() == this)
  419. win->set_focused_widget(nullptr);
  420. }
  421. }
  422. void Widget::set_font(const Gfx::Font* font)
  423. {
  424. if (m_font.ptr() == font)
  425. return;
  426. if (!font)
  427. m_font = Gfx::Font::default_font();
  428. else
  429. m_font = *font;
  430. did_change_font();
  431. update();
  432. }
  433. void Widget::set_global_cursor_tracking(bool enabled)
  434. {
  435. auto* win = window();
  436. if (!win)
  437. return;
  438. win->set_global_cursor_tracking_widget(enabled ? this : nullptr);
  439. }
  440. bool Widget::global_cursor_tracking() const
  441. {
  442. auto* win = window();
  443. if (!win)
  444. return false;
  445. return win->global_cursor_tracking_widget() == this;
  446. }
  447. void Widget::set_preferred_size(const Gfx::Size& size)
  448. {
  449. if (m_preferred_size == size)
  450. return;
  451. m_preferred_size = size;
  452. invalidate_layout();
  453. }
  454. void Widget::set_size_policy(Orientation orientation, SizePolicy policy)
  455. {
  456. if (orientation == Orientation::Horizontal)
  457. set_size_policy(policy, m_vertical_size_policy);
  458. else
  459. set_size_policy(m_horizontal_size_policy, policy);
  460. }
  461. void Widget::set_size_policy(SizePolicy horizontal_policy, SizePolicy vertical_policy)
  462. {
  463. if (m_horizontal_size_policy == horizontal_policy && m_vertical_size_policy == vertical_policy)
  464. return;
  465. m_horizontal_size_policy = horizontal_policy;
  466. m_vertical_size_policy = vertical_policy;
  467. invalidate_layout();
  468. }
  469. void Widget::invalidate_layout()
  470. {
  471. if (window())
  472. window()->schedule_relayout();
  473. }
  474. void Widget::set_visible(bool visible)
  475. {
  476. if (visible == m_visible)
  477. return;
  478. m_visible = visible;
  479. if (auto* parent = parent_widget())
  480. parent->invalidate_layout();
  481. if (m_visible)
  482. update();
  483. if (m_visible) {
  484. ShowEvent e;
  485. event(e);
  486. } else {
  487. HideEvent e;
  488. event(e);
  489. }
  490. }
  491. bool Widget::spans_entire_window_horizontally() const
  492. {
  493. auto* w = window();
  494. if (!w)
  495. return false;
  496. auto* main_widget = w->main_widget();
  497. if (!main_widget)
  498. return false;
  499. if (main_widget == this)
  500. return true;
  501. auto wrr = window_relative_rect();
  502. return wrr.left() == main_widget->rect().left() && wrr.right() == main_widget->rect().right();
  503. }
  504. void Widget::set_enabled(bool enabled)
  505. {
  506. if (m_enabled == enabled)
  507. return;
  508. m_enabled = enabled;
  509. Event e(Event::EnabledChange);
  510. event(e);
  511. update();
  512. }
  513. void Widget::move_to_front()
  514. {
  515. auto* parent = parent_widget();
  516. if (!parent)
  517. return;
  518. if (parent->children().size() == 1)
  519. return;
  520. parent->children().remove_first_matching([this](auto& entry) {
  521. return entry == this;
  522. });
  523. parent->children().append(*this);
  524. parent->update();
  525. }
  526. void Widget::move_to_back()
  527. {
  528. auto* parent = parent_widget();
  529. if (!parent)
  530. return;
  531. if (parent->children().size() == 1)
  532. return;
  533. parent->children().remove_first_matching([this](auto& entry) {
  534. return entry == this;
  535. });
  536. parent->children().prepend(*this);
  537. parent->update();
  538. }
  539. bool Widget::is_frontmost() const
  540. {
  541. auto* parent = parent_widget();
  542. if (!parent)
  543. return true;
  544. return &parent->children().last() == this;
  545. }
  546. bool Widget::is_backmost() const
  547. {
  548. auto* parent = parent_widget();
  549. if (!parent)
  550. return true;
  551. return &parent->children().first() == this;
  552. }
  553. Action* Widget::action_for_key_event(const KeyEvent& event)
  554. {
  555. Shortcut shortcut(event.modifiers(), (KeyCode)event.key());
  556. Action* found_action = nullptr;
  557. for_each_child_of_type<Action>([&](auto& action) {
  558. if (action.shortcut() == shortcut) {
  559. found_action = &action;
  560. return IterationDecision::Break;
  561. }
  562. return IterationDecision::Continue;
  563. });
  564. return found_action;
  565. }
  566. void Widget::set_updates_enabled(bool enabled)
  567. {
  568. if (m_updates_enabled == enabled)
  569. return;
  570. m_updates_enabled = enabled;
  571. if (enabled)
  572. update();
  573. }
  574. void Widget::focus_previous_widget()
  575. {
  576. auto focusable_widgets = window()->focusable_widgets();
  577. for (int i = focusable_widgets.size() - 1; i >= 0; --i) {
  578. if (focusable_widgets[i] != this)
  579. continue;
  580. if (i > 0)
  581. focusable_widgets[i - 1]->set_focus(true);
  582. else
  583. focusable_widgets.last()->set_focus(true);
  584. }
  585. }
  586. void Widget::focus_next_widget()
  587. {
  588. auto focusable_widgets = window()->focusable_widgets();
  589. for (int i = 0; i < focusable_widgets.size(); ++i) {
  590. if (focusable_widgets[i] != this)
  591. continue;
  592. if (i < focusable_widgets.size() - 1)
  593. focusable_widgets[i + 1]->set_focus(true);
  594. else
  595. focusable_widgets.first()->set_focus(true);
  596. }
  597. }
  598. void Widget::set_backcolor(const StringView& color_string)
  599. {
  600. auto color = Color::from_string(color_string);
  601. if (!color.has_value())
  602. return;
  603. set_background_color(color.value());
  604. }
  605. void Widget::set_forecolor(const StringView& color_string)
  606. {
  607. auto color = Color::from_string(color_string);
  608. if (!color.has_value())
  609. return;
  610. set_foreground_color(color.value());
  611. }
  612. void Widget::save_to(AK::JsonObject& json)
  613. {
  614. json.set("relative_rect", relative_rect().to_string());
  615. json.set("fill_with_background_color", fill_with_background_color());
  616. json.set("tooltip", tooltip());
  617. json.set("visible", is_visible());
  618. json.set("focused", is_focused());
  619. json.set("enabled", is_enabled());
  620. json.set("background_color", background_color().to_string());
  621. json.set("foreground_color", foreground_color().to_string());
  622. json.set("preferred_size", preferred_size().to_string());
  623. json.set("size_policy", String::format("[%s,%s]", to_string(horizontal_size_policy()), to_string(vertical_size_policy())));
  624. Core::Object::save_to(json);
  625. }
  626. Vector<Widget*> Widget::child_widgets() const
  627. {
  628. Vector<Widget*> widgets;
  629. widgets.ensure_capacity(children().size());
  630. for (auto& child : const_cast<Widget*>(this)->children()) {
  631. if (child.is_widget())
  632. widgets.append(static_cast<Widget*>(&child));
  633. }
  634. return widgets;
  635. }
  636. void Widget::set_palette(const Palette& palette)
  637. {
  638. m_palette = palette.impl();
  639. }
  640. }