Screen.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "Screen.h"
  7. #include "Compositor.h"
  8. #include "Event.h"
  9. #include "EventLoop.h"
  10. #include "WindowManager.h"
  11. #include <AK/Debug.h>
  12. #include <Kernel/API/FB.h>
  13. #include <Kernel/API/MousePacket.h>
  14. #include <fcntl.h>
  15. #include <stdio.h>
  16. #include <sys/mman.h>
  17. #include <unistd.h>
  18. namespace WindowServer {
  19. NonnullOwnPtrVector<Screen, default_screen_count> Screen::s_screens;
  20. Screen* Screen::s_main_screen { nullptr };
  21. Gfx::IntRect Screen::s_bounding_screens_rect {};
  22. ScreenLayout Screen::s_layout;
  23. Vector<int, default_scale_factors_in_use_count> Screen::s_scale_factors_in_use;
  24. struct ScreenFBData {
  25. Vector<FBRect, 32> pending_flush_rects;
  26. bool too_many_pending_flush_rects { false };
  27. };
  28. ScreenInput& ScreenInput::the()
  29. {
  30. static ScreenInput s_the;
  31. return s_the;
  32. }
  33. Screen& ScreenInput::cursor_location_screen()
  34. {
  35. auto* screen = Screen::find_by_location(m_cursor_location);
  36. VERIFY(screen);
  37. return *screen;
  38. }
  39. const Screen& ScreenInput::cursor_location_screen() const
  40. {
  41. auto* screen = Screen::find_by_location(m_cursor_location);
  42. VERIFY(screen);
  43. return *screen;
  44. }
  45. bool Screen::apply_layout(ScreenLayout&& screen_layout, String& error_msg)
  46. {
  47. if (!screen_layout.is_valid(&error_msg))
  48. return false;
  49. auto screens_backup = move(s_screens);
  50. auto layout_backup = move(s_layout);
  51. for (auto& old_screen : screens_backup)
  52. old_screen.close_device();
  53. AK::ArmedScopeGuard rollback([&] {
  54. for (auto& screen : s_screens)
  55. screen.close_device();
  56. s_screens = move(screens_backup);
  57. s_layout = move(layout_backup);
  58. for (auto& old_screen : screens_backup) {
  59. if (!old_screen.open_device()) {
  60. // Don't set error_msg here, it should already be set
  61. dbgln("Rolling back screen layout failed: could not open device");
  62. }
  63. }
  64. update_bounding_rect();
  65. });
  66. s_layout = move(screen_layout);
  67. for (size_t index = 0; index < s_layout.screens.size(); index++) {
  68. auto* screen = WindowServer::Screen::create(s_layout.screens[index]);
  69. if (!screen) {
  70. error_msg = String::formatted("Error creating screen #{}", index);
  71. return false;
  72. }
  73. if (s_layout.main_screen_index == index)
  74. screen->make_main_screen();
  75. screen->open_device();
  76. }
  77. rollback.disarm();
  78. update_bounding_rect();
  79. update_scale_factors_in_use();
  80. return true;
  81. }
  82. void Screen::update_scale_factors_in_use()
  83. {
  84. s_scale_factors_in_use.clear();
  85. for_each([&](auto& screen) {
  86. auto scale_factor = screen.scale_factor();
  87. // The This doesn't have to be extremely efficient as this
  88. // code is only run when we start up or the screen configuration
  89. // changes. But using a vector allows for efficient iteration,
  90. // which is the most common use case.
  91. if (!s_scale_factors_in_use.contains_slow(scale_factor))
  92. s_scale_factors_in_use.append(scale_factor);
  93. return IterationDecision::Continue;
  94. });
  95. }
  96. Screen::Screen(ScreenLayout::Screen& screen_info)
  97. : m_virtual_rect(screen_info.location, { screen_info.resolution.width() / screen_info.scale_factor, screen_info.resolution.height() / screen_info.scale_factor })
  98. , m_framebuffer_data(adopt_own(*new ScreenFBData()))
  99. , m_info(screen_info)
  100. {
  101. open_device();
  102. // If the cursor is not in a valid screen (yet), force it into one
  103. dbgln("Screen() current physical cursor location: {} rect: {}", ScreenInput::the().cursor_location(), rect());
  104. if (!find_by_location(ScreenInput::the().cursor_location()))
  105. ScreenInput::the().set_cursor_location(rect().center());
  106. }
  107. Screen::~Screen()
  108. {
  109. close_device();
  110. }
  111. bool Screen::open_device()
  112. {
  113. close_device();
  114. m_framebuffer_fd = open(m_info.device.characters(), O_RDWR | O_CLOEXEC);
  115. if (m_framebuffer_fd < 0) {
  116. perror(String::formatted("failed to open {}", m_info.device).characters());
  117. return false;
  118. }
  119. m_can_set_buffer = (fb_set_buffer(m_framebuffer_fd, 0) == 0);
  120. m_can_device_flush_buffers = true; // If the device can't do it we revert to false
  121. set_resolution(true);
  122. return true;
  123. }
  124. void Screen::close_device()
  125. {
  126. if (m_framebuffer_fd >= 0) {
  127. close(m_framebuffer_fd);
  128. m_framebuffer_fd = -1;
  129. }
  130. if (m_framebuffer) {
  131. int rc = munmap(m_framebuffer, m_size_in_bytes);
  132. VERIFY(rc == 0);
  133. m_framebuffer = nullptr;
  134. m_size_in_bytes = 0;
  135. }
  136. }
  137. void Screen::init()
  138. {
  139. set_resolution(true);
  140. }
  141. Screen& Screen::closest_to_rect(const Gfx::IntRect& rect)
  142. {
  143. Screen* best_screen = nullptr;
  144. int best_area = 0;
  145. for (auto& screen : s_screens) {
  146. auto r = screen.rect().intersected(rect);
  147. int area = r.width() * r.height();
  148. if (!best_screen || area > best_area) {
  149. best_screen = &screen;
  150. best_area = area;
  151. }
  152. }
  153. if (!best_screen) {
  154. // TODO: try to find the best screen in close proximity
  155. best_screen = &Screen::main();
  156. }
  157. return *best_screen;
  158. }
  159. Screen& Screen::closest_to_location(const Gfx::IntPoint& point)
  160. {
  161. for (auto& screen : s_screens) {
  162. if (screen.rect().contains(point))
  163. return screen;
  164. }
  165. // TODO: guess based on how close the point is to the next screen rectangle
  166. return Screen::main();
  167. }
  168. void Screen::update_bounding_rect()
  169. {
  170. if (!s_screens.is_empty()) {
  171. s_bounding_screens_rect = s_screens[0].rect();
  172. for (size_t i = 1; i < s_screens.size(); i++)
  173. s_bounding_screens_rect = s_bounding_screens_rect.united(s_screens[i].rect());
  174. } else {
  175. s_bounding_screens_rect = {};
  176. }
  177. }
  178. bool Screen::set_resolution(bool initial)
  179. {
  180. // Remember the screen that the cursor is on. Make sure it stays on the same screen if we change its resolution...
  181. Screen* screen_with_cursor = nullptr;
  182. if (!initial)
  183. screen_with_cursor = &ScreenInput::the().cursor_location_screen();
  184. FBResolution physical_resolution { 0, (unsigned)m_info.resolution.width(), (unsigned)m_info.resolution.height() };
  185. int rc = fb_set_resolution(m_framebuffer_fd, &physical_resolution);
  186. dbgln_if(WSSCREEN_DEBUG, "Screen #{}: fb_set_resolution() - return code {}", index(), rc);
  187. auto on_change_resolution = [&]() {
  188. if (initial || physical_resolution.width != (unsigned)m_info.resolution.width() || physical_resolution.height != (unsigned)m_info.resolution.height()) {
  189. if (m_framebuffer) {
  190. size_t previous_size_in_bytes = m_size_in_bytes;
  191. int rc = munmap(m_framebuffer, previous_size_in_bytes);
  192. VERIFY(rc == 0);
  193. }
  194. int rc = fb_get_size_in_bytes(m_framebuffer_fd, &m_size_in_bytes);
  195. VERIFY(rc == 0);
  196. m_framebuffer = (Gfx::RGBA32*)mmap(nullptr, m_size_in_bytes, PROT_READ | PROT_WRITE, MAP_SHARED, m_framebuffer_fd, 0);
  197. VERIFY(m_framebuffer && m_framebuffer != (void*)-1);
  198. }
  199. m_info.resolution = { physical_resolution.width, physical_resolution.height };
  200. m_pitch = physical_resolution.pitch;
  201. if (this == screen_with_cursor) {
  202. auto& screen_input = ScreenInput::the();
  203. screen_input.set_cursor_location(screen_input.cursor_location().constrained(rect()));
  204. }
  205. };
  206. if (rc == 0) {
  207. on_change_resolution();
  208. return true;
  209. }
  210. if (rc == -1) {
  211. int err = errno;
  212. dbgln("Screen #{}: Failed to set resolution {}: {}", index(), m_info.resolution, strerror(err));
  213. on_change_resolution();
  214. return false;
  215. }
  216. VERIFY_NOT_REACHED();
  217. }
  218. void Screen::set_buffer(int index)
  219. {
  220. VERIFY(m_can_set_buffer);
  221. int rc = fb_set_buffer(m_framebuffer_fd, index);
  222. VERIFY(rc == 0);
  223. }
  224. void ScreenInput::set_acceleration_factor(double factor)
  225. {
  226. VERIFY(factor >= mouse_accel_min && factor <= mouse_accel_max);
  227. m_acceleration_factor = factor;
  228. }
  229. void ScreenInput::set_scroll_step_size(unsigned step_size)
  230. {
  231. VERIFY(step_size >= scroll_step_size_min);
  232. m_scroll_step_size = step_size;
  233. }
  234. void ScreenInput::on_receive_mouse_data(const MousePacket& packet)
  235. {
  236. auto& current_screen = cursor_location_screen();
  237. auto prev_location = m_cursor_location;
  238. if (packet.is_relative) {
  239. m_cursor_location.translate_by(packet.x * m_acceleration_factor, packet.y * m_acceleration_factor);
  240. dbgln_if(WSSCREEN_DEBUG, "Screen: New Relative mouse point @ {}", m_cursor_location);
  241. } else {
  242. m_cursor_location = { packet.x * current_screen.width() / 0xffff, packet.y * current_screen.height() / 0xffff };
  243. dbgln_if(WSSCREEN_DEBUG, "Screen: New Absolute mouse point @ {}", m_cursor_location);
  244. }
  245. auto* moved_to_screen = Screen::find_by_location(m_cursor_location);
  246. if (!moved_to_screen) {
  247. m_cursor_location = m_cursor_location.constrained(current_screen.rect());
  248. moved_to_screen = &current_screen;
  249. }
  250. unsigned buttons = packet.buttons;
  251. unsigned prev_buttons = m_mouse_button_state;
  252. m_mouse_button_state = buttons;
  253. unsigned changed_buttons = prev_buttons ^ buttons;
  254. auto post_mousedown_or_mouseup_if_needed = [&](MouseButton button) {
  255. if (!(changed_buttons & (unsigned)button))
  256. return;
  257. auto message = make<MouseEvent>(buttons & (unsigned)button ? Event::MouseDown : Event::MouseUp, m_cursor_location, buttons, button, m_modifiers);
  258. Core::EventLoop::current().post_event(WindowManager::the(), move(message));
  259. };
  260. post_mousedown_or_mouseup_if_needed(MouseButton::Left);
  261. post_mousedown_or_mouseup_if_needed(MouseButton::Right);
  262. post_mousedown_or_mouseup_if_needed(MouseButton::Middle);
  263. post_mousedown_or_mouseup_if_needed(MouseButton::Back);
  264. post_mousedown_or_mouseup_if_needed(MouseButton::Forward);
  265. if (m_cursor_location != prev_location) {
  266. auto message = make<MouseEvent>(Event::MouseMove, m_cursor_location, buttons, MouseButton::None, m_modifiers);
  267. if (WindowManager::the().dnd_client())
  268. message->set_mime_data(WindowManager::the().dnd_mime_data());
  269. Core::EventLoop::current().post_event(WindowManager::the(), move(message));
  270. }
  271. if (packet.z) {
  272. auto message = make<MouseEvent>(Event::MouseWheel, m_cursor_location, buttons, MouseButton::None, m_modifiers, packet.z * m_scroll_step_size);
  273. Core::EventLoop::current().post_event(WindowManager::the(), move(message));
  274. }
  275. if (m_cursor_location != prev_location)
  276. Compositor::the().invalidate_cursor();
  277. }
  278. void ScreenInput::on_receive_keyboard_data(::KeyEvent kernel_event)
  279. {
  280. m_modifiers = kernel_event.modifiers();
  281. auto message = make<KeyEvent>(kernel_event.is_press() ? Event::KeyDown : Event::KeyUp, kernel_event.key, kernel_event.code_point, kernel_event.modifiers(), kernel_event.scancode);
  282. Core::EventLoop::current().post_event(WindowManager::the(), move(message));
  283. }
  284. void Screen::queue_flush_display_rect(Gfx::IntRect const& flush_region)
  285. {
  286. // NOTE: we don't scale until in Screen::flush_display so that when
  287. // there are too many rectangles that we end up throwing away, we didn't
  288. // waste accounting for scale factor!
  289. auto& fb_data = *m_framebuffer_data;
  290. if (fb_data.too_many_pending_flush_rects) {
  291. // We already have too many, just make sure we extend it if needed
  292. VERIFY(!fb_data.pending_flush_rects.is_empty());
  293. if (fb_data.pending_flush_rects.size() == 1) {
  294. auto& union_rect = fb_data.pending_flush_rects[0];
  295. auto new_union = flush_region.united(Gfx::IntRect((int)union_rect.x, (int)union_rect.y, (int)union_rect.width, (int)union_rect.height));
  296. union_rect.x = new_union.left();
  297. union_rect.y = new_union.top();
  298. union_rect.width = new_union.width();
  299. union_rect.height = new_union.height();
  300. } else {
  301. // Convert all the rectangles into one union
  302. auto new_union = flush_region;
  303. for (auto& flush_rect : fb_data.pending_flush_rects)
  304. new_union = new_union.united(Gfx::IntRect((int)flush_rect.x, (int)flush_rect.y, (int)flush_rect.width, (int)flush_rect.height));
  305. fb_data.pending_flush_rects.resize(1, true);
  306. auto& union_rect = fb_data.pending_flush_rects[0];
  307. union_rect.x = new_union.left();
  308. union_rect.y = new_union.top();
  309. union_rect.width = new_union.width();
  310. union_rect.height = new_union.height();
  311. }
  312. return;
  313. }
  314. VERIFY(fb_data.pending_flush_rects.size() < fb_data.pending_flush_rects.capacity());
  315. fb_data.pending_flush_rects.append({ (unsigned)flush_region.left(),
  316. (unsigned)flush_region.top(),
  317. (unsigned)flush_region.width(),
  318. (unsigned)flush_region.height() });
  319. if (fb_data.pending_flush_rects.size() == fb_data.pending_flush_rects.capacity()) {
  320. // If we get one more rectangle then we need to convert it to a single union rectangle
  321. fb_data.too_many_pending_flush_rects = true;
  322. }
  323. }
  324. void Screen::flush_display(int buffer_index)
  325. {
  326. VERIFY(m_can_device_flush_buffers);
  327. auto& fb_data = *m_framebuffer_data;
  328. if (fb_data.pending_flush_rects.is_empty())
  329. return;
  330. // Now that we have a final set of rects, apply the scale factor
  331. auto scale_factor = this->scale_factor();
  332. for (auto& flush_rect : fb_data.pending_flush_rects) {
  333. flush_rect.x *= scale_factor;
  334. flush_rect.y *= scale_factor;
  335. flush_rect.width *= scale_factor;
  336. flush_rect.height *= scale_factor;
  337. }
  338. if (fb_flush_buffers(m_framebuffer_fd, buffer_index, fb_data.pending_flush_rects.data(), (unsigned)fb_data.pending_flush_rects.size()) < 0) {
  339. int err = errno;
  340. if (err == ENOTSUP)
  341. m_can_device_flush_buffers = false;
  342. else
  343. dbgln("Screen #{}: Error ({}) flushing display: {}", index(), err, strerror(err));
  344. }
  345. fb_data.too_many_pending_flush_rects = false;
  346. fb_data.pending_flush_rects.clear_with_capacity();
  347. }
  348. }