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.

751 lines
21KB

  1. #include <map>
  2. #include <queue>
  3. #include <thread>
  4. #if defined ARCH_MAC
  5. // For CGAssociateMouseAndMouseCursorPosition
  6. #include <ApplicationServices/ApplicationServices.h>
  7. #endif
  8. #include <stb_image_write.h>
  9. #include <osdialog.h>
  10. #include <window/Window.hpp>
  11. #include <asset.hpp>
  12. #include <widget/Widget.hpp>
  13. #include <app/Scene.hpp>
  14. #include <keyboard.hpp>
  15. #include <gamepad.hpp>
  16. #include <context.hpp>
  17. #include <patch.hpp>
  18. #include <settings.hpp>
  19. #include <plugin.hpp> // used in Window::screenshot
  20. #include <system.hpp> // used in Window::screenshot
  21. namespace rack {
  22. namespace window {
  23. static const math::Vec minWindowSize = math::Vec(640, 480);
  24. void Font::loadFile(const std::string& filename, NVGcontext* vg) {
  25. this->vg = vg;
  26. handle = nvgCreateFont(vg, filename.c_str(), filename.c_str());
  27. if (handle < 0)
  28. throw Exception("Failed to load font %s", filename.c_str());
  29. INFO("Loaded font %s", filename.c_str());
  30. }
  31. Font::~Font() {
  32. // There is no NanoVG deleteFont() function yet, so do nothing
  33. }
  34. std::shared_ptr<Font> Font::load(const std::string& filename) {
  35. return APP->window->loadFont(filename);
  36. }
  37. void Image::loadFile(const std::string& filename, NVGcontext* vg) {
  38. this->vg = vg;
  39. handle = nvgCreateImage(vg, filename.c_str(), NVG_IMAGE_REPEATX | NVG_IMAGE_REPEATY);
  40. if (handle <= 0)
  41. throw Exception("Failed to load image %s", filename.c_str());
  42. INFO("Loaded image %s", filename.c_str());
  43. }
  44. Image::~Image() {
  45. // TODO What if handle is invalid?
  46. if (handle >= 0)
  47. nvgDeleteImage(vg, handle);
  48. }
  49. std::shared_ptr<Image> Image::load(const std::string& filename) {
  50. return APP->window->loadImage(filename);
  51. }
  52. struct Window::Internal {
  53. std::string lastWindowTitle;
  54. int lastWindowX = 0;
  55. int lastWindowY = 0;
  56. int lastWindowWidth = 0;
  57. int lastWindowHeight = 0;
  58. int frame = 0;
  59. bool ignoreNextMouseDelta = false;
  60. int frameSwapInterval = -1;
  61. double monitorRefreshRate = 0.0;
  62. double frameTime = 0.0;
  63. double lastFrameDuration = 0.0;
  64. math::Vec lastMousePos;
  65. std::map<std::string, std::shared_ptr<Font>> fontCache;
  66. std::map<std::string, std::shared_ptr<Image>> imageCache;
  67. bool fbDirtyOnSubpixelChange = true;
  68. };
  69. static void windowPosCallback(GLFWwindow* win, int x, int y) {
  70. if (glfwGetWindowAttrib(win, GLFW_MAXIMIZED))
  71. return;
  72. if (glfwGetWindowMonitor(win))
  73. return;
  74. settings::windowPos = math::Vec(x, y);
  75. // DEBUG("windowPosCallback %d %d", x, y);
  76. }
  77. static void windowSizeCallback(GLFWwindow* win, int width, int height) {
  78. if (glfwGetWindowAttrib(win, GLFW_MAXIMIZED))
  79. return;
  80. if (glfwGetWindowMonitor(win))
  81. return;
  82. settings::windowSize = math::Vec(width, height);
  83. // DEBUG("windowSizeCallback %d %d", width, height);
  84. }
  85. static void windowMaximizeCallback(GLFWwindow* win, int maximized) {
  86. settings::windowMaximized = maximized;
  87. // DEBUG("windowMaximizeCallback %d", maximized);
  88. }
  89. static void mouseButtonCallback(GLFWwindow* win, int button, int action, int mods) {
  90. contextSet((Context*) glfwGetWindowUserPointer(win));
  91. #if defined ARCH_MAC
  92. // Remap Ctrl-left click to right click on Mac
  93. if (button == GLFW_MOUSE_BUTTON_LEFT && (mods & RACK_MOD_MASK) == GLFW_MOD_CONTROL) {
  94. button = GLFW_MOUSE_BUTTON_RIGHT;
  95. mods &= ~GLFW_MOD_CONTROL;
  96. }
  97. // Remap Ctrl-shift-left click to middle click on Mac
  98. if (button == GLFW_MOUSE_BUTTON_LEFT && (mods & RACK_MOD_MASK) == (GLFW_MOD_CONTROL | GLFW_MOD_SHIFT)) {
  99. button = GLFW_MOUSE_BUTTON_MIDDLE;
  100. mods &= ~(GLFW_MOD_CONTROL | GLFW_MOD_SHIFT);
  101. }
  102. #endif
  103. APP->event->handleButton(APP->window->internal->lastMousePos, button, action, mods);
  104. }
  105. static void cursorPosCallback(GLFWwindow* win, double xpos, double ypos) {
  106. contextSet((Context*) glfwGetWindowUserPointer(win));
  107. math::Vec mousePos = math::Vec(xpos, ypos).div(APP->window->pixelRatio / APP->window->windowRatio).round();
  108. math::Vec mouseDelta = mousePos.minus(APP->window->internal->lastMousePos);
  109. // Workaround for GLFW warping mouse to a different position when the cursor is locked or unlocked.
  110. if (APP->window->internal->ignoreNextMouseDelta) {
  111. APP->window->internal->ignoreNextMouseDelta = false;
  112. mouseDelta = math::Vec();
  113. }
  114. int cursorMode = glfwGetInputMode(win, GLFW_CURSOR);
  115. (void) cursorMode;
  116. #if defined ARCH_MAC
  117. // Workaround for Mac. We can't use GLFW_CURSOR_DISABLED because it's buggy, so implement it on our own.
  118. // This is not an ideal implementation. For example, if the user drags off the screen, the new mouse position will be clamped.
  119. if (cursorMode == GLFW_CURSOR_HIDDEN) {
  120. // CGSetLocalEventsSuppressionInterval(0.0);
  121. glfwSetCursorPos(win, APP->window->internal->lastMousePos.x, APP->window->internal->lastMousePos.y);
  122. CGAssociateMouseAndMouseCursorPosition(true);
  123. mousePos = APP->window->internal->lastMousePos;
  124. }
  125. // Because sometimes the cursor turns into an arrow when its position is on the boundary of the window
  126. glfwSetCursor(win, NULL);
  127. #endif
  128. APP->window->internal->lastMousePos = mousePos;
  129. APP->event->handleHover(mousePos, mouseDelta);
  130. // Keyboard/mouse MIDI driver
  131. int width, height;
  132. glfwGetWindowSize(win, &width, &height);
  133. math::Vec scaledPos(xpos / width, ypos / height);
  134. keyboard::mouseMove(scaledPos);
  135. }
  136. static void cursorEnterCallback(GLFWwindow* win, int entered) {
  137. contextSet((Context*) glfwGetWindowUserPointer(win));
  138. if (!entered) {
  139. APP->event->handleLeave();
  140. }
  141. }
  142. static void scrollCallback(GLFWwindow* win, double x, double y) {
  143. contextSet((Context*) glfwGetWindowUserPointer(win));
  144. math::Vec scrollDelta = math::Vec(x, y);
  145. #if defined ARCH_MAC
  146. scrollDelta = scrollDelta.mult(10.0);
  147. #else
  148. scrollDelta = scrollDelta.mult(50.0);
  149. #endif
  150. APP->event->handleScroll(APP->window->internal->lastMousePos, scrollDelta);
  151. }
  152. static void charCallback(GLFWwindow* win, unsigned int codepoint) {
  153. contextSet((Context*) glfwGetWindowUserPointer(win));
  154. if (APP->event->handleText(APP->window->internal->lastMousePos, codepoint))
  155. return;
  156. }
  157. static void keyCallback(GLFWwindow* win, int key, int scancode, int action, int mods) {
  158. contextSet((Context*) glfwGetWindowUserPointer(win));
  159. if (APP->event->handleKey(APP->window->internal->lastMousePos, key, scancode, action, mods))
  160. return;
  161. // Keyboard/mouse MIDI driver
  162. if (action == GLFW_PRESS && (mods & RACK_MOD_MASK) == 0) {
  163. keyboard::press(key);
  164. }
  165. if (action == GLFW_RELEASE) {
  166. keyboard::release(key);
  167. }
  168. }
  169. static void dropCallback(GLFWwindow* win, int count, const char** paths) {
  170. contextSet((Context*) glfwGetWindowUserPointer(win));
  171. std::vector<std::string> pathsVec;
  172. for (int i = 0; i < count; i++) {
  173. pathsVec.push_back(paths[i]);
  174. }
  175. APP->event->handleDrop(APP->window->internal->lastMousePos, pathsVec);
  176. }
  177. static void errorCallback(int error, const char* description) {
  178. WARN("GLFW error %d: %s", error, description);
  179. }
  180. Window::Window() {
  181. internal = new Internal;
  182. int err;
  183. // Set window hints
  184. #if defined NANOVG_GL2
  185. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
  186. glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
  187. #elif defined NANOVG_GL3
  188. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  189. glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
  190. glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  191. glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  192. #endif
  193. glfwWindowHint(GLFW_DOUBLEBUFFER, GLFW_TRUE);
  194. glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
  195. #if defined ARCH_MAC
  196. glfwWindowHint(GLFW_COCOA_RETINA_FRAMEBUFFER, GLFW_TRUE);
  197. #endif
  198. // Create window
  199. win = glfwCreateWindow(1024, 768, "", NULL, NULL);
  200. if (!win) {
  201. osdialog_message(OSDIALOG_ERROR, OSDIALOG_OK, "Could not open GLFW window. Does your graphics card support OpenGL 2.0 or greater? If so, make sure you have the latest graphics drivers installed.");
  202. exit(1);
  203. }
  204. float contentScale;
  205. glfwGetWindowContentScale(win, &contentScale, NULL);
  206. INFO("Window content scale: %f", contentScale);
  207. glfwSetWindowSizeLimits(win, minWindowSize.x, minWindowSize.y, GLFW_DONT_CARE, GLFW_DONT_CARE);
  208. glfwSetWindowSize(win, settings::windowSize.x, settings::windowSize.y);
  209. if (settings::windowPos.isFinite()) {
  210. glfwSetWindowPos(win, settings::windowPos.x, settings::windowPos.y);
  211. }
  212. if (settings::windowMaximized) {
  213. glfwMaximizeWindow(win);
  214. }
  215. glfwShowWindow(win);
  216. glfwSetWindowUserPointer(win, contextGet());
  217. glfwSetInputMode(win, GLFW_LOCK_KEY_MODS, 1);
  218. glfwMakeContextCurrent(win);
  219. glfwSwapInterval(1);
  220. const GLFWvidmode* monitorMode = glfwGetVideoMode(glfwGetPrimaryMonitor());
  221. internal->monitorRefreshRate = monitorMode->refreshRate;
  222. // Set window callbacks
  223. glfwSetWindowPosCallback(win, windowPosCallback);
  224. glfwSetWindowSizeCallback(win, windowSizeCallback);
  225. glfwSetWindowMaximizeCallback(win, windowMaximizeCallback);
  226. glfwSetMouseButtonCallback(win, mouseButtonCallback);
  227. // Call this ourselves, but on every frame instead of only when the mouse moves
  228. // glfwSetCursorPosCallback(win, cursorPosCallback);
  229. glfwSetCursorEnterCallback(win, cursorEnterCallback);
  230. glfwSetScrollCallback(win, scrollCallback);
  231. glfwSetCharCallback(win, charCallback);
  232. glfwSetKeyCallback(win, keyCallback);
  233. glfwSetDropCallback(win, dropCallback);
  234. // Set up GLEW
  235. glewExperimental = GL_TRUE;
  236. err = glewInit();
  237. if (err != GLEW_OK) {
  238. osdialog_message(OSDIALOG_ERROR, OSDIALOG_OK, "Could not initialize GLEW. Does your graphics card support OpenGL 2.0 or greater? If so, make sure you have the latest graphics drivers installed.");
  239. exit(1);
  240. }
  241. const GLubyte* vendor = glGetString(GL_VENDOR);
  242. const GLubyte* renderer = glGetString(GL_RENDERER);
  243. const GLubyte* version = glGetString(GL_VERSION);
  244. INFO("Renderer: %s %s", vendor, renderer);
  245. INFO("OpenGL: %s", version);
  246. // GLEW generates GL error because it calls glGetString(GL_EXTENSIONS), we'll consume it here.
  247. glGetError();
  248. // Set up NanoVG
  249. int nvgFlags = NVG_ANTIALIAS;
  250. #if defined NANOVG_GL2
  251. vg = nvgCreateGL2(nvgFlags);
  252. fbVg = nvgCreateSharedGL2(vg, nvgFlags);
  253. #elif defined NANOVG_GL3
  254. vg = nvgCreateGL3(nvgFlags);
  255. #elif defined NANOVG_GLES2
  256. vg = nvgCreateGLES2(nvgFlags);
  257. #endif
  258. if (!vg) {
  259. osdialog_message(OSDIALOG_ERROR, OSDIALOG_OK, "Could not initialize NanoVG. Does your graphics card support OpenGL 2.0 or greater? If so, make sure you have the latest graphics drivers installed.");
  260. exit(1);
  261. }
  262. // Load default Blendish font
  263. uiFont = loadFont(asset::system("res/fonts/DejaVuSans.ttf"));
  264. bndSetFont(uiFont->handle);
  265. if (APP->scene) {
  266. widget::Widget::ContextCreateEvent e;
  267. APP->scene->onContextCreate(e);
  268. }
  269. }
  270. Window::~Window() {
  271. if (APP->scene) {
  272. widget::Widget::ContextDestroyEvent e;
  273. APP->scene->onContextDestroy(e);
  274. }
  275. // Fonts and Images in the cache must be deleted before the NanoVG context is deleted
  276. internal->fontCache.clear();
  277. internal->imageCache.clear();
  278. // nvgDeleteClone(fbVg);
  279. #if defined NANOVG_GL2
  280. nvgDeleteGL2(vg);
  281. nvgDeleteGL2(fbVg);
  282. #elif defined NANOVG_GL3
  283. nvgDeleteGL3(vg);
  284. #elif defined NANOVG_GLES2
  285. nvgDeleteGLES2(vg);
  286. #endif
  287. glfwDestroyWindow(win);
  288. delete internal;
  289. }
  290. math::Vec Window::getSize() {
  291. int width, height;
  292. glfwGetWindowSize(win, &width, &height);
  293. return math::Vec(width, height);
  294. }
  295. void Window::setSize(math::Vec size) {
  296. size = size.max(minWindowSize);
  297. glfwSetWindowSize(win, size.x, size.y);
  298. }
  299. void Window::run() {
  300. internal->frame = 0;
  301. while (!glfwWindowShouldClose(win)) {
  302. step();
  303. }
  304. }
  305. void Window::step() {
  306. double frameTime = system::getTime();
  307. double lastFrameTime = internal->frameTime;
  308. internal->frameTime = frameTime;
  309. internal->lastFrameDuration = frameTime - lastFrameTime;
  310. // DEBUG("%.2lf Hz", 1.0 / internal->lastFrameDuration);
  311. double t1 = 0.0, t2 = 0.0, t3 = 0.0, t4 = 0.0, t5 = 0.0;
  312. // Make event handlers and step() have a clean NanoVG context
  313. nvgReset(vg);
  314. bndSetFont(uiFont->handle);
  315. // Poll events
  316. // Save and restore context because event handler set their own context based on which window they originate from.
  317. Context* context = contextGet();
  318. glfwPollEvents();
  319. contextSet(context);
  320. // In case glfwPollEvents() sets another OpenGL context
  321. glfwMakeContextCurrent(win);
  322. if (settings::frameSwapInterval != internal->frameSwapInterval) {
  323. glfwSwapInterval(settings::frameSwapInterval);
  324. internal->frameSwapInterval = settings::frameSwapInterval;
  325. }
  326. // Call cursorPosCallback every frame, not just when the mouse moves
  327. {
  328. double xpos, ypos;
  329. glfwGetCursorPos(win, &xpos, &ypos);
  330. cursorPosCallback(win, xpos, ypos);
  331. }
  332. gamepad::step();
  333. // Set window title
  334. std::string windowTitle = APP_NAME + " " + APP_EDITION_NAME + " " + APP_VERSION;
  335. if (APP->patch->path != "") {
  336. windowTitle += " - ";
  337. if (!APP->history->isSaved())
  338. windowTitle += "*";
  339. windowTitle += system::getFilename(APP->patch->path);
  340. }
  341. if (windowTitle != internal->lastWindowTitle) {
  342. glfwSetWindowTitle(win, windowTitle.c_str());
  343. internal->lastWindowTitle = windowTitle;
  344. }
  345. // Get desired pixel ratio
  346. float newPixelRatio;
  347. if (settings::pixelRatio > 0.0) {
  348. newPixelRatio = settings::pixelRatio;
  349. }
  350. else {
  351. glfwGetWindowContentScale(win, &newPixelRatio, NULL);
  352. newPixelRatio = std::floor(newPixelRatio + 0.5);
  353. }
  354. if (newPixelRatio != pixelRatio) {
  355. pixelRatio = newPixelRatio;
  356. APP->event->handleDirty();
  357. }
  358. // Get framebuffer/window ratio
  359. int fbWidth, fbHeight;
  360. glfwGetFramebufferSize(win, &fbWidth, &fbHeight);
  361. int winWidth, winHeight;
  362. glfwGetWindowSize(win, &winWidth, &winHeight);
  363. windowRatio = (float)fbWidth / winWidth;
  364. t1 = system::getTime();
  365. if (APP->scene) {
  366. // DEBUG("%f %f %d %d", pixelRatio, windowRatio, fbWidth, winWidth);
  367. // Resize scene
  368. APP->scene->box.size = math::Vec(fbWidth, fbHeight).div(pixelRatio);
  369. // Step scene
  370. APP->scene->step();
  371. t2 = system::getTime();
  372. // Render scene
  373. bool visible = glfwGetWindowAttrib(win, GLFW_VISIBLE) && !glfwGetWindowAttrib(win, GLFW_ICONIFIED);
  374. if (visible) {
  375. // Update and render
  376. nvgBeginFrame(vg, fbWidth, fbHeight, pixelRatio);
  377. nvgScale(vg, pixelRatio, pixelRatio);
  378. // Draw scene
  379. widget::Widget::DrawArgs args;
  380. args.vg = vg;
  381. args.clipBox = APP->scene->box.zeroPos();
  382. APP->scene->draw(args);
  383. t3 = system::getTime();
  384. glViewport(0, 0, fbWidth, fbHeight);
  385. glClearColor(0.0, 0.0, 0.0, 1.0);
  386. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  387. nvgEndFrame(vg);
  388. t4 = system::getTime();
  389. }
  390. }
  391. glfwSwapBuffers(win);
  392. // On some platforms, glfwSwapBuffers() doesn't wait on monitor refresh, so we have to sleep as a fallback.
  393. double frameDurationRemaining = getFrameDurationRemaining();
  394. if (frameDurationRemaining > 0.0) {
  395. std::this_thread::sleep_for(std::chrono::duration<double>(frameDurationRemaining));
  396. }
  397. t5 = system::getTime();
  398. // DEBUG("pre-step %6.1f step %6.1f draw %6.1f nvgEndFrame %6.1f glfwSwapBuffers %6.1f total %6.1f",
  399. // (t1 - frameTime) * 1e3f,
  400. // (t2 - t1) * 1e3f,
  401. // (t3 - t2) * 1e3f,
  402. // (t4 - t2) * 1e3f,
  403. // (t5 - t4) * 1e3f,
  404. // (t5 - frameTime) * 1e3f
  405. // );
  406. internal->frame++;
  407. }
  408. static void flipBitmap(uint8_t* pixels, int width, int height, int depth) {
  409. for (int y = 0; y < height / 2; y++) {
  410. int flipY = height - y - 1;
  411. uint8_t tmp[width * depth];
  412. std::memcpy(tmp, &pixels[y * width * depth], width * depth);
  413. std::memcpy(&pixels[y * width * depth], &pixels[flipY * width * depth], width * depth);
  414. std::memcpy(&pixels[flipY * width * depth], tmp, width * depth);
  415. }
  416. }
  417. void Window::screenshot(const std::string& screenshotPath) {
  418. // Get window framebuffer size
  419. int width, height;
  420. glfwGetFramebufferSize(APP->window->win, &width, &height);
  421. // Allocate pixel color buffer
  422. uint8_t* pixels = new uint8_t[height * width * 4];
  423. // glReadPixels defaults to GL_BACK, but the back-buffer is unstable, so use the front buffer (what the user sees)
  424. glReadBuffer(GL_FRONT);
  425. glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  426. // Write pixels to PNG
  427. flipBitmap(pixels, width, height, 4);
  428. stbi_write_png(screenshotPath.c_str(), width, height, 4, pixels, width * 4);
  429. delete[] pixels;
  430. }
  431. void Window::screenshotModules(const std::string& screenshotsDir, float zoom) {
  432. // Iterate plugins and create directories
  433. system::createDirectories(screenshotsDir);
  434. for (plugin::Plugin* p : plugin::plugins) {
  435. std::string dir = system::join(screenshotsDir, p->slug);
  436. system::createDirectory(dir);
  437. for (plugin::Model* model : p->models) {
  438. std::string filename = system::join(dir, model->slug + ".png");
  439. // Skip model if screenshot already exists
  440. if (system::isFile(filename))
  441. continue;
  442. INFO("Screenshotting %s %s to %s", p->slug.c_str(), model->slug.c_str(), filename.c_str());
  443. // Create widgets
  444. widget::FramebufferWidget* fbw = new widget::FramebufferWidget;
  445. fbw->oversample = 2;
  446. app::ModuleWidget* mw = model->createModuleWidget(NULL);
  447. fbw->addChild(mw);
  448. fbw->box.size = mw->box.size;
  449. // Step to allow the ModuleWidget state to set its default appearance.
  450. fbw->step();
  451. // Draw to framebuffer
  452. fbw->render(math::Vec(zoom, zoom));
  453. // Read pixels
  454. nvgluBindFramebuffer(fbw->getFramebuffer());
  455. int width, height;
  456. nvgImageSize(vg, fbw->getImageHandle(), &width, &height);
  457. uint8_t* pixels = new uint8_t[height * width * 4];
  458. glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  459. // Write pixels to PNG
  460. flipBitmap(pixels, width, height, 4);
  461. stbi_write_png(filename.c_str(), width, height, 4, pixels, width * 4);
  462. // Cleanup
  463. delete[] pixels;
  464. nvgluBindFramebuffer(NULL);
  465. delete fbw;
  466. }
  467. }
  468. }
  469. void Window::close() {
  470. glfwSetWindowShouldClose(win, GLFW_TRUE);
  471. }
  472. void Window::cursorLock() {
  473. if (!settings::allowCursorLock)
  474. return;
  475. #if defined ARCH_MAC
  476. glfwSetInputMode(win, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
  477. #else
  478. glfwSetInputMode(win, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
  479. #endif
  480. internal->ignoreNextMouseDelta = true;
  481. }
  482. void Window::cursorUnlock() {
  483. if (!settings::allowCursorLock)
  484. return;
  485. glfwSetInputMode(win, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
  486. internal->ignoreNextMouseDelta = true;
  487. }
  488. bool Window::isCursorLocked() {
  489. return glfwGetInputMode(win, GLFW_CURSOR) != GLFW_CURSOR_NORMAL;
  490. }
  491. int Window::getMods() {
  492. int mods = 0;
  493. if (glfwGetKey(win, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(win, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS)
  494. mods |= GLFW_MOD_SHIFT;
  495. if (glfwGetKey(win, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS || glfwGetKey(win, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS)
  496. mods |= GLFW_MOD_CONTROL;
  497. if (glfwGetKey(win, GLFW_KEY_LEFT_ALT) == GLFW_PRESS || glfwGetKey(win, GLFW_KEY_RIGHT_ALT) == GLFW_PRESS)
  498. mods |= GLFW_MOD_ALT;
  499. if (glfwGetKey(win, GLFW_KEY_LEFT_SUPER) == GLFW_PRESS || glfwGetKey(win, GLFW_KEY_RIGHT_SUPER) == GLFW_PRESS)
  500. mods |= GLFW_MOD_SUPER;
  501. return mods;
  502. }
  503. void Window::setFullScreen(bool fullScreen) {
  504. if (!fullScreen) {
  505. glfwSetWindowMonitor(win, NULL, internal->lastWindowX, internal->lastWindowY, internal->lastWindowWidth, internal->lastWindowHeight, GLFW_DONT_CARE);
  506. }
  507. else {
  508. glfwGetWindowPos(win, &internal->lastWindowX, &internal->lastWindowY);
  509. glfwGetWindowSize(win, &internal->lastWindowWidth, &internal->lastWindowHeight);
  510. GLFWmonitor* monitor = glfwGetPrimaryMonitor();
  511. const GLFWvidmode* mode = glfwGetVideoMode(monitor);
  512. glfwSetWindowMonitor(win, monitor, 0, 0, mode->width, mode->height, mode->refreshRate);
  513. }
  514. }
  515. bool Window::isFullScreen() {
  516. GLFWmonitor* monitor = glfwGetWindowMonitor(win);
  517. return monitor != NULL;
  518. }
  519. double Window::getMonitorRefreshRate() {
  520. return internal->monitorRefreshRate;
  521. }
  522. double Window::getFrameTime() {
  523. return internal->frameTime;
  524. }
  525. double Window::getLastFrameDuration() {
  526. return internal->lastFrameDuration;
  527. }
  528. double Window::getFrameDurationRemaining() {
  529. double frameDurationDesired = internal->frameSwapInterval / internal->monitorRefreshRate;
  530. return frameDurationDesired - (system::getTime() - internal->frameTime);
  531. }
  532. std::shared_ptr<Font> Window::loadFont(const std::string& filename) {
  533. const auto& pair = internal->fontCache.find(filename);
  534. if (pair != internal->fontCache.end())
  535. return pair->second;
  536. // Load font
  537. std::shared_ptr<Font> font;
  538. try {
  539. font = std::make_shared<Font>();
  540. font->loadFile(filename, vg);
  541. }
  542. catch (Exception& e) {
  543. WARN("%s", e.what());
  544. font = NULL;
  545. }
  546. internal->fontCache[filename] = font;
  547. return font;
  548. }
  549. std::shared_ptr<Image> Window::loadImage(const std::string& filename) {
  550. const auto& pair = internal->imageCache.find(filename);
  551. if (pair != internal->imageCache.end())
  552. return pair->second;
  553. // Load image
  554. std::shared_ptr<Image> image;
  555. try {
  556. image = std::make_shared<Image>();
  557. image->loadFile(filename, vg);
  558. }
  559. catch (Exception& e) {
  560. WARN("%s", e.what());
  561. image = NULL;
  562. }
  563. internal->imageCache[filename] = image;
  564. return image;
  565. }
  566. bool& Window::fbDirtyOnSubpixelChange() {
  567. return internal->fbDirtyOnSubpixelChange;
  568. }
  569. void init() {
  570. int err;
  571. // Set up GLFW
  572. #if defined ARCH_MAC
  573. glfwInitHint(GLFW_COCOA_CHDIR_RESOURCES, GLFW_TRUE);
  574. glfwInitHint(GLFW_COCOA_MENUBAR, GLFW_TRUE);
  575. #endif
  576. glfwSetErrorCallback(errorCallback);
  577. err = glfwInit();
  578. if (err != GLFW_TRUE) {
  579. osdialog_message(OSDIALOG_ERROR, OSDIALOG_OK, "Could not initialize GLFW.");
  580. exit(1);
  581. }
  582. }
  583. void destroy() {
  584. glfwTerminate();
  585. }
  586. } // namespace window
  587. } // namespace rack