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.

564 lines
16KB

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