Window.cpp 33 KB

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