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.

593 lines
17KB

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