Window.cpp 38 KB

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