Window.cpp 38 KB

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