BsLinuxDropTarget.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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. #define INIT_ATOM(name) s##name = XInternAtom(xDisplay, #name, False);
  183. INIT_ATOM(XdndAware)
  184. INIT_ATOM(XdndSelection)
  185. INIT_ATOM(XdndEnter)
  186. INIT_ATOM(XdndLeave)
  187. INIT_ATOM(XdndPosition)
  188. INIT_ATOM(XdndStatus)
  189. INIT_ATOM(XdndDrop)
  190. INIT_ATOM(XdndFinished)
  191. INIT_ATOM(XdndActionCopy)
  192. INIT_ATOM(XdndTypeList)
  193. INIT_ATOM(PRIMARY)
  194. #undef INIT_ATOM
  195. }
  196. void LinuxDragAndDrop::shutDown()
  197. {
  198. // Do nothing
  199. }
  200. void LinuxDragAndDrop::makeDNDAware(::Window xWindow)
  201. {
  202. UINT32 dndVersion = 5;
  203. XChangeProperty(sXDisplay, xWindow, sXdndAware, XA_ATOM, 32, PropModeReplace, (unsigned char*)&dndVersion, 1);
  204. }
  205. void LinuxDragAndDrop::registerDropTarget(DropTarget* target)
  206. {
  207. Lock lock(sMutex);
  208. sQueuedAreaOperations.push_back(DropAreaOp(target, DropAreaOpType::Register, target->getArea()));
  209. }
  210. void LinuxDragAndDrop::unregisterDropTarget(DropTarget* target)
  211. {
  212. Lock lock(sMutex);
  213. sQueuedAreaOperations.push_back(DropAreaOp(target, DropAreaOpType::Unregister));
  214. }
  215. void LinuxDragAndDrop::updateDropTarget(DropTarget* target)
  216. {
  217. Lock lock(sMutex);
  218. sQueuedAreaOperations.push_back(DropAreaOp(target, DropAreaOpType::Update, target->getArea()));
  219. }
  220. bool LinuxDragAndDrop::handleClientMessage(XClientMessageEvent& event)
  221. {
  222. // First handle any queued registration/unregistration
  223. {
  224. Lock lock(sMutex);
  225. for(auto& entry : sQueuedAreaOperations)
  226. {
  227. switch(entry.type)
  228. {
  229. case DropAreaOpType::Register:
  230. sDropAreas.push_back(DropArea(entry.target, entry.area));
  231. break;
  232. case DropAreaOpType::Unregister:
  233. // Remove any operations queued for this target
  234. for(auto iter = sQueuedOperations.begin(); iter !=sQueuedOperations.end();)
  235. {
  236. if(iter->target == entry.target)
  237. iter = sQueuedOperations.erase(iter);
  238. else
  239. ++iter;
  240. }
  241. // Remove the area
  242. {
  243. auto iterFind = std::find_if(sDropAreas.begin(), sDropAreas.end(), [&](const DropArea& area)
  244. {
  245. return area.target == entry.target;
  246. });
  247. sDropAreas.erase(iterFind);
  248. }
  249. break;
  250. case DropAreaOpType::Update:
  251. {
  252. auto iterFind = std::find_if(sDropAreas.begin(), sDropAreas.end(), [&](const DropArea& area)
  253. {
  254. return area.target == entry.target;
  255. });
  256. if (iterFind != sDropAreas.end())
  257. iterFind->area = entry.area;
  258. }
  259. break;
  260. }
  261. }
  262. sQueuedAreaOperations.clear();
  263. }
  264. // Source window notifies us a drag has just entered our window area
  265. if(event.message_type == sXdndEnter)
  266. {
  267. sDNDSource = (::Window)event.data.l[0];
  268. bool isList = (event.data.l[1] & 1) != 0;
  269. sDNDVersion = (INT32)(event.data.l[1] >> 24);
  270. // Get a list of properties are determine if there are any relevant ones
  271. Atom* propertyList = nullptr;
  272. UINT32 numProperties = 0;
  273. // If more than 3 properties we need to read the list property to get them all
  274. if(isList)
  275. {
  276. X11Property property = readX11Property(sXDisplay, sDNDSource, sXdndTypeList);
  277. propertyList = (Atom*)property.data;
  278. numProperties = property.count;
  279. }
  280. else
  281. {
  282. propertyList = bs_stack_alloc<Atom>(3);
  283. for(int i = 0; i < 3; i++)
  284. {
  285. if(event.data.l[2 + i])
  286. {
  287. propertyList[i] = (Atom)event.data.l[2 + i];
  288. numProperties++;
  289. }
  290. }
  291. }
  292. // Scan the list for URI list (file list), which is the only one we support (currently)
  293. bool foundSupportedType = false;
  294. for (UINT32 i = 0; i < numProperties; ++i)
  295. {
  296. char* name = XGetAtomName(sXDisplay, propertyList[i]);
  297. if(strcmp(name, "text/uri-list") == 0)
  298. {
  299. sDNDType = propertyList[i];
  300. XFree(name);
  301. foundSupportedType = true;
  302. break;
  303. }
  304. XFree(name);
  305. }
  306. // Free the property list
  307. if(isList)
  308. XFree(propertyList);
  309. else
  310. bs_stack_free(propertyList);
  311. sDragActive = foundSupportedType;
  312. }
  313. // Cursor moved while drag is active (also includes the initial cursor activity when drag entered)
  314. else if(event.message_type == sXdndPosition)
  315. {
  316. ::Window source = (::Window)event.data.l[0];
  317. sDragPosition.x = (INT32)((event.data.l[2] >> 16) & 0xFFFF);
  318. sDragPosition.y = (INT32)((event.data.l[2]) & 0xFFFF);
  319. // Respond with a status message, we either accept or reject the dnd
  320. XClientMessageEvent response;
  321. bs_zero_out(response);
  322. response.type = ClientMessage;
  323. response.display = event.display;
  324. response.window = source;
  325. response.message_type = sXdndStatus;
  326. response.format = 32;
  327. response.data.l[0] = event.window;
  328. response.data.l[1] = 0; // Reject drop by default
  329. response.data.l[2] = 0; // Empty rectangle
  330. response.data.l[3] = 0; // Empty rectangle
  331. response.data.l[4] = sXdndActionCopy;
  332. if(sDragActive)
  333. {
  334. for(auto& dropArea : sDropAreas)
  335. {
  336. LinuxWindow* linuxWindow;
  337. dropArea.target->_getOwnerWindow()->getCustomAttribute("WINDOW", &linuxWindow);
  338. ::Window xWindow = linuxWindow->_getXWindow();
  339. if(xWindow == event.window)
  340. {
  341. Vector2I windowPos = linuxWindow->screenToWindowPos(sDragPosition);
  342. if(dropArea.area.contains(windowPos))
  343. {
  344. // Accept drop
  345. response.data.l[1] = 1;
  346. if(dropArea.target->_isActive())
  347. {
  348. Lock lock(sMutex);
  349. sQueuedOperations.push_back(DragAndDropOp(DragAndDropOpType::DragOver, dropArea.target,
  350. windowPos));
  351. }
  352. else
  353. {
  354. Lock lock(sMutex);
  355. sQueuedOperations.push_back(DragAndDropOp(DragAndDropOpType::Enter, dropArea.target,
  356. windowPos));
  357. }
  358. dropArea.target->_setActive(true);
  359. }
  360. else
  361. {
  362. // Cursor left previously active target's area
  363. if(dropArea.target->_isActive())
  364. {
  365. {
  366. Lock lock(sMutex);
  367. sQueuedOperations.push_back(DragAndDropOp(DragAndDropOpType::Leave, dropArea.target));
  368. }
  369. dropArea.target->_setActive(false);
  370. }
  371. }
  372. }
  373. }
  374. }
  375. XSendEvent(sXDisplay, source, False, NoEventMask, (XEvent*)&response);
  376. XFlush(sXDisplay);
  377. }
  378. // Cursor left the target window, or the drop was rejected
  379. else if(event.message_type == sXdndLeave)
  380. {
  381. for(auto& dropArea : sDropAreas)
  382. {
  383. if(dropArea.target->_isActive())
  384. {
  385. {
  386. Lock lock(sMutex);
  387. sQueuedOperations.push_back(DragAndDropOp(DragAndDropOpType::Leave, dropArea.target));
  388. }
  389. dropArea.target->_setActive(false);
  390. }
  391. }
  392. sDragActive = false;
  393. }
  394. else if(event.message_type == sXdndDrop)
  395. {
  396. ::Window source = (::Window)event.data.l[0];
  397. bool dropAccepted = false;
  398. if(sDragActive)
  399. {
  400. for (auto& dropArea : sDropAreas)
  401. {
  402. if (dropArea.target->_isActive())
  403. dropAccepted = true;
  404. }
  405. }
  406. if(dropAccepted)
  407. {
  408. Time timestamp;
  409. if(sDNDVersion >= 1)
  410. timestamp = (Time)event.data.l[2];
  411. else
  412. timestamp = CurrentTime;
  413. XConvertSelection(sXDisplay, sXdndSelection, sDNDType, sPRIMARY, LinuxPlatform::getMainXWindow(), timestamp);
  414. // Now we wait for SelectionNotify
  415. }
  416. else
  417. {
  418. // Respond with a status message that we reject the drop
  419. XClientMessageEvent response;
  420. bs_zero_out(response);
  421. response.type = ClientMessage;
  422. response.display = event.display;
  423. response.window = source;
  424. response.message_type = sXdndFinished;
  425. response.format = 32;
  426. response.data.l[0] = LinuxPlatform::getMainXWindow();
  427. response.data.l[1] = 0;
  428. response.data.l[2] = 0;
  429. response.data.l[3] = 0;
  430. response.data.l[4] = 0;
  431. XSendEvent(sXDisplay, source, False, NoEventMask, (XEvent*)&response);
  432. XFlush(sXDisplay);
  433. sDragActive = false;
  434. }
  435. }
  436. else
  437. return false;
  438. return true;
  439. }
  440. bool LinuxDragAndDrop::handleSelectionNotify(XSelectionEvent& event)
  441. {
  442. if(event.target != sDNDType)
  443. return false;
  444. if(!sDragActive)
  445. return true;
  446. // Read data
  447. X11Property property = readX11Property(sXDisplay, LinuxPlatform::getMainXWindow(), sXdndTypeList);
  448. if(property.format == 8)
  449. {
  450. // Assuming this is a file list, since we rejected any other drop type
  451. Vector<Path> filePaths;
  452. char* token = strtok((char*)property.data, "\r\n");
  453. while(token != nullptr)
  454. {
  455. char* filePath = convertURIToLocalPath(token);
  456. if(filePath != nullptr)
  457. filePaths.push_back(String(filePath));
  458. token = strtok(nullptr, "\r\n");
  459. }
  460. for(auto& dropArea : sDropAreas)
  461. {
  462. if(!dropArea.target->_isActive())
  463. continue;
  464. LinuxWindow* linuxWindow;
  465. dropArea.target->_getOwnerWindow()->getCustomAttribute("WINDOW", &linuxWindow);
  466. Vector2I windowPos = linuxWindow->screenToWindowPos(sDragPosition);
  467. Lock lock(sMutex);
  468. sQueuedOperations.push_back(DragAndDropOp(DragAndDropOpType::Drop, dropArea.target, windowPos, filePaths));
  469. dropArea.target->_setActive(false);
  470. }
  471. }
  472. XFree(property.data);
  473. // Respond with a status message that we accepted the drop
  474. XClientMessageEvent response;
  475. bs_zero_out(response);
  476. response.type = ClientMessage;
  477. response.display = event.display;
  478. response.window = sDNDSource;
  479. response.message_type = sXdndFinished;
  480. response.format = 32;
  481. response.data.l[0] = LinuxPlatform::getMainXWindow();
  482. response.data.l[1] = 1;
  483. response.data.l[2] = sXdndActionCopy;
  484. response.data.l[3] = 0;
  485. response.data.l[4] = 0;
  486. XSendEvent(sXDisplay, sDNDSource, False, NoEventMask, (XEvent*)&response);
  487. XFlush(sXDisplay);
  488. sDragActive = false;
  489. return true;
  490. }
  491. void LinuxDragAndDrop::update()
  492. {
  493. Vector<DragAndDropOp> operations;
  494. {
  495. Lock lock(sMutex);
  496. std::swap(operations, sQueuedOperations);
  497. }
  498. for(auto& op : operations)
  499. {
  500. switch(op.type)
  501. {
  502. case DragAndDropOpType::Enter:
  503. op.target->onEnter(op.position.x, op.position.y);
  504. break;
  505. case DragAndDropOpType::DragOver:
  506. op.target->onDragOver(op.position.x, op.position.y);
  507. break;
  508. case DragAndDropOpType::Drop:
  509. op.target->_setFileList(op.fileList);
  510. op.target->onDrop(op.position.x, op.position.y);
  511. break;
  512. case DragAndDropOpType::Leave:
  513. op.target->_clear();
  514. op.target->onLeave();
  515. break;
  516. }
  517. }
  518. }
  519. }