Window.cpp 33 KB

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