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 15KB

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