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.

Fl_Monitor_Arrangement.cxx 15KB

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