dragdrop_handler.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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._top = blankImage.offsetTop;
  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. };
  100. this.onDragEnter = function(e) {
  101. if (editor.getReadOnly() || !canAccept(e.dataTransfer))
  102. return;
  103. if (!dragSelectionMarker)
  104. addDragMarker();
  105. counter++;
  106. // dataTransfer object does not save dropEffect across events on IE, so we store it in dragOperation
  107. e.dataTransfer.dropEffect = dragOperation = getDropEffect(e);
  108. return event.preventDefault(e);
  109. };
  110. this.onDragOver = function(e) {
  111. if (editor.getReadOnly() || !canAccept(e.dataTransfer))
  112. return;
  113. // Opera doesn't trigger dragenter event on drag start
  114. if (!dragSelectionMarker) {
  115. addDragMarker();
  116. counter++;
  117. }
  118. if (onMouseMoveTimer !== null)
  119. onMouseMoveTimer = null;
  120. x = e.clientX;
  121. y = e.clientY;
  122. e.dataTransfer.dropEffect = dragOperation = getDropEffect(e);
  123. return event.preventDefault(e);
  124. };
  125. this.onDragLeave = function(e) {
  126. counter--;
  127. if (counter <= 0 && dragSelectionMarker) {
  128. clearDragMarker();
  129. dragOperation = null;
  130. return event.preventDefault(e);
  131. }
  132. };
  133. this.onDrop = function(e) {
  134. if (!dragSelectionMarker)
  135. return;
  136. var dataTransfer = e.dataTransfer;
  137. if (isInternal) {
  138. switch (dragOperation) {
  139. case "move":
  140. if (range.contains(dragCursor.row, dragCursor.column)) {
  141. // clear selection
  142. range = {
  143. start: dragCursor,
  144. end: dragCursor
  145. };
  146. } else {
  147. // move text
  148. range = editor.moveText(range, dragCursor);
  149. }
  150. break;
  151. case "copy":
  152. // copy text
  153. range = editor.moveText(range, dragCursor, true);
  154. break;
  155. }
  156. } else {
  157. var dropData = dataTransfer.getData('Text');
  158. range = {
  159. start: dragCursor,
  160. end: editor.session.insert(dragCursor, dropData)
  161. };
  162. editor.focus();
  163. dragOperation = null;
  164. }
  165. clearDragMarker();
  166. return event.preventDefault(e);
  167. };
  168. event.addListener(mouseTarget, "dragstart", this.onDragStart.bind(mouseHandler));
  169. event.addListener(mouseTarget, "dragend", this.onDragEnd.bind(mouseHandler));
  170. event.addListener(mouseTarget, "dragenter", this.onDragEnter.bind(mouseHandler));
  171. event.addListener(mouseTarget, "dragover", this.onDragOver.bind(mouseHandler));
  172. event.addListener(mouseTarget, "dragleave", this.onDragLeave.bind(mouseHandler));
  173. event.addListener(mouseTarget, "drop", this.onDrop.bind(mouseHandler));
  174. function scrollCursorIntoView(cursor, prevCursor) {
  175. var now = new Date().getTime();
  176. var vMovement = !prevCursor || cursor.row != prevCursor.row;
  177. var hMovement = !prevCursor || cursor.column != prevCursor.column;
  178. if (!cursorMovedTime || vMovement || hMovement) {
  179. editor.$blockScrolling += 1;
  180. editor.moveCursorToPosition(cursor);
  181. editor.$blockScrolling -= 1;
  182. cursorMovedTime = now;
  183. cursorPointOnCaretMoved = {x: x, y: y};
  184. } else {
  185. var distance = calcDistance(cursorPointOnCaretMoved.x, cursorPointOnCaretMoved.y, x, y);
  186. if (distance > SCROLL_CURSOR_HYSTERESIS) {
  187. cursorMovedTime = null;
  188. } else if (now - cursorMovedTime >= SCROLL_CURSOR_DELAY) {
  189. editor.renderer.scrollCursorIntoView();
  190. cursorMovedTime = null;
  191. }
  192. }
  193. }
  194. function autoScroll(cursor, prevCursor) {
  195. var now = new Date().getTime();
  196. var lineHeight = editor.renderer.layerConfig.lineHeight;
  197. var characterWidth = editor.renderer.layerConfig.characterWidth;
  198. var editorRect = editor.renderer.scroller.getBoundingClientRect();
  199. var offsets = {
  200. x: {
  201. left: x - editorRect.left,
  202. right: editorRect.right - x
  203. },
  204. y: {
  205. top: y - editorRect.top,
  206. bottom: editorRect.bottom - y
  207. }
  208. };
  209. var nearestXOffset = Math.min(offsets.x.left, offsets.x.right);
  210. var nearestYOffset = Math.min(offsets.y.top, offsets.y.bottom);
  211. var scrollCursor = {row: cursor.row, column: cursor.column};
  212. if (nearestXOffset / characterWidth <= 2) {
  213. scrollCursor.column += (offsets.x.left < offsets.x.right ? -3 : +2);
  214. }
  215. if (nearestYOffset / lineHeight <= 1) {
  216. scrollCursor.row += (offsets.y.top < offsets.y.bottom ? -1 : +1);
  217. }
  218. var vScroll = cursor.row != scrollCursor.row;
  219. var hScroll = cursor.column != scrollCursor.column;
  220. var vMovement = !prevCursor || cursor.row != prevCursor.row;
  221. if (vScroll || (hScroll && !vMovement)) {
  222. if (!autoScrollStartTime)
  223. autoScrollStartTime = now;
  224. else if (now - autoScrollStartTime >= AUTOSCROLL_DELAY)
  225. editor.renderer.scrollCursorIntoView(scrollCursor);
  226. } else {
  227. autoScrollStartTime = null;
  228. }
  229. }
  230. function onDragInterval() {
  231. var prevCursor = dragCursor;
  232. dragCursor = editor.renderer.screenToTextCoordinates(x, y);
  233. scrollCursorIntoView(dragCursor, prevCursor);
  234. autoScroll(dragCursor, prevCursor);
  235. }
  236. function addDragMarker() {
  237. range = editor.selection.toOrientedRange();
  238. dragSelectionMarker = editor.session.addMarker(range, "ace_selection", editor.getSelectionStyle());
  239. editor.clearSelection();
  240. if (editor.isFocused())
  241. editor.renderer.$cursorLayer.setBlinking(false);
  242. clearInterval(timerId);
  243. timerId = setInterval(onDragInterval, 20);
  244. counter = 0;
  245. event.addListener(document, "mousemove", onMouseMove);
  246. }
  247. function clearDragMarker() {
  248. clearInterval(timerId);
  249. editor.session.removeMarker(dragSelectionMarker);
  250. dragSelectionMarker = null;
  251. editor.$blockScrolling += 1;
  252. editor.selection.fromOrientedRange(range);
  253. editor.$blockScrolling -= 1;
  254. if (editor.isFocused() && !isInternal)
  255. editor.renderer.$cursorLayer.setBlinking(!editor.getReadOnly());
  256. range = null;
  257. counter = 0;
  258. autoScrollStartTime = null;
  259. cursorMovedTime = null;
  260. event.removeListener(document, "mousemove", onMouseMove);
  261. }
  262. // sometimes other code on the page can stop dragleave event leaving editor stuck in the drag state
  263. var onMouseMoveTimer = null;
  264. function onMouseMove() {
  265. if (onMouseMoveTimer == null) {
  266. onMouseMoveTimer = setTimeout(function() {
  267. if (onMouseMoveTimer != null && dragSelectionMarker)
  268. clearDragMarker();
  269. }, 20);
  270. }
  271. }
  272. function canAccept(dataTransfer) {
  273. var types = dataTransfer.types;
  274. return !types || Array.prototype.some.call(types, function(type) {
  275. return type == 'text/plain' || type == 'Text';
  276. });
  277. }
  278. function getDropEffect(e) {
  279. var copyAllowed = ['copy', 'copymove', 'all', 'uninitialized'];
  280. var moveAllowed = ['move', 'copymove', 'linkmove', 'all', 'uninitialized'];
  281. var copyModifierState = useragent.isMac ? e.altKey : e.ctrlKey;
  282. // IE throws error while dragging from another app
  283. var effectAllowed = "uninitialized";
  284. try {
  285. effectAllowed = e.dataTransfer.effectAllowed.toLowerCase();
  286. } catch (e) {}
  287. var dropEffect = "none";
  288. if (copyModifierState && copyAllowed.indexOf(effectAllowed) >= 0)
  289. dropEffect = "copy";
  290. else if (moveAllowed.indexOf(effectAllowed) >= 0)
  291. dropEffect = "move";
  292. else if (copyAllowed.indexOf(effectAllowed) >= 0)
  293. dropEffect = "copy";
  294. return dropEffect;
  295. }
  296. }
  297. (function() {
  298. this.dragWait = function() {
  299. var interval = (new Date()).getTime() - this.mousedownEvent.time;
  300. if (interval > this.editor.getDragDelay())
  301. this.startDrag();
  302. };
  303. this.dragWaitEnd = function() {
  304. var target = this.editor.container;
  305. target.draggable = false;
  306. this.startSelect(this.mousedownEvent.getDocumentPosition());
  307. this.selectEnd();
  308. };
  309. this.dragReadyEnd = function(e) {
  310. this.editor.renderer.$cursorLayer.setBlinking(!this.editor.getReadOnly());
  311. this.editor.unsetStyle("ace_dragging");
  312. this.dragWaitEnd();
  313. };
  314. this.startDrag = function(){
  315. this.cancelDrag = false;
  316. var target = this.editor.container;
  317. target.draggable = true;
  318. this.editor.renderer.$cursorLayer.setBlinking(false);
  319. this.editor.setStyle("ace_dragging");
  320. this.setState("dragReady");
  321. };
  322. this.onMouseDrag = function(e) {
  323. var target = this.editor.container;
  324. if (useragent.isIE && this.state == "dragReady") {
  325. // IE does not handle [draggable] attribute set after mousedown
  326. var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y);
  327. if (distance > 3)
  328. target.dragDrop();
  329. }
  330. if (this.state === "dragWait") {
  331. var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y);
  332. if (distance > 0) {
  333. target.draggable = false;
  334. this.startSelect(this.mousedownEvent.getDocumentPosition());
  335. }
  336. }
  337. };
  338. this.onMouseDown = function(e) {
  339. if (!this.$dragEnabled)
  340. return;
  341. this.mousedownEvent = e;
  342. var editor = this.editor;
  343. var inSelection = e.inSelection();
  344. var button = e.getButton();
  345. var clickCount = e.domEvent.detail || 1;
  346. if (clickCount === 1 && button === 0 && inSelection) {
  347. this.mousedownEvent.time = (new Date()).getTime();
  348. var eventTarget = e.domEvent.target || e.domEvent.srcElement;
  349. if ("unselectable" in eventTarget)
  350. eventTarget.unselectable = "on";
  351. if (editor.getDragDelay()) {
  352. // https://code.google.com/p/chromium/issues/detail?id=286700
  353. if (useragent.isWebKit) {
  354. self.cancelDrag = true;
  355. var mouseTarget = editor.container;
  356. mouseTarget.draggable = true;
  357. }
  358. this.setState("dragWait");
  359. } else {
  360. this.startDrag();
  361. }
  362. this.captureMouse(e, this.onMouseDrag.bind(this));
  363. // TODO: a better way to prevent default handler without preventing browser default action
  364. e.defaultPrevented = true;
  365. }
  366. };
  367. }).call(DragdropHandler.prototype);
  368. function calcDistance(ax, ay, bx, by) {
  369. return Math.sqrt(Math.pow(bx - ax, 2) + Math.pow(by - ay, 2));
  370. }
  371. exports.DragdropHandler = DragdropHandler;
  372. });