Window.cpp 39 KB

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