Screen.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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. if (m_can_set_buffer) {
  199. unsigned buffer_offset = 0;
  200. rc = fb_get_buffer_offset(m_framebuffer_fd, 1, &buffer_offset);
  201. if (rc == 0) {
  202. m_back_buffer_offset = buffer_offset;
  203. } else {
  204. // fall back to assuming the second buffer starts right after the last line of the first
  205. m_back_buffer_offset = physical_resolution.pitch * physical_resolution.height;
  206. }
  207. } else {
  208. m_back_buffer_offset = 0;
  209. }
  210. }
  211. m_info.resolution = { physical_resolution.width, physical_resolution.height };
  212. m_pitch = physical_resolution.pitch;
  213. if (this == screen_with_cursor) {
  214. auto& screen_input = ScreenInput::the();
  215. screen_input.set_cursor_location(screen_input.cursor_location().constrained(rect()));
  216. }
  217. };
  218. if (rc == 0) {
  219. on_change_resolution();
  220. return true;
  221. }
  222. if (rc == -1) {
  223. int err = errno;
  224. dbgln("Screen #{}: Failed to set resolution {}: {}", index(), m_info.resolution, strerror(err));
  225. on_change_resolution();
  226. return false;
  227. }
  228. VERIFY_NOT_REACHED();
  229. }
  230. void Screen::set_buffer(int index)
  231. {
  232. VERIFY(m_can_set_buffer);
  233. int rc = fb_set_buffer(m_framebuffer_fd, index);
  234. VERIFY(rc == 0);
  235. }
  236. size_t Screen::buffer_offset(int index) const
  237. {
  238. if (index == 0)
  239. return 0;
  240. if (index == 1)
  241. return m_back_buffer_offset;
  242. VERIFY_NOT_REACHED();
  243. }
  244. void ScreenInput::set_acceleration_factor(double factor)
  245. {
  246. VERIFY(factor >= mouse_accel_min && factor <= mouse_accel_max);
  247. m_acceleration_factor = factor;
  248. }
  249. void ScreenInput::set_scroll_step_size(unsigned step_size)
  250. {
  251. VERIFY(step_size >= scroll_step_size_min);
  252. m_scroll_step_size = step_size;
  253. }
  254. void ScreenInput::on_receive_mouse_data(const MousePacket& packet)
  255. {
  256. auto& current_screen = cursor_location_screen();
  257. auto prev_location = m_cursor_location;
  258. if (packet.is_relative) {
  259. m_cursor_location.translate_by(packet.x * m_acceleration_factor, packet.y * m_acceleration_factor);
  260. dbgln_if(WSSCREEN_DEBUG, "Screen: New Relative mouse point @ {}", m_cursor_location);
  261. } else {
  262. m_cursor_location = { packet.x * current_screen.width() / 0xffff, packet.y * current_screen.height() / 0xffff };
  263. dbgln_if(WSSCREEN_DEBUG, "Screen: New Absolute mouse point @ {}", m_cursor_location);
  264. }
  265. auto* moved_to_screen = Screen::find_by_location(m_cursor_location);
  266. if (!moved_to_screen) {
  267. m_cursor_location = m_cursor_location.constrained(current_screen.rect());
  268. moved_to_screen = &current_screen;
  269. }
  270. unsigned buttons = packet.buttons;
  271. unsigned prev_buttons = m_mouse_button_state;
  272. m_mouse_button_state = buttons;
  273. unsigned changed_buttons = prev_buttons ^ buttons;
  274. auto post_mousedown_or_mouseup_if_needed = [&](MouseButton button) {
  275. if (!(changed_buttons & (unsigned)button))
  276. return;
  277. auto message = make<MouseEvent>(buttons & (unsigned)button ? Event::MouseDown : Event::MouseUp, m_cursor_location, buttons, button, m_modifiers);
  278. Core::EventLoop::current().post_event(WindowManager::the(), move(message));
  279. };
  280. post_mousedown_or_mouseup_if_needed(MouseButton::Left);
  281. post_mousedown_or_mouseup_if_needed(MouseButton::Right);
  282. post_mousedown_or_mouseup_if_needed(MouseButton::Middle);
  283. post_mousedown_or_mouseup_if_needed(MouseButton::Back);
  284. post_mousedown_or_mouseup_if_needed(MouseButton::Forward);
  285. if (m_cursor_location != prev_location) {
  286. auto message = make<MouseEvent>(Event::MouseMove, m_cursor_location, buttons, MouseButton::None, m_modifiers);
  287. if (WindowManager::the().dnd_client())
  288. message->set_mime_data(WindowManager::the().dnd_mime_data());
  289. Core::EventLoop::current().post_event(WindowManager::the(), move(message));
  290. }
  291. if (packet.z) {
  292. auto message = make<MouseEvent>(Event::MouseWheel, m_cursor_location, buttons, MouseButton::None, m_modifiers, packet.z * m_scroll_step_size);
  293. Core::EventLoop::current().post_event(WindowManager::the(), move(message));
  294. }
  295. if (m_cursor_location != prev_location)
  296. Compositor::the().invalidate_cursor();
  297. }
  298. void ScreenInput::on_receive_keyboard_data(::KeyEvent kernel_event)
  299. {
  300. m_modifiers = kernel_event.modifiers();
  301. 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);
  302. Core::EventLoop::current().post_event(WindowManager::the(), move(message));
  303. }
  304. void Screen::queue_flush_display_rect(Gfx::IntRect const& flush_region)
  305. {
  306. // NOTE: we don't scale until in Screen::flush_display so that when
  307. // there are too many rectangles that we end up throwing away, we didn't
  308. // waste accounting for scale factor!
  309. auto& fb_data = *m_framebuffer_data;
  310. if (fb_data.too_many_pending_flush_rects) {
  311. // We already have too many, just make sure we extend it if needed
  312. VERIFY(!fb_data.pending_flush_rects.is_empty());
  313. if (fb_data.pending_flush_rects.size() == 1) {
  314. auto& union_rect = fb_data.pending_flush_rects[0];
  315. auto new_union = flush_region.united(Gfx::IntRect((int)union_rect.x, (int)union_rect.y, (int)union_rect.width, (int)union_rect.height));
  316. union_rect.x = new_union.left();
  317. union_rect.y = new_union.top();
  318. union_rect.width = new_union.width();
  319. union_rect.height = new_union.height();
  320. } else {
  321. // Convert all the rectangles into one union
  322. auto new_union = flush_region;
  323. for (auto& flush_rect : fb_data.pending_flush_rects)
  324. new_union = new_union.united(Gfx::IntRect((int)flush_rect.x, (int)flush_rect.y, (int)flush_rect.width, (int)flush_rect.height));
  325. fb_data.pending_flush_rects.resize(1, true);
  326. auto& union_rect = fb_data.pending_flush_rects[0];
  327. union_rect.x = new_union.left();
  328. union_rect.y = new_union.top();
  329. union_rect.width = new_union.width();
  330. union_rect.height = new_union.height();
  331. }
  332. return;
  333. }
  334. VERIFY(fb_data.pending_flush_rects.size() < fb_data.pending_flush_rects.capacity());
  335. fb_data.pending_flush_rects.append({ (unsigned)flush_region.left(),
  336. (unsigned)flush_region.top(),
  337. (unsigned)flush_region.width(),
  338. (unsigned)flush_region.height() });
  339. if (fb_data.pending_flush_rects.size() == fb_data.pending_flush_rects.capacity()) {
  340. // If we get one more rectangle then we need to convert it to a single union rectangle
  341. fb_data.too_many_pending_flush_rects = true;
  342. }
  343. }
  344. void Screen::flush_display(int buffer_index)
  345. {
  346. VERIFY(m_can_device_flush_buffers);
  347. auto& fb_data = *m_framebuffer_data;
  348. if (fb_data.pending_flush_rects.is_empty())
  349. return;
  350. // Now that we have a final set of rects, apply the scale factor
  351. auto scale_factor = this->scale_factor();
  352. for (auto& flush_rect : fb_data.pending_flush_rects) {
  353. flush_rect.x *= scale_factor;
  354. flush_rect.y *= scale_factor;
  355. flush_rect.width *= scale_factor;
  356. flush_rect.height *= scale_factor;
  357. }
  358. if (fb_flush_buffers(m_framebuffer_fd, buffer_index, fb_data.pending_flush_rects.data(), (unsigned)fb_data.pending_flush_rects.size()) < 0) {
  359. int err = errno;
  360. if (err == ENOTSUP)
  361. m_can_device_flush_buffers = false;
  362. else
  363. dbgln("Screen #{}: Error ({}) flushing display: {}", index(), err, strerror(err));
  364. }
  365. fb_data.too_many_pending_flush_rects = false;
  366. fb_data.pending_flush_rects.clear_with_capacity();
  367. }
  368. void Screen::flush_display_front_buffer(int front_buffer_index, Gfx::IntRect& rect)
  369. {
  370. VERIFY(m_can_device_flush_buffers);
  371. auto scale_factor = this->scale_factor();
  372. FBRect flush_rect {
  373. .x = (unsigned)(rect.x() * scale_factor),
  374. .y = (unsigned)(rect.y() * scale_factor),
  375. .width = (unsigned)(rect.width() * scale_factor),
  376. .height = (unsigned)(rect.height() * scale_factor)
  377. };
  378. if (fb_flush_buffers(m_framebuffer_fd, front_buffer_index, &flush_rect, 1) < 0) {
  379. int err = errno;
  380. if (err == ENOTSUP)
  381. m_can_device_flush_buffers = false;
  382. else
  383. dbgln("Screen #{}: Error ({}) flushing display front buffer: {}", index(), err, strerror(err));
  384. }
  385. }
  386. }