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.

567 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. handle = nvgCreateFont(vg, filename.c_str(), filename.c_str());
  24. if (handle >= 0) {
  25. INFO("Loaded font %s", filename.c_str());
  26. }
  27. else {
  28. WARN("Failed to load font %s", filename.c_str());
  29. }
  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. handle = nvgCreateImage(vg, filename.c_str(), NVG_IMAGE_REPEATX | NVG_IMAGE_REPEATY);
  39. if (handle > 0) {
  40. INFO("Loaded image %s", filename.c_str());
  41. }
  42. else {
  43. WARN("Failed to load image %s", filename.c_str());
  44. }
  45. }
  46. Image::~Image() {
  47. // TODO What if handle is invalid?
  48. if (handle >= 0)
  49. nvgDeleteImage(vg, handle);
  50. }
  51. std::shared_ptr<Image> Image::load(const std::string &filename) {
  52. return APP->window->loadImage(filename);
  53. }
  54. void Svg::loadFile(const std::string &filename) {
  55. handle = nsvgParseFromFile(filename.c_str(), "px", app::SVG_DPI);
  56. if (handle) {
  57. INFO("Loaded SVG %s", filename.c_str());
  58. }
  59. else {
  60. WARN("Failed to load SVG %s", filename.c_str());
  61. }
  62. }
  63. Svg::~Svg() {
  64. if (handle)
  65. nsvgDelete(handle);
  66. }
  67. std::shared_ptr<Svg> Svg::load(const std::string &filename) {
  68. return APP->window->loadSvg(filename);
  69. }
  70. struct Window::Internal {
  71. std::string lastWindowTitle;
  72. int lastWindowX = 0;
  73. int lastWindowY = 0;
  74. int lastWindowWidth = 0;
  75. int lastWindowHeight = 0;
  76. };
  77. static void windowSizeCallback(GLFWwindow *win, int width, int height) {
  78. // Do nothing. Window size is reset each frame anyway.
  79. }
  80. static void mouseButtonCallback(GLFWwindow *win, int button, int action, int mods) {
  81. Window *window = (Window*) glfwGetWindowUserPointer(win);
  82. #if defined ARCH_MAC
  83. // Remap Ctrl-left click to right click on Mac
  84. if (button == GLFW_MOUSE_BUTTON_LEFT && (mods & GLFW_MOD_CONTROL)) {
  85. button = GLFW_MOUSE_BUTTON_RIGHT;
  86. mods &= ~GLFW_MOD_CONTROL;
  87. }
  88. #endif
  89. APP->event->handleButton(window->mousePos, button, action, mods);
  90. }
  91. static void cursorPosCallback(GLFWwindow *win, double xpos, double ypos) {
  92. Window *window = (Window*) glfwGetWindowUserPointer(win);
  93. math::Vec mousePos = math::Vec(xpos, ypos).div(window->pixelRatio / window->windowRatio).round();
  94. math::Vec mouseDelta = mousePos.minus(window->mousePos);
  95. int cursorMode = glfwGetInputMode(win, GLFW_CURSOR);
  96. (void) cursorMode;
  97. #if defined ARCH_MAC
  98. // Workaround for Mac. We can't use GLFW_CURSOR_DISABLED because it's buggy, so implement it on our own.
  99. // This is not an ideal implementation. For example, if the user drags off the screen, the new mouse position will be clamped.
  100. if (cursorMode == GLFW_CURSOR_HIDDEN) {
  101. // CGSetLocalEventsSuppressionInterval(0.0);
  102. glfwSetCursorPos(win, window->mousePos.x, window->mousePos.y);
  103. CGAssociateMouseAndMouseCursorPosition(true);
  104. mousePos = window->mousePos;
  105. }
  106. // Because sometimes the cursor turns into an arrow when its position is on the boundary of the window
  107. glfwSetCursor(win, NULL);
  108. #endif
  109. window->mousePos = mousePos;
  110. APP->event->handleHover(mousePos, mouseDelta);
  111. }
  112. static void cursorEnterCallback(GLFWwindow *win, int entered) {
  113. if (!entered) {
  114. APP->event->handleLeave();
  115. }
  116. }
  117. static void scrollCallback(GLFWwindow *win, double x, double y) {
  118. Window *window = (Window*) glfwGetWindowUserPointer(win);
  119. math::Vec scrollDelta = math::Vec(x, y);
  120. scrollDelta = scrollDelta.mult(50.0);
  121. APP->event->handleScroll(window->mousePos, scrollDelta);
  122. }
  123. static void charCallback(GLFWwindow *win, unsigned int codepoint) {
  124. Window *window = (Window*) glfwGetWindowUserPointer(win);
  125. APP->event->handleText(window->mousePos, codepoint);
  126. }
  127. static void keyCallback(GLFWwindow *win, int key, int scancode, int action, int mods) {
  128. Window *window = (Window*) glfwGetWindowUserPointer(win);
  129. if (APP->event->handleKey(window->mousePos, key, scancode, action, mods))
  130. return;
  131. // Keyboard MIDI driver
  132. if ((mods & RACK_MOD_MASK) == 0) {
  133. if (action == GLFW_PRESS) {
  134. keyboard::press(key);
  135. }
  136. else if (action == GLFW_RELEASE) {
  137. keyboard::release(key);
  138. }
  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;
  275. windowTitle = app::APP_NAME;
  276. windowTitle += " v";
  277. windowTitle += app::APP_VERSION;
  278. if (!APP->patch->path.empty()) {
  279. windowTitle += " - ";
  280. if (!APP->history->isSaved())
  281. windowTitle += "*";
  282. windowTitle += string::filename(APP->patch->path);
  283. }
  284. if (windowTitle != internal->lastWindowTitle) {
  285. glfwSetWindowTitle(win, windowTitle.c_str());
  286. internal->lastWindowTitle = windowTitle;
  287. }
  288. // Get desired scaling
  289. float pixelRatio;
  290. glfwGetWindowContentScale(win, &pixelRatio, NULL);
  291. pixelRatio = std::floor(pixelRatio + 0.5);
  292. if (pixelRatio != this->pixelRatio) {
  293. APP->event->handleZoom();
  294. this->pixelRatio = pixelRatio;
  295. }
  296. // Get framebuffer/window ratio
  297. int fbWidth, fbHeight;
  298. glfwGetFramebufferSize(win, &fbWidth, &fbHeight);
  299. int winWidth, winHeight;
  300. glfwGetWindowSize(win, &winWidth, &winHeight);
  301. windowRatio = (float)fbWidth / winWidth;
  302. // DEBUG("%f %f %d %d", pixelRatio, windowRatio, fbWidth, winWidth);
  303. // Resize scene
  304. APP->scene->box.size = math::Vec(fbWidth, fbHeight).div(pixelRatio);
  305. // Step scene
  306. APP->scene->step();
  307. // Render scene
  308. bool visible = glfwGetWindowAttrib(win, GLFW_VISIBLE) && !glfwGetWindowAttrib(win, GLFW_ICONIFIED);
  309. if (visible) {
  310. // Update and render
  311. nvgBeginFrame(vg, fbWidth, fbHeight, pixelRatio);
  312. nvgScale(vg, pixelRatio, pixelRatio);
  313. // Draw scene
  314. widget::Widget::DrawArgs args;
  315. args.vg = vg;
  316. args.clipBox = APP->scene->box.zeroPos();
  317. APP->scene->draw(args);
  318. glViewport(0, 0, fbWidth, fbHeight);
  319. glClearColor(0.0, 0.0, 0.0, 1.0);
  320. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  321. nvgEndFrame(vg);
  322. glfwSwapBuffers(win);
  323. }
  324. // Limit frame rate
  325. double frameTimeEnd = glfwGetTime();
  326. if (settings::frameRateLimit > 0.0) {
  327. double frameDuration = frameTimeEnd - frameTimeStart;
  328. double waitDuration = 1.0 / settings::frameRateLimit - frameDuration;
  329. if (waitDuration > 0.0) {
  330. std::this_thread::sleep_for(std::chrono::duration<double>(waitDuration));
  331. }
  332. }
  333. // Compute actual frame rate
  334. frameTimeEnd = glfwGetTime();
  335. // DEBUG("%g fps", 1 / (endTime - startTime));
  336. frame++;
  337. }
  338. }
  339. void Window::screenshot(float zoom) {
  340. // Iterate plugins and create directories
  341. std::string screenshotsDir = asset::user("screenshots");
  342. system::createDirectory(screenshotsDir);
  343. for (plugin::Plugin *p : plugin::plugins) {
  344. std::string dir = screenshotsDir + "/" + p->slug;
  345. system::createDirectory(dir);
  346. for (plugin::Model *model : p->models) {
  347. std::string filename = dir + "/" + model->slug + ".png";
  348. // Skip model if screenshot already exists
  349. if (system::isFile(filename))
  350. continue;
  351. INFO("Screenshotting %s %s to %s", p->slug.c_str(), model->slug.c_str(), filename.c_str());
  352. // Create widgets
  353. app::ModuleWidget *mw = model->createModuleWidgetNull();
  354. widget::FramebufferWidget *fb = new widget::FramebufferWidget;
  355. fb->addChild(mw);
  356. fb->scale = math::Vec(zoom, zoom);
  357. // Draw to framebuffer
  358. frameTimeStart = glfwGetTime();
  359. fb->step();
  360. nvgluBindFramebuffer(fb->fb);
  361. // Read pixels
  362. int width, height;
  363. nvgImageSize(vg, fb->getImageHandle(), &width, &height);
  364. uint8_t *data = new uint8_t[height * width * 4];
  365. glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, data);
  366. // Flip image vertically
  367. for (int y = 0; y < height / 2; y++) {
  368. int flipY = height - y - 1;
  369. uint8_t tmp[width * 4];
  370. memcpy(tmp, &data[y * width * 4], width * 4);
  371. memcpy(&data[y * width * 4], &data[flipY * width * 4], width * 4);
  372. memcpy(&data[flipY * width * 4], tmp, width * 4);
  373. }
  374. // Write pixels to PNG
  375. stbi_write_png(filename.c_str(), width, height, 4, data, width * 4);
  376. // Cleanup
  377. delete[] data;
  378. nvgluBindFramebuffer(NULL);
  379. delete fb;
  380. }
  381. }
  382. }
  383. void Window::close() {
  384. glfwSetWindowShouldClose(win, GLFW_TRUE);
  385. }
  386. void Window::cursorLock() {
  387. if (settings::allowCursorLock) {
  388. #if defined ARCH_MAC
  389. glfwSetInputMode(win, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
  390. #else
  391. glfwSetInputMode(win, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
  392. #endif
  393. }
  394. }
  395. void Window::cursorUnlock() {
  396. if (settings::allowCursorLock) {
  397. glfwSetInputMode(win, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
  398. }
  399. }
  400. int Window::getMods() {
  401. int mods = 0;
  402. if (glfwGetKey(win, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(win, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS)
  403. mods |= GLFW_MOD_SHIFT;
  404. if (glfwGetKey(win, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS || glfwGetKey(win, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS)
  405. mods |= GLFW_MOD_CONTROL;
  406. if (glfwGetKey(win, GLFW_KEY_LEFT_ALT) == GLFW_PRESS || glfwGetKey(win, GLFW_KEY_RIGHT_ALT) == GLFW_PRESS)
  407. mods |= GLFW_MOD_ALT;
  408. if (glfwGetKey(win, GLFW_KEY_LEFT_SUPER) == GLFW_PRESS || glfwGetKey(win, GLFW_KEY_RIGHT_SUPER) == GLFW_PRESS)
  409. mods |= GLFW_MOD_SUPER;
  410. return mods;
  411. }
  412. void Window::setFullScreen(bool fullScreen) {
  413. if (!fullScreen) {
  414. glfwSetWindowMonitor(win, NULL, internal->lastWindowX, internal->lastWindowY, internal->lastWindowWidth, internal->lastWindowHeight, GLFW_DONT_CARE);
  415. }
  416. else {
  417. glfwGetWindowPos(win, &internal->lastWindowX, &internal->lastWindowY);
  418. glfwGetWindowSize(win, &internal->lastWindowWidth, &internal->lastWindowHeight);
  419. GLFWmonitor *monitor = glfwGetPrimaryMonitor();
  420. const GLFWvidmode* mode = glfwGetVideoMode(monitor);
  421. glfwSetWindowMonitor(win, monitor, 0, 0, mode->width, mode->height, mode->refreshRate);
  422. }
  423. }
  424. bool Window::isFullScreen() {
  425. GLFWmonitor *monitor = glfwGetWindowMonitor(win);
  426. return monitor != NULL;
  427. }
  428. bool Window::isFrameOverdue() {
  429. if (settings::frameRateLimit == 0.0)
  430. return false;
  431. double frameDuration = glfwGetTime() - frameTimeStart;
  432. return frameDuration > 1.0 / settings::frameRateLimit;
  433. }
  434. std::shared_ptr<Font> Window::loadFont(const std::string &filename) {
  435. auto sp = fontCache[filename].lock();
  436. if (!sp) {
  437. fontCache[filename] = sp = std::make_shared<Font>();
  438. sp->loadFile(filename, vg);
  439. }
  440. return sp;
  441. }
  442. std::shared_ptr<Image> Window::loadImage(const std::string &filename) {
  443. auto sp = imageCache[filename].lock();
  444. if (!sp) {
  445. imageCache[filename] = sp = std::make_shared<Image>();
  446. sp->loadFile(filename, vg);
  447. }
  448. return sp;
  449. }
  450. std::shared_ptr<Svg> Window::loadSvg(const std::string &filename) {
  451. auto sp = svgCache[filename].lock();
  452. if (!sp) {
  453. svgCache[filename] = sp = std::make_shared<Svg>();
  454. sp->loadFile(filename);
  455. }
  456. return sp;
  457. }
  458. void windowInit() {
  459. int err;
  460. // Set up GLFW
  461. #if defined ARCH_MAC
  462. glfwInitHint(GLFW_COCOA_CHDIR_RESOURCES, GLFW_TRUE);
  463. glfwInitHint(GLFW_COCOA_MENUBAR, GLFW_TRUE);
  464. #endif
  465. glfwSetErrorCallback(errorCallback);
  466. err = glfwInit();
  467. if (err != GLFW_TRUE) {
  468. osdialog_message(OSDIALOG_ERROR, OSDIALOG_OK, "Could not initialize GLFW.");
  469. exit(1);
  470. }
  471. }
  472. void windowDestroy() {
  473. glfwTerminate();
  474. }
  475. } // namespace rack