dragdrop_handler.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. /* ***** BEGIN LICENSE BLOCK *****
  2. * Distributed under the BSD license:
  3. *
  4. * Copyright (c) 2010, Ajax.org B.V.
  5. * All rights reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. * * Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * * Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * * Neither the name of Ajax.org B.V. nor the
  15. * names of its contributors may be used to endorse or promote products
  16. * derived from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *
  29. * ***** END LICENSE BLOCK ***** */
  30. define(function(require, exports, module) {
  31. "use strict";
  32. var dom = require("../lib/dom");
  33. var event = require("../lib/event");
  34. var useragent = require("../lib/useragent");
  35. var AUTOSCROLL_DELAY = 200;
  36. var SCROLL_CURSOR_DELAY = 200;
  37. var SCROLL_CURSOR_HYSTERESIS = 5;
  38. function DragdropHandler(mouseHandler) {
  39. var editor = mouseHandler.editor;
  40. var blankImage = dom.createElement("img");
  41. // Safari crashes without image data
  42. blankImage.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  43. if (useragent.isOpera)
  44. blankImage.style.cssText = "width:1px;height:1px;position:fixed;top:0;left:0;z-index:2147483647;opacity:0;";
  45. var exports = ["dragWait", "dragWaitEnd", "startDrag", "dragReadyEnd", "onMouseDrag"];
  46. exports.forEach(function(x) {
  47. mouseHandler[x] = this[x];
  48. }, this);
  49. editor.addEventListener("mousedown", this.onMouseDown.bind(mouseHandler));
  50. var mouseTarget = editor.container;
  51. var dragSelectionMarker, x, y;
  52. var timerId, range;
  53. var dragCursor, counter = 0;
  54. var dragOperation;
  55. var isInternal;
  56. var autoScrollStartTime;
  57. var cursorMovedTime;
  58. var cursorPointOnCaretMoved;
  59. this.onDragStart = function(e) {
  60. // webkit workaround, see this.onMouseDown
  61. if (this.cancelDrag || !mouseTarget.draggable) {
  62. var self = this;
  63. setTimeout(function(){
  64. self.startSelect();
  65. self.captureMouse(e);
  66. }, 0);
  67. return e.preventDefault();
  68. }
  69. range = editor.getSelectionRange();
  70. var dataTransfer = e.dataTransfer;
  71. dataTransfer.effectAllowed = editor.getReadOnly() ? "copy" : "copyMove";
  72. if (useragent.isOpera) {
  73. editor.container.appendChild(blankImage);
  74. // force layout
  75. blankImage.scrollTop = 0;
  76. }
  77. dataTransfer.setDragImage && dataTransfer.setDragImage(blankImage, 0, 0);
  78. if (useragent.isOpera) {
  79. editor.container.removeChild(blankImage);
  80. }
  81. // clear Opera garbage
  82. dataTransfer.clearData();
  83. dataTransfer.setData("Text", editor.session.getTextRange());
  84. isInternal = true;
  85. this.setState("drag");
  86. };
  87. this.onDragEnd = function(e) {
  88. mouseTarget.draggable = false;
  89. isInternal = false;
  90. this.setState(null);
  91. if (!editor.getReadOnly()) {
  92. var dropEffect = e.dataTransfer.dropEffect;
  93. if (!dragOperation && dropEffect == "move")
  94. // text was dragged outside the editor
  95. editor.session.remove(editor.getSelectionRange());
  96. editor.renderer.$cursorLayer.setBlinking(true);
  97. }
  98. this.editor.unsetStyle("ace_dragging");
  99. this.editor.renderer.setCursorStyle("");
  100. };
  101. this.onDragEnter = function(e) {
  102. if (editor.getReadOnly() || !canAccept(e.dataTransfer))
  103. return;
  104. x = e.clientX;
  105. y = e.clientY;
  106. if (!dragSelectionMarker)
  107. addDragMarker();
  108. counter++;
  109. // dataTransfer object does not save dropEffect across events on IE, so we store it in dragOperation
  110. e.dataTransfer.dropEffect = dragOperation = getDropEffect(e);
  111. return event.preventDefault(e);
  112. };
  113. this.onDragOver = function(e) {
  114. if (editor.getReadOnly() || !canAccept(e.dataTransfer))
  115. return;
  116. x = e.clientX;
  117. y = e.clientY;
  118. // Opera doesn't trigger dragenter event on drag start
  119. if (!dragSelectionMarker) {
  120. addDragMarker();
  121. counter++;
  122. }
  123. if (onMouseMoveTimer !== null)
  124. onMouseMoveTimer = null;
  125. e.dataTransfer.dropEffect = dragOperation = getDropEffect(e);
  126. return event.preventDefault(e);
  127. };
  128. this.onDragLeave = function(e) {
  129. counter--;
  130. if (counter <= 0 && dragSelectionMarker) {
  131. clearDragMarker();
  132. dragOperation = null;
  133. return event.preventDefault(e);
  134. }
  135. };
  136. this.onDrop = function(e) {
  137. if (!dragCursor)
  138. return;
  139. var dataTransfer = e.dataTransfer;
  140. if (isInternal) {
  141. switch (dragOperation) {
  142. case "move":
  143. if (range.contains(dragCursor.row, dragCursor.column)) {
  144. // clear selection
  145. range = {
  146. start: dragCursor,
  147. end: dragCursor
  148. };
  149. } else {
  150. // move text
  151. range = editor.moveText(range, dragCursor);
  152. }
  153. break;
  154. case "copy":
  155. // copy text
  156. range = editor.moveText(range, dragCursor, true);
  157. break;
  158. }
  159. } else {
  160. var dropData = dataTransfer.getData('Text');
  161. range = {
  162. start: dragCursor,
  163. end: editor.session.insert(dragCursor, dropData)
  164. };
  165. editor.focus();
  166. dragOperation = null;
  167. }
  168. clearDragMarker();
  169. return event.preventDefault(e);
  170. };
  171. event.addListener(mouseTarget, "dragstart", this.onDragStart.bind(mouseHandler));
  172. event.addListener(mouseTarget, "dragend", this.onDragEnd.bind(mouseHandler));
  173. event.addListener(mouseTarget, "dragenter", this.onDragEnter.bind(mouseHandler));
  174. event.addListener(mouseTarget, "dragover", this.onDragOver.bind(mouseHandler));
  175. event.addListener(mouseTarget, "dragleave", this.onDragLeave.bind(mouseHandler));
  176. event.addListener(mouseTarget, "drop", this.onDrop.bind(mouseHandler));
  177. function scrollCursorIntoView(cursor, prevCursor) {
  178. var now = Date.now();
  179. var vMovement = !prevCursor || cursor.row != prevCursor.row;
  180. var hMovement = !prevCursor || cursor.column != prevCursor.column;
  181. if (!cursorMovedTime || vMovement || hMovement) {
  182. editor.$blockScrolling += 1;
  183. editor.moveCursorToPosition(cursor);
  184. editor.$blockScrolling -= 1;
  185. cursorMovedTime = now;
  186. cursorPointOnCaretMoved = {x: x, y: y};
  187. } else {
  188. var distance = calcDistance(cursorPointOnCaretMoved.x, cursorPointOnCaretMoved.y, x, y);
  189. if (distance > SCROLL_CURSOR_HYSTERESIS) {
  190. cursorMovedTime = null;
  191. } else if (now - cursorMovedTime >= SCROLL_CURSOR_DELAY) {
  192. editor.renderer.scrollCursorIntoView();
  193. cursorMovedTime = null;
  194. }
  195. }
  196. }
  197. function autoScroll(cursor, prevCursor) {
  198. var now = Date.now();
  199. var lineHeight = editor.renderer.layerConfig.lineHeight;
  200. var characterWidth = editor.renderer.layerConfig.characterWidth;
  201. var editorRect = editor.renderer.scroller.getBoundingClientRect();
  202. var offsets = {
  203. x: {
  204. left: x - editorRect.left,
  205. right: editorRect.right - x
  206. },
  207. y: {
  208. top: y - editorRect.top,
  209. bottom: editorRect.bottom - y
  210. }
  211. };
  212. var nearestXOffset = Math.min(offsets.x.left, offsets.x.right);
  213. var nearestYOffset = Math.min(offsets.y.top, offsets.y.bottom);
  214. var scrollCursor = {row: cursor.row, column: cursor.column};
  215. if (nearestXOffset / characterWidth <= 2) {
  216. scrollCursor.column += (offsets.x.left < offsets.x.right ? -3 : +2);
  217. }
  218. if (nearestYOffset / lineHeight <= 1) {
  219. scrollCursor.row += (offsets.y.top < offsets.y.bottom ? -1 : +1);
  220. }
  221. var vScroll = cursor.row != scrollCursor.row;
  222. var hScroll = cursor.column != scrollCursor.column;
  223. var vMovement = !prevCursor || cursor.row != prevCursor.row;
  224. if (vScroll || (hScroll && !vMovement)) {
  225. if (!autoScrollStartTime)
  226. autoScrollStartTime = now;
  227. else if (now - autoScrollStartTime >= AUTOSCROLL_DELAY)
  228. editor.renderer.scrollCursorIntoView(scrollCursor);
  229. } else {
  230. autoScrollStartTime = null;
  231. }
  232. }
  233. function onDragInterval() {
  234. var prevCursor = dragCursor;
  235. dragCursor = editor.renderer.screenToTextCoordinates(x, y);
  236. scrollCursorIntoView(dragCursor, prevCursor);
  237. autoScroll(dragCursor, prevCursor);
  238. }
  239. function addDragMarker() {
  240. range = editor.selection.toOrientedRange();
  241. dragSelectionMarker = editor.session.addMarker(range, "ace_selection", editor.getSelectionStyle());
  242. editor.clearSelection();
  243. if (editor.isFocused())
  244. editor.renderer.$cursorLayer.setBlinking(false);
  245. clearInterval(timerId);
  246. onDragInterval();
  247. timerId = setInterval(onDragInterval, 20);
  248. counter = 0;
  249. event.addListener(document, "mousemove", onMouseMove);
  250. }
  251. function clearDragMarker() {
  252. clearInterval(timerId);
  253. editor.session.removeMarker(dragSelectionMarker);
  254. dragSelectionMarker = null;
  255. editor.$blockScrolling += 1;
  256. editor.selection.fromOrientedRange(range);
  257. editor.$blockScrolling -= 1;
  258. if (editor.isFocused() && !isInternal)
  259. editor.renderer.$cursorLayer.setBlinking(!editor.getReadOnly());
  260. range = null;
  261. dragCursor = null;
  262. counter = 0;
  263. autoScrollStartTime = null;
  264. cursorMovedTime = null;
  265. event.removeListener(document, "mousemove", onMouseMove);
  266. }
  267. // sometimes other code on the page can stop dragleave event leaving editor stuck in the drag state
  268. var onMouseMoveTimer = null;
  269. function onMouseMove() {
  270. if (onMouseMoveTimer == null) {
  271. onMouseMoveTimer = setTimeout(function() {
  272. if (onMouseMoveTimer != null && dragSelectionMarker)
  273. clearDragMarker();
  274. }, 20);
  275. }
  276. }
  277. function canAccept(dataTransfer) {
  278. var types = dataTransfer.types;
  279. return !types || Array.prototype.some.call(types, function(type) {
  280. return type == 'text/plain' || type == 'Text';
  281. });
  282. }
  283. function getDropEffect(e) {
  284. var copyAllowed = ['copy', 'copymove', 'all', 'uninitialized'];
  285. var moveAllowed = ['move', 'copymove', 'linkmove', 'all', 'uninitialized'];
  286. var copyModifierState = useragent.isMac ? e.altKey : e.ctrlKey;
  287. // IE throws error while dragging from another app
  288. var effectAllowed = "uninitialized";
  289. try {
  290. effectAllowed = e.dataTransfer.effectAllowed.toLowerCase();
  291. } catch (e) {}
  292. var dropEffect = "none";
  293. if (copyModifierState && copyAllowed.indexOf(effectAllowed) >= 0)
  294. dropEffect = "copy";
  295. else if (moveAllowed.indexOf(effectAllowed) >= 0)
  296. dropEffect = "move";
  297. else if (copyAllowed.indexOf(effectAllowed) >= 0)
  298. dropEffect = "copy";
  299. return dropEffect;
  300. }
  301. }
  302. (function() {
  303. this.dragWait = function() {
  304. var interval = Date.now() - this.mousedownEvent.time;
  305. if (interval > this.editor.getDragDelay())
  306. this.startDrag();
  307. };
  308. this.dragWaitEnd = function() {
  309. var target = this.editor.container;
  310. target.draggable = false;
  311. this.startSelect(this.mousedownEvent.getDocumentPosition());
  312. this.selectEnd();
  313. };
  314. this.dragReadyEnd = function(e) {
  315. this.editor.renderer.$cursorLayer.setBlinking(!this.editor.getReadOnly());
  316. this.editor.unsetStyle("ace_dragging");
  317. this.editor.renderer.setCursorStyle("");
  318. this.dragWaitEnd();
  319. };
  320. this.startDrag = function(){
  321. this.cancelDrag = false;
  322. var editor = this.editor;
  323. var target = editor.container;
  324. target.draggable = true;
  325. editor.renderer.$cursorLayer.setBlinking(false);
  326. editor.setStyle("ace_dragging");
  327. var cursorStyle = useragent.isWin ? "default" : "move";
  328. editor.renderer.setCursorStyle(cursorStyle);
  329. this.setState("dragReady");
  330. };
  331. this.onMouseDrag = function(e) {
  332. var target = this.editor.container;
  333. if (useragent.isIE && this.state == "dragReady") {
  334. // IE does not handle [draggable] attribute set after mousedown
  335. var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y);
  336. if (distance > 3)
  337. target.dragDrop();
  338. }
  339. if (this.state === "dragWait") {
  340. var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y);
  341. if (distance > 0) {
  342. target.draggable = false;
  343. this.startSelect(this.mousedownEvent.getDocumentPosition());
  344. }
  345. }
  346. };
  347. this.onMouseDown = function(e) {
  348. if (!this.$dragEnabled)
  349. return;
  350. this.mousedownEvent = e;
  351. var editor = this.editor;
  352. var inSelection = e.inSelection();
  353. var button = e.getButton();
  354. var clickCount = e.domEvent.detail || 1;
  355. if (clickCount === 1 && button === 0 && inSelection) {
  356. if (e.editor.inMultiSelectMode && (e.getAccelKey() || e.getShiftKey()))
  357. return;
  358. this.mousedownEvent.time = Date.now();
  359. var eventTarget = e.domEvent.target || e.domEvent.srcElement;
  360. if ("unselectable" in eventTarget)
  361. eventTarget.unselectable = "on";
  362. if (editor.getDragDelay()) {
  363. // https://code.google.com/p/chromium/issues/detail?id=286700
  364. if (useragent.isWebKit) {
  365. this.cancelDrag = true;
  366. var mouseTarget = editor.container;
  367. mouseTarget.draggable = true;
  368. }
  369. this.setState("dragWait");
  370. } else {
  371. this.startDrag();
  372. }
  373. this.captureMouse(e, this.onMouseDrag.bind(this));
  374. // TODO: a better way to prevent default handler without preventing browser default action
  375. e.defaultPrevented = true;
  376. }
  377. };
  378. }).call(DragdropHandler.prototype);
  379. function calcDistance(ax, ay, bx, by) {
  380. return Math.sqrt(Math.pow(bx - ax, 2) + Math.pow(by - ay, 2));
  381. }
  382. exports.DragdropHandler = DragdropHandler;
  383. });