Window.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  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/Debug.h>
  27. #include <AK/HashMap.h>
  28. #include <AK/JsonObject.h>
  29. #include <AK/NeverDestroyed.h>
  30. #include <AK/ScopeGuard.h>
  31. #include <LibCore/EventLoop.h>
  32. #include <LibCore/MimeData.h>
  33. #include <LibGUI/Action.h>
  34. #include <LibGUI/Application.h>
  35. #include <LibGUI/Desktop.h>
  36. #include <LibGUI/Event.h>
  37. #include <LibGUI/MenuBar.h>
  38. #include <LibGUI/Painter.h>
  39. #include <LibGUI/Widget.h>
  40. #include <LibGUI/Window.h>
  41. #include <LibGUI/WindowServerConnection.h>
  42. #include <LibGfx/Bitmap.h>
  43. #include <fcntl.h>
  44. #include <serenity.h>
  45. #include <stdio.h>
  46. #include <stdlib.h>
  47. #include <unistd.h>
  48. namespace GUI {
  49. static i32 s_next_backing_store_serial;
  50. class WindowBackingStore {
  51. public:
  52. WindowBackingStore(NonnullRefPtr<Gfx::Bitmap> bitmap)
  53. : m_bitmap(bitmap)
  54. , m_serial(++s_next_backing_store_serial)
  55. {
  56. }
  57. Gfx::Bitmap& bitmap() { return *m_bitmap; }
  58. const Gfx::Bitmap& bitmap() const { return *m_bitmap; }
  59. Gfx::IntSize size() const { return m_bitmap->size(); }
  60. i32 serial() const { return m_serial; }
  61. private:
  62. NonnullRefPtr<Gfx::Bitmap> m_bitmap;
  63. const i32 m_serial;
  64. };
  65. static NeverDestroyed<HashTable<Window*>> all_windows;
  66. static NeverDestroyed<HashMap<int, Window*>> reified_windows;
  67. Window* Window::from_window_id(int window_id)
  68. {
  69. auto it = reified_windows->find(window_id);
  70. if (it != reified_windows->end())
  71. return (*it).value;
  72. return nullptr;
  73. }
  74. Window::Window(Core::Object* parent)
  75. : Core::Object(parent)
  76. {
  77. all_windows->set(this);
  78. m_rect_when_windowless = { -5000, -5000, 140, 140 };
  79. m_title_when_windowless = "GUI::Window";
  80. register_property(
  81. "title",
  82. [this] { return title(); },
  83. [this](auto& value) {
  84. set_title(value.to_string());
  85. return true;
  86. });
  87. register_property("visible", [this] { return is_visible(); });
  88. register_property("active", [this] { return is_active(); });
  89. REGISTER_BOOL_PROPERTY("minimizable", is_minimizable, set_minimizable);
  90. REGISTER_BOOL_PROPERTY("resizable", is_resizable, set_resizable);
  91. REGISTER_BOOL_PROPERTY("fullscreen", is_fullscreen, set_fullscreen);
  92. REGISTER_RECT_PROPERTY("rect", rect, set_rect);
  93. REGISTER_SIZE_PROPERTY("base_size", base_size, set_base_size);
  94. REGISTER_SIZE_PROPERTY("size_increment", size_increment, set_size_increment);
  95. }
  96. Window::~Window()
  97. {
  98. all_windows->remove(this);
  99. hide();
  100. }
  101. void Window::close()
  102. {
  103. hide();
  104. if (on_close)
  105. on_close();
  106. }
  107. void Window::move_to_front()
  108. {
  109. if (!is_visible())
  110. return;
  111. WindowServerConnection::the().send_sync<Messages::WindowServer::MoveWindowToFront>(m_window_id);
  112. }
  113. void Window::show()
  114. {
  115. if (is_visible())
  116. return;
  117. auto* parent_window = find_parent_window();
  118. m_cursor = Gfx::StandardCursor::None;
  119. auto response = WindowServerConnection::the().send_sync<Messages::WindowServer::CreateWindow>(
  120. m_rect_when_windowless,
  121. !m_moved_by_client,
  122. m_has_alpha_channel,
  123. m_modal,
  124. m_minimizable,
  125. m_resizable,
  126. m_fullscreen,
  127. m_frameless,
  128. m_accessory,
  129. m_opacity_when_windowless,
  130. m_alpha_hit_threshold,
  131. m_base_size,
  132. m_size_increment,
  133. m_minimum_size_when_windowless,
  134. m_resize_aspect_ratio,
  135. (i32)m_window_type,
  136. m_title_when_windowless,
  137. parent_window ? parent_window->window_id() : 0);
  138. m_window_id = response->window_id();
  139. m_visible = true;
  140. apply_icon();
  141. reified_windows->set(m_window_id, this);
  142. Application::the()->did_create_window({});
  143. update();
  144. }
  145. Window* Window::find_parent_window()
  146. {
  147. for (auto* ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
  148. if (is<Window>(ancestor))
  149. return static_cast<Window*>(ancestor);
  150. }
  151. return nullptr;
  152. }
  153. void Window::server_did_destroy()
  154. {
  155. reified_windows->remove(m_window_id);
  156. m_window_id = 0;
  157. m_visible = false;
  158. m_pending_paint_event_rects.clear();
  159. m_back_store = nullptr;
  160. m_front_store = nullptr;
  161. m_cursor = Gfx::StandardCursor::None;
  162. }
  163. void Window::hide()
  164. {
  165. if (!is_visible())
  166. return;
  167. auto response = WindowServerConnection::the().send_sync<Messages::WindowServer::DestroyWindow>(m_window_id);
  168. server_did_destroy();
  169. for (auto child_window_id : response->destroyed_window_ids()) {
  170. if (auto* window = Window::from_window_id(child_window_id)) {
  171. window->server_did_destroy();
  172. }
  173. }
  174. if (auto* app = Application::the()) {
  175. bool app_has_visible_windows = false;
  176. for (auto& window : *all_windows) {
  177. if (window->is_visible()) {
  178. app_has_visible_windows = true;
  179. break;
  180. }
  181. }
  182. if (!app_has_visible_windows)
  183. app->did_delete_last_window({});
  184. }
  185. }
  186. void Window::set_title(const StringView& title)
  187. {
  188. m_title_when_windowless = title;
  189. if (!is_visible())
  190. return;
  191. WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowTitle>(m_window_id, title);
  192. }
  193. String Window::title() const
  194. {
  195. if (!is_visible())
  196. return m_title_when_windowless;
  197. return WindowServerConnection::the().send_sync<Messages::WindowServer::GetWindowTitle>(m_window_id)->title();
  198. }
  199. Gfx::IntRect Window::rect_in_menubar() const
  200. {
  201. VERIFY(m_window_type == WindowType::MenuApplet);
  202. return WindowServerConnection::the().send_sync<Messages::WindowServer::GetWindowRectInMenubar>(m_window_id)->rect();
  203. }
  204. Gfx::IntRect Window::rect() const
  205. {
  206. if (!is_visible())
  207. return m_rect_when_windowless;
  208. return WindowServerConnection::the().send_sync<Messages::WindowServer::GetWindowRect>(m_window_id)->rect();
  209. }
  210. void Window::set_rect(const Gfx::IntRect& a_rect)
  211. {
  212. if (a_rect.location() != m_rect_when_windowless.location()) {
  213. m_moved_by_client = true;
  214. }
  215. m_rect_when_windowless = a_rect;
  216. if (!is_visible()) {
  217. if (m_main_widget)
  218. m_main_widget->resize(m_rect_when_windowless.size());
  219. return;
  220. }
  221. auto window_rect = WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowRect>(m_window_id, a_rect)->rect();
  222. if (m_back_store && m_back_store->size() != window_rect.size())
  223. m_back_store = nullptr;
  224. if (m_front_store && m_front_store->size() != window_rect.size())
  225. m_front_store = nullptr;
  226. if (m_main_widget)
  227. m_main_widget->resize(window_rect.size());
  228. }
  229. Gfx::IntSize Window::minimum_size() const
  230. {
  231. if (!is_visible())
  232. return m_minimum_size_when_windowless;
  233. return WindowServerConnection::the().send_sync<Messages::WindowServer::GetWindowMinimumSize>(m_window_id)->size();
  234. }
  235. void Window::set_minimum_size(const Gfx::IntSize& size)
  236. {
  237. m_minimum_size_modified = true;
  238. m_minimum_size_when_windowless = size;
  239. if (is_visible())
  240. WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowMinimumSize>(m_window_id, size);
  241. }
  242. void Window::center_on_screen()
  243. {
  244. auto window_rect = rect();
  245. window_rect.center_within(Desktop::the().rect());
  246. set_rect(window_rect);
  247. }
  248. void Window::center_within(const Window& other)
  249. {
  250. if (this == &other)
  251. return;
  252. auto window_rect = rect();
  253. window_rect.center_within(other.rect());
  254. set_rect(window_rect);
  255. }
  256. void Window::set_window_type(WindowType window_type)
  257. {
  258. m_window_type = window_type;
  259. if (!m_minimum_size_modified) {
  260. // Apply minimum size defaults.
  261. if (m_window_type == WindowType::Normal || m_window_type == WindowType::ToolWindow)
  262. m_minimum_size_when_windowless = { 50, 50 };
  263. else
  264. m_minimum_size_when_windowless = { 1, 1 };
  265. }
  266. }
  267. void Window::set_cursor(Gfx::StandardCursor cursor)
  268. {
  269. if (m_cursor == cursor)
  270. return;
  271. m_cursor = cursor;
  272. m_custom_cursor = nullptr;
  273. update_cursor();
  274. }
  275. void Window::set_cursor(const Gfx::Bitmap& cursor)
  276. {
  277. if (m_custom_cursor == &cursor)
  278. return;
  279. m_cursor = Gfx::StandardCursor::None;
  280. m_custom_cursor = &cursor;
  281. update_cursor();
  282. }
  283. void Window::handle_drop_event(DropEvent& event)
  284. {
  285. if (!m_main_widget)
  286. return;
  287. auto result = m_main_widget->hit_test(event.position());
  288. auto local_event = make<DropEvent>(result.local_position, event.text(), event.mime_data());
  289. VERIFY(result.widget);
  290. result.widget->dispatch_event(*local_event, this);
  291. Application::the()->set_drag_hovered_widget({}, nullptr);
  292. }
  293. void Window::handle_mouse_event(MouseEvent& event)
  294. {
  295. if (m_global_cursor_tracking_widget) {
  296. auto window_relative_rect = m_global_cursor_tracking_widget->window_relative_rect();
  297. Gfx::IntPoint local_point { event.x() - window_relative_rect.x(), event.y() - window_relative_rect.y() };
  298. auto local_event = make<MouseEvent>((Event::Type)event.type(), local_point, event.buttons(), event.button(), event.modifiers(), event.wheel_delta());
  299. m_global_cursor_tracking_widget->dispatch_event(*local_event, this);
  300. return;
  301. }
  302. if (m_automatic_cursor_tracking_widget) {
  303. auto window_relative_rect = m_automatic_cursor_tracking_widget->window_relative_rect();
  304. Gfx::IntPoint local_point { event.x() - window_relative_rect.x(), event.y() - window_relative_rect.y() };
  305. auto local_event = make<MouseEvent>((Event::Type)event.type(), local_point, event.buttons(), event.button(), event.modifiers(), event.wheel_delta());
  306. m_automatic_cursor_tracking_widget->dispatch_event(*local_event, this);
  307. if (event.buttons() == 0)
  308. m_automatic_cursor_tracking_widget = nullptr;
  309. return;
  310. }
  311. if (!m_main_widget)
  312. return;
  313. auto result = m_main_widget->hit_test(event.position());
  314. auto local_event = make<MouseEvent>((Event::Type)event.type(), result.local_position, event.buttons(), event.button(), event.modifiers(), event.wheel_delta());
  315. VERIFY(result.widget);
  316. set_hovered_widget(result.widget);
  317. if (event.buttons() != 0 && !m_automatic_cursor_tracking_widget)
  318. m_automatic_cursor_tracking_widget = *result.widget;
  319. if (result.widget != m_global_cursor_tracking_widget.ptr())
  320. result.widget->dispatch_event(*local_event, this);
  321. if (!m_pending_paint_event_rects.is_empty()) {
  322. MultiPaintEvent paint_event(move(m_pending_paint_event_rects), size());
  323. handle_multi_paint_event(paint_event);
  324. }
  325. }
  326. void Window::handle_multi_paint_event(MultiPaintEvent& event)
  327. {
  328. if (!is_visible())
  329. return;
  330. if (!m_main_widget)
  331. return;
  332. auto rects = event.rects();
  333. if (!m_pending_paint_event_rects.is_empty()) {
  334. // It's possible that there had been some calls to update() that
  335. // haven't been flushed. We can handle these right now, avoiding
  336. // another round trip.
  337. rects.append(move(m_pending_paint_event_rects));
  338. }
  339. VERIFY(!rects.is_empty());
  340. if (m_back_store && m_back_store->size() != event.window_size()) {
  341. // Eagerly discard the backing store if we learn from this paint event that it needs to be bigger.
  342. // Otherwise we would have to wait for a resize event to tell us. This way we don't waste the
  343. // effort on painting into an undersized bitmap that will be thrown away anyway.
  344. m_back_store = nullptr;
  345. }
  346. bool created_new_backing_store = !m_back_store;
  347. if (!m_back_store) {
  348. m_back_store = create_backing_store(event.window_size());
  349. VERIFY(m_back_store);
  350. } else if (m_double_buffering_enabled) {
  351. bool still_has_pixels = m_back_store->bitmap().set_nonvolatile();
  352. if (!still_has_pixels) {
  353. m_back_store = create_backing_store(event.window_size());
  354. VERIFY(m_back_store);
  355. created_new_backing_store = true;
  356. }
  357. }
  358. auto rect = rects.first();
  359. if (rect.is_empty() || created_new_backing_store) {
  360. rects.clear();
  361. rects.append({ {}, event.window_size() });
  362. }
  363. for (auto& rect : rects) {
  364. PaintEvent paint_event(rect);
  365. m_main_widget->dispatch_event(paint_event, this);
  366. }
  367. if (m_double_buffering_enabled)
  368. flip(rects);
  369. else if (created_new_backing_store)
  370. set_current_backing_store(*m_back_store, true);
  371. if (is_visible())
  372. WindowServerConnection::the().post_message(Messages::WindowServer::DidFinishPainting(m_window_id, rects));
  373. }
  374. void Window::handle_key_event(KeyEvent& event)
  375. {
  376. if (!m_focused_widget && event.type() == Event::KeyDown && event.key() == Key_Tab && !event.ctrl() && !event.alt() && !event.super()) {
  377. focus_a_widget_if_possible(FocusSource::Keyboard);
  378. return;
  379. }
  380. if (m_focused_widget)
  381. return m_focused_widget->dispatch_event(event, this);
  382. if (m_main_widget)
  383. return m_main_widget->dispatch_event(event, this);
  384. }
  385. void Window::handle_resize_event(ResizeEvent& event)
  386. {
  387. auto new_size = event.size();
  388. if (m_back_store && m_back_store->size() != new_size)
  389. m_back_store = nullptr;
  390. if (!m_pending_paint_event_rects.is_empty()) {
  391. m_pending_paint_event_rects.clear_with_capacity();
  392. m_pending_paint_event_rects.append({ {}, new_size });
  393. }
  394. m_rect_when_windowless = { {}, new_size };
  395. if (m_main_widget)
  396. m_main_widget->set_relative_rect({ {}, new_size });
  397. }
  398. void Window::handle_input_entered_or_left_event(Core::Event& event)
  399. {
  400. m_is_active_input = event.type() == Event::WindowInputEntered;
  401. if (on_active_input_change)
  402. on_active_input_change(m_is_active_input);
  403. if (m_main_widget)
  404. m_main_widget->dispatch_event(event, this);
  405. if (m_focused_widget)
  406. m_focused_widget->update();
  407. }
  408. void Window::handle_became_active_or_inactive_event(Core::Event& event)
  409. {
  410. if (event.type() == Event::WindowBecameActive)
  411. Application::the()->window_did_become_active({}, *this);
  412. else
  413. Application::the()->window_did_become_inactive({}, *this);
  414. if (m_main_widget)
  415. m_main_widget->dispatch_event(event, this);
  416. if (m_focused_widget)
  417. m_focused_widget->update();
  418. }
  419. void Window::handle_close_request()
  420. {
  421. if (on_close_request) {
  422. if (on_close_request() == Window::CloseRequestDecision::StayOpen)
  423. return;
  424. }
  425. close();
  426. }
  427. void Window::handle_theme_change_event(ThemeChangeEvent& event)
  428. {
  429. if (!m_main_widget)
  430. return;
  431. auto dispatch_theme_change = [&](auto& widget, auto recursive) {
  432. widget.dispatch_event(event, this);
  433. widget.for_each_child_widget([&](auto& widget) -> IterationDecision {
  434. widget.dispatch_event(event, this);
  435. recursive(widget, recursive);
  436. return IterationDecision::Continue;
  437. });
  438. };
  439. dispatch_theme_change(*m_main_widget.ptr(), dispatch_theme_change);
  440. }
  441. void Window::handle_drag_move_event(DragEvent& event)
  442. {
  443. if (!m_main_widget)
  444. return;
  445. auto result = m_main_widget->hit_test(event.position());
  446. VERIFY(result.widget);
  447. Application::the()->set_drag_hovered_widget({}, result.widget, result.local_position, event.mime_types());
  448. // NOTE: Setting the drag hovered widget may have executed arbitrary code, so re-check that the widget is still there.
  449. if (!result.widget)
  450. return;
  451. if (result.widget->has_pending_drop()) {
  452. DragEvent drag_move_event(static_cast<Event::Type>(event.type()), result.local_position, event.mime_types());
  453. result.widget->dispatch_event(drag_move_event, this);
  454. }
  455. }
  456. void Window::handle_left_event()
  457. {
  458. set_hovered_widget(nullptr);
  459. Application::the()->set_drag_hovered_widget({}, nullptr);
  460. }
  461. void Window::event(Core::Event& event)
  462. {
  463. ScopeGuard guard([&] {
  464. // Accept the event so it doesn't bubble up to parent windows!
  465. event.accept();
  466. });
  467. if (event.type() == Event::Drop)
  468. return handle_drop_event(static_cast<DropEvent&>(event));
  469. if (event.type() == Event::MouseUp || event.type() == Event::MouseDown || event.type() == Event::MouseDoubleClick || event.type() == Event::MouseMove || event.type() == Event::MouseWheel)
  470. return handle_mouse_event(static_cast<MouseEvent&>(event));
  471. if (event.type() == Event::MultiPaint)
  472. return handle_multi_paint_event(static_cast<MultiPaintEvent&>(event));
  473. if (event.type() == Event::KeyUp || event.type() == Event::KeyDown)
  474. return handle_key_event(static_cast<KeyEvent&>(event));
  475. if (event.type() == Event::WindowBecameActive || event.type() == Event::WindowBecameInactive)
  476. return handle_became_active_or_inactive_event(event);
  477. if (event.type() == Event::WindowInputEntered || event.type() == Event::WindowInputLeft)
  478. return handle_input_entered_or_left_event(event);
  479. if (event.type() == Event::WindowCloseRequest)
  480. return handle_close_request();
  481. if (event.type() == Event::WindowLeft)
  482. return handle_left_event();
  483. if (event.type() == Event::Resize)
  484. return handle_resize_event(static_cast<ResizeEvent&>(event));
  485. if (event.type() > Event::__Begin_WM_Events && event.type() < Event::__End_WM_Events)
  486. return wm_event(static_cast<WMEvent&>(event));
  487. if (event.type() == Event::DragMove)
  488. return handle_drag_move_event(static_cast<DragEvent&>(event));
  489. if (event.type() == Event::ThemeChange)
  490. return handle_theme_change_event(static_cast<ThemeChangeEvent&>(event));
  491. Core::Object::event(event);
  492. }
  493. bool Window::is_visible() const
  494. {
  495. return m_visible;
  496. }
  497. void Window::update()
  498. {
  499. auto rect = this->rect();
  500. update({ 0, 0, rect.width(), rect.height() });
  501. }
  502. void Window::force_update()
  503. {
  504. if (!is_visible())
  505. return;
  506. auto rect = this->rect();
  507. WindowServerConnection::the().post_message(Messages::WindowServer::InvalidateRect(m_window_id, { { 0, 0, rect.width(), rect.height() } }, true));
  508. }
  509. void Window::update(const Gfx::IntRect& a_rect)
  510. {
  511. if (!is_visible())
  512. return;
  513. for (auto& pending_rect : m_pending_paint_event_rects) {
  514. if (pending_rect.contains(a_rect)) {
  515. #if UPDATE_COALESCING_DEBUG
  516. dbgln("Ignoring {} since it's contained by pending rect {}", a_rect, pending_rect);
  517. #endif
  518. return;
  519. }
  520. }
  521. if (m_pending_paint_event_rects.is_empty()) {
  522. deferred_invoke([this](auto&) {
  523. auto rects = move(m_pending_paint_event_rects);
  524. if (rects.is_empty())
  525. return;
  526. WindowServerConnection::the().post_message(Messages::WindowServer::InvalidateRect(m_window_id, rects, false));
  527. });
  528. }
  529. m_pending_paint_event_rects.append(a_rect);
  530. }
  531. void Window::set_main_widget(Widget* widget)
  532. {
  533. if (m_main_widget == widget)
  534. return;
  535. if (m_main_widget) {
  536. m_main_widget->set_window(nullptr);
  537. remove_child(*m_main_widget);
  538. }
  539. m_main_widget = widget;
  540. if (m_main_widget) {
  541. add_child(*widget);
  542. auto new_window_rect = rect();
  543. if (m_main_widget->min_width() >= 0)
  544. new_window_rect.set_width(max(new_window_rect.width(), m_main_widget->min_width()));
  545. if (m_main_widget->min_height() >= 0)
  546. new_window_rect.set_height(max(new_window_rect.height(), m_main_widget->min_height()));
  547. set_rect(new_window_rect);
  548. m_main_widget->set_relative_rect({ {}, new_window_rect.size() });
  549. m_main_widget->set_window(this);
  550. if (m_main_widget->focus_policy() != FocusPolicy::NoFocus)
  551. m_main_widget->set_focus(true);
  552. }
  553. update();
  554. }
  555. void Window::set_focused_widget(Widget* widget, FocusSource source)
  556. {
  557. if (m_focused_widget == widget)
  558. return;
  559. WeakPtr<Widget> previously_focused_widget = m_focused_widget;
  560. m_focused_widget = widget;
  561. if (previously_focused_widget) {
  562. Core::EventLoop::current().post_event(*previously_focused_widget, make<FocusEvent>(Event::FocusOut, source));
  563. previously_focused_widget->update();
  564. if (previously_focused_widget && previously_focused_widget->on_focus_change)
  565. previously_focused_widget->on_focus_change(previously_focused_widget->is_focused(), source);
  566. }
  567. if (m_focused_widget) {
  568. Core::EventLoop::current().post_event(*m_focused_widget, make<FocusEvent>(Event::FocusIn, source));
  569. m_focused_widget->update();
  570. if (m_focused_widget && m_focused_widget->on_focus_change)
  571. m_focused_widget->on_focus_change(m_focused_widget->is_focused(), source);
  572. }
  573. }
  574. void Window::set_global_cursor_tracking_widget(Widget* widget)
  575. {
  576. if (widget == m_global_cursor_tracking_widget)
  577. return;
  578. m_global_cursor_tracking_widget = widget;
  579. }
  580. void Window::set_automatic_cursor_tracking_widget(Widget* widget)
  581. {
  582. if (widget == m_automatic_cursor_tracking_widget)
  583. return;
  584. m_automatic_cursor_tracking_widget = widget;
  585. }
  586. void Window::set_has_alpha_channel(bool value)
  587. {
  588. if (m_has_alpha_channel == value)
  589. return;
  590. m_has_alpha_channel = value;
  591. if (!is_visible())
  592. return;
  593. m_pending_paint_event_rects.clear();
  594. m_back_store = nullptr;
  595. m_front_store = nullptr;
  596. WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowHasAlphaChannel>(m_window_id, value);
  597. update();
  598. }
  599. void Window::set_double_buffering_enabled(bool value)
  600. {
  601. VERIFY(!is_visible());
  602. m_double_buffering_enabled = value;
  603. }
  604. void Window::set_opacity(float opacity)
  605. {
  606. m_opacity_when_windowless = opacity;
  607. if (!is_visible())
  608. return;
  609. WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowOpacity>(m_window_id, opacity);
  610. }
  611. void Window::set_alpha_hit_threshold(float threshold)
  612. {
  613. if (threshold < 0.0f)
  614. threshold = 0.0f;
  615. else if (threshold > 1.0f)
  616. threshold = 1.0f;
  617. if (m_alpha_hit_threshold == threshold)
  618. return;
  619. m_alpha_hit_threshold = threshold;
  620. if (!is_visible())
  621. return;
  622. WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowAlphaHitThreshold>(m_window_id, threshold);
  623. }
  624. void Window::set_hovered_widget(Widget* widget)
  625. {
  626. if (widget == m_hovered_widget)
  627. return;
  628. if (m_hovered_widget)
  629. Core::EventLoop::current().post_event(*m_hovered_widget, make<Event>(Event::Leave));
  630. m_hovered_widget = widget;
  631. if (m_hovered_widget)
  632. Core::EventLoop::current().post_event(*m_hovered_widget, make<Event>(Event::Enter));
  633. }
  634. void Window::set_current_backing_store(WindowBackingStore& backing_store, bool flush_immediately)
  635. {
  636. auto& bitmap = backing_store.bitmap();
  637. WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowBackingStore>(m_window_id, 32, bitmap.pitch(), bitmap.anon_fd(), backing_store.serial(), bitmap.has_alpha_channel(), bitmap.size(), flush_immediately);
  638. }
  639. void Window::flip(const Vector<Gfx::IntRect, 32>& dirty_rects)
  640. {
  641. swap(m_front_store, m_back_store);
  642. set_current_backing_store(*m_front_store);
  643. if (!m_back_store || m_back_store->size() != m_front_store->size()) {
  644. m_back_store = create_backing_store(m_front_store->size());
  645. VERIFY(m_back_store);
  646. memcpy(m_back_store->bitmap().scanline(0), m_front_store->bitmap().scanline(0), m_front_store->bitmap().size_in_bytes());
  647. m_back_store->bitmap().set_volatile();
  648. return;
  649. }
  650. // Copy whatever was painted from the front to the back.
  651. Painter painter(m_back_store->bitmap());
  652. for (auto& dirty_rect : dirty_rects)
  653. painter.blit(dirty_rect.location(), m_front_store->bitmap(), dirty_rect, 1.0f, false);
  654. m_back_store->bitmap().set_volatile();
  655. }
  656. OwnPtr<WindowBackingStore> Window::create_backing_store(const Gfx::IntSize& size)
  657. {
  658. auto format = m_has_alpha_channel ? Gfx::BitmapFormat::BGRA8888 : Gfx::BitmapFormat::BGRx8888;
  659. VERIFY(!size.is_empty());
  660. size_t pitch = Gfx::Bitmap::minimum_pitch(size.width(), format);
  661. size_t size_in_bytes = size.height() * pitch;
  662. auto anon_fd = anon_create(round_up_to_power_of_two(size_in_bytes, PAGE_SIZE), O_CLOEXEC);
  663. if (anon_fd < 0) {
  664. perror("anon_create");
  665. return {};
  666. }
  667. // FIXME: Plumb scale factor here eventually.
  668. auto bitmap = Gfx::Bitmap::create_with_anon_fd(format, anon_fd, size, 1, {}, Gfx::Bitmap::ShouldCloseAnonymousFile::No);
  669. if (!bitmap)
  670. return {};
  671. return make<WindowBackingStore>(bitmap.release_nonnull());
  672. }
  673. void Window::set_modal(bool modal)
  674. {
  675. VERIFY(!is_visible());
  676. m_modal = modal;
  677. }
  678. void Window::wm_event(WMEvent&)
  679. {
  680. }
  681. void Window::set_icon(const Gfx::Bitmap* icon)
  682. {
  683. if (m_icon == icon)
  684. return;
  685. Gfx::IntSize icon_size = icon ? icon->size() : Gfx::IntSize(16, 16);
  686. m_icon = Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, icon_size);
  687. VERIFY(m_icon);
  688. if (icon) {
  689. Painter painter(*m_icon);
  690. painter.blit({ 0, 0 }, *icon, icon->rect());
  691. }
  692. apply_icon();
  693. }
  694. void Window::apply_icon()
  695. {
  696. if (!m_icon)
  697. return;
  698. if (!is_visible())
  699. return;
  700. WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowIconBitmap>(m_window_id, m_icon->to_shareable_bitmap());
  701. }
  702. void Window::start_interactive_resize()
  703. {
  704. WindowServerConnection::the().post_message(Messages::WindowServer::StartWindowResize(m_window_id));
  705. }
  706. Vector<Widget*> Window::focusable_widgets(FocusSource source) const
  707. {
  708. if (!m_main_widget)
  709. return {};
  710. HashTable<Widget*> seen_widgets;
  711. Vector<Widget*> collected_widgets;
  712. Function<void(Widget&)> collect_focusable_widgets = [&](auto& widget) {
  713. bool widget_accepts_focus = false;
  714. switch (source) {
  715. case FocusSource::Keyboard:
  716. widget_accepts_focus = has_flag(widget.focus_policy(), FocusPolicy::TabFocus);
  717. break;
  718. case FocusSource::Mouse:
  719. widget_accepts_focus = has_flag(widget.focus_policy(), FocusPolicy::ClickFocus);
  720. break;
  721. case FocusSource::Programmatic:
  722. widget_accepts_focus = widget.focus_policy() != FocusPolicy::NoFocus;
  723. break;
  724. }
  725. if (widget_accepts_focus) {
  726. auto& effective_focus_widget = widget.focus_proxy() ? *widget.focus_proxy() : widget;
  727. if (seen_widgets.set(&effective_focus_widget) == AK::HashSetResult::InsertedNewEntry)
  728. collected_widgets.append(&effective_focus_widget);
  729. }
  730. widget.for_each_child_widget([&](auto& child) {
  731. if (!child.is_visible())
  732. return IterationDecision::Continue;
  733. if (!child.is_enabled())
  734. return IterationDecision::Continue;
  735. collect_focusable_widgets(child);
  736. return IterationDecision::Continue;
  737. });
  738. };
  739. collect_focusable_widgets(const_cast<Widget&>(*m_main_widget));
  740. return collected_widgets;
  741. }
  742. void Window::set_fullscreen(bool fullscreen)
  743. {
  744. if (m_fullscreen == fullscreen)
  745. return;
  746. m_fullscreen = fullscreen;
  747. if (!is_visible())
  748. return;
  749. WindowServerConnection::the().send_sync<Messages::WindowServer::SetFullscreen>(m_window_id, fullscreen);
  750. }
  751. void Window::set_frameless(bool frameless)
  752. {
  753. if (m_frameless == frameless)
  754. return;
  755. m_frameless = frameless;
  756. if (!is_visible())
  757. return;
  758. WindowServerConnection::the().send_sync<Messages::WindowServer::SetFrameless>(m_window_id, frameless);
  759. }
  760. bool Window::is_maximized() const
  761. {
  762. if (!is_visible())
  763. return false;
  764. return WindowServerConnection::the().send_sync<Messages::WindowServer::IsMaximized>(m_window_id)->maximized();
  765. }
  766. void Window::schedule_relayout()
  767. {
  768. if (m_layout_pending)
  769. return;
  770. m_layout_pending = true;
  771. deferred_invoke([this](auto&) {
  772. if (main_widget())
  773. main_widget()->do_layout();
  774. update();
  775. m_layout_pending = false;
  776. });
  777. }
  778. void Window::refresh_system_theme()
  779. {
  780. WindowServerConnection::the().post_message(Messages::WindowServer::RefreshSystemTheme());
  781. }
  782. void Window::for_each_window(Badge<WindowServerConnection>, Function<void(Window&)> callback)
  783. {
  784. for (auto& e : *reified_windows) {
  785. VERIFY(e.value);
  786. callback(*e.value);
  787. }
  788. }
  789. void Window::update_all_windows(Badge<WindowServerConnection>)
  790. {
  791. for (auto& e : *reified_windows) {
  792. e.value->force_update();
  793. }
  794. }
  795. void Window::notify_state_changed(Badge<WindowServerConnection>, bool minimized, bool occluded)
  796. {
  797. m_visible_for_timer_purposes = !minimized && !occluded;
  798. // When double buffering is enabled, minimization/occlusion means we can mark the front bitmap volatile (in addition to the back bitmap.)
  799. // When double buffering is disabled, there is only the back bitmap (which we can now mark volatile!)
  800. auto& store = m_double_buffering_enabled ? m_front_store : m_back_store;
  801. if (!store)
  802. return;
  803. if (minimized || occluded) {
  804. store->bitmap().set_volatile();
  805. } else {
  806. if (!store->bitmap().set_nonvolatile()) {
  807. store = nullptr;
  808. update();
  809. }
  810. }
  811. }
  812. Action* Window::action_for_key_event(const KeyEvent& event)
  813. {
  814. Shortcut shortcut(event.modifiers(), (KeyCode)event.key());
  815. Action* found_action = nullptr;
  816. for_each_child_of_type<Action>([&](auto& action) {
  817. if (action.shortcut() == shortcut) {
  818. found_action = &action;
  819. return IterationDecision::Break;
  820. }
  821. return IterationDecision::Continue;
  822. });
  823. return found_action;
  824. }
  825. void Window::set_base_size(const Gfx::IntSize& base_size)
  826. {
  827. if (m_base_size == base_size)
  828. return;
  829. m_base_size = base_size;
  830. if (is_visible())
  831. WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowBaseSizeAndSizeIncrement>(m_window_id, m_base_size, m_size_increment);
  832. }
  833. void Window::set_size_increment(const Gfx::IntSize& size_increment)
  834. {
  835. if (m_size_increment == size_increment)
  836. return;
  837. m_size_increment = size_increment;
  838. if (is_visible())
  839. WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowBaseSizeAndSizeIncrement>(m_window_id, m_base_size, m_size_increment);
  840. }
  841. void Window::set_resize_aspect_ratio(const Optional<Gfx::IntSize>& ratio)
  842. {
  843. if (m_resize_aspect_ratio == ratio)
  844. return;
  845. m_resize_aspect_ratio = ratio;
  846. if (is_visible())
  847. WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowResizeAspectRatio>(m_window_id, m_resize_aspect_ratio);
  848. }
  849. void Window::did_add_widget(Badge<Widget>, Widget&)
  850. {
  851. if (!m_focused_widget)
  852. focus_a_widget_if_possible(FocusSource::Mouse);
  853. }
  854. void Window::did_remove_widget(Badge<Widget>, Widget& widget)
  855. {
  856. if (m_focused_widget == &widget)
  857. m_focused_widget = nullptr;
  858. if (m_hovered_widget == &widget)
  859. m_hovered_widget = nullptr;
  860. if (m_global_cursor_tracking_widget == &widget)
  861. m_global_cursor_tracking_widget = nullptr;
  862. if (m_automatic_cursor_tracking_widget == &widget)
  863. m_automatic_cursor_tracking_widget = nullptr;
  864. }
  865. void Window::set_progress(int progress)
  866. {
  867. VERIFY(m_window_id);
  868. WindowServerConnection::the().post_message(Messages::WindowServer::SetWindowProgress(m_window_id, progress));
  869. }
  870. void Window::update_cursor()
  871. {
  872. Gfx::StandardCursor new_cursor;
  873. if (m_hovered_widget && m_hovered_widget->override_cursor() != Gfx::StandardCursor::None)
  874. new_cursor = m_hovered_widget->override_cursor();
  875. else
  876. new_cursor = m_cursor;
  877. if (m_effective_cursor == new_cursor)
  878. return;
  879. m_effective_cursor = new_cursor;
  880. if (m_custom_cursor)
  881. WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowCustomCursor>(m_window_id, m_custom_cursor->to_shareable_bitmap());
  882. else
  883. WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowCursor>(m_window_id, (u32)m_effective_cursor);
  884. }
  885. void Window::focus_a_widget_if_possible(FocusSource source)
  886. {
  887. auto focusable_widgets = this->focusable_widgets(source);
  888. if (!focusable_widgets.is_empty())
  889. set_focused_widget(focusable_widgets[0], source);
  890. }
  891. void Window::did_disable_focused_widget(Badge<Widget>)
  892. {
  893. focus_a_widget_if_possible(FocusSource::Mouse);
  894. }
  895. bool Window::is_active() const
  896. {
  897. VERIFY(Application::the());
  898. return this == Application::the()->active_window();
  899. }
  900. Gfx::Bitmap* Window::back_bitmap()
  901. {
  902. return m_back_store ? &m_back_store->bitmap() : nullptr;
  903. }
  904. void Window::set_menubar(RefPtr<MenuBar> menubar)
  905. {
  906. if (m_menubar == menubar)
  907. return;
  908. m_menubar = move(menubar);
  909. if (m_window_id && m_menubar)
  910. WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowMenubar>(m_window_id, m_menubar->menubar_id());
  911. }
  912. }