PolySDLCore.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  1. /*
  2. Copyright (C) 2011 by Ivan Safrin
  3. Permission is hereby granted, free of charge, to any person obtaining a copy
  4. of this software and associated documentation files (the "Software"), to deal
  5. in the Software without restriction, including without limitation the rights
  6. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. copies of the Software, and to permit persons to whom the Software is
  8. furnished to do so, subject to the following conditions:
  9. The above copyright notice and this permission notice shall be included in
  10. all copies or substantial portions of the Software.
  11. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17. THE SOFTWARE.
  18. */
  19. #include "PolySDLCore.h"
  20. #include "PolycodeView.h"
  21. #include "PolyCoreServices.h"
  22. #include "PolyCoreInput.h"
  23. #include "PolyMaterialManager.h"
  24. #include "PolyThreaded.h"
  25. #include "PolyGLRenderer.h"
  26. #include "PolyGLSLShaderModule.h"
  27. #include "PolyRectangle.h"
  28. #include <SDL/SDL.h>
  29. #include <SDL/SDL_syswm.h>
  30. #include <stdio.h>
  31. #include <limits.h>
  32. #include <iostream>
  33. #include <unistd.h>
  34. #include <sys/types.h>
  35. #include <sys/stat.h>
  36. #include <sys/wait.h>
  37. #include <pwd.h>
  38. #ifdef USE_X11
  39. // SDL scrap
  40. #define T(A, B, C, D) (int)((A<<24)|(B<<16)|(C<<8)|(D<<0))
  41. int init_scrap(void);
  42. int lost_scrap(void);
  43. void put_scrap(int type, int srclen, const char *src);
  44. void get_scrap(int type, int *dstlen, char **dst);
  45. // end SDL scrap
  46. // X11 cursor
  47. #include <X11/cursorfont.h>
  48. namespace {
  49. void set_cursor(int cursorType);
  50. void free_cursors();
  51. } // namespace
  52. // end X11 cursor
  53. #endif
  54. using namespace Polycode;
  55. using std::vector;
  56. long getThreadID() {
  57. return (long)pthread_self();
  58. }
  59. void Core::getScreenInfo(int *width, int *height, int *hz) {
  60. SDL_Init(SDL_INIT_VIDEO); // Or GetVideoInfo will not work
  61. const SDL_VideoInfo *video = SDL_GetVideoInfo();
  62. if (width) *width = video->current_w;
  63. if (height) *height = video->current_h;
  64. if (hz) *hz = 0;
  65. }
  66. SDLCore::SDLCore(PolycodeView *view, int _xRes, int _yRes, bool fullScreen, bool vSync, int aaLevel, int anisotropyLevel, int frameRate, int monitorIndex, bool retinaSupport) : Core(_xRes, _yRes, fullScreen, vSync, aaLevel, anisotropyLevel, frameRate, monitorIndex) {
  67. this->resizableWindow = view->resizable;
  68. char *buffer = getcwd(NULL, 0);
  69. defaultWorkingDirectory = String(buffer);
  70. free(buffer);
  71. struct passwd *pw = getpwuid(getuid());
  72. const char *homedir = pw->pw_dir;
  73. userHomeDirectory = String(homedir);
  74. String *windowTitle = (String*)view->windowData;
  75. if(resizableWindow) {
  76. unsetenv("SDL_VIDEO_CENTERED");
  77. } else {
  78. setenv("SDL_VIDEO_CENTERED", "1", 1);
  79. }
  80. if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_JOYSTICK) < 0) {
  81. }
  82. eventMutex = createMutex();
  83. renderer = new OpenGLRenderer();
  84. services->setRenderer(renderer);
  85. setVideoMode(xRes, yRes, fullScreen, vSync, aaLevel, anisotropyLevel);
  86. SDL_WM_SetCaption(windowTitle->c_str(), windowTitle->c_str());
  87. SDL_EnableUNICODE(1);
  88. SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
  89. SDL_JoystickEventState(SDL_ENABLE);
  90. int numJoysticks = SDL_NumJoysticks();
  91. for(int i=0; i < numJoysticks; i++) {
  92. SDL_JoystickOpen(i);
  93. input->addJoystick(i);
  94. }
  95. #ifdef USE_X11
  96. // Start listening to clipboard events.
  97. // (Yes on X11 you need to actively listen to
  98. // clipboard events and respond to them)
  99. init_scrap();
  100. #endif // USE_X11
  101. ((OpenGLRenderer*)renderer)->Init();
  102. CoreServices::getInstance()->installModule(new GLSLShaderModule());
  103. }
  104. void SDLCore::setVideoMode(int xRes, int yRes, bool fullScreen, bool vSync, int aaLevel, int anisotropyLevel, bool retinaSupport) {
  105. this->xRes = xRes;
  106. this->yRes = yRes;
  107. this->fullScreen = fullScreen;
  108. this->aaLevel = aaLevel;
  109. SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 24);
  110. SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1);
  111. SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8);
  112. SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 8);
  113. SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8);
  114. SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 8);
  115. if(aaLevel > 0) {
  116. SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, 1);
  117. SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, aaLevel); //0, 2, 4
  118. } else {
  119. SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, 0);
  120. SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, 0);
  121. }
  122. flags = SDL_OPENGL;
  123. if(fullScreen) {
  124. flags |= SDL_FULLSCREEN;
  125. }
  126. if(resizableWindow) {
  127. flags |= SDL_RESIZABLE;
  128. }
  129. /*
  130. if(vSync) {
  131. flags |= SDL_DOUBLEBUF;
  132. SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  133. SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 1);
  134. } else {
  135. SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 0);
  136. SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 0);
  137. }
  138. */
  139. SDL_SetVideoMode(xRes, yRes, 0, flags);
  140. renderer->Resize(xRes, yRes);
  141. //CoreServices::getInstance()->getMaterialManager()->reloadProgramsAndTextures();
  142. dispatchEvent(new Event(), EVENT_CORE_RESIZE);
  143. }
  144. vector<Polycode::Rectangle> SDLCore::getVideoModes() {
  145. vector<Polycode::Rectangle> retVector;
  146. SDL_Rect **modes;
  147. modes=SDL_ListModes(NULL, SDL_FULLSCREEN);
  148. for(int i=0;modes[i];++i) {
  149. Rectangle res;
  150. res.w = modes[i]->w;
  151. res.h = modes[i]->h;
  152. retVector.push_back(res);
  153. }
  154. return retVector;
  155. }
  156. SDLCore::~SDLCore() {
  157. #ifdef USE_X11
  158. free_cursors();
  159. #endif // USE_X11
  160. SDL_Quit();
  161. }
  162. void SDLCore::openURL(String url) {
  163. int childExitStatus;
  164. pid_t pid = fork();
  165. if (pid == 0) {
  166. execl("/usr/bin/xdg-open", "/usr/bin/xdg-open", url.c_str(), (char *)0);
  167. } else {
  168. pid_t ws = waitpid( pid, &childExitStatus, WNOHANG);
  169. }
  170. }
  171. String SDLCore::executeExternalCommand(String command, String args, String inDirectory) {
  172. String finalCommand = command + " " + args;
  173. if(inDirectory != "") {
  174. finalCommand = "cd " + inDirectory + " && " + finalCommand;
  175. }
  176. FILE *fp = popen(finalCommand.c_str(), "r");
  177. if(!fp) {
  178. return "Unable to execute command";
  179. }
  180. int fd = fileno(fp);
  181. char path[2048];
  182. String retString;
  183. while (fgets(path, sizeof(path), fp) != NULL) {
  184. retString = retString + String(path);
  185. }
  186. pclose(fp);
  187. return retString;
  188. }
  189. int SDLThreadFunc(void *data) {
  190. Threaded *target = (Threaded*)data;
  191. target->runThread();
  192. return 1;
  193. }
  194. void SDLCore::createThread(Threaded *target) {
  195. SDL_CreateThread(SDLThreadFunc, (void*)target);
  196. }
  197. unsigned int SDLCore::getTicks() {
  198. return SDL_GetTicks();
  199. }
  200. void SDLCore::enableMouse(bool newval) {
  201. if(newval) {
  202. SDL_ShowCursor(1);
  203. SDL_WM_GrabInput(SDL_GRAB_OFF);
  204. } else {
  205. SDL_ShowCursor(0);
  206. SDL_WM_GrabInput(SDL_GRAB_ON);
  207. }
  208. Core::enableMouse(newval);
  209. }
  210. void SDLCore::captureMouse(bool newval) {
  211. if(newval) {
  212. SDL_WM_GrabInput(SDL_GRAB_ON);
  213. } else {
  214. SDL_WM_GrabInput(SDL_GRAB_OFF);
  215. }
  216. Core::captureMouse(newval);
  217. }
  218. bool SDLCore::checkSpecialKeyEvents(PolyKEY key) {
  219. if(key == KEY_a && (input->getKeyState(KEY_LCTRL) || input->getKeyState(KEY_RCTRL))) {
  220. dispatchEvent(new Event(), Core::EVENT_SELECT_ALL);
  221. return true;
  222. }
  223. if(key == KEY_c && (input->getKeyState(KEY_LCTRL) || input->getKeyState(KEY_RCTRL))) {
  224. dispatchEvent(new Event(), Core::EVENT_COPY);
  225. return true;
  226. }
  227. if(key == KEY_x && (input->getKeyState(KEY_LCTRL) || input->getKeyState(KEY_RCTRL))) {
  228. dispatchEvent(new Event(), Core::EVENT_CUT);
  229. return true;
  230. }
  231. if(key == KEY_z && (input->getKeyState(KEY_LCTRL) || input->getKeyState(KEY_RCTRL)) && (input->getKeyState(KEY_LSHIFT) || input->getKeyState(KEY_RSHIFT))) {
  232. dispatchEvent(new Event(), Core::EVENT_REDO);
  233. return true;
  234. }
  235. if(key == KEY_z && (input->getKeyState(KEY_LCTRL) || input->getKeyState(KEY_RCTRL))) {
  236. dispatchEvent(new Event(), Core::EVENT_UNDO);
  237. return true;
  238. }
  239. if(key == KEY_v && (input->getKeyState(KEY_LCTRL) || input->getKeyState(KEY_RCTRL))) {
  240. dispatchEvent(new Event(), Core::EVENT_PASTE);
  241. return true;
  242. }
  243. return false;
  244. }
  245. void SDLCore::Render() {
  246. renderer->BeginRender();
  247. services->Render();
  248. renderer->EndRender();
  249. SDL_GL_SwapBuffers();
  250. }
  251. bool SDLCore::systemUpdate() {
  252. if(!running)
  253. return false;
  254. doSleep();
  255. updateCore();
  256. SDL_Event event;
  257. while ( SDL_PollEvent(&event) ) {
  258. switch (event.type) {
  259. case SDL_QUIT:
  260. running = false;
  261. break;
  262. case SDL_VIDEORESIZE:
  263. if(resizableWindow) {
  264. unsetenv("SDL_VIDEO_CENTERED");
  265. } else {
  266. setenv("SDL_VIDEO_CENTERED", "1", 1);
  267. }
  268. this->xRes = event.resize.w;
  269. this->yRes = event.resize.h;
  270. SDL_SetVideoMode(xRes, yRes, 0, flags);
  271. renderer->Resize(xRes, yRes);
  272. dispatchEvent(new Event(), EVENT_CORE_RESIZE);
  273. break;
  274. case SDL_ACTIVEEVENT:
  275. if(event.active.state == SDL_APPINPUTFOCUS) {
  276. if(event.active.gain == 1) {
  277. gainFocus();
  278. } else {
  279. loseFocus();
  280. }
  281. }
  282. break;
  283. case SDL_JOYAXISMOTION:
  284. input->joystickAxisMoved(event.jaxis.axis, ((Number)event.jaxis.value)/32767.0, event.jaxis.which);
  285. break;
  286. case SDL_JOYBUTTONDOWN:
  287. input->joystickButtonDown(event.jbutton.button, event.jbutton.which);
  288. break;
  289. case SDL_JOYBUTTONUP:
  290. input->joystickButtonUp(event.jbutton.button, event.jbutton.which);
  291. break;
  292. case SDL_KEYDOWN:
  293. if(!checkSpecialKeyEvents((PolyKEY)(event.key.keysym.sym))) {
  294. input->setKeyState((PolyKEY)(event.key.keysym.sym), (char)event.key.keysym.unicode, true, getTicks());
  295. }
  296. break;
  297. case SDL_KEYUP:
  298. input->setKeyState((PolyKEY)(event.key.keysym.sym), (char)event.key.keysym.unicode, false, getTicks());
  299. break;
  300. case SDL_MOUSEBUTTONDOWN:
  301. if(event.button.button == SDL_BUTTON_WHEELUP) {
  302. input->mouseWheelUp(getTicks());
  303. } else if(event.button.button == SDL_BUTTON_WHEELDOWN) {
  304. input->mouseWheelDown(getTicks());
  305. } else {
  306. switch(event.button.button) {
  307. case SDL_BUTTON_LEFT:
  308. input->setMouseButtonState(CoreInput::MOUSE_BUTTON1, true, getTicks());
  309. break;
  310. case SDL_BUTTON_RIGHT:
  311. input->setMouseButtonState(CoreInput::MOUSE_BUTTON2, true, getTicks());
  312. break;
  313. case SDL_BUTTON_MIDDLE:
  314. input->setMouseButtonState(CoreInput::MOUSE_BUTTON3, true, getTicks());
  315. break;
  316. }
  317. }
  318. break;
  319. case SDL_MOUSEBUTTONUP:
  320. if(event.button.button == SDL_BUTTON_WHEELUP || event.button.button == SDL_BUTTON_WHEELDOWN) {
  321. } else {
  322. switch(event.button.button) {
  323. case SDL_BUTTON_LEFT:
  324. input->setMouseButtonState(CoreInput::MOUSE_BUTTON1, false, getTicks());
  325. break;
  326. case SDL_BUTTON_RIGHT:
  327. input->setMouseButtonState(CoreInput::MOUSE_BUTTON2, false, getTicks());
  328. break;
  329. case SDL_BUTTON_MIDDLE:
  330. input->setMouseButtonState(CoreInput::MOUSE_BUTTON3, false, getTicks());
  331. break;
  332. }
  333. }
  334. break;
  335. case SDL_MOUSEMOTION:
  336. input->setDeltaPosition(event.motion.xrel, event.motion.yrel);
  337. input->setMousePosition(event.motion.x, event.motion.y, getTicks());
  338. break;
  339. default:
  340. break;
  341. }
  342. }
  343. return running;
  344. }
  345. void SDLCore::setCursor(int cursorType) {
  346. #ifdef USE_X11
  347. set_cursor(cursorType);
  348. #endif // USE_X11
  349. }
  350. void SDLCore::warpCursor(int x, int y) {
  351. SDL_WarpMouse(x, y);
  352. }
  353. void SDLCore::lockMutex(CoreMutex *mutex) {
  354. SDLCoreMutex *smutex = (SDLCoreMutex*)mutex;
  355. SDL_mutexP(smutex->pMutex);
  356. }
  357. void SDLCore::unlockMutex(CoreMutex *mutex) {
  358. SDLCoreMutex *smutex = (SDLCoreMutex*)mutex;
  359. SDL_mutexV(smutex->pMutex);
  360. }
  361. CoreMutex *SDLCore::createMutex() {
  362. SDLCoreMutex *mutex = new SDLCoreMutex();
  363. mutex->pMutex = SDL_CreateMutex();
  364. return mutex;
  365. }
  366. void SDLCore::copyStringToClipboard(const String& str) {
  367. #ifdef USE_X11
  368. put_scrap(T('T', 'E', 'X', 'T'), str.size(), str.c_str());
  369. #endif
  370. }
  371. String SDLCore::getClipboardString() {
  372. #ifdef USE_X11
  373. int dstlen;
  374. char* buffer;
  375. get_scrap(T('T', 'E', 'X', 'T'), &dstlen, &buffer);
  376. String rval(buffer, dstlen);
  377. free(buffer);
  378. return rval;
  379. #endif
  380. }
  381. void SDLCore::createFolder(const String& folderPath) {
  382. mkdir(folderPath.c_str(), 0700);
  383. }
  384. void SDLCore::copyDiskItem(const String& itemPath, const String& destItemPath) {
  385. int childExitStatus;
  386. pid_t pid = fork();
  387. if (pid == 0) {
  388. execl("/bin/cp", "/bin/cp", "-RT", itemPath.c_str(), destItemPath.c_str(), (char *)0);
  389. } else {
  390. pid_t ws = waitpid( pid, &childExitStatus, 0);
  391. }
  392. }
  393. void SDLCore::moveDiskItem(const String& itemPath, const String& destItemPath) {
  394. int childExitStatus;
  395. pid_t pid = fork();
  396. if (pid == 0) {
  397. execl("/bin/mv", "/bin/mv", itemPath.c_str(), destItemPath.c_str(), (char *)0);
  398. } else {
  399. pid_t ws = waitpid( pid, &childExitStatus, 0);
  400. }
  401. }
  402. void SDLCore::removeDiskItem(const String& itemPath) {
  403. int childExitStatus;
  404. pid_t pid = fork();
  405. if (pid == 0) {
  406. execl("/bin/rm", "/bin/rm", "-rf", itemPath.c_str(), (char *)0);
  407. } else {
  408. pid_t ws = waitpid( pid, &childExitStatus, 0);
  409. }
  410. }
  411. String SDLCore::openFolderPicker() {
  412. String r = "";
  413. return r;
  414. }
  415. vector<String> SDLCore::openFilePicker(vector<CoreFileExtension> extensions, bool allowMultiple) {
  416. vector<String> r;
  417. return r;
  418. }
  419. String SDLCore::saveFilePicker(std::vector<CoreFileExtension> extensions) {
  420. String r = "";
  421. return r;
  422. }
  423. void SDLCore::resizeTo(int xRes, int yRes) {
  424. renderer->Resize(xRes, yRes);
  425. }
  426. #ifdef USE_X11
  427. // SDL_scrap.c
  428. // Credits to Sam Lantinga for making this
  429. // Changes include:
  430. // - All non-X11 stuff was removed
  431. // - Uses the X11 CLIPBOARD atom in addition to PRIMARY
  432. // =======================================
  433. /* Handle clipboard text and data in arbitrary formats */
  434. /* Miscellaneous defines */
  435. #define PUBLIC
  436. #define PRIVATE static
  437. #define X11_SCRAP
  438. typedef Atom scrap_type;
  439. static Display *SDL_Display;
  440. static Window SDL_Window;
  441. static void (*Lock_Display)(void);
  442. static void (*Unlock_Display)(void);
  443. #define FORMAT_PREFIX "SDL_scrap_0x"
  444. PRIVATE scrap_type
  445. convert_format(int type)
  446. {
  447. switch (type)
  448. {
  449. case T('T', 'E', 'X', 'T'):
  450. return XA_STRING;
  451. default:
  452. {
  453. char format[sizeof(FORMAT_PREFIX)+8+1];
  454. sprintf(format, "%s%08lx", FORMAT_PREFIX, (unsigned long)type);
  455. return XInternAtom(SDL_Display, format, False);
  456. }
  457. }
  458. }
  459. /* Convert internal data to scrap format */
  460. PRIVATE int
  461. convert_data(int type, char *dst, const char *src, int srclen)
  462. {
  463. int dstlen;
  464. dstlen = 0;
  465. switch (type)
  466. {
  467. case T('T', 'E', 'X', 'T'):
  468. if ( dst )
  469. {
  470. while ( --srclen >= 0 )
  471. {
  472. if ( *src == '\r' )
  473. {
  474. *dst++ = '\n';
  475. ++dstlen;
  476. }
  477. else
  478. {
  479. *dst++ = *src;
  480. ++dstlen;
  481. }
  482. ++src;
  483. }
  484. *dst = '\0';
  485. ++dstlen;
  486. }
  487. else
  488. {
  489. while ( --srclen >= 0 )
  490. {
  491. if ( *src == '\r' )
  492. {
  493. ++dstlen;
  494. }
  495. else
  496. {
  497. ++dstlen;
  498. }
  499. ++src;
  500. }
  501. ++dstlen;
  502. }
  503. break;
  504. default:
  505. if ( dst )
  506. {
  507. *(int *)dst = srclen;
  508. dst += sizeof(int);
  509. memcpy(dst, src, srclen);
  510. }
  511. dstlen = sizeof(int)+srclen;
  512. break;
  513. }
  514. return(dstlen);
  515. }
  516. /* Convert scrap data to internal format */
  517. PRIVATE int
  518. convert_scrap(int type, char *dst, char *src, int srclen)
  519. {
  520. int dstlen;
  521. dstlen = 0;
  522. switch (type)
  523. {
  524. case T('T', 'E', 'X', 'T'):
  525. {
  526. if ( srclen == 0 )
  527. srclen = strlen(src);
  528. if ( dst )
  529. {
  530. while ( --srclen >= 0 )
  531. {
  532. if ( *src == '\n' )
  533. {
  534. *dst++ = '\r';
  535. ++dstlen;
  536. }
  537. else
  538. {
  539. *dst++ = *src;
  540. ++dstlen;
  541. }
  542. ++src;
  543. }
  544. *dst = '\0';
  545. ++dstlen;
  546. }
  547. else
  548. {
  549. while ( --srclen >= 0 )
  550. {
  551. ++dstlen;
  552. ++src;
  553. }
  554. ++dstlen;
  555. }
  556. }
  557. break;
  558. default:
  559. dstlen = *(int *)src;
  560. if ( dst )
  561. {
  562. if ( srclen == 0 )
  563. memcpy(dst, src+sizeof(int), dstlen);
  564. else
  565. memcpy(dst, src+sizeof(int), srclen-sizeof(int));
  566. }
  567. break;
  568. }
  569. return dstlen;
  570. }
  571. /* The system message filter function -- handle clipboard messages */
  572. PRIVATE int clipboard_filter(const SDL_Event *event);
  573. PUBLIC int
  574. init_scrap(void)
  575. {
  576. SDL_SysWMinfo info;
  577. int retval;
  578. /* Grab the window manager specific information */
  579. retval = -1;
  580. SDL_SetError("SDL is not running on known window manager");
  581. SDL_VERSION(&info.version);
  582. if ( SDL_GetWMInfo(&info) )
  583. {
  584. /* Save the information for later use */
  585. /* * */
  586. if ( info.subsystem == SDL_SYSWM_X11 )
  587. {
  588. SDL_Display = info.info.x11.display;
  589. SDL_Window = info.info.x11.window;
  590. Lock_Display = info.info.x11.lock_func;
  591. Unlock_Display = info.info.x11.unlock_func;
  592. /* Enable the special window hook events */
  593. SDL_EventState(SDL_SYSWMEVENT, SDL_ENABLE);
  594. SDL_SetEventFilter(clipboard_filter);
  595. retval = 0;
  596. }
  597. else
  598. {
  599. SDL_SetError("SDL is not running on X11");
  600. }
  601. }
  602. return(retval);
  603. }
  604. PUBLIC int
  605. lost_scrap(void)
  606. {
  607. int retval;
  608. /* * */
  609. Lock_Display();
  610. retval = ( XGetSelectionOwner(SDL_Display, XA_PRIMARY) != SDL_Window );
  611. Unlock_Display();
  612. return(retval);
  613. }
  614. PUBLIC void
  615. put_scrap(int type, int srclen, const char *src)
  616. {
  617. scrap_type format;
  618. int dstlen;
  619. char *dst;
  620. format = convert_format(type);
  621. dstlen = convert_data(type, NULL, src, srclen);
  622. /* * */
  623. dst = (char *)malloc(dstlen);
  624. if ( dst != NULL )
  625. {
  626. Lock_Display();
  627. convert_data(type, dst, src, srclen);
  628. XChangeProperty(SDL_Display, DefaultRootWindow(SDL_Display),
  629. XA_CUT_BUFFER0, format, 8, PropModeReplace, (unsigned char*) dst, dstlen);
  630. free(dst);
  631. Atom XA_CLIPBOARD = XInternAtom(SDL_Display, "CLIPBOARD", 0);
  632. if ( lost_scrap() ) {
  633. XSetSelectionOwner(SDL_Display, XA_PRIMARY, SDL_Window, CurrentTime);
  634. XSetSelectionOwner(SDL_Display, XA_CLIPBOARD, SDL_Window, CurrentTime);
  635. }
  636. Unlock_Display();
  637. }
  638. }
  639. PUBLIC void
  640. get_scrap(int type, int *dstlen, char **dst)
  641. {
  642. scrap_type format;
  643. *dstlen = 0;
  644. format = convert_format(type);
  645. /* * */
  646. {
  647. Window owner;
  648. Atom selection;
  649. Atom seln_type;
  650. int seln_format;
  651. unsigned long nbytes;
  652. unsigned long overflow;
  653. char *src;
  654. Lock_Display();
  655. Atom XA_CLIPBOARD = XInternAtom(SDL_Display, "CLIPBOARD", 0);
  656. owner = XGetSelectionOwner(SDL_Display, XA_PRIMARY);
  657. Unlock_Display();
  658. if ( (owner == None) || (owner == SDL_Window) )
  659. {
  660. owner = DefaultRootWindow(SDL_Display);
  661. selection = XA_CUT_BUFFER0;
  662. }
  663. else
  664. {
  665. int selection_response = 0;
  666. SDL_Event event;
  667. owner = SDL_Window;
  668. Lock_Display();
  669. selection = XInternAtom(SDL_Display, "SDL_SELECTION", False);
  670. XConvertSelection(SDL_Display, XA_PRIMARY, format,
  671. selection, owner, CurrentTime);
  672. XConvertSelection(SDL_Display, XA_CLIPBOARD, format,
  673. selection, owner, CurrentTime);
  674. Unlock_Display();
  675. while ( ! selection_response )
  676. {
  677. SDL_WaitEvent(&event);
  678. if ( event.type == SDL_SYSWMEVENT )
  679. {
  680. XEvent xevent = event.syswm.msg->event.xevent;
  681. if ( (xevent.type == SelectionNotify) &&
  682. (xevent.xselection.requestor == owner) )
  683. selection_response = 1;
  684. }
  685. }
  686. }
  687. Lock_Display();
  688. if ( XGetWindowProperty(SDL_Display, owner, selection, 0, INT_MAX/4,
  689. False, format, &seln_type, &seln_format,
  690. &nbytes, &overflow, (unsigned char **)&src) == Success )
  691. {
  692. if ( seln_type == format )
  693. {
  694. *dstlen = convert_scrap(type, NULL, src, nbytes);
  695. *dst = (char *)malloc(*dstlen);
  696. if ( *dst == NULL )
  697. *dstlen = 0;
  698. else
  699. convert_scrap(type, *dst, src, nbytes);
  700. }
  701. XFree(src);
  702. }
  703. }
  704. Unlock_Display();
  705. }
  706. PRIVATE int clipboard_filter(const SDL_Event *event)
  707. {
  708. /* Post all non-window manager specific events */
  709. if ( event->type != SDL_SYSWMEVENT ) {
  710. return(1);
  711. }
  712. /* Handle window-manager specific clipboard events */
  713. switch (event->syswm.msg->event.xevent.type) {
  714. /* Copy the selection from XA_CUT_BUFFER0 to the requested property */
  715. case SelectionRequest: {
  716. XSelectionRequestEvent *req;
  717. XEvent sevent;
  718. int seln_format;
  719. unsigned long nbytes;
  720. unsigned long overflow;
  721. unsigned char *seln_data;
  722. req = &event->syswm.msg->event.xevent.xselectionrequest;
  723. sevent.xselection.type = SelectionNotify;
  724. sevent.xselection.display = req->display;
  725. sevent.xselection.selection = req->selection;
  726. sevent.xselection.target = None;
  727. sevent.xselection.property = None;
  728. sevent.xselection.requestor = req->requestor;
  729. sevent.xselection.time = req->time;
  730. if ( XGetWindowProperty(SDL_Display, DefaultRootWindow(SDL_Display),
  731. XA_CUT_BUFFER0, 0, INT_MAX/4, False, req->target,
  732. &sevent.xselection.target, &seln_format,
  733. &nbytes, &overflow, &seln_data) == Success )
  734. {
  735. if ( sevent.xselection.target == req->target )
  736. {
  737. if ( sevent.xselection.target == XA_STRING )
  738. {
  739. if ( seln_data[nbytes-1] == '\0' )
  740. --nbytes;
  741. }
  742. XChangeProperty(SDL_Display, req->requestor, req->property,
  743. sevent.xselection.target, seln_format, PropModeReplace,
  744. seln_data, nbytes);
  745. sevent.xselection.property = req->property;
  746. }
  747. XFree(seln_data);
  748. }
  749. XSendEvent(SDL_Display,req->requestor,False,0,&sevent);
  750. XSync(SDL_Display, False);
  751. }
  752. break;
  753. }
  754. /* Post the event for X11 clipboard reading above */
  755. return(1);
  756. }
  757. // X11 cursor
  758. namespace {
  759. // WARNING: These functions rely on the SDL_Display and SDL_Window previously initialized by init_scrap
  760. const int CURSOR_COUNT = 7;
  761. Cursor defined_cursors[CURSOR_COUNT] = {0};
  762. void set_cursor(int cursorType) {
  763. Cursor cursor = 0;
  764. if(cursorType >= 0 && cursorType < CURSOR_COUNT) {
  765. cursor = defined_cursors[cursorType];
  766. if(!cursor) {
  767. switch(cursorType) {
  768. case Polycode::Core::CURSOR_TEXT:
  769. cursor = XCreateFontCursor (SDL_Display, XC_xterm);
  770. break;
  771. case Polycode::Core::CURSOR_POINTER:
  772. cursor = XCreateFontCursor (SDL_Display, XC_hand1);
  773. break;
  774. case Polycode::Core::CURSOR_CROSSHAIR:
  775. cursor = XCreateFontCursor (SDL_Display, XC_crosshair);
  776. break;
  777. case Polycode::Core::CURSOR_RESIZE_LEFT_RIGHT:
  778. cursor = XCreateFontCursor (SDL_Display, XC_sb_h_double_arrow);
  779. break;
  780. case Polycode::Core::CURSOR_RESIZE_UP_DOWN:
  781. cursor = XCreateFontCursor (SDL_Display, XC_sb_v_double_arrow);
  782. break;
  783. case Polycode::Core::CURSOR_OPEN_HAND:
  784. cursor = XCreateFontCursor (SDL_Display, XC_fleur);
  785. break;
  786. case Polycode::Core::CURSOR_ARROW:
  787. cursor = 0;
  788. break;
  789. }
  790. defined_cursors[cursorType] = cursor;
  791. }
  792. }
  793. if(!cursor) {
  794. // Restore the normal cursor.
  795. XUndefineCursor(SDL_Display, SDL_Window);
  796. } else {
  797. XDefineCursor(SDL_Display, SDL_Window, cursor);
  798. }
  799. XFlush(SDL_Display);
  800. }
  801. void free_cursors() {
  802. XUndefineCursor(SDL_Display, SDL_Window);
  803. for(int i = 0; i < CURSOR_COUNT; i++) {
  804. if(defined_cursors[i]) {
  805. XFreeCursor(SDL_Display, defined_cursors[i]);
  806. defined_cursors[i] = 0;
  807. }
  808. }
  809. }
  810. } // namespace
  811. // end X11 cursor
  812. #endif // USE_X11