2
0

PolySDLCore.cpp 22 KB

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