BsLinuxDropTarget.cpp 15 KB

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