mouse_events.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. import { delayBlurEvent, ensureFocus } from "../display/focus.js"
  2. import { operation } from "../display/operations.js"
  3. import { visibleLines } from "../display/update_lines.js"
  4. import { clipPos, cmp, maxPos, minPos, Pos } from "../line/pos.js"
  5. import { getLine, lineAtHeight } from "../line/utils_line.js"
  6. import { posFromMouse } from "../measurement/position_measurement.js"
  7. import { eventInWidget } from "../measurement/widgets.js"
  8. import { normalizeSelection, Range, Selection } from "../model/selection.js"
  9. import { extendRange, extendSelection, replaceOneSelection, setSelection } from "../model/selection_updates.js"
  10. import { captureRightClick, chromeOS, ie, ie_version, mac, webkit } from "../util/browser.js"
  11. import { getOrder, getBidiPartAt } from "../util/bidi.js"
  12. import { activeElt } from "../util/dom.js"
  13. import { e_button, e_defaultPrevented, e_preventDefault, e_target, hasHandler, off, on, signal, signalDOMEvent } from "../util/event.js"
  14. import { dragAndDrop } from "../util/feature_detection.js"
  15. import { bind, countColumn, findColumn, sel_mouse } from "../util/misc.js"
  16. import { addModifierNames } from "../input/keymap.js"
  17. import { Pass } from "../util/misc.js"
  18. import { dispatchKey } from "./key_events.js"
  19. import { commands } from "./commands.js"
  20. const DOUBLECLICK_DELAY = 400
  21. class PastClick {
  22. constructor(time, pos, button) {
  23. this.time = time
  24. this.pos = pos
  25. this.button = button
  26. }
  27. compare(time, pos, button) {
  28. return this.time + DOUBLECLICK_DELAY > time &&
  29. cmp(pos, this.pos) == 0 && button == this.button
  30. }
  31. }
  32. let lastClick, lastDoubleClick
  33. function clickRepeat(pos, button) {
  34. let now = +new Date
  35. if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
  36. lastClick = lastDoubleClick = null
  37. return "triple"
  38. } else if (lastClick && lastClick.compare(now, pos, button)) {
  39. lastDoubleClick = new PastClick(now, pos, button)
  40. lastClick = null
  41. return "double"
  42. } else {
  43. lastClick = new PastClick(now, pos, button)
  44. lastDoubleClick = null
  45. return "single"
  46. }
  47. }
  48. // A mouse down can be a single click, double click, triple click,
  49. // start of selection drag, start of text drag, new cursor
  50. // (ctrl-click), rectangle drag (alt-drag), or xwin
  51. // middle-click-paste. Or it might be a click on something we should
  52. // not interfere with, such as a scrollbar or widget.
  53. export function onMouseDown(e) {
  54. let cm = this, display = cm.display
  55. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) return
  56. display.input.ensurePolled()
  57. display.shift = e.shiftKey
  58. if (eventInWidget(display, e)) {
  59. if (!webkit) {
  60. // Briefly turn off draggability, to allow widgets to do
  61. // normal dragging things.
  62. display.scroller.draggable = false
  63. setTimeout(() => display.scroller.draggable = true, 100)
  64. }
  65. return
  66. }
  67. let button = e_button(e)
  68. if (button == 3 && captureRightClick ? contextMenuInGutter(cm, e) : clickInGutter(cm, e)) return
  69. let pos = posFromMouse(cm, e), repeat = pos ? clickRepeat(pos, button) : "single"
  70. window.focus()
  71. // #3261: make sure, that we're not starting a second selection
  72. if (button == 1 && cm.state.selectingText)
  73. cm.state.selectingText(e)
  74. if (pos && handleMappedButton(cm, button, pos, repeat, e)) return
  75. if (button == 1) {
  76. if (pos) leftButtonDown(cm, pos, repeat, e)
  77. else if (e_target(e) == display.scroller) e_preventDefault(e)
  78. } else if (button == 2) {
  79. if (pos) extendSelection(cm.doc, pos)
  80. setTimeout(() => display.input.focus(), 20)
  81. } else if (button == 3) {
  82. if (captureRightClick) onContextMenu(cm, e)
  83. else delayBlurEvent(cm)
  84. }
  85. }
  86. function handleMappedButton(cm, button, pos, repeat, event) {
  87. let name = "Click"
  88. if (repeat == "double") name = "Double" + name
  89. else if (repeat == "triple") name = "Triple" + name
  90. name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name
  91. return dispatchKey(cm, addModifierNames(name, event), event, bound => {
  92. if (typeof bound == "string") bound = commands[bound]
  93. if (!bound) return false
  94. let done = false
  95. try {
  96. if (cm.isReadOnly()) cm.state.suppressEdits = true
  97. done = bound(cm, pos) != Pass
  98. } finally {
  99. cm.state.suppressEdits = false
  100. }
  101. return done
  102. })
  103. }
  104. function configureMouse(cm, repeat, event) {
  105. let option = cm.getOption("configureMouse")
  106. let value = option ? option(cm, repeat, event) : {}
  107. if (value.unit == null) {
  108. let rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey
  109. value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line"
  110. }
  111. if (value.extend == null || cm.doc.extend) value.extend = cm.doc.extend || event.shiftKey
  112. if (value.addNew == null) value.addNew = mac ? event.metaKey : event.ctrlKey
  113. if (value.moveOnDrag == null) value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey)
  114. return value
  115. }
  116. function leftButtonDown(cm, pos, repeat, event) {
  117. if (ie) setTimeout(bind(ensureFocus, cm), 0)
  118. else cm.curOp.focus = activeElt()
  119. let behavior = configureMouse(cm, repeat, event)
  120. let sel = cm.doc.sel, contained
  121. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  122. repeat == "single" && (contained = sel.contains(pos)) > -1 &&
  123. (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
  124. (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
  125. leftButtonStartDrag(cm, event, pos, behavior)
  126. else
  127. leftButtonSelect(cm, event, pos, behavior)
  128. }
  129. // Start a text drag. When it ends, see if any dragging actually
  130. // happen, and treat as a click if it didn't.
  131. function leftButtonStartDrag(cm, event, pos, behavior) {
  132. let display = cm.display, moved = false
  133. let dragEnd = operation(cm, e => {
  134. if (webkit) display.scroller.draggable = false
  135. cm.state.draggingText = false
  136. off(display.wrapper.ownerDocument, "mouseup", dragEnd)
  137. off(display.wrapper.ownerDocument, "mousemove", mouseMove)
  138. off(display.scroller, "dragstart", dragStart)
  139. off(display.scroller, "drop", dragEnd)
  140. if (!moved) {
  141. e_preventDefault(e)
  142. if (!behavior.addNew)
  143. extendSelection(cm.doc, pos, null, null, behavior.extend)
  144. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  145. if (webkit || ie && ie_version == 9)
  146. setTimeout(() => {display.wrapper.ownerDocument.body.focus(); display.input.focus()}, 20)
  147. else
  148. display.input.focus()
  149. }
  150. })
  151. let mouseMove = function(e2) {
  152. moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10
  153. }
  154. let dragStart = () => moved = true
  155. // Let the drag handler handle this.
  156. if (webkit) display.scroller.draggable = true
  157. cm.state.draggingText = dragEnd
  158. dragEnd.copy = !behavior.moveOnDrag
  159. // IE's approach to draggable
  160. if (display.scroller.dragDrop) display.scroller.dragDrop()
  161. on(display.wrapper.ownerDocument, "mouseup", dragEnd)
  162. on(display.wrapper.ownerDocument, "mousemove", mouseMove)
  163. on(display.scroller, "dragstart", dragStart)
  164. on(display.scroller, "drop", dragEnd)
  165. delayBlurEvent(cm)
  166. setTimeout(() => display.input.focus(), 20)
  167. }
  168. function rangeForUnit(cm, pos, unit) {
  169. if (unit == "char") return new Range(pos, pos)
  170. if (unit == "word") return cm.findWordAt(pos)
  171. if (unit == "line") return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)))
  172. let result = unit(cm, pos)
  173. return new Range(result.from, result.to)
  174. }
  175. // Normal selection, as opposed to text dragging.
  176. function leftButtonSelect(cm, event, start, behavior) {
  177. let display = cm.display, doc = cm.doc
  178. e_preventDefault(event)
  179. let ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges
  180. if (behavior.addNew && !behavior.extend) {
  181. ourIndex = doc.sel.contains(start)
  182. if (ourIndex > -1)
  183. ourRange = ranges[ourIndex]
  184. else
  185. ourRange = new Range(start, start)
  186. } else {
  187. ourRange = doc.sel.primary()
  188. ourIndex = doc.sel.primIndex
  189. }
  190. if (behavior.unit == "rectangle") {
  191. if (!behavior.addNew) ourRange = new Range(start, start)
  192. start = posFromMouse(cm, event, true, true)
  193. ourIndex = -1
  194. } else {
  195. let range = rangeForUnit(cm, start, behavior.unit)
  196. if (behavior.extend)
  197. ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend)
  198. else
  199. ourRange = range
  200. }
  201. if (!behavior.addNew) {
  202. ourIndex = 0
  203. setSelection(doc, new Selection([ourRange], 0), sel_mouse)
  204. startSel = doc.sel
  205. } else if (ourIndex == -1) {
  206. ourIndex = ranges.length
  207. setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
  208. {scroll: false, origin: "*mouse"})
  209. } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
  210. setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  211. {scroll: false, origin: "*mouse"})
  212. startSel = doc.sel
  213. } else {
  214. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse)
  215. }
  216. let lastPos = start
  217. function extendTo(pos) {
  218. if (cmp(lastPos, pos) == 0) return
  219. lastPos = pos
  220. if (behavior.unit == "rectangle") {
  221. let ranges = [], tabSize = cm.options.tabSize
  222. let startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize)
  223. let posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize)
  224. let left = Math.min(startCol, posCol), right = Math.max(startCol, posCol)
  225. for (let line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  226. line <= end; line++) {
  227. let text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize)
  228. if (left == right)
  229. ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)))
  230. else if (text.length > leftPos)
  231. ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))))
  232. }
  233. if (!ranges.length) ranges.push(new Range(start, start))
  234. setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  235. {origin: "*mouse", scroll: false})
  236. cm.scrollIntoView(pos)
  237. } else {
  238. let oldRange = ourRange
  239. let range = rangeForUnit(cm, pos, behavior.unit)
  240. let anchor = oldRange.anchor, head
  241. if (cmp(range.anchor, anchor) > 0) {
  242. head = range.head
  243. anchor = minPos(oldRange.from(), range.anchor)
  244. } else {
  245. head = range.anchor
  246. anchor = maxPos(oldRange.to(), range.head)
  247. }
  248. let ranges = startSel.ranges.slice(0)
  249. ranges[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head))
  250. setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse)
  251. }
  252. }
  253. let editorSize = display.wrapper.getBoundingClientRect()
  254. // Used to ensure timeout re-tries don't fire when another extend
  255. // happened in the meantime (clearTimeout isn't reliable -- at
  256. // least on Chrome, the timeouts still happen even when cleared,
  257. // if the clear happens after their scheduled firing time).
  258. let counter = 0
  259. function extend(e) {
  260. let curCount = ++counter
  261. let cur = posFromMouse(cm, e, true, behavior.unit == "rectangle")
  262. if (!cur) return
  263. if (cmp(cur, lastPos) != 0) {
  264. cm.curOp.focus = activeElt()
  265. extendTo(cur)
  266. let visible = visibleLines(display, doc)
  267. if (cur.line >= visible.to || cur.line < visible.from)
  268. setTimeout(operation(cm, () => {if (counter == curCount) extend(e)}), 150)
  269. } else {
  270. let outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0
  271. if (outside) setTimeout(operation(cm, () => {
  272. if (counter != curCount) return
  273. display.scroller.scrollTop += outside
  274. extend(e)
  275. }), 50)
  276. }
  277. }
  278. function done(e) {
  279. cm.state.selectingText = false
  280. counter = Infinity
  281. e_preventDefault(e)
  282. display.input.focus()
  283. off(display.wrapper.ownerDocument, "mousemove", move)
  284. off(display.wrapper.ownerDocument, "mouseup", up)
  285. doc.history.lastSelOrigin = null
  286. }
  287. let move = operation(cm, e => {
  288. if (e.buttons === 0 || !e_button(e)) done(e)
  289. else extend(e)
  290. })
  291. let up = operation(cm, done)
  292. cm.state.selectingText = up
  293. on(display.wrapper.ownerDocument, "mousemove", move)
  294. on(display.wrapper.ownerDocument, "mouseup", up)
  295. }
  296. // Used when mouse-selecting to adjust the anchor to the proper side
  297. // of a bidi jump depending on the visual position of the head.
  298. function bidiSimplify(cm, range) {
  299. let {anchor, head} = range, anchorLine = getLine(cm.doc, anchor.line)
  300. if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) return range
  301. let order = getOrder(anchorLine)
  302. if (!order) return range
  303. let index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index]
  304. if (part.from != anchor.ch && part.to != anchor.ch) return range
  305. let boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1)
  306. if (boundary == 0 || boundary == order.length) return range
  307. // Compute the relative visual position of the head compared to the
  308. // anchor (<0 is to the left, >0 to the right)
  309. let leftSide
  310. if (head.line != anchor.line) {
  311. leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0
  312. } else {
  313. let headIndex = getBidiPartAt(order, head.ch, head.sticky)
  314. let dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1)
  315. if (headIndex == boundary - 1 || headIndex == boundary)
  316. leftSide = dir < 0
  317. else
  318. leftSide = dir > 0
  319. }
  320. let usePart = order[boundary + (leftSide ? -1 : 0)]
  321. let from = leftSide == (usePart.level == 1)
  322. let ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before"
  323. return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head)
  324. }
  325. // Determines whether an event happened in the gutter, and fires the
  326. // handlers for the corresponding event.
  327. function gutterEvent(cm, e, type, prevent) {
  328. let mX, mY
  329. if (e.touches) {
  330. mX = e.touches[0].clientX
  331. mY = e.touches[0].clientY
  332. } else {
  333. try { mX = e.clientX; mY = e.clientY }
  334. catch(e) { return false }
  335. }
  336. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false
  337. if (prevent) e_preventDefault(e)
  338. let display = cm.display
  339. let lineBox = display.lineDiv.getBoundingClientRect()
  340. if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e)
  341. mY -= lineBox.top - display.viewOffset
  342. for (let i = 0; i < cm.options.gutters.length; ++i) {
  343. let g = display.gutters.childNodes[i]
  344. if (g && g.getBoundingClientRect().right >= mX) {
  345. let line = lineAtHeight(cm.doc, mY)
  346. let gutter = cm.options.gutters[i]
  347. signal(cm, type, cm, line, gutter, e)
  348. return e_defaultPrevented(e)
  349. }
  350. }
  351. }
  352. export function clickInGutter(cm, e) {
  353. return gutterEvent(cm, e, "gutterClick", true)
  354. }
  355. // CONTEXT MENU HANDLING
  356. // To make the context menu work, we need to briefly unhide the
  357. // textarea (making it as unobtrusive as possible) to let the
  358. // right-click take effect on it.
  359. export function onContextMenu(cm, e) {
  360. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return
  361. if (signalDOMEvent(cm, e, "contextmenu")) return
  362. cm.display.input.onContextMenu(e)
  363. }
  364. function contextMenuInGutter(cm, e) {
  365. if (!hasHandler(cm, "gutterContextMenu")) return false
  366. return gutterEvent(cm, e, "gutterContextMenu", false)
  367. }