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.

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