Window.cpp 36 KB

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