BsLinuxDropTarget.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "String/BsUnicode.h"
  4. #include "Platform/BsPlatform.h"
  5. #include "Platform/BsDropTarget.h"
  6. #include "RenderAPI/BsRenderWindow.h"
  7. #include "Math/BsRect2I.h"
  8. #include "BsLinuxDropTarget.h"
  9. #include "BsLinuxWindow.h"
  10. #include "BsLinuxPlatform.h"
  11. #include <X11/Xatom.h>
  12. #include <X11/Xlib.h>
  13. #undef None
  14. namespace bs
  15. {
  16. ::Display* LinuxDragAndDrop::sXDisplay = nullptr;
  17. bool LinuxDragAndDrop::sDragActive = false;
  18. Vector<LinuxDragAndDrop::DropArea> LinuxDragAndDrop::sDropAreas;
  19. Mutex LinuxDragAndDrop::sMutex;
  20. INT32 LinuxDragAndDrop::sDNDVersion = 0;
  21. Atom LinuxDragAndDrop::sDNDType = 0;
  22. ::Window LinuxDragAndDrop::sDNDSource = 0;
  23. Vector2I LinuxDragAndDrop::sDragPosition;
  24. Vector<LinuxDragAndDrop::DragAndDropOp> LinuxDragAndDrop::sQueuedOperations;
  25. Vector<LinuxDragAndDrop::DropAreaOp> LinuxDragAndDrop::sQueuedAreaOperations;
  26. Atom LinuxDragAndDrop::sXdndAware;
  27. Atom LinuxDragAndDrop::sXdndSelection;
  28. Atom LinuxDragAndDrop::sXdndEnter;
  29. Atom LinuxDragAndDrop::sXdndLeave;
  30. Atom LinuxDragAndDrop::sXdndPosition;
  31. Atom LinuxDragAndDrop::sXdndStatus;
  32. Atom LinuxDragAndDrop::sXdndDrop;
  33. Atom LinuxDragAndDrop::sXdndFinished;
  34. Atom LinuxDragAndDrop::sXdndActionCopy;
  35. Atom LinuxDragAndDrop::sXdndTypeList;
  36. Atom LinuxDragAndDrop::sPRIMARY;
  37. struct X11Property
  38. {
  39. UINT8* data;
  40. INT32 format;
  41. UINT32 count;
  42. Atom type;
  43. };
  44. // Results must be freed using XFree
  45. X11Property readX11Property(::Display *display, ::Window window, Atom type)
  46. {
  47. X11Property output;
  48. output.data = nullptr;
  49. unsigned long bytesLeft;
  50. int bytesToFetch = 0;
  51. do
  52. {
  53. if(output.data != nullptr)
  54. XFree(output.data);
  55. XGetWindowProperty(display, window, type, 0, bytesToFetch, False, AnyPropertyType,
  56. &output.type, &output.format, (unsigned long*)&output.count, &bytesLeft, &output.data);
  57. bytesToFetch += bytesLeft;
  58. } while(bytesLeft != 0);
  59. return output;
  60. }
  61. /**
  62. * Decodes percent (%) encoded characters in an URI to actual characters. Characters are decoded into the input string.
  63. */
  64. void decodeURI(char* uri)
  65. {
  66. if(uri == nullptr)
  67. return;
  68. UINT32 length = (UINT32)strlen(uri);
  69. UINT8 decodedChar = '\0';
  70. UINT32 writeIdx = 0;
  71. UINT32 decodeState = 0; // 0 - Not decoding, 1 - found a % char, 2- found a % and following char
  72. for(UINT32 i = 0; i < length; i++)
  73. {
  74. // Not currently decoding, check for % or write as-is
  75. if(decodeState == 0)
  76. {
  77. // Potentially an encoded char, start decode
  78. if(uri[i] == '%')
  79. {
  80. decodedChar = '\0';
  81. decodeState = 1;
  82. }
  83. else // Normal char, write as-is
  84. {
  85. uri[writeIdx] = uri[i];
  86. writeIdx++;
  87. }
  88. }
  89. else // Currently decoding, check if following chars are valid
  90. {
  91. char isa = uri[i] >= 'a' && uri[i] <= 'f';
  92. char isA = uri[i] >= 'A' && uri[i] <= 'F';
  93. char isn = uri[i] >= '0' && uri[i] <= '9';
  94. bool isHex = isa || isA || isn;
  95. if(!isHex)
  96. {
  97. // If not a hex, this can't be an encoded character. Write the last "decodeState" characters as normal
  98. for(UINT32 j = decodeState; j > 0; j--)
  99. {
  100. uri[writeIdx] = uri[i - j];
  101. writeIdx++;
  102. }
  103. decodeState = 0;
  104. }
  105. else
  106. {
  107. // Decode the hex character into a number
  108. char offset = '\0';
  109. if(isn)
  110. offset = 0 - '0';
  111. else if(isa)
  112. offset = 10 - 'a';
  113. else if(isA)
  114. offset = 10 - 'A';
  115. decodedChar |= (uri[i] + offset) << ((2 - decodeState) * 4);
  116. // Check if done decoding and write
  117. if(decodeState == 2)
  118. {
  119. uri[writeIdx] = decodedChar;
  120. writeIdx++;
  121. decodeState = 0;
  122. }
  123. else // decodeState == 1
  124. decodeState = 2;
  125. }
  126. }
  127. }
  128. uri[writeIdx] = '\0';
  129. }
  130. char* convertURIToLocalPath(char* uri)
  131. {
  132. if (memcmp(uri, "file:/", 6) == 0)
  133. uri += 6;
  134. else if (strstr(uri, ":/") != nullptr)
  135. return nullptr;
  136. bool isLocal = uri[0] != '/' || (uri[0] != '\0' && uri[1] == '/');
  137. // Ignore hostname
  138. if (!isLocal && uri[0] == '/' && uri[2] != '/')
  139. {
  140. char* hostnameEnd = strchr(uri+1, '/');
  141. if (hostnameEnd != nullptr)
  142. {
  143. char hostname[257];
  144. if (gethostname(hostname, 255) == 0)
  145. {
  146. hostname[256] = '\0';
  147. if (memcmp(uri+1, hostname, hostnameEnd - (uri+1)) == 0)
  148. {
  149. uri = hostnameEnd + 1;
  150. isLocal = true;
  151. }
  152. }
  153. }
  154. }
  155. if (isLocal)
  156. {
  157. decodeURI(uri);
  158. if (uri[1] == '/')
  159. uri++;
  160. else
  161. uri--;
  162. return uri;
  163. }
  164. return nullptr;
  165. }
  166. DropTarget::DropTarget(const RenderWindow* ownerWindow, const Rect2I& area)
  167. : mArea(area), mActive(false), mOwnerWindow(ownerWindow), mDropType(DropTargetType::None)
  168. {
  169. LinuxDragAndDrop::registerDropTarget(this);
  170. }
  171. DropTarget::~DropTarget()
  172. {
  173. LinuxDragAndDrop::unregisterDropTarget(this);
  174. _clear();
  175. }
  176. void DropTarget::setArea(const Rect2I& area)
  177. {
  178. mArea = area;
  179. LinuxDragAndDrop::updateDropTarget(this);
  180. }
  181. void LinuxDragAndDrop::startUp(::Display* xDisplay)
  182. {
  183. sXDisplay = xDisplay;
  184. #define INIT_ATOM(name) s##name = XInternAtom(xDisplay, #name, False);
  185. INIT_ATOM(XdndAware)
  186. INIT_ATOM(XdndSelection)
  187. INIT_ATOM(XdndEnter)
  188. INIT_ATOM(XdndLeave)
  189. INIT_ATOM(XdndPosition)
  190. INIT_ATOM(XdndStatus)
  191. INIT_ATOM(XdndDrop)
  192. INIT_ATOM(XdndFinished)
  193. INIT_ATOM(XdndActionCopy)
  194. INIT_ATOM(XdndTypeList)
  195. INIT_ATOM(PRIMARY)
  196. #undef INIT_ATOM
  197. }
  198. void LinuxDragAndDrop::shutDown()
  199. {
  200. sXDisplay = nullptr;
  201. }
  202. void LinuxDragAndDrop::makeDNDAware(::Window xWindow)
  203. {
  204. UINT32 dndVersion = 5;
  205. XChangeProperty(sXDisplay, xWindow, sXdndAware, XA_ATOM, 32, PropModeReplace, (unsigned char*)&dndVersion, 1);
  206. }
  207. void LinuxDragAndDrop::registerDropTarget(DropTarget* target)
  208. {
  209. Lock lock(sMutex);
  210. sQueuedAreaOperations.push_back(DropAreaOp(target, DropAreaOpType::Register, target->getArea()));
  211. }
  212. void LinuxDragAndDrop::unregisterDropTarget(DropTarget* target)
  213. {
  214. Lock lock(sMutex);
  215. sQueuedAreaOperations.push_back(DropAreaOp(target, DropAreaOpType::Unregister));
  216. }
  217. void LinuxDragAndDrop::updateDropTarget(DropTarget* target)
  218. {
  219. Lock lock(sMutex);
  220. sQueuedAreaOperations.push_back(DropAreaOp(target, DropAreaOpType::Update, target->getArea()));
  221. }
  222. bool LinuxDragAndDrop::handleClientMessage(XClientMessageEvent& event)
  223. {
  224. // First handle any queued registration/unregistration
  225. {
  226. Lock lock(sMutex);
  227. for(auto& entry : sQueuedAreaOperations)
  228. {
  229. switch(entry.type)
  230. {
  231. case DropAreaOpType::Register:
  232. sDropAreas.push_back(DropArea(entry.target, entry.area));
  233. break;
  234. case DropAreaOpType::Unregister:
  235. // Remove any operations queued for this target
  236. for(auto iter = sQueuedOperations.begin(); iter !=sQueuedOperations.end();)
  237. {
  238. if(iter->target == entry.target)
  239. iter = sQueuedOperations.erase(iter);
  240. else
  241. ++iter;
  242. }
  243. // Remove the area
  244. {
  245. auto iterFind = std::find_if(sDropAreas.begin(), sDropAreas.end(), [&](const DropArea& area)
  246. {
  247. return area.target == entry.target;
  248. });
  249. sDropAreas.erase(iterFind);
  250. }
  251. break;
  252. case DropAreaOpType::Update:
  253. {
  254. auto iterFind = std::find_if(sDropAreas.begin(), sDropAreas.end(), [&](const DropArea& area)
  255. {
  256. return area.target == entry.target;
  257. });
  258. if (iterFind != sDropAreas.end())
  259. iterFind->area = entry.area;
  260. }
  261. break;
  262. }
  263. }
  264. sQueuedAreaOperations.clear();
  265. }
  266. // Source window notifies us a drag has just entered our window area
  267. if(event.message_type == sXdndEnter)
  268. {
  269. sDNDSource = (::Window)event.data.l[0];
  270. bool isList = (event.data.l[1] & 1) != 0;
  271. sDNDVersion = (INT32)(event.data.l[1] >> 24);
  272. // Get a list of properties are determine if there are any relevant ones
  273. Atom* propertyList = nullptr;
  274. UINT32 numProperties = 0;
  275. // If more than 3 properties we need to read the list property to get them all
  276. if(isList)
  277. {
  278. X11Property property = readX11Property(sXDisplay, sDNDSource, sXdndTypeList);
  279. propertyList = (Atom*)property.data;
  280. numProperties = property.count;
  281. }
  282. else
  283. {
  284. propertyList = bs_stack_alloc<Atom>(3);
  285. for(int i = 0; i < 3; i++)
  286. {
  287. if(event.data.l[2 + i])
  288. {
  289. propertyList[i] = (Atom)event.data.l[2 + i];
  290. numProperties++;
  291. }
  292. }
  293. }
  294. // Scan the list for URI list (file list), which is the only one we support (currently)
  295. bool foundSupportedType = false;
  296. for (UINT32 i = 0; i < numProperties; ++i)
  297. {
  298. char* name = XGetAtomName(sXDisplay, propertyList[i]);
  299. if(strcmp(name, "text/uri-list") == 0)
  300. {
  301. sDNDType = propertyList[i];
  302. XFree(name);
  303. foundSupportedType = true;
  304. break;
  305. }
  306. XFree(name);
  307. }
  308. // Free the property list
  309. if(isList)
  310. XFree(propertyList);
  311. else
  312. bs_stack_free(propertyList);
  313. sDragActive = foundSupportedType;
  314. }
  315. // Cursor moved while drag is active (also includes the initial cursor activity when drag entered)
  316. else if(event.message_type == sXdndPosition)
  317. {
  318. ::Window source = (::Window)event.data.l[0];
  319. sDragPosition.x = (INT32)((event.data.l[2] >> 16) & 0xFFFF);
  320. sDragPosition.y = (INT32)((event.data.l[2]) & 0xFFFF);
  321. // Respond with a status message, we either accept or reject the dnd
  322. XClientMessageEvent response;
  323. bs_zero_out(response);
  324. response.type = ClientMessage;
  325. response.display = event.display;
  326. response.window = source;
  327. response.message_type = sXdndStatus;
  328. response.format = 32;
  329. response.data.l[0] = event.window;
  330. response.data.l[1] = 0; // Reject drop by default
  331. response.data.l[2] = 0; // Empty rectangle
  332. response.data.l[3] = 0; // Empty rectangle
  333. response.data.l[4] = sXdndActionCopy;
  334. if(sDragActive)
  335. {
  336. for(auto& dropArea : sDropAreas)
  337. {
  338. LinuxWindow* linuxWindow;
  339. dropArea.target->_getOwnerWindow()->getCustomAttribute("LINUX_WINDOW", &linuxWindow);
  340. ::Window xWindow = linuxWindow->_getXWindow();
  341. if(xWindow == event.window)
  342. {
  343. Vector2I windowPos = linuxWindow->screenToWindowPos(sDragPosition);
  344. if(dropArea.area.contains(windowPos))
  345. {
  346. // Accept drop
  347. response.data.l[1] = 1;
  348. if(dropArea.target->_isActive())
  349. {
  350. Lock lock(sMutex);
  351. sQueuedOperations.push_back(DragAndDropOp(DragAndDropOpType::DragOver, dropArea.target,
  352. windowPos));
  353. }
  354. else
  355. {
  356. Lock lock(sMutex);
  357. sQueuedOperations.push_back(DragAndDropOp(DragAndDropOpType::Enter, dropArea.target,
  358. windowPos));
  359. }
  360. dropArea.target->_setActive(true);
  361. }
  362. else
  363. {
  364. // Cursor left previously active target's area
  365. if(dropArea.target->_isActive())
  366. {
  367. {
  368. Lock lock(sMutex);
  369. sQueuedOperations.push_back(DragAndDropOp(DragAndDropOpType::Leave, dropArea.target));
  370. }
  371. dropArea.target->_setActive(false);
  372. }
  373. }
  374. }
  375. }
  376. }
  377. XSendEvent(sXDisplay, source, False, NoEventMask, (XEvent*)&response);
  378. XFlush(sXDisplay);
  379. }
  380. // Cursor left the target window, or the drop was rejected
  381. else if(event.message_type == sXdndLeave)
  382. {
  383. for(auto& dropArea : sDropAreas)
  384. {
  385. if(dropArea.target->_isActive())
  386. {
  387. {
  388. Lock lock(sMutex);
  389. sQueuedOperations.push_back(DragAndDropOp(DragAndDropOpType::Leave, dropArea.target));
  390. }
  391. dropArea.target->_setActive(false);
  392. }
  393. }
  394. sDragActive = false;
  395. }
  396. else if(event.message_type == sXdndDrop)
  397. {
  398. ::Window source = (::Window)event.data.l[0];
  399. bool dropAccepted = false;
  400. if(sDragActive)
  401. {
  402. for (auto& dropArea : sDropAreas)
  403. {
  404. if (dropArea.target->_isActive())
  405. dropAccepted = true;
  406. }
  407. }
  408. if(dropAccepted)
  409. {
  410. Time timestamp;
  411. if(sDNDVersion >= 1)
  412. timestamp = (Time)event.data.l[2];
  413. else
  414. timestamp = CurrentTime;
  415. XConvertSelection(sXDisplay, sXdndSelection, sDNDType, sPRIMARY, LinuxPlatform::getMainXWindow(), timestamp);
  416. // Now we wait for SelectionNotify
  417. }
  418. else
  419. {
  420. // Respond with a status message that we reject the drop
  421. XClientMessageEvent response;
  422. bs_zero_out(response);
  423. response.type = ClientMessage;
  424. response.display = event.display;
  425. response.window = source;
  426. response.message_type = sXdndFinished;
  427. response.format = 32;
  428. response.data.l[0] = LinuxPlatform::getMainXWindow();
  429. response.data.l[1] = 0;
  430. response.data.l[2] = 0;
  431. response.data.l[3] = 0;
  432. response.data.l[4] = 0;
  433. XSendEvent(sXDisplay, source, False, NoEventMask, (XEvent*)&response);
  434. XFlush(sXDisplay);
  435. sDragActive = false;
  436. }
  437. }
  438. else
  439. return false;
  440. return true;
  441. }
  442. bool LinuxDragAndDrop::handleSelectionNotify(XSelectionEvent& event)
  443. {
  444. if(event.target != sDNDType)
  445. return false;
  446. if(!sDragActive)
  447. return true;
  448. // Read data
  449. X11Property property = readX11Property(sXDisplay, LinuxPlatform::getMainXWindow(), sPRIMARY);
  450. if(property.format == 8)
  451. {
  452. // Assuming this is a file list, since we rejected any other drop type
  453. Vector<Path> filePaths;
  454. char* token = strtok((char*)property.data, "\r\n");
  455. while(token != nullptr)
  456. {
  457. char* filePath = convertURIToLocalPath(token);
  458. if(filePath != nullptr)
  459. filePaths.push_back(String(filePath));
  460. token = strtok(nullptr, "\r\n");
  461. }
  462. for(auto& dropArea : sDropAreas)
  463. {
  464. if(!dropArea.target->_isActive())
  465. continue;
  466. LinuxWindow* linuxWindow;
  467. dropArea.target->_getOwnerWindow()->getCustomAttribute("LINUX_WINDOW", &linuxWindow);
  468. Vector2I windowPos = linuxWindow->screenToWindowPos(sDragPosition);
  469. Lock lock(sMutex);
  470. sQueuedOperations.push_back(DragAndDropOp(DragAndDropOpType::Drop, dropArea.target, windowPos, filePaths));
  471. dropArea.target->_setActive(false);
  472. }
  473. }
  474. XFree(property.data);
  475. // Respond with a status message that we accepted the drop
  476. XClientMessageEvent response;
  477. bs_zero_out(response);
  478. response.type = ClientMessage;
  479. response.display = event.display;
  480. response.window = sDNDSource;
  481. response.message_type = sXdndFinished;
  482. response.format = 32;
  483. response.data.l[0] = LinuxPlatform::getMainXWindow();
  484. response.data.l[1] = 1;
  485. response.data.l[2] = sXdndActionCopy;
  486. response.data.l[3] = 0;
  487. response.data.l[4] = 0;
  488. XSendEvent(sXDisplay, sDNDSource, False, NoEventMask, (XEvent*)&response);
  489. XFlush(sXDisplay);
  490. sDragActive = false;
  491. return true;
  492. }
  493. void LinuxDragAndDrop::update()
  494. {
  495. Vector<DragAndDropOp> operations;
  496. {
  497. Lock lock(sMutex);
  498. std::swap(operations, sQueuedOperations);
  499. }
  500. for(auto& op : operations)
  501. {
  502. switch(op.type)
  503. {
  504. case DragAndDropOpType::Enter:
  505. op.target->onEnter(op.position.x, op.position.y);
  506. break;
  507. case DragAndDropOpType::DragOver:
  508. op.target->onDragOver(op.position.x, op.position.y);
  509. break;
  510. case DragAndDropOpType::Drop:
  511. op.target->_setFileList(op.fileList);
  512. op.target->onDrop(op.position.x, op.position.y);
  513. break;
  514. case DragAndDropOpType::Leave:
  515. op.target->_clear();
  516. op.target->onLeave();
  517. break;
  518. }
  519. }
  520. }
  521. }