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.

714 lines
20KB

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