position_measurement.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  1. import { buildLineContent, LineView } from "../line/line_data.js"
  2. import { clipPos, Pos } from "../line/pos.js"
  3. import { collapsedSpanAround, heightAtLine, lineIsHidden, visualLine } from "../line/spans.js"
  4. import { getLine, lineAtHeight, lineNo, updateLineHeight } from "../line/utils_line.js"
  5. import { bidiOther, getBidiPartAt, getOrder } from "../util/bidi.js"
  6. import { chrome, android, ie, ie_version } from "../util/browser.js"
  7. import { elt, removeChildren, range, removeChildrenAndAdd } from "../util/dom.js"
  8. import { e_target } from "../util/event.js"
  9. import { hasBadZoomedRects } from "../util/feature_detection.js"
  10. import { countColumn, findFirst, isExtendingChar, scrollerGap, skipExtendingChars } from "../util/misc.js"
  11. import { updateLineForChanges } from "../display/update_line.js"
  12. import { widgetHeight } from "./widgets.js"
  13. // POSITION MEASUREMENT
  14. export function paddingTop(display) {return display.lineSpace.offsetTop}
  15. export function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
  16. export function paddingH(display) {
  17. if (display.cachedPaddingH) return display.cachedPaddingH
  18. let e = removeChildrenAndAdd(display.measure, elt("pre", "x"))
  19. let style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle
  20. let data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}
  21. if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data
  22. return data
  23. }
  24. export function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
  25. export function displayWidth(cm) {
  26. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  27. }
  28. export function displayHeight(cm) {
  29. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  30. }
  31. // Ensure the lineView.wrapping.heights array is populated. This is
  32. // an array of bottom offsets for the lines that make up a drawn
  33. // line. When lineWrapping is on, there might be more than one
  34. // height.
  35. function ensureLineHeights(cm, lineView, rect) {
  36. let wrapping = cm.options.lineWrapping
  37. let curWidth = wrapping && displayWidth(cm)
  38. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  39. let heights = lineView.measure.heights = []
  40. if (wrapping) {
  41. lineView.measure.width = curWidth
  42. let rects = lineView.text.firstChild.getClientRects()
  43. for (let i = 0; i < rects.length - 1; i++) {
  44. let cur = rects[i], next = rects[i + 1]
  45. if (Math.abs(cur.bottom - next.bottom) > 2)
  46. heights.push((cur.bottom + next.top) / 2 - rect.top)
  47. }
  48. }
  49. heights.push(rect.bottom - rect.top)
  50. }
  51. }
  52. // Find a line map (mapping character offsets to text nodes) and a
  53. // measurement cache for the given line number. (A line view might
  54. // contain multiple lines when collapsed ranges are present.)
  55. export function mapFromLineView(lineView, line, lineN) {
  56. if (lineView.line == line)
  57. return {map: lineView.measure.map, cache: lineView.measure.cache}
  58. for (let i = 0; i < lineView.rest.length; i++)
  59. if (lineView.rest[i] == line)
  60. return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]}
  61. for (let i = 0; i < lineView.rest.length; i++)
  62. if (lineNo(lineView.rest[i]) > lineN)
  63. return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true}
  64. }
  65. // Render a line into the hidden node display.externalMeasured. Used
  66. // when measurement is needed for a line that's not in the viewport.
  67. function updateExternalMeasurement(cm, line) {
  68. line = visualLine(line)
  69. let lineN = lineNo(line)
  70. let view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN)
  71. view.lineN = lineN
  72. let built = view.built = buildLineContent(cm, view)
  73. view.text = built.pre
  74. removeChildrenAndAdd(cm.display.lineMeasure, built.pre)
  75. return view
  76. }
  77. // Get a {top, bottom, left, right} box (in line-local coordinates)
  78. // for a given character.
  79. export function measureChar(cm, line, ch, bias) {
  80. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  81. }
  82. // Find a line view that corresponds to the given line number.
  83. export function findViewForLine(cm, lineN) {
  84. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  85. return cm.display.view[findViewIndex(cm, lineN)]
  86. let ext = cm.display.externalMeasured
  87. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  88. return ext
  89. }
  90. // Measurement can be split in two steps, the set-up work that
  91. // applies to the whole line, and the measurement of the actual
  92. // character. Functions like coordsChar, that need to do a lot of
  93. // measurements in a row, can thus ensure that the set-up work is
  94. // only done once.
  95. export function prepareMeasureForLine(cm, line) {
  96. let lineN = lineNo(line)
  97. let view = findViewForLine(cm, lineN)
  98. if (view && !view.text) {
  99. view = null
  100. } else if (view && view.changes) {
  101. updateLineForChanges(cm, view, lineN, getDimensions(cm))
  102. cm.curOp.forceUpdate = true
  103. }
  104. if (!view)
  105. view = updateExternalMeasurement(cm, line)
  106. let info = mapFromLineView(view, line, lineN)
  107. return {
  108. line: line, view: view, rect: null,
  109. map: info.map, cache: info.cache, before: info.before,
  110. hasHeights: false
  111. }
  112. }
  113. // Given a prepared measurement object, measures the position of an
  114. // actual character (or fetches it from the cache).
  115. export function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  116. if (prepared.before) ch = -1
  117. let key = ch + (bias || ""), found
  118. if (prepared.cache.hasOwnProperty(key)) {
  119. found = prepared.cache[key]
  120. } else {
  121. if (!prepared.rect)
  122. prepared.rect = prepared.view.text.getBoundingClientRect()
  123. if (!prepared.hasHeights) {
  124. ensureLineHeights(cm, prepared.view, prepared.rect)
  125. prepared.hasHeights = true
  126. }
  127. found = measureCharInner(cm, prepared, ch, bias)
  128. if (!found.bogus) prepared.cache[key] = found
  129. }
  130. return {left: found.left, right: found.right,
  131. top: varHeight ? found.rtop : found.top,
  132. bottom: varHeight ? found.rbottom : found.bottom}
  133. }
  134. let nullRect = {left: 0, right: 0, top: 0, bottom: 0}
  135. export function nodeAndOffsetInLineMap(map, ch, bias) {
  136. let node, start, end, collapse, mStart, mEnd
  137. // First, search the line map for the text node corresponding to,
  138. // or closest to, the target character.
  139. for (let i = 0; i < map.length; i += 3) {
  140. mStart = map[i]
  141. mEnd = map[i + 1]
  142. if (ch < mStart) {
  143. start = 0; end = 1
  144. collapse = "left"
  145. } else if (ch < mEnd) {
  146. start = ch - mStart
  147. end = start + 1
  148. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  149. end = mEnd - mStart
  150. start = end - 1
  151. if (ch >= mEnd) collapse = "right"
  152. }
  153. if (start != null) {
  154. node = map[i + 2]
  155. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  156. collapse = bias
  157. if (bias == "left" && start == 0)
  158. while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  159. node = map[(i -= 3) + 2]
  160. collapse = "left"
  161. }
  162. if (bias == "right" && start == mEnd - mStart)
  163. while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  164. node = map[(i += 3) + 2]
  165. collapse = "right"
  166. }
  167. break
  168. }
  169. }
  170. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
  171. }
  172. function getUsefulRect(rects, bias) {
  173. let rect = nullRect
  174. if (bias == "left") for (let i = 0; i < rects.length; i++) {
  175. if ((rect = rects[i]).left != rect.right) break
  176. } else for (let i = rects.length - 1; i >= 0; i--) {
  177. if ((rect = rects[i]).left != rect.right) break
  178. }
  179. return rect
  180. }
  181. function measureCharInner(cm, prepared, ch, bias) {
  182. let place = nodeAndOffsetInLineMap(prepared.map, ch, bias)
  183. let node = place.node, start = place.start, end = place.end, collapse = place.collapse
  184. let rect
  185. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  186. for (let i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  187. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start
  188. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end
  189. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  190. rect = node.parentNode.getBoundingClientRect()
  191. else
  192. rect = getUsefulRect(range(node, start, end).getClientRects(), bias)
  193. if (rect.left || rect.right || start == 0) break
  194. end = start
  195. start = start - 1
  196. collapse = "right"
  197. }
  198. if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect)
  199. } else { // If it is a widget, simply get the box for the whole widget.
  200. if (start > 0) collapse = bias = "right"
  201. let rects
  202. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  203. rect = rects[bias == "right" ? rects.length - 1 : 0]
  204. else
  205. rect = node.getBoundingClientRect()
  206. }
  207. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  208. let rSpan = node.parentNode.getClientRects()[0]
  209. if (rSpan)
  210. rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}
  211. else
  212. rect = nullRect
  213. }
  214. let rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top
  215. let mid = (rtop + rbot) / 2
  216. let heights = prepared.view.measure.heights
  217. let i = 0
  218. for (; i < heights.length - 1; i++)
  219. if (mid < heights[i]) break
  220. let top = i ? heights[i - 1] : 0, bot = heights[i]
  221. let result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  222. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  223. top: top, bottom: bot}
  224. if (!rect.left && !rect.right) result.bogus = true
  225. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot }
  226. return result
  227. }
  228. // Work around problem with bounding client rects on ranges being
  229. // returned incorrectly when zoomed on IE10 and below.
  230. function maybeUpdateRectForZooming(measure, rect) {
  231. if (!window.screen || screen.logicalXDPI == null ||
  232. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  233. return rect
  234. let scaleX = screen.logicalXDPI / screen.deviceXDPI
  235. let scaleY = screen.logicalYDPI / screen.deviceYDPI
  236. return {left: rect.left * scaleX, right: rect.right * scaleX,
  237. top: rect.top * scaleY, bottom: rect.bottom * scaleY}
  238. }
  239. export function clearLineMeasurementCacheFor(lineView) {
  240. if (lineView.measure) {
  241. lineView.measure.cache = {}
  242. lineView.measure.heights = null
  243. if (lineView.rest) for (let i = 0; i < lineView.rest.length; i++)
  244. lineView.measure.caches[i] = {}
  245. }
  246. }
  247. export function clearLineMeasurementCache(cm) {
  248. cm.display.externalMeasure = null
  249. removeChildren(cm.display.lineMeasure)
  250. for (let i = 0; i < cm.display.view.length; i++)
  251. clearLineMeasurementCacheFor(cm.display.view[i])
  252. }
  253. export function clearCaches(cm) {
  254. clearLineMeasurementCache(cm)
  255. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null
  256. if (!cm.options.lineWrapping) cm.display.maxLineChanged = true
  257. cm.display.lineNumChars = null
  258. }
  259. function pageScrollX() {
  260. // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
  261. // which causes page_Offset and bounding client rects to use
  262. // different reference viewports and invalidate our calculations.
  263. if (chrome && android) return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft))
  264. return window.pageXOffset || (document.documentElement || document.body).scrollLeft
  265. }
  266. function pageScrollY() {
  267. if (chrome && android) return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop))
  268. return window.pageYOffset || (document.documentElement || document.body).scrollTop
  269. }
  270. function widgetTopHeight(lineObj) {
  271. let height = 0
  272. if (lineObj.widgets) for (let i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above)
  273. height += widgetHeight(lineObj.widgets[i])
  274. return height
  275. }
  276. // Converts a {top, bottom, left, right} box from line-local
  277. // coordinates into another coordinate system. Context may be one of
  278. // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  279. // or "page".
  280. export function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  281. if (!includeWidgets) {
  282. let height = widgetTopHeight(lineObj)
  283. rect.top += height; rect.bottom += height
  284. }
  285. if (context == "line") return rect
  286. if (!context) context = "local"
  287. let yOff = heightAtLine(lineObj)
  288. if (context == "local") yOff += paddingTop(cm.display)
  289. else yOff -= cm.display.viewOffset
  290. if (context == "page" || context == "window") {
  291. let lOff = cm.display.lineSpace.getBoundingClientRect()
  292. yOff += lOff.top + (context == "window" ? 0 : pageScrollY())
  293. let xOff = lOff.left + (context == "window" ? 0 : pageScrollX())
  294. rect.left += xOff; rect.right += xOff
  295. }
  296. rect.top += yOff; rect.bottom += yOff
  297. return rect
  298. }
  299. // Coverts a box from "div" coords to another coordinate system.
  300. // Context may be "window", "page", "div", or "local"./null.
  301. export function fromCoordSystem(cm, coords, context) {
  302. if (context == "div") return coords
  303. let left = coords.left, top = coords.top
  304. // First move into "page" coordinate system
  305. if (context == "page") {
  306. left -= pageScrollX()
  307. top -= pageScrollY()
  308. } else if (context == "local" || !context) {
  309. let localBox = cm.display.sizer.getBoundingClientRect()
  310. left += localBox.left
  311. top += localBox.top
  312. }
  313. let lineSpaceBox = cm.display.lineSpace.getBoundingClientRect()
  314. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
  315. }
  316. export function charCoords(cm, pos, context, lineObj, bias) {
  317. if (!lineObj) lineObj = getLine(cm.doc, pos.line)
  318. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  319. }
  320. // Returns a box for a given cursor position, which may have an
  321. // 'other' property containing the position of the secondary cursor
  322. // on a bidi boundary.
  323. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
  324. // and after `char - 1` in writing order of `char - 1`
  325. // A cursor Pos(line, char, "after") is on the same visual line as `char`
  326. // and before `char` in writing order of `char`
  327. // Examples (upper-case letters are RTL, lower-case are LTR):
  328. // Pos(0, 1, ...)
  329. // before after
  330. // ab a|b a|b
  331. // aB a|B aB|
  332. // Ab |Ab A|b
  333. // AB B|A B|A
  334. // Every position after the last character on a line is considered to stick
  335. // to the last character on the line.
  336. export function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  337. lineObj = lineObj || getLine(cm.doc, pos.line)
  338. if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj)
  339. function get(ch, right) {
  340. let m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight)
  341. if (right) m.left = m.right; else m.right = m.left
  342. return intoCoordSystem(cm, lineObj, m, context)
  343. }
  344. let order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky
  345. if (ch >= lineObj.text.length) {
  346. ch = lineObj.text.length
  347. sticky = "before"
  348. } else if (ch <= 0) {
  349. ch = 0
  350. sticky = "after"
  351. }
  352. if (!order) return get(sticky == "before" ? ch - 1 : ch, sticky == "before")
  353. function getBidi(ch, partPos, invert) {
  354. let part = order[partPos], right = part.level == 1
  355. return get(invert ? ch - 1 : ch, right != invert)
  356. }
  357. let partPos = getBidiPartAt(order, ch, sticky)
  358. let other = bidiOther
  359. let val = getBidi(ch, partPos, sticky == "before")
  360. if (other != null) val.other = getBidi(ch, other, sticky != "before")
  361. return val
  362. }
  363. // Used to cheaply estimate the coordinates for a position. Used for
  364. // intermediate scroll updates.
  365. export function estimateCoords(cm, pos) {
  366. let left = 0
  367. pos = clipPos(cm.doc, pos)
  368. if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch
  369. let lineObj = getLine(cm.doc, pos.line)
  370. let top = heightAtLine(lineObj) + paddingTop(cm.display)
  371. return {left: left, right: left, top: top, bottom: top + lineObj.height}
  372. }
  373. // Positions returned by coordsChar contain some extra information.
  374. // xRel is the relative x position of the input coordinates compared
  375. // to the found position (so xRel > 0 means the coordinates are to
  376. // the right of the character position, for example). When outside
  377. // is true, that means the coordinates lie outside the line's
  378. // vertical range.
  379. function PosWithInfo(line, ch, sticky, outside, xRel) {
  380. let pos = Pos(line, ch, sticky)
  381. pos.xRel = xRel
  382. if (outside) pos.outside = true
  383. return pos
  384. }
  385. // Compute the character position closest to the given coordinates.
  386. // Input must be lineSpace-local ("div" coordinate system).
  387. export function coordsChar(cm, x, y) {
  388. let doc = cm.doc
  389. y += cm.display.viewOffset
  390. if (y < 0) return PosWithInfo(doc.first, 0, null, true, -1)
  391. let lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1
  392. if (lineN > last)
  393. return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1)
  394. if (x < 0) x = 0
  395. let lineObj = getLine(doc, lineN)
  396. for (;;) {
  397. let found = coordsCharInner(cm, lineObj, lineN, x, y)
  398. let collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 ? 1 : 0))
  399. if (!collapsed) return found
  400. let rangeEnd = collapsed.find(1)
  401. if (rangeEnd.line == lineN) return rangeEnd
  402. lineObj = getLine(doc, lineN = rangeEnd.line)
  403. }
  404. }
  405. function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
  406. y -= widgetTopHeight(lineObj)
  407. let end = lineObj.text.length
  408. let begin = findFirst(ch => measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y, end, 0)
  409. end = findFirst(ch => measureCharPrepared(cm, preparedMeasure, ch).top > y, begin, end)
  410. return {begin, end}
  411. }
  412. export function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
  413. if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj)
  414. let targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top
  415. return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
  416. }
  417. // Returns true if the given side of a box is after the given
  418. // coordinates, in top-to-bottom, left-to-right order.
  419. function boxIsAfter(box, x, y, left) {
  420. return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
  421. }
  422. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  423. // Move y into line-local coordinate space
  424. y -= heightAtLine(lineObj)
  425. let preparedMeasure = prepareMeasureForLine(cm, lineObj)
  426. // When directly calling `measureCharPrepared`, we have to adjust
  427. // for the widgets at this line.
  428. let widgetHeight = widgetTopHeight(lineObj)
  429. let begin = 0, end = lineObj.text.length, ltr = true
  430. let order = getOrder(lineObj, cm.doc.direction)
  431. // If the line isn't plain left-to-right text, first figure out
  432. // which bidi section the coordinates fall into.
  433. if (order) {
  434. let part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
  435. (cm, lineObj, lineNo, preparedMeasure, order, x, y)
  436. ltr = part.level != 1
  437. // The awkward -1 offsets are needed because findFirst (called
  438. // on these below) will treat its first bound as inclusive,
  439. // second as exclusive, but we want to actually address the
  440. // characters in the part's range
  441. begin = ltr ? part.from : part.to - 1
  442. end = ltr ? part.to : part.from - 1
  443. }
  444. // A binary search to find the first character whose bounding box
  445. // starts after the coordinates. If we run across any whose box wrap
  446. // the coordinates, store that.
  447. let chAround = null, boxAround = null
  448. let ch = findFirst(ch => {
  449. let box = measureCharPrepared(cm, preparedMeasure, ch)
  450. box.top += widgetHeight; box.bottom += widgetHeight
  451. if (!boxIsAfter(box, x, y, false)) return false
  452. if (box.top <= y && box.left <= x) {
  453. chAround = ch
  454. boxAround = box
  455. }
  456. return true
  457. }, begin, end)
  458. let baseX, sticky, outside = false
  459. // If a box around the coordinates was found, use that
  460. if (boxAround) {
  461. // Distinguish coordinates nearer to the left or right side of the box
  462. let atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr
  463. ch = chAround + (atStart ? 0 : 1)
  464. sticky = atStart ? "after" : "before"
  465. baseX = atLeft ? boxAround.left : boxAround.right
  466. } else {
  467. // (Adjust for extended bound, if necessary.)
  468. if (!ltr && (ch == end || ch == begin)) ch++
  469. // To determine which side to associate with, get the box to the
  470. // left of the character and compare it's vertical position to the
  471. // coordinates
  472. sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
  473. (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ?
  474. "after" : "before"
  475. // Now get accurate coordinates for this place, in order to get a
  476. // base X position
  477. let coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure)
  478. baseX = coords.left
  479. outside = y < coords.top || y >= coords.bottom
  480. }
  481. ch = skipExtendingChars(lineObj.text, ch, 1)
  482. return PosWithInfo(lineNo, ch, sticky, outside, x - baseX)
  483. }
  484. function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) {
  485. // Bidi parts are sorted left-to-right, and in a non-line-wrapping
  486. // situation, we can take this ordering to correspond to the visual
  487. // ordering. This finds the first part whose end is after the given
  488. // coordinates.
  489. let index = findFirst(i => {
  490. let part = order[i], ltr = part.level != 1
  491. return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"),
  492. "line", lineObj, preparedMeasure), x, y, true)
  493. }, 0, order.length - 1)
  494. let part = order[index]
  495. // If this isn't the first part, the part's start is also after
  496. // the coordinates, and the coordinates aren't on the same line as
  497. // that start, move one part back.
  498. if (index > 0) {
  499. let ltr = part.level != 1
  500. let start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"),
  501. "line", lineObj, preparedMeasure)
  502. if (boxIsAfter(start, x, y, true) && start.top > y)
  503. part = order[index - 1]
  504. }
  505. return part
  506. }
  507. function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
  508. // In a wrapped line, rtl text on wrapping boundaries can do things
  509. // that don't correspond to the ordering in our `order` array at
  510. // all, so a binary search doesn't work, and we want to return a
  511. // part that only spans one line so that the binary search in
  512. // coordsCharInner is safe. As such, we first find the extent of the
  513. // wrapped line, and then do a flat search in which we discard any
  514. // spans that aren't on the line.
  515. let {begin, end} = wrappedLineExtent(cm, lineObj, preparedMeasure, y)
  516. if (/\s/.test(lineObj.text.charAt(end - 1))) end--
  517. let part = null, closestDist = null
  518. for (let i = 0; i < order.length; i++) {
  519. let p = order[i]
  520. if (p.from >= end || p.to <= begin) continue
  521. let ltr = p.level != 1
  522. let endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right
  523. // Weigh against spans ending before this, so that they are only
  524. // picked if nothing ends after
  525. let dist = endX < x ? x - endX + 1e9 : endX - x
  526. if (!part || closestDist > dist) {
  527. part = p
  528. closestDist = dist
  529. }
  530. }
  531. if (!part) part = order[order.length - 1]
  532. // Clip the part to the wrapped line.
  533. if (part.from < begin) part = {from: begin, to: part.to, level: part.level}
  534. if (part.to > end) part = {from: part.from, to: end, level: part.level}
  535. return part
  536. }
  537. let measureText
  538. // Compute the default text height.
  539. export function textHeight(display) {
  540. if (display.cachedTextHeight != null) return display.cachedTextHeight
  541. if (measureText == null) {
  542. measureText = elt("pre")
  543. // Measure a bunch of lines, for browsers that compute
  544. // fractional heights.
  545. for (let i = 0; i < 49; ++i) {
  546. measureText.appendChild(document.createTextNode("x"))
  547. measureText.appendChild(elt("br"))
  548. }
  549. measureText.appendChild(document.createTextNode("x"))
  550. }
  551. removeChildrenAndAdd(display.measure, measureText)
  552. let height = measureText.offsetHeight / 50
  553. if (height > 3) display.cachedTextHeight = height
  554. removeChildren(display.measure)
  555. return height || 1
  556. }
  557. // Compute the default character width.
  558. export function charWidth(display) {
  559. if (display.cachedCharWidth != null) return display.cachedCharWidth
  560. let anchor = elt("span", "xxxxxxxxxx")
  561. let pre = elt("pre", [anchor])
  562. removeChildrenAndAdd(display.measure, pre)
  563. let rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10
  564. if (width > 2) display.cachedCharWidth = width
  565. return width || 10
  566. }
  567. // Do a bulk-read of the DOM positions and sizes needed to draw the
  568. // view, so that we don't interleave reading and writing to the DOM.
  569. export function getDimensions(cm) {
  570. let d = cm.display, left = {}, width = {}
  571. let gutterLeft = d.gutters.clientLeft
  572. for (let n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  573. left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft
  574. width[cm.options.gutters[i]] = n.clientWidth
  575. }
  576. return {fixedPos: compensateForHScroll(d),
  577. gutterTotalWidth: d.gutters.offsetWidth,
  578. gutterLeft: left,
  579. gutterWidth: width,
  580. wrapperWidth: d.wrapper.clientWidth}
  581. }
  582. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  583. // but using getBoundingClientRect to get a sub-pixel-accurate
  584. // result.
  585. export function compensateForHScroll(display) {
  586. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  587. }
  588. // Returns a function that estimates the height of a line, to use as
  589. // first approximation until the line becomes visible (and is thus
  590. // properly measurable).
  591. export function estimateHeight(cm) {
  592. let th = textHeight(cm.display), wrapping = cm.options.lineWrapping
  593. let perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3)
  594. return line => {
  595. if (lineIsHidden(cm.doc, line)) return 0
  596. let widgetsHeight = 0
  597. if (line.widgets) for (let i = 0; i < line.widgets.length; i++) {
  598. if (line.widgets[i].height) widgetsHeight += line.widgets[i].height
  599. }
  600. if (wrapping)
  601. return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th
  602. else
  603. return widgetsHeight + th
  604. }
  605. }
  606. export function estimateLineHeights(cm) {
  607. let doc = cm.doc, est = estimateHeight(cm)
  608. doc.iter(line => {
  609. let estHeight = est(line)
  610. if (estHeight != line.height) updateLineHeight(line, estHeight)
  611. })
  612. }
  613. // Given a mouse event, find the corresponding position. If liberal
  614. // is false, it checks whether a gutter or scrollbar was clicked,
  615. // and returns null if it was. forRect is used by rectangular
  616. // selections, and tries to estimate a character position even for
  617. // coordinates beyond the right of the text.
  618. export function posFromMouse(cm, e, liberal, forRect) {
  619. let display = cm.display
  620. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null
  621. let x, y, space = display.lineSpace.getBoundingClientRect()
  622. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  623. try { x = e.clientX - space.left; y = e.clientY - space.top }
  624. catch (e) { return null }
  625. let coords = coordsChar(cm, x, y), line
  626. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  627. let colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length
  628. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff))
  629. }
  630. return coords
  631. }
  632. // Find the view element corresponding to a given line. Return null
  633. // when the line isn't visible.
  634. export function findViewIndex(cm, n) {
  635. if (n >= cm.display.viewTo) return null
  636. n -= cm.display.viewFrom
  637. if (n < 0) return null
  638. let view = cm.display.view
  639. for (let i = 0; i < view.length; i++) {
  640. n -= view[i].size
  641. if (n < 0) return i
  642. }
  643. }