You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MonitorArrangement.cxx 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. /* Copyright 2021 Hugo Lundin <huglu@cendio.se> for Cendio AB.
  2. * Copyright 2021 Pierre Ossman for Cendio AB
  3. *
  4. * This is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 2 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This software is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this software; if not, write to the Free Software
  16. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
  17. * USA.
  18. */
  19. #include <set>
  20. #include <vector>
  21. #include <string>
  22. #include <utility>
  23. #include <sstream>
  24. #include <assert.h>
  25. #include <algorithm>
  26. #include <FL/Fl.H>
  27. #include <FL/fl_draw.H>
  28. #include <FL/Fl_Button.H>
  29. #if defined(HAVE_XRANDR) && !defined(__APPLE__)
  30. #include <X11/extensions/Xrandr.h>
  31. #include <X11/X.h>
  32. #include <X11/Xlib.h>
  33. #include <X11/Xutil.h>
  34. #endif
  35. #ifdef __APPLE__
  36. #include <Carbon/Carbon.h>
  37. #include <IOKit/graphics/IOGraphicsLib.h>
  38. #include <IOKit/hidsystem/IOHIDLib.h>
  39. #include <IOKit/hidsystem/IOHIDParameter.h>
  40. #endif
  41. #include <rfb/Rect.h>
  42. #include <rfb/LogWriter.h>
  43. #ifdef WIN32
  44. #include "win32.h"
  45. #endif
  46. #include "i18n.h"
  47. #include "MonitorArrangement.h"
  48. static std::set<MonitorArrangement *> instances;
  49. static rfb::LogWriter vlog("MonitorArrangement");
  50. static const Fl_Boxtype FL_CHECKERED_BOX = FL_FREE_BOXTYPE;
  51. MonitorArrangement::MonitorArrangement(
  52. int x, int y, int w, int h)
  53. : Fl_Group(x, y, w, h),
  54. SELECTION_COLOR(fl_lighter(FL_BLUE)),
  55. AVAILABLE_COLOR(fl_lighter(fl_lighter(fl_lighter(FL_BACKGROUND_COLOR))))
  56. {
  57. // Used for required monitors.
  58. Fl::set_boxtype(FL_CHECKERED_BOX, checkered_pattern_draw, 0, 0, 0, 0);
  59. if (instances.size() == 0)
  60. Fl::add_handler(fltk_event_handler);
  61. instances.insert(this);
  62. box(FL_DOWN_BOX);
  63. color(fl_lighter(FL_BACKGROUND_COLOR));
  64. layout();
  65. end();
  66. }
  67. MonitorArrangement::~MonitorArrangement()
  68. {
  69. instances.erase(this);
  70. if (instances.size() == 0)
  71. Fl::remove_handler(fltk_event_handler);
  72. }
  73. std::set<int> MonitorArrangement::get()
  74. {
  75. std::set<int> indices;
  76. MonitorMap::const_iterator iter;
  77. for (iter = monitors.begin(); iter != monitors.end(); ++iter) {
  78. if (iter->second->value() == 1)
  79. indices.insert(iter->first);
  80. }
  81. return indices;
  82. }
  83. void MonitorArrangement::set(std::set<int> indices)
  84. {
  85. MonitorMap::const_iterator iter;
  86. for (iter = monitors.begin(); iter != monitors.end(); ++iter) {
  87. bool selected = std::find(indices.begin(), indices.end(),
  88. iter->first) != indices.end();
  89. iter->second->value(selected ? 1 : 0);
  90. }
  91. }
  92. void MonitorArrangement::draw()
  93. {
  94. MonitorMap::const_iterator iter;
  95. for (iter = monitors.begin(); iter != monitors.end(); ++iter) {
  96. Fl_Button * monitor = iter->second;
  97. if (is_required(iter->first)) {
  98. monitor->box(FL_CHECKERED_BOX);
  99. monitor->color(SELECTION_COLOR);
  100. } else {
  101. monitor->box(FL_BORDER_BOX);
  102. monitor->color(AVAILABLE_COLOR);
  103. monitor->selection_color(SELECTION_COLOR);
  104. }
  105. }
  106. Fl_Group::draw();
  107. }
  108. void MonitorArrangement::layout()
  109. {
  110. int x, y, w, h;
  111. double scale = this->scale();
  112. const double MARGIN_SCALE_FACTOR = 0.99;
  113. std::pair<int, int> offset = this->offset();
  114. for (int i = 0; i < Fl::screen_count(); i++) {
  115. bool match;
  116. Fl::screen_xywh(x, y, w, h, i);
  117. // Only keep a single entry for mirrored screens
  118. match = false;
  119. for (int j = 0; j < i; j++) {
  120. int x2, y2, w2, h2;
  121. Fl::screen_xywh(x2, y2, w2, h2, j);
  122. if ((x != x2) || (y != y2) || (w != w2) || (h != h2))
  123. continue;
  124. match = true;
  125. break;
  126. }
  127. if (match)
  128. continue;
  129. Fl_Button *monitor = new Fl_Button(
  130. /* x = */ this->x() + offset.first + x*scale + (1 - MARGIN_SCALE_FACTOR)*x*scale,
  131. /* y = */ this->y() + offset.second + y*scale + (1 - MARGIN_SCALE_FACTOR)*y*scale,
  132. /* w = */ w*scale*MARGIN_SCALE_FACTOR,
  133. /* h = */ h*scale*MARGIN_SCALE_FACTOR
  134. );
  135. monitor->clear_visible_focus();
  136. monitor->callback(monitor_pressed, this);
  137. monitor->type(FL_TOGGLE_BUTTON);
  138. monitor->when(FL_WHEN_CHANGED);
  139. monitor->copy_tooltip(description(i).c_str());
  140. monitors[i] = monitor;
  141. }
  142. }
  143. void MonitorArrangement::refresh()
  144. {
  145. // The selection state is only saved persistently when "OK" is
  146. // pressed. We need to manually restore the current selection
  147. // when the widget is refreshed.
  148. std::set<int> indices = get();
  149. monitors.clear();
  150. // FLTK recursively deletes all children for us.
  151. clear();
  152. begin();
  153. layout();
  154. end();
  155. // Restore the current selection state.
  156. set(indices);
  157. redraw();
  158. }
  159. bool MonitorArrangement::is_required(int m)
  160. {
  161. // A selected monitor is never required.
  162. if (monitors[m]->value() == 1)
  163. return false;
  164. // If no monitors are selected, none are required.
  165. std::set<int> selected = get();
  166. if (selected.size() <= 0)
  167. return false;
  168. // Go through all selected monitors and find the monitor
  169. // indices that bounds the fullscreen frame buffer. If
  170. // the given monitor's coordinates are inside the bounds,
  171. // while not being selected, it is instead required.
  172. int x, y, w, h;
  173. int top_y, bottom_y, left_x, right_x;
  174. std::set<int>::iterator it = selected.begin();
  175. // Base the rest of the calculations on the dimensions
  176. // obtained for the first monitor.
  177. Fl::screen_xywh(x, y, w, h, *it);
  178. top_y = y;
  179. bottom_y = y + h;
  180. left_x = x;
  181. right_x = x + w;
  182. // Go through the rest of the monitors,
  183. // exhausting the rest of the iterator.
  184. for (; it != selected.end(); it++) {
  185. Fl::screen_xywh(x, y, w, h, *it);
  186. if (y < top_y) {
  187. top_y = y;
  188. }
  189. if ((y + h) > bottom_y) {
  190. bottom_y = y + h;
  191. }
  192. if (x < left_x) {
  193. left_x = x;
  194. }
  195. if ((x + w) > right_x) {
  196. right_x = x + w;
  197. }
  198. }
  199. rfb::Rect viewport, monitor;
  200. viewport.setXYWH(left_x, top_y, right_x - left_x, bottom_y - top_y);
  201. Fl::screen_xywh(x, y, w, h, m);
  202. monitor.setXYWH(x, y, w, h);
  203. return monitor.enclosed_by(viewport);
  204. }
  205. double MonitorArrangement::scale()
  206. {
  207. const int MARGIN = 20;
  208. std::pair<int, int> size = this->size();
  209. double s_w = static_cast<double>(this->w()-MARGIN) / static_cast<double>(size.first);
  210. double s_h = static_cast<double>(this->h()-MARGIN) / static_cast<double>(size.second);
  211. // Choose the one that scales the least, in order to
  212. // maximize our use of the given bounding area.
  213. if (s_w > s_h)
  214. return s_h;
  215. else
  216. return s_w;
  217. }
  218. std::pair<int, int> MonitorArrangement::size()
  219. {
  220. int x, y, w, h;
  221. int top, bottom, left, right;
  222. int x_min, x_max, y_min, y_max;
  223. x_min = x_max = y_min = y_max = 0;
  224. for (int i = 0; i < Fl::screen_count(); i++) {
  225. Fl::screen_xywh(x, y, w, h, i);
  226. top = y;
  227. bottom = y + h;
  228. left = x;
  229. right = x + w;
  230. if (top < y_min)
  231. y_min = top;
  232. if (bottom > y_max)
  233. y_max = bottom;
  234. if (left < x_min)
  235. x_min = left;
  236. if (right > x_max)
  237. x_max = right;
  238. }
  239. return std::make_pair(x_max - x_min, y_max - y_min);
  240. }
  241. std::pair<int, int> MonitorArrangement::offset()
  242. {
  243. double scale = this->scale();
  244. std::pair<int, int> size = this->size();
  245. std::pair<int, int> origin = this->origin();
  246. int offset_x = (this->w()/2) - (size.first/2 * scale);
  247. int offset_y = (this->h()/2) - (size.second/2 * scale);
  248. return std::make_pair(offset_x + abs(origin.first)*scale, offset_y + abs(origin.second)*scale);
  249. }
  250. std::pair<int, int> MonitorArrangement::origin()
  251. {
  252. int x, y, w, h, ox, oy;
  253. ox = oy = 0;
  254. for (int i = 0; i < Fl::screen_count(); i++) {
  255. Fl::screen_xywh(x, y, w, h, i);
  256. if (x < ox)
  257. ox = x;
  258. if (y < oy)
  259. oy = y;
  260. }
  261. return std::make_pair(ox, oy);
  262. }
  263. std::string MonitorArrangement::description(int m)
  264. {
  265. assert(m < Fl::screen_count());
  266. const size_t name_len = 1024;
  267. char name[name_len] = {};
  268. int bytes_written = get_monitor_name(m, name, name_len);
  269. int x, y, w, h;
  270. Fl::screen_xywh(x, y, w, h, m);
  271. std::stringstream ss;
  272. if (bytes_written > 0)
  273. ss << name << " (" << w << "x" << h << ")";
  274. else
  275. ss << w << "x" << h;
  276. return ss.str();
  277. }
  278. #if defined(WIN32)
  279. static BOOL CALLBACK EnumDisplayMonitorsCallback(
  280. HMONITOR monitor, HDC deviceContext, LPRECT rect, LPARAM userData)
  281. {
  282. std::set<HMONITOR>* sys_monitors = (std::set<HMONITOR>*)userData;
  283. sys_monitors->insert(monitor);
  284. return TRUE;
  285. }
  286. #endif
  287. int MonitorArrangement::get_monitor_name(int m, char name[], size_t name_len)
  288. {
  289. #if defined(WIN32)
  290. std::set<HMONITOR> sys_monitors;
  291. std::set<HMONITOR>::const_iterator iter;
  292. int x, y, w, h;
  293. Fl::screen_xywh(x, y, w, h, m);
  294. EnumDisplayMonitors(NULL, NULL, EnumDisplayMonitorsCallback,
  295. (LPARAM)&sys_monitors);
  296. for (iter = sys_monitors.begin(); iter != sys_monitors.end(); ++iter) {
  297. MONITORINFOEX info;
  298. info.cbSize = sizeof(info);
  299. GetMonitorInfo(*iter, (LPMONITORINFO)&info);
  300. if (info.rcMonitor.left != x)
  301. continue;
  302. if (info.rcMonitor.top != y)
  303. continue;
  304. if ((info.rcMonitor.right - info.rcMonitor.left) != w)
  305. continue;
  306. if ((info.rcMonitor.bottom - info.rcMonitor.top) != h)
  307. continue;
  308. return snprintf(name, name_len, "%.*s", (int)(name_len - 1), info.szDevice);
  309. }
  310. return -1;
  311. #elif defined(__APPLE__)
  312. CGDisplayCount count;
  313. int bytes_written = 0;
  314. CGDirectDisplayID displays[16];
  315. if (CGGetActiveDisplayList(16, displays, &count) != kCGErrorSuccess)
  316. return -1;
  317. if (count != (unsigned)Fl::screen_count())
  318. return -1;
  319. if (m >= (int)count)
  320. return -1;
  321. // Notice: Here we assume indices to be ordered the same as in FLTK (we rely on that in cocoa.mm as well).
  322. CGDirectDisplayID displayID = displays[m];
  323. CFDictionaryRef info = IODisplayCreateInfoDictionary(
  324. /* display = */ CGDisplayIOServicePort(displayID),
  325. /* options = */ kIODisplayOnlyPreferredName);
  326. CFDictionaryRef dict = (CFDictionaryRef) CFDictionaryGetValue(info, CFSTR(kDisplayProductName));
  327. CFIndex dict_len = CFDictionaryGetCount(dict);
  328. if (dict_len > 0) {
  329. CFTypeRef * names = new CFTypeRef[dict_len];
  330. CFDictionaryGetKeysAndValues(dict, NULL, (const void **) names);
  331. if (names[0]) {
  332. // Because of `kIODisplayOnlyPreferredName` names *should* only contain the name with
  333. // the current system localization.
  334. CFStringRef localized_name = (CFStringRef) names[0];
  335. CFIndex localized_name_len = CFStringGetLength(localized_name);
  336. // Even though we already have the length of `localized_name` above, we know that we will format it
  337. // as UTF-8 when we put it in the destination buffer. Therefore we need to check whether the name
  338. // with that encoding will fit.
  339. CFIndex localized_name_max_size = CFStringGetMaximumSizeForEncoding(localized_name_len, kCFStringEncodingUTF8) + 1;
  340. if (name_len > (size_t)localized_name_max_size) {
  341. if (CFStringGetCString(
  342. /* ref = */ localized_name,
  343. /* dest = */ name,
  344. /* dest_len = */ name_len,
  345. /* encoding = */ kCFStringEncodingUTF8))
  346. {
  347. bytes_written = strlen(name);
  348. }
  349. }
  350. }
  351. delete[] names;
  352. }
  353. CFRelease(info);
  354. return bytes_written;
  355. #else
  356. #if defined (HAVE_XRANDR)
  357. int x, y, w, h;
  358. int ev, err, xi_major;
  359. fl_open_display();
  360. assert(fl_display != NULL);
  361. Fl::screen_xywh(x, y, w, h, m);
  362. if (!XQueryExtension(fl_display, "RANDR", &xi_major, &ev, &err)) {
  363. vlog.info(_("Failed to get monitor name because X11 RandR could not be found"));
  364. return -1;
  365. }
  366. XRRScreenResources *res = XRRGetScreenResources(fl_display, DefaultRootWindow(fl_display));
  367. if (!res) {
  368. vlog.error(_("Failed to get system monitor configuration"));
  369. return -1;
  370. }
  371. for (int i = 0; i < res->ncrtc; i++) {
  372. XRRCrtcInfo *crtc = XRRGetCrtcInfo(fl_display, res, res->crtcs[i]);
  373. if (!crtc) {
  374. vlog.error(_("Failed to get information about CRTC %d"), i);
  375. continue;
  376. }
  377. for (int j = 0; j < crtc->noutput; j++) {
  378. bool monitor_found = (crtc->x == x) &&
  379. (crtc->y == y) &&
  380. (crtc->width == ((unsigned int) w)) &&
  381. (crtc->height == ((unsigned int) h));
  382. if (monitor_found) {
  383. XRROutputInfo *output = XRRGetOutputInfo(fl_display, res, crtc->outputs[j]);
  384. if (!output) {
  385. vlog.error(_("Failed to get information about output %d for CRTC %d"), j, i);
  386. continue;
  387. }
  388. if (strlen(output->name) >= name_len)
  389. return -1;
  390. return snprintf(name, name_len, "%.*s", (int)name_len, output->name);
  391. }
  392. }
  393. }
  394. return -1;
  395. #endif // !HAVE_XRANDR
  396. return 0;
  397. #endif
  398. }
  399. int MonitorArrangement::fltk_event_handler(int event)
  400. {
  401. std::set<MonitorArrangement *>::iterator it;
  402. if (event != FL_SCREEN_CONFIGURATION_CHANGED)
  403. return 0;
  404. for (it = instances.begin(); it != instances.end(); it++)
  405. (*it)->refresh();
  406. return 0;
  407. }
  408. void MonitorArrangement::monitor_pressed(Fl_Widget *widget, void *user_data)
  409. {
  410. MonitorArrangement *self = (MonitorArrangement *) user_data;
  411. // When a monitor is selected, FLTK changes the state of it for us.
  412. // However, selecting a monitor might implicitly change the state of
  413. // others (if they become required). FLTK only redraws the selected
  414. // monitor. Therefore, we must trigger a redraw of the whole widget
  415. // manually.
  416. self->redraw();
  417. }
  418. void MonitorArrangement::checkered_pattern_draw(
  419. int x, int y, int width, int height, Fl_Color color)
  420. {
  421. bool draw_checker = false;
  422. const int CHECKER_SIZE = 8;
  423. fl_color(fl_lighter(fl_lighter(fl_lighter(color))));
  424. fl_rectf(x, y, width, height);
  425. fl_color(Fl::draw_box_active() ? color : fl_inactive(color));
  426. // Round up the square count. Later on, we remove square area that are
  427. // outside the given bounding area.
  428. const int count = (width + CHECKER_SIZE - 1) / CHECKER_SIZE;
  429. for (int i = 0; i < count; i++) {
  430. for (int j = 0; j < count; j++) {
  431. draw_checker = (i + j) % 2 == 0;
  432. if (draw_checker) {
  433. fl_rectf(
  434. /* x = */ x + i * CHECKER_SIZE,
  435. /* y = */ y + j * CHECKER_SIZE,
  436. /* w = */ CHECKER_SIZE - std::max(0, ((i + 1) * CHECKER_SIZE) - width),
  437. /* h = */ CHECKER_SIZE - std::max(0, ((j + 1) * CHECKER_SIZE) - height)
  438. );
  439. }
  440. }
  441. }
  442. fl_color(Fl::draw_box_active() ? FL_BLACK : fl_inactive(FL_BLACK));
  443. fl_rect(x, y, width, height);
  444. }