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

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