Window.cpp 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  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_base_size,
  130. m_size_increment,
  131. m_resize_aspect_ratio,
  132. (i32)m_window_type,
  133. m_title_when_windowless,
  134. parent_window ? parent_window->window_id() : 0);
  135. m_window_id = response->window_id();
  136. m_visible = true;
  137. apply_icon();
  138. reified_windows->set(m_window_id, this);
  139. Application::the()->did_create_window({});
  140. update();
  141. }
  142. Window* Window::find_parent_window()
  143. {
  144. for (auto* ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
  145. if (is<Window>(ancestor))
  146. return static_cast<Window*>(ancestor);
  147. }
  148. return nullptr;
  149. }
  150. void Window::server_did_destroy()
  151. {
  152. reified_windows->remove(m_window_id);
  153. m_window_id = 0;
  154. m_visible = false;
  155. m_pending_paint_event_rects.clear();
  156. m_back_store = nullptr;
  157. m_front_store = nullptr;
  158. m_cursor = Gfx::StandardCursor::None;
  159. }
  160. void Window::hide()
  161. {
  162. if (!is_visible())
  163. return;
  164. auto response = WindowServerConnection::the().send_sync<Messages::WindowServer::DestroyWindow>(m_window_id);
  165. server_did_destroy();
  166. for (auto child_window_id : response->destroyed_window_ids()) {
  167. if (auto* window = Window::from_window_id(child_window_id)) {
  168. window->server_did_destroy();
  169. }
  170. }
  171. if (auto* app = Application::the()) {
  172. bool app_has_visible_windows = false;
  173. for (auto& window : *all_windows) {
  174. if (window->is_visible()) {
  175. app_has_visible_windows = true;
  176. break;
  177. }
  178. }
  179. if (!app_has_visible_windows)
  180. app->did_delete_last_window({});
  181. }
  182. }
  183. void Window::set_title(const StringView& title)
  184. {
  185. m_title_when_windowless = title;
  186. if (!is_visible())
  187. return;
  188. WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowTitle>(m_window_id, title);
  189. }
  190. String Window::title() const
  191. {
  192. if (!is_visible())
  193. return m_title_when_windowless;
  194. return WindowServerConnection::the().send_sync<Messages::WindowServer::GetWindowTitle>(m_window_id)->title();
  195. }
  196. Gfx::IntRect Window::rect_in_menubar() const
  197. {
  198. ASSERT(m_window_type == WindowType::MenuApplet);
  199. return WindowServerConnection::the().send_sync<Messages::WindowServer::GetWindowRectInMenubar>(m_window_id)->rect();
  200. }
  201. Gfx::IntRect Window::rect() const
  202. {
  203. if (!is_visible())
  204. return m_rect_when_windowless;
  205. return WindowServerConnection::the().send_sync<Messages::WindowServer::GetWindowRect>(m_window_id)->rect();
  206. }
  207. void Window::set_rect(const Gfx::IntRect& a_rect)
  208. {
  209. if (a_rect.location() != m_rect_when_windowless.location()) {
  210. m_moved_by_client = true;
  211. }
  212. m_rect_when_windowless = a_rect;
  213. if (!is_visible()) {
  214. if (m_main_widget)
  215. m_main_widget->resize(m_rect_when_windowless.size());
  216. return;
  217. }
  218. auto window_rect = WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowRect>(m_window_id, a_rect)->rect();
  219. if (m_back_store && m_back_store->size() != window_rect.size())
  220. m_back_store = nullptr;
  221. if (m_front_store && m_front_store->size() != window_rect.size())
  222. m_front_store = nullptr;
  223. if (m_main_widget)
  224. m_main_widget->resize(window_rect.size());
  225. }
  226. void Window::center_on_screen()
  227. {
  228. auto window_rect = rect();
  229. window_rect.center_within(Desktop::the().rect());
  230. set_rect(window_rect);
  231. }
  232. void Window::center_within(const Window& other)
  233. {
  234. if (this == &other)
  235. return;
  236. auto window_rect = rect();
  237. window_rect.center_within(other.rect());
  238. set_rect(window_rect);
  239. }
  240. void Window::set_window_type(WindowType window_type)
  241. {
  242. m_window_type = window_type;
  243. }
  244. void Window::set_cursor(Gfx::StandardCursor cursor)
  245. {
  246. if (m_cursor == cursor)
  247. return;
  248. m_cursor = cursor;
  249. m_custom_cursor = nullptr;
  250. update_cursor();
  251. }
  252. void Window::set_cursor(const Gfx::Bitmap& cursor)
  253. {
  254. if (m_custom_cursor == &cursor)
  255. return;
  256. m_cursor = Gfx::StandardCursor::None;
  257. m_custom_cursor = &cursor;
  258. update_cursor();
  259. }
  260. void Window::handle_drop_event(DropEvent& event)
  261. {
  262. if (!m_main_widget)
  263. return;
  264. auto result = m_main_widget->hit_test(event.position());
  265. auto local_event = make<DropEvent>(result.local_position, event.text(), event.mime_data());
  266. ASSERT(result.widget);
  267. result.widget->dispatch_event(*local_event, this);
  268. Application::the()->set_drag_hovered_widget({}, nullptr);
  269. }
  270. void Window::handle_mouse_event(MouseEvent& event)
  271. {
  272. if (m_global_cursor_tracking_widget) {
  273. auto window_relative_rect = m_global_cursor_tracking_widget->window_relative_rect();
  274. Gfx::IntPoint local_point { event.x() - window_relative_rect.x(), event.y() - window_relative_rect.y() };
  275. auto local_event = make<MouseEvent>((Event::Type)event.type(), local_point, event.buttons(), event.button(), event.modifiers(), event.wheel_delta());
  276. m_global_cursor_tracking_widget->dispatch_event(*local_event, this);
  277. return;
  278. }
  279. if (m_automatic_cursor_tracking_widget) {
  280. auto window_relative_rect = m_automatic_cursor_tracking_widget->window_relative_rect();
  281. Gfx::IntPoint local_point { event.x() - window_relative_rect.x(), event.y() - window_relative_rect.y() };
  282. auto local_event = make<MouseEvent>((Event::Type)event.type(), local_point, event.buttons(), event.button(), event.modifiers(), event.wheel_delta());
  283. m_automatic_cursor_tracking_widget->dispatch_event(*local_event, this);
  284. if (event.buttons() == 0)
  285. m_automatic_cursor_tracking_widget = nullptr;
  286. return;
  287. }
  288. if (!m_main_widget)
  289. return;
  290. auto result = m_main_widget->hit_test(event.position());
  291. auto local_event = make<MouseEvent>((Event::Type)event.type(), result.local_position, event.buttons(), event.button(), event.modifiers(), event.wheel_delta());
  292. ASSERT(result.widget);
  293. set_hovered_widget(result.widget);
  294. if (event.buttons() != 0 && !m_automatic_cursor_tracking_widget)
  295. m_automatic_cursor_tracking_widget = *result.widget;
  296. if (result.widget != m_global_cursor_tracking_widget.ptr())
  297. return result.widget->dispatch_event(*local_event, this);
  298. return;
  299. }
  300. void Window::handle_multi_paint_event(MultiPaintEvent& event)
  301. {
  302. if (!is_visible())
  303. return;
  304. if (!m_main_widget)
  305. return;
  306. auto rects = event.rects();
  307. ASSERT(!rects.is_empty());
  308. if (m_back_store && m_back_store->size() != event.window_size()) {
  309. // Eagerly discard the backing store if we learn from this paint event that it needs to be bigger.
  310. // Otherwise we would have to wait for a resize event to tell us. This way we don't waste the
  311. // effort on painting into an undersized bitmap that will be thrown away anyway.
  312. m_back_store = nullptr;
  313. }
  314. bool created_new_backing_store = !m_back_store;
  315. if (!m_back_store) {
  316. m_back_store = create_backing_store(event.window_size());
  317. ASSERT(m_back_store);
  318. } else if (m_double_buffering_enabled) {
  319. bool still_has_pixels = m_back_store->bitmap().set_nonvolatile();
  320. if (!still_has_pixels) {
  321. m_back_store = create_backing_store(event.window_size());
  322. ASSERT(m_back_store);
  323. created_new_backing_store = true;
  324. }
  325. }
  326. auto rect = rects.first();
  327. if (rect.is_empty() || created_new_backing_store) {
  328. rects.clear();
  329. rects.append({ {}, event.window_size() });
  330. }
  331. for (auto& rect : rects) {
  332. PaintEvent paint_event(rect);
  333. m_main_widget->dispatch_event(paint_event, this);
  334. }
  335. if (m_double_buffering_enabled)
  336. flip(rects);
  337. else if (created_new_backing_store)
  338. set_current_backing_store(*m_back_store, true);
  339. if (is_visible()) {
  340. Vector<Gfx::IntRect> rects_to_send;
  341. for (auto& r : rects)
  342. rects_to_send.append(r);
  343. WindowServerConnection::the().post_message(Messages::WindowServer::DidFinishPainting(m_window_id, rects_to_send));
  344. }
  345. }
  346. void Window::handle_key_event(KeyEvent& event)
  347. {
  348. if (!m_focused_widget && event.type() == Event::KeyDown && event.key() == Key_Tab && !event.ctrl() && !event.alt() && !event.logo()) {
  349. focus_a_widget_if_possible(FocusSource::Keyboard);
  350. return;
  351. }
  352. if (m_focused_widget)
  353. return m_focused_widget->dispatch_event(event, this);
  354. if (m_main_widget)
  355. return m_main_widget->dispatch_event(event, this);
  356. }
  357. void Window::handle_resize_event(ResizeEvent& event)
  358. {
  359. auto new_size = event.size();
  360. if (m_back_store && m_back_store->size() != new_size)
  361. m_back_store = nullptr;
  362. if (!m_pending_paint_event_rects.is_empty()) {
  363. m_pending_paint_event_rects.clear_with_capacity();
  364. m_pending_paint_event_rects.append({ {}, new_size });
  365. }
  366. m_rect_when_windowless = { {}, new_size };
  367. if (m_main_widget)
  368. m_main_widget->set_relative_rect({ {}, new_size });
  369. }
  370. void Window::handle_input_entered_or_left_event(Core::Event& event)
  371. {
  372. m_is_active_input = event.type() == Event::WindowInputEntered;
  373. if (on_active_input_change)
  374. on_active_input_change(m_is_active_input);
  375. if (m_main_widget)
  376. m_main_widget->dispatch_event(event, this);
  377. if (m_focused_widget)
  378. m_focused_widget->update();
  379. }
  380. void Window::handle_became_active_or_inactive_event(Core::Event& event)
  381. {
  382. if (event.type() == Event::WindowBecameActive)
  383. Application::the()->window_did_become_active({}, *this);
  384. else
  385. Application::the()->window_did_become_inactive({}, *this);
  386. if (m_main_widget)
  387. m_main_widget->dispatch_event(event, this);
  388. if (m_focused_widget)
  389. m_focused_widget->update();
  390. }
  391. void Window::handle_close_request()
  392. {
  393. if (on_close_request) {
  394. if (on_close_request() == Window::CloseRequestDecision::StayOpen)
  395. return;
  396. }
  397. close();
  398. }
  399. void Window::handle_theme_change_event(ThemeChangeEvent& event)
  400. {
  401. if (!m_main_widget)
  402. return;
  403. auto dispatch_theme_change = [&](auto& widget, auto recursive) {
  404. widget.dispatch_event(event, this);
  405. widget.for_each_child_widget([&](auto& widget) -> IterationDecision {
  406. widget.dispatch_event(event, this);
  407. recursive(widget, recursive);
  408. return IterationDecision::Continue;
  409. });
  410. };
  411. dispatch_theme_change(*m_main_widget.ptr(), dispatch_theme_change);
  412. }
  413. void Window::handle_drag_move_event(DragEvent& event)
  414. {
  415. if (!m_main_widget)
  416. return;
  417. auto result = m_main_widget->hit_test(event.position());
  418. ASSERT(result.widget);
  419. Application::the()->set_drag_hovered_widget({}, result.widget, result.local_position, event.mime_types());
  420. // NOTE: Setting the drag hovered widget may have executed arbitrary code, so re-check that the widget is still there.
  421. if (!result.widget)
  422. return;
  423. if (result.widget->has_pending_drop()) {
  424. DragEvent drag_move_event(static_cast<Event::Type>(event.type()), result.local_position, event.mime_types());
  425. result.widget->dispatch_event(drag_move_event, this);
  426. }
  427. }
  428. void Window::handle_left_event()
  429. {
  430. set_hovered_widget(nullptr);
  431. Application::the()->set_drag_hovered_widget({}, nullptr);
  432. }
  433. void Window::event(Core::Event& event)
  434. {
  435. ScopeGuard guard([&] {
  436. // Accept the event so it doesn't bubble up to parent windows!
  437. event.accept();
  438. });
  439. if (event.type() == Event::Drop)
  440. return handle_drop_event(static_cast<DropEvent&>(event));
  441. if (event.type() == Event::MouseUp || event.type() == Event::MouseDown || event.type() == Event::MouseDoubleClick || event.type() == Event::MouseMove || event.type() == Event::MouseWheel)
  442. return handle_mouse_event(static_cast<MouseEvent&>(event));
  443. if (event.type() == Event::MultiPaint)
  444. return handle_multi_paint_event(static_cast<MultiPaintEvent&>(event));
  445. if (event.type() == Event::KeyUp || event.type() == Event::KeyDown)
  446. return handle_key_event(static_cast<KeyEvent&>(event));
  447. if (event.type() == Event::WindowBecameActive || event.type() == Event::WindowBecameInactive)
  448. return handle_became_active_or_inactive_event(event);
  449. if (event.type() == Event::WindowInputEntered || event.type() == Event::WindowInputLeft)
  450. return handle_input_entered_or_left_event(event);
  451. if (event.type() == Event::WindowCloseRequest)
  452. return handle_close_request();
  453. if (event.type() == Event::WindowLeft)
  454. return handle_left_event();
  455. if (event.type() == Event::Resize)
  456. return handle_resize_event(static_cast<ResizeEvent&>(event));
  457. if (event.type() > Event::__Begin_WM_Events && event.type() < Event::__End_WM_Events)
  458. return wm_event(static_cast<WMEvent&>(event));
  459. if (event.type() == Event::DragMove)
  460. return handle_drag_move_event(static_cast<DragEvent&>(event));
  461. if (event.type() == Event::ThemeChange)
  462. return handle_theme_change_event(static_cast<ThemeChangeEvent&>(event));
  463. Core::Object::event(event);
  464. }
  465. bool Window::is_visible() const
  466. {
  467. return m_visible;
  468. }
  469. void Window::update()
  470. {
  471. auto rect = this->rect();
  472. update({ 0, 0, rect.width(), rect.height() });
  473. }
  474. void Window::force_update()
  475. {
  476. if (!is_visible())
  477. return;
  478. auto rect = this->rect();
  479. WindowServerConnection::the().post_message(Messages::WindowServer::InvalidateRect(m_window_id, { { 0, 0, rect.width(), rect.height() } }, true));
  480. }
  481. void Window::update(const Gfx::IntRect& a_rect)
  482. {
  483. if (!is_visible())
  484. return;
  485. for (auto& pending_rect : m_pending_paint_event_rects) {
  486. if (pending_rect.contains(a_rect)) {
  487. #if UPDATE_COALESCING_DEBUG
  488. dbgln("Ignoring {} since it's contained by pending rect {}", a_rect, pending_rect);
  489. #endif
  490. return;
  491. }
  492. }
  493. if (m_pending_paint_event_rects.is_empty()) {
  494. deferred_invoke([this](auto&) {
  495. auto rects = move(m_pending_paint_event_rects);
  496. if (rects.is_empty())
  497. return;
  498. Vector<Gfx::IntRect> rects_to_send;
  499. for (auto& r : rects)
  500. rects_to_send.append(r);
  501. WindowServerConnection::the().post_message(Messages::WindowServer::InvalidateRect(m_window_id, rects_to_send, false));
  502. });
  503. }
  504. m_pending_paint_event_rects.append(a_rect);
  505. }
  506. void Window::set_main_widget(Widget* widget)
  507. {
  508. if (m_main_widget == widget)
  509. return;
  510. if (m_main_widget) {
  511. m_main_widget->set_window(nullptr);
  512. remove_child(*m_main_widget);
  513. }
  514. m_main_widget = widget;
  515. if (m_main_widget) {
  516. add_child(*widget);
  517. auto new_window_rect = rect();
  518. if (m_main_widget->min_width() >= 0)
  519. new_window_rect.set_width(max(new_window_rect.width(), m_main_widget->min_width()));
  520. if (m_main_widget->min_height() >= 0)
  521. new_window_rect.set_height(max(new_window_rect.height(), m_main_widget->min_height()));
  522. set_rect(new_window_rect);
  523. m_main_widget->set_relative_rect({ {}, new_window_rect.size() });
  524. m_main_widget->set_window(this);
  525. if (m_main_widget->focus_policy() != FocusPolicy::NoFocus)
  526. m_main_widget->set_focus(true);
  527. }
  528. update();
  529. }
  530. void Window::set_focused_widget(Widget* widget, FocusSource source)
  531. {
  532. if (m_focused_widget == widget)
  533. return;
  534. WeakPtr<Widget> previously_focused_widget = m_focused_widget;
  535. m_focused_widget = widget;
  536. if (previously_focused_widget) {
  537. Core::EventLoop::current().post_event(*previously_focused_widget, make<FocusEvent>(Event::FocusOut, source));
  538. previously_focused_widget->update();
  539. if (previously_focused_widget && previously_focused_widget->on_focus_change)
  540. previously_focused_widget->on_focus_change(previously_focused_widget->is_focused(), source);
  541. }
  542. if (m_focused_widget) {
  543. Core::EventLoop::current().post_event(*m_focused_widget, make<FocusEvent>(Event::FocusIn, source));
  544. m_focused_widget->update();
  545. if (m_focused_widget && m_focused_widget->on_focus_change)
  546. m_focused_widget->on_focus_change(m_focused_widget->is_focused(), source);
  547. }
  548. }
  549. void Window::set_global_cursor_tracking_widget(Widget* widget)
  550. {
  551. if (widget == m_global_cursor_tracking_widget)
  552. return;
  553. m_global_cursor_tracking_widget = widget;
  554. }
  555. void Window::set_automatic_cursor_tracking_widget(Widget* widget)
  556. {
  557. if (widget == m_automatic_cursor_tracking_widget)
  558. return;
  559. m_automatic_cursor_tracking_widget = widget;
  560. }
  561. void Window::set_has_alpha_channel(bool value)
  562. {
  563. if (m_has_alpha_channel == value)
  564. return;
  565. m_has_alpha_channel = value;
  566. if (!is_visible())
  567. return;
  568. m_pending_paint_event_rects.clear();
  569. m_back_store = nullptr;
  570. m_front_store = nullptr;
  571. WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowHasAlphaChannel>(m_window_id, value);
  572. update();
  573. }
  574. void Window::set_double_buffering_enabled(bool value)
  575. {
  576. ASSERT(!is_visible());
  577. m_double_buffering_enabled = value;
  578. }
  579. void Window::set_opacity(float opacity)
  580. {
  581. m_opacity_when_windowless = opacity;
  582. if (!is_visible())
  583. return;
  584. WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowOpacity>(m_window_id, opacity);
  585. }
  586. void Window::set_hovered_widget(Widget* widget)
  587. {
  588. if (widget == m_hovered_widget)
  589. return;
  590. if (m_hovered_widget)
  591. Core::EventLoop::current().post_event(*m_hovered_widget, make<Event>(Event::Leave));
  592. m_hovered_widget = widget;
  593. if (m_hovered_widget)
  594. Core::EventLoop::current().post_event(*m_hovered_widget, make<Event>(Event::Enter));
  595. }
  596. void Window::set_current_backing_store(WindowBackingStore& backing_store, bool flush_immediately)
  597. {
  598. auto& bitmap = backing_store.bitmap();
  599. 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);
  600. }
  601. void Window::flip(const Vector<Gfx::IntRect, 32>& dirty_rects)
  602. {
  603. swap(m_front_store, m_back_store);
  604. set_current_backing_store(*m_front_store);
  605. if (!m_back_store || m_back_store->size() != m_front_store->size()) {
  606. m_back_store = create_backing_store(m_front_store->size());
  607. ASSERT(m_back_store);
  608. memcpy(m_back_store->bitmap().scanline(0), m_front_store->bitmap().scanline(0), m_front_store->bitmap().size_in_bytes());
  609. m_back_store->bitmap().set_volatile();
  610. return;
  611. }
  612. // Copy whatever was painted from the front to the back.
  613. Painter painter(m_back_store->bitmap());
  614. for (auto& dirty_rect : dirty_rects)
  615. painter.blit(dirty_rect.location(), m_front_store->bitmap(), dirty_rect);
  616. m_back_store->bitmap().set_volatile();
  617. }
  618. OwnPtr<WindowBackingStore> Window::create_backing_store(const Gfx::IntSize& size)
  619. {
  620. auto format = m_has_alpha_channel ? Gfx::BitmapFormat::RGBA32 : Gfx::BitmapFormat::RGB32;
  621. ASSERT(!size.is_empty());
  622. size_t pitch = Gfx::Bitmap::minimum_pitch(size.width(), format);
  623. size_t size_in_bytes = size.height() * pitch;
  624. auto anon_fd = anon_create(round_up_to_power_of_two(size_in_bytes, PAGE_SIZE), O_CLOEXEC);
  625. if (anon_fd < 0) {
  626. perror("anon_create");
  627. return {};
  628. }
  629. // FIXME: Plumb scale factor here eventually.
  630. auto bitmap = Gfx::Bitmap::create_with_anon_fd(format, anon_fd, size, 1, {}, Gfx::Bitmap::ShouldCloseAnonymousFile::No);
  631. if (!bitmap)
  632. return {};
  633. return make<WindowBackingStore>(bitmap.release_nonnull());
  634. }
  635. void Window::set_modal(bool modal)
  636. {
  637. ASSERT(!is_visible());
  638. m_modal = modal;
  639. }
  640. void Window::wm_event(WMEvent&)
  641. {
  642. }
  643. void Window::set_icon(const Gfx::Bitmap* icon)
  644. {
  645. if (m_icon == icon)
  646. return;
  647. Gfx::IntSize icon_size = icon ? icon->size() : Gfx::IntSize(16, 16);
  648. m_icon = Gfx::Bitmap::create(Gfx::BitmapFormat::RGBA32, icon_size);
  649. ASSERT(m_icon);
  650. if (icon) {
  651. Painter painter(*m_icon);
  652. painter.blit({ 0, 0 }, *icon, icon->rect());
  653. }
  654. apply_icon();
  655. }
  656. void Window::apply_icon()
  657. {
  658. if (!m_icon)
  659. return;
  660. if (!is_visible())
  661. return;
  662. WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowIconBitmap>(m_window_id, m_icon->to_shareable_bitmap());
  663. }
  664. void Window::start_wm_resize()
  665. {
  666. WindowServerConnection::the().post_message(Messages::WindowServer::WM_StartWindowResize(WindowServerConnection::the().my_client_id(), m_window_id));
  667. }
  668. Vector<Widget*> Window::focusable_widgets(FocusSource source) const
  669. {
  670. if (!m_main_widget)
  671. return {};
  672. HashTable<Widget*> seen_widgets;
  673. Vector<Widget*> collected_widgets;
  674. Function<void(Widget&)> collect_focusable_widgets = [&](auto& widget) {
  675. bool widget_accepts_focus = false;
  676. switch (source) {
  677. case FocusSource::Keyboard:
  678. widget_accepts_focus = ((unsigned)widget.focus_policy() & (unsigned)FocusPolicy::TabFocus);
  679. break;
  680. case FocusSource::Mouse:
  681. widget_accepts_focus = ((unsigned)widget.focus_policy() & (unsigned)FocusPolicy::ClickFocus);
  682. break;
  683. case FocusSource::Programmatic:
  684. widget_accepts_focus = widget.focus_policy() != FocusPolicy::NoFocus;
  685. break;
  686. }
  687. if (widget_accepts_focus) {
  688. auto& effective_focus_widget = widget.focus_proxy() ? *widget.focus_proxy() : widget;
  689. if (seen_widgets.set(&effective_focus_widget) == AK::HashSetResult::InsertedNewEntry)
  690. collected_widgets.append(&effective_focus_widget);
  691. }
  692. widget.for_each_child_widget([&](auto& child) {
  693. if (!child.is_visible())
  694. return IterationDecision::Continue;
  695. if (!child.is_enabled())
  696. return IterationDecision::Continue;
  697. collect_focusable_widgets(child);
  698. return IterationDecision::Continue;
  699. });
  700. };
  701. collect_focusable_widgets(const_cast<Widget&>(*m_main_widget));
  702. return collected_widgets;
  703. }
  704. void Window::set_fullscreen(bool fullscreen)
  705. {
  706. if (m_fullscreen == fullscreen)
  707. return;
  708. m_fullscreen = fullscreen;
  709. if (!is_visible())
  710. return;
  711. WindowServerConnection::the().send_sync<Messages::WindowServer::SetFullscreen>(m_window_id, fullscreen);
  712. }
  713. bool Window::is_maximized() const
  714. {
  715. if (!is_visible())
  716. return false;
  717. return WindowServerConnection::the().send_sync<Messages::WindowServer::IsMaximized>(m_window_id)->maximized();
  718. }
  719. void Window::schedule_relayout()
  720. {
  721. if (m_layout_pending)
  722. return;
  723. m_layout_pending = true;
  724. deferred_invoke([this](auto&) {
  725. if (main_widget())
  726. main_widget()->do_layout();
  727. update();
  728. m_layout_pending = false;
  729. });
  730. }
  731. void Window::refresh_system_theme()
  732. {
  733. WindowServerConnection::the().post_message(Messages::WindowServer::RefreshSystemTheme());
  734. }
  735. void Window::for_each_window(Badge<WindowServerConnection>, Function<void(Window&)> callback)
  736. {
  737. for (auto& e : *reified_windows) {
  738. ASSERT(e.value);
  739. callback(*e.value);
  740. }
  741. }
  742. void Window::update_all_windows(Badge<WindowServerConnection>)
  743. {
  744. for (auto& e : *reified_windows) {
  745. e.value->force_update();
  746. }
  747. }
  748. void Window::notify_state_changed(Badge<WindowServerConnection>, bool minimized, bool occluded)
  749. {
  750. m_visible_for_timer_purposes = !minimized && !occluded;
  751. // When double buffering is enabled, minimization/occlusion means we can mark the front bitmap volatile (in addition to the back bitmap.)
  752. // When double buffering is disabled, there is only the back bitmap (which we can now mark volatile!)
  753. auto& store = m_double_buffering_enabled ? m_front_store : m_back_store;
  754. if (!store)
  755. return;
  756. if (minimized || occluded) {
  757. store->bitmap().set_volatile();
  758. } else {
  759. if (!store->bitmap().set_nonvolatile()) {
  760. store = nullptr;
  761. update();
  762. }
  763. }
  764. }
  765. Action* Window::action_for_key_event(const KeyEvent& event)
  766. {
  767. Shortcut shortcut(event.modifiers(), (KeyCode)event.key());
  768. Action* found_action = nullptr;
  769. for_each_child_of_type<Action>([&](auto& action) {
  770. if (action.shortcut() == shortcut) {
  771. found_action = &action;
  772. return IterationDecision::Break;
  773. }
  774. return IterationDecision::Continue;
  775. });
  776. return found_action;
  777. }
  778. void Window::set_base_size(const Gfx::IntSize& base_size)
  779. {
  780. if (m_base_size == base_size)
  781. return;
  782. m_base_size = base_size;
  783. if (is_visible())
  784. WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowBaseSizeAndSizeIncrement>(m_window_id, m_base_size, m_size_increment);
  785. }
  786. void Window::set_size_increment(const Gfx::IntSize& size_increment)
  787. {
  788. if (m_size_increment == size_increment)
  789. return;
  790. m_size_increment = size_increment;
  791. if (is_visible())
  792. WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowBaseSizeAndSizeIncrement>(m_window_id, m_base_size, m_size_increment);
  793. }
  794. void Window::set_resize_aspect_ratio(const Optional<Gfx::IntSize>& ratio)
  795. {
  796. if (m_resize_aspect_ratio == ratio)
  797. return;
  798. m_resize_aspect_ratio = ratio;
  799. if (is_visible())
  800. WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowResizeAspectRatio>(m_window_id, m_resize_aspect_ratio);
  801. }
  802. void Window::did_add_widget(Badge<Widget>, Widget&)
  803. {
  804. if (!m_focused_widget)
  805. focus_a_widget_if_possible(FocusSource::Mouse);
  806. }
  807. void Window::did_remove_widget(Badge<Widget>, Widget& widget)
  808. {
  809. if (m_focused_widget == &widget)
  810. m_focused_widget = nullptr;
  811. if (m_hovered_widget == &widget)
  812. m_hovered_widget = nullptr;
  813. if (m_global_cursor_tracking_widget == &widget)
  814. m_global_cursor_tracking_widget = nullptr;
  815. if (m_automatic_cursor_tracking_widget == &widget)
  816. m_automatic_cursor_tracking_widget = nullptr;
  817. }
  818. void Window::set_progress(int progress)
  819. {
  820. ASSERT(m_window_id);
  821. WindowServerConnection::the().post_message(Messages::WindowServer::SetWindowProgress(m_window_id, progress));
  822. }
  823. void Window::update_cursor()
  824. {
  825. Gfx::StandardCursor new_cursor;
  826. if (m_hovered_widget && m_hovered_widget->override_cursor() != Gfx::StandardCursor::None)
  827. new_cursor = m_hovered_widget->override_cursor();
  828. else
  829. new_cursor = m_cursor;
  830. if (m_effective_cursor == new_cursor)
  831. return;
  832. m_effective_cursor = new_cursor;
  833. if (m_custom_cursor)
  834. WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowCustomCursor>(m_window_id, m_custom_cursor->to_shareable_bitmap());
  835. else
  836. WindowServerConnection::the().send_sync<Messages::WindowServer::SetWindowCursor>(m_window_id, (u32)m_effective_cursor);
  837. }
  838. void Window::focus_a_widget_if_possible(FocusSource source)
  839. {
  840. auto focusable_widgets = this->focusable_widgets(source);
  841. if (!focusable_widgets.is_empty())
  842. set_focused_widget(focusable_widgets[0], source);
  843. }
  844. void Window::did_disable_focused_widget(Badge<Widget>)
  845. {
  846. focus_a_widget_if_possible(FocusSource::Mouse);
  847. }
  848. bool Window::is_active() const
  849. {
  850. ASSERT(Application::the());
  851. return this == Application::the()->active_window();
  852. }
  853. Gfx::Bitmap* Window::back_bitmap()
  854. {
  855. return m_back_store ? &m_back_store->bitmap() : nullptr;
  856. }
  857. }