BsLinuxDropTarget.cpp 15 KB

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