PdfController.coffee 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. define [
  2. "base"
  3. "ace/ace"
  4. "ide/human-readable-logs/HumanReadableLogs"
  5. "libs/bib-log-parser"
  6. "services/log-hints-feedback"
  7. ], (App, Ace, HumanReadableLogs, BibLogParser) ->
  8. AUTO_COMPILE_TIMEOUT = 5000
  9. OP_ACKNOWLEDGEMENT_TIMEOUT = 1100
  10. App.controller "PdfController", ($scope, $http, ide, $modal, synctex, event_tracking, logHintsFeedback, localStorage) ->
  11. # enable per-user containers by default
  12. perUserCompile = true
  13. autoCompile = true
  14. # pdf.view = uncompiled | pdf | errors
  15. $scope.pdf.view = if $scope?.pdf?.url then 'pdf' else 'uncompiled'
  16. $scope.shouldShowLogs = false
  17. $scope.wikiEnabled = window.wikiEnabled;
  18. # view logic to check whether the files dropdown should "drop up" or "drop down"
  19. $scope.shouldDropUp = false
  20. logsContainerEl = document.querySelector ".pdf-logs"
  21. filesDropdownEl = logsContainerEl?.querySelector ".files-dropdown"
  22. # get the top coordinate of the files dropdown as a ratio (to the logs container height)
  23. # logs container supports scrollable content, so it's possible that ratio > 1.
  24. getFilesDropdownTopCoordAsRatio = () ->
  25. filesDropdownEl?.getBoundingClientRect().top / logsContainerEl?.getBoundingClientRect().height
  26. $scope.$watch "shouldShowLogs", (shouldShow) ->
  27. if shouldShow
  28. $scope.$applyAsync () ->
  29. $scope.shouldDropUp = getFilesDropdownTopCoordAsRatio() > 0.65
  30. # log hints tracking
  31. $scope.logHintsNegFeedbackValues = logHintsFeedback.feedbackOpts
  32. $scope.trackLogHintsLearnMore = () ->
  33. event_tracking.sendMB "logs-hints-learn-more"
  34. trackLogHintsFeedback = (isPositive, hintId) ->
  35. event_tracking.send "log-hints", (if isPositive then "feedback-positive" else "feedback-negative"), hintId
  36. event_tracking.sendMB (if isPositive then "log-hints-feedback-positive" else "log-hints-feedback-negative"), { hintId }
  37. $scope.trackLogHintsNegFeedbackDetails = (hintId, feedbackOpt, feedbackOtherVal) ->
  38. logHintsFeedback.submitFeedback hintId, feedbackOpt, feedbackOtherVal
  39. $scope.trackLogHintsPositiveFeedback = (hintId) -> trackLogHintsFeedback true, hintId
  40. $scope.trackLogHintsNegativeFeedback = (hintId) -> trackLogHintsFeedback false, hintId
  41. if ace.require("ace/lib/useragent").isMac
  42. $scope.modifierKey = "Cmd"
  43. else
  44. $scope.modifierKey = "Ctrl"
  45. # utility for making a query string from a hash, could use jquery $.param
  46. createQueryString = (args) ->
  47. qs_args = ("#{k}=#{v}" for k, v of args)
  48. if qs_args.length then "?" + qs_args.join("&") else ""
  49. $scope.stripHTMLFromString = (htmlStr) ->
  50. tmp = document.createElement("DIV")
  51. tmp.innerHTML = htmlStr
  52. return tmp.textContent || tmp.innerText || ""
  53. $scope.$on "project:joined", () ->
  54. return if !autoCompile
  55. autoCompile = false
  56. $scope.recompile(isAutoCompile: true)
  57. $scope.hasPremiumCompile = $scope.project.features.compileGroup == "priority"
  58. $scope.$on "pdf:error:display", () ->
  59. $scope.pdf.view = 'errors'
  60. $scope.pdf.renderingError = true
  61. autoCompileTimeout = null
  62. triggerAutoCompile = () ->
  63. return if autoCompileTimeout or $scope.ui.pdfHidden
  64. timeSinceLastCompile = Date.now() - $scope.recompiledAt
  65. # If time is non-monotonic, assume that the user's system clock has been
  66. # changed and continue with recompile
  67. isTimeNonMonotonic = timeSinceLastCompile < 0
  68. if isTimeNonMonotonic || timeSinceLastCompile >= AUTO_COMPILE_TIMEOUT
  69. if (!ide.$scope.hasLintingError)
  70. $scope.recompile(isBackgroundAutoCompile: true)
  71. else
  72. # Extend remainder of timeout
  73. autoCompileTimeout = setTimeout () ->
  74. autoCompileTimeout = null
  75. triggerAutoCompile()
  76. , AUTO_COMPILE_TIMEOUT - timeSinceLastCompile
  77. autoCompileListener = null
  78. toggleAutoCompile = (enabling) ->
  79. if enabling
  80. autoCompileListener = ide.$scope.$on "ide:opAcknowledged", _.debounce(triggerAutoCompile, OP_ACKNOWLEDGEMENT_TIMEOUT)
  81. else
  82. autoCompileListener() if autoCompileListener
  83. autoCompileListener = null
  84. $scope.autocompile_enabled = localStorage("autocompile_enabled:#{$scope.project_id}") or false
  85. $scope.$watch "autocompile_enabled", (newValue, oldValue) ->
  86. if newValue? and oldValue != newValue
  87. localStorage("autocompile_enabled:#{$scope.project_id}", newValue)
  88. toggleAutoCompile(newValue)
  89. event_tracking.sendMB "autocompile-setting-changed", { value: newValue }
  90. if window.user?.betaProgram and $scope.autocompile_enabled
  91. toggleAutoCompile(true)
  92. # abort compile if syntax checks fail
  93. $scope.stop_on_validation_error = localStorage("stop_on_validation_error:#{$scope.project_id}")
  94. $scope.stop_on_validation_error ?= true # turn on for all users by default
  95. $scope.$watch "stop_on_validation_error", (new_value, old_value) ->
  96. if new_value? and old_value != new_value
  97. localStorage("stop_on_validation_error:#{$scope.project_id}", new_value)
  98. $scope.draft = localStorage("draft:#{$scope.project_id}") or false
  99. $scope.$watch "draft", (new_value, old_value) ->
  100. if new_value? and old_value != new_value
  101. localStorage("draft:#{$scope.project_id}", new_value)
  102. sendCompileRequest = (options = {}) ->
  103. url = "/project/#{$scope.project_id}/compile"
  104. params = {}
  105. if options.isAutoCompile
  106. params["auto_compile"]=true
  107. # if the previous run was a check, clear the error logs
  108. $scope.pdf.logEntries = [] if $scope.check
  109. # keep track of whether this is a compile or check
  110. $scope.check = if options.check then true else false
  111. event_tracking.sendMB "syntax-check-request" if options.check
  112. # send appropriate check type to clsi
  113. checkType = switch
  114. when $scope.check then "validate" # validate only
  115. when options.try then "silent" # allow use to try compile once
  116. when $scope.stop_on_validation_error then "error" # try to compile
  117. else "silent" # ignore errors
  118. return $http.post url, {
  119. rootDoc_id: options.rootDocOverride_id or null
  120. draft: $scope.draft
  121. check: checkType
  122. # use incremental compile for beta users but revert to a full
  123. # compile if there is a server error
  124. incrementalCompilesEnabled: window.user?.betaProgram and not $scope.pdf.error
  125. _csrf: window.csrfToken
  126. }, {params: params}
  127. parseCompileResponse = (response) ->
  128. # keep last url
  129. last_pdf_url = $scope.pdf.url
  130. # Reset everything
  131. $scope.pdf.error = false
  132. $scope.pdf.timedout = false
  133. $scope.pdf.failure = false
  134. $scope.pdf.url = null
  135. $scope.pdf.clsiMaintenance = false
  136. $scope.pdf.tooRecentlyCompiled = false
  137. $scope.pdf.renderingError = false
  138. $scope.pdf.projectTooLarge = false
  139. $scope.pdf.compileTerminated = false
  140. $scope.pdf.compileExited = false
  141. $scope.pdf.failedCheck = false
  142. # make a cache to look up files by name
  143. fileByPath = {}
  144. if response?.outputFiles?
  145. for file in response?.outputFiles
  146. fileByPath[file.path] = file
  147. # prepare query string
  148. qs = {}
  149. # add a query string parameter for the compile group
  150. if response.compileGroup?
  151. ide.compileGroup = qs.compileGroup = response.compileGroup
  152. # add a query string parameter for the clsi server id
  153. if response.clsiServerId?
  154. ide.clsiServerId = qs.clsiserverid = response.clsiServerId
  155. if response.status == "timedout"
  156. $scope.pdf.view = 'errors'
  157. $scope.pdf.timedout = true
  158. fetchLogs(fileByPath)
  159. else if response.status == "terminated"
  160. $scope.pdf.view = 'errors'
  161. $scope.pdf.compileTerminated = true
  162. fetchLogs(fileByPath)
  163. else if response.status in ["validation-fail", "validation-pass"]
  164. $scope.pdf.view = 'pdf'
  165. $scope.pdf.url = last_pdf_url
  166. $scope.shouldShowLogs = true
  167. $scope.pdf.failedCheck = true if response.status is "validation-fail"
  168. event_tracking.sendMB "syntax-check-#{response.status}"
  169. fetchLogs(fileByPath, { validation: true })
  170. else if response.status == "exited"
  171. $scope.pdf.view = 'pdf'
  172. $scope.pdf.compileExited = true
  173. $scope.pdf.url = last_pdf_url
  174. $scope.shouldShowLogs = true
  175. fetchLogs(fileByPath)
  176. else if response.status == "autocompile-backoff"
  177. $scope.pdf.view = 'uncompiled'
  178. else if response.status == "project-too-large"
  179. $scope.pdf.view = 'errors'
  180. $scope.pdf.projectTooLarge = true
  181. else if response.status == "failure"
  182. $scope.pdf.view = 'errors'
  183. $scope.pdf.failure = true
  184. $scope.shouldShowLogs = true
  185. fetchLogs(fileByPath)
  186. else if response.status == 'clsi-maintenance'
  187. $scope.pdf.view = 'errors'
  188. $scope.pdf.clsiMaintenance = true
  189. else if response.status == "too-recently-compiled"
  190. $scope.pdf.view = 'errors'
  191. $scope.pdf.tooRecentlyCompiled = true
  192. else if response.status == "validation-problems"
  193. $scope.pdf.view = "validation-problems"
  194. $scope.pdf.validation = response.validationProblems
  195. else if response.status == "success"
  196. $scope.pdf.view = 'pdf'
  197. $scope.shouldShowLogs = false
  198. # define the base url. if the pdf file has a build number, pass it to the clsi in the url
  199. if fileByPath['output.pdf']?.url?
  200. $scope.pdf.url = fileByPath['output.pdf'].url
  201. else if fileByPath['output.pdf']?.build?
  202. build = fileByPath['output.pdf'].build
  203. $scope.pdf.url = "/project/#{$scope.project_id}/build/#{build}/output/output.pdf"
  204. else
  205. $scope.pdf.url = "/project/#{$scope.project_id}/output/output.pdf"
  206. # check if we need to bust cache (build id is unique so don't need it in that case)
  207. if not fileByPath['output.pdf']?.build?
  208. qs.cache_bust = "#{Date.now()}"
  209. # convert the qs hash into a query string and append it
  210. $scope.pdf.url += createQueryString qs
  211. # Save all downloads as files
  212. qs.popupDownload = true
  213. $scope.pdf.downloadUrl = "/project/#{$scope.project_id}/output/output.pdf" + createQueryString(qs)
  214. fetchLogs(fileByPath)
  215. IGNORE_FILES = ["output.fls", "output.fdb_latexmk"]
  216. $scope.pdf.outputFiles = []
  217. if !response.outputFiles?
  218. return
  219. # prepare list of output files for download dropdown
  220. qs = {}
  221. if response.clsiServerId?
  222. qs.clsiserverid = response.clsiServerId
  223. for file in response.outputFiles
  224. if IGNORE_FILES.indexOf(file.path) == -1
  225. isOutputFile = file.path.match(/^output\./)
  226. $scope.pdf.outputFiles.push {
  227. # Turn 'output.blg' into 'blg file'.
  228. name: if isOutputFile then "#{file.path.replace(/^output\./, "")} file" else file.path
  229. url: "/project/#{project_id}/output/#{file.path}" + createQueryString qs
  230. main: if isOutputFile then true else false
  231. }
  232. # sort the output files into order, main files first, then others
  233. $scope.pdf.outputFiles.sort (a,b) -> (b.main - a.main) || a.name.localeCompare(b.name)
  234. fetchLogs = (fileByPath, options) ->
  235. if options?.validation
  236. chktexFile = fileByPath['output.chktex']
  237. else
  238. logFile = fileByPath['output.log']
  239. blgFile = fileByPath['output.blg']
  240. getFile = (name, file) ->
  241. opts =
  242. method:"GET"
  243. params:
  244. compileGroup:ide.compileGroup
  245. clsiserverid:ide.clsiServerId
  246. if file?.url? # FIXME clean this up when we have file.urls out consistently
  247. opts.url = file.url
  248. else if file?.build?
  249. opts.url = "/project/#{$scope.project_id}/build/#{file.build}/output/#{name}"
  250. else
  251. opts.url = "/project/#{$scope.project_id}/output/#{name}"
  252. # check if we need to bust cache (build id is unique so don't need it in that case)
  253. if not file?.build?
  254. opts.params.cache_bust = "#{Date.now()}"
  255. return $http(opts)
  256. # accumulate the log entries
  257. logEntries =
  258. all: []
  259. errors: []
  260. warnings: []
  261. accumulateResults = (newEntries) ->
  262. for key in ['all', 'errors', 'warnings']
  263. if newEntries.type?
  264. entry.type = newEntries.type for entry in newEntries[key]
  265. logEntries[key] = logEntries[key].concat newEntries[key]
  266. # use the parsers for each file type
  267. processLog = (log) ->
  268. $scope.pdf.rawLog = log
  269. {errors, warnings, typesetting} = HumanReadableLogs.parse(log, ignoreDuplicates: true)
  270. all = [].concat errors, warnings, typesetting
  271. accumulateResults {all, errors, warnings}
  272. processChkTex = (log) ->
  273. errors = []
  274. warnings = []
  275. for line in log.split("\n")
  276. if m = line.match /^(\S+):(\d+):(\d+): (Error|Warning): (.*)/
  277. result = { file:m[1], line:m[2], column:m[3], level:m[4].toLowerCase(), message: "#{m[4]}: #{m[5]}"}
  278. if result.level is 'error'
  279. errors.push result
  280. else
  281. warnings.push result
  282. all = [].concat errors, warnings
  283. logHints = HumanReadableLogs.parse {type: "Syntax", all, errors, warnings}
  284. event_tracking.sendMB "syntax-check-return-count", {errors:errors.length, warnings:warnings.length}
  285. accumulateResults logHints
  286. processBiber = (log) ->
  287. {errors, warnings} = BibLogParser.parse(log, {})
  288. all = [].concat errors, warnings
  289. accumulateResults {type: "BibTeX", all, errors, warnings}
  290. # output the results
  291. handleError = () ->
  292. $scope.pdf.logEntries = []
  293. $scope.pdf.rawLog = ""
  294. annotateFiles = () ->
  295. $scope.pdf.logEntries = logEntries
  296. $scope.pdf.logEntryAnnotations = {}
  297. for entry in logEntries.all
  298. if entry.file?
  299. entry.file = normalizeFilePath(entry.file)
  300. entity = ide.fileTreeManager.findEntityByPath(entry.file)
  301. if entity?
  302. $scope.pdf.logEntryAnnotations[entity.id] ||= []
  303. $scope.pdf.logEntryAnnotations[entity.id].push {
  304. row: entry.line - 1
  305. type: if entry.level == "error" then "error" else "warning"
  306. text: entry.message
  307. }
  308. # retrieve the logfile and process it
  309. if logFile?
  310. response = getFile('output.log', logFile)
  311. .then (response) -> processLog(response.data)
  312. if blgFile? # retrieve the blg file if present
  313. response = response.then () ->
  314. getFile('output.blg', blgFile)
  315. .then(
  316. (response) -> processBiber(response.data),
  317. () -> true # ignore errors in biber file
  318. )
  319. if response?
  320. response.catch handleError
  321. else
  322. handleError()
  323. if chktexFile?
  324. getChkTex = () ->
  325. getFile('output.chktex', chktexFile)
  326. .then (response) -> processChkTex(response.data)
  327. # always retrieve the chktex file if present
  328. if response?
  329. response = response.then getChkTex, getChkTex
  330. else
  331. response = getChkTex()
  332. # display the combined result
  333. if response?
  334. response.finally annotateFiles
  335. getRootDocOverride_id = () ->
  336. doc = ide.editorManager.getCurrentDocValue()
  337. return null if !doc?
  338. for line in doc.split("\n")
  339. match = line.match /^[^%]*\\documentclass/
  340. if match
  341. return ide.editorManager.getCurrentDocId()
  342. return null
  343. normalizeFilePath = (path) ->
  344. path = path.replace(/^(.*)\/compiles\/[0-9a-f]{24}(-[0-9a-f]{24})?\/(\.\/)?/, "")
  345. path = path.replace(/^\/compile\//, "")
  346. rootDocDirname = ide.fileTreeManager.getRootDocDirname()
  347. if rootDocDirname?
  348. path = path.replace(/^\.\//, rootDocDirname + "/")
  349. return path
  350. $scope.recompile = (options = {}) ->
  351. return if $scope.pdf.compiling
  352. event_tracking.sendMBSampled "editor-recompile-sampled", options
  353. $scope.pdf.compiling = true
  354. if options?.force
  355. # for forced compile, turn off validation check and ignore errors
  356. $scope.stop_on_validation_error = false
  357. $scope.shouldShowLogs = false # hide the logs while compiling
  358. event_tracking.sendMB "syntax-check-turn-off-checking"
  359. if options?.try
  360. $scope.shouldShowLogs = false # hide the logs while compiling
  361. event_tracking.sendMB "syntax-check-try-compile-anyway"
  362. ide.$scope.$broadcast("flush-changes")
  363. options.rootDocOverride_id = getRootDocOverride_id()
  364. sendCompileRequest(options)
  365. .then (response) ->
  366. { data } = response
  367. $scope.pdf.view = "pdf"
  368. $scope.pdf.compiling = false
  369. parseCompileResponse(data)
  370. .catch (response) ->
  371. { data, status } = response
  372. if status == 429
  373. $scope.pdf.rateLimited = true
  374. $scope.pdf.compiling = false
  375. $scope.pdf.renderingError = false
  376. $scope.pdf.error = true
  377. $scope.pdf.view = 'errors'
  378. .finally () ->
  379. $scope.recompiledAt = Date.now()
  380. # This needs to be public.
  381. ide.$scope.recompile = $scope.recompile
  382. # This method is a simply wrapper and exists only for tracking purposes.
  383. ide.$scope.recompileViaKey = () ->
  384. $scope.recompile { keyShortcut: true }
  385. $scope.stop = () ->
  386. return if !$scope.pdf.compiling
  387. $http {
  388. url: "/project/#{$scope.project_id}/compile/stop"
  389. method: "POST"
  390. params:
  391. clsiserverid:ide.clsiServerId
  392. headers:
  393. "X-Csrf-Token": window.csrfToken
  394. }
  395. $scope.clearCache = () ->
  396. $http {
  397. url: "/project/#{$scope.project_id}/output"
  398. method: "DELETE"
  399. params:
  400. clsiserverid:ide.clsiServerId
  401. headers:
  402. "X-Csrf-Token": window.csrfToken
  403. }
  404. $scope.toggleLogs = () ->
  405. $scope.shouldShowLogs = !$scope.shouldShowLogs
  406. event_tracking.sendMBOnce "ide-open-logs-once" if $scope.shouldShowLogs
  407. $scope.showPdf = () ->
  408. $scope.pdf.view = "pdf"
  409. $scope.shouldShowLogs = false
  410. $scope.toggleRawLog = () ->
  411. $scope.pdf.showRawLog = !$scope.pdf.showRawLog
  412. event_tracking.sendMB "logs-view-raw" if $scope.pdf.showRawLog
  413. $scope.openClearCacheModal = () ->
  414. modalInstance = $modal.open(
  415. templateUrl: "clearCacheModalTemplate"
  416. controller: "ClearCacheModalController"
  417. scope: $scope
  418. )
  419. $scope.syncToCode = (position) ->
  420. synctex
  421. .syncToCode(position)
  422. .then (data) ->
  423. {doc, line} = data
  424. ide.editorManager.openDoc(doc, gotoLine: line)
  425. $scope.switchToFlatLayout = () ->
  426. $scope.ui.pdfLayout = 'flat'
  427. $scope.ui.view = 'pdf'
  428. ide.localStorage "pdf.layout", "flat"
  429. $scope.switchToSideBySideLayout = () ->
  430. $scope.ui.pdfLayout = 'sideBySide'
  431. $scope.ui.view = 'editor'
  432. localStorage "pdf.layout", "split"
  433. if pdfLayout = localStorage("pdf.layout")
  434. $scope.switchToSideBySideLayout() if pdfLayout == "split"
  435. $scope.switchToFlatLayout() if pdfLayout == "flat"
  436. else
  437. $scope.switchToSideBySideLayout()
  438. $scope.startFreeTrial = (source) ->
  439. ga?('send', 'event', 'subscription-funnel', 'compile-timeout', source)
  440. event_tracking.sendMB "subscription-start-trial", { source }
  441. window.open("/user/subscription/new?planCode=#{$scope.startTrialPlanCode}")
  442. $scope.startedFreeTrial = true
  443. App.factory "synctex", ["ide", "$http", "$q", (ide, $http, $q) ->
  444. # enable per-user containers by default
  445. perUserCompile = true
  446. synctex =
  447. syncToPdf: (cursorPosition) ->
  448. deferred = $q.defer()
  449. doc_id = ide.editorManager.getCurrentDocId()
  450. if !doc_id?
  451. deferred.reject()
  452. return deferred.promise
  453. doc = ide.fileTreeManager.findEntityById(doc_id)
  454. if !doc?
  455. deferred.reject()
  456. return deferred.promise
  457. path = ide.fileTreeManager.getEntityPath(doc)
  458. if !path?
  459. deferred.reject()
  460. return deferred.promise
  461. # If the root file is folder/main.tex, then synctex sees the
  462. # path as folder/./main.tex
  463. rootDocDirname = ide.fileTreeManager.getRootDocDirname()
  464. if rootDocDirname? and rootDocDirname != ""
  465. path = path.replace(RegExp("^#{rootDocDirname}"), "#{rootDocDirname}/.")
  466. {row, column} = cursorPosition
  467. $http({
  468. url: "/project/#{ide.project_id}/sync/code",
  469. method: "GET",
  470. params: {
  471. file: path
  472. line: row + 1
  473. column: column
  474. clsiserverid:ide.clsiServerId
  475. }
  476. })
  477. .then (response) ->
  478. { data } = response
  479. deferred.resolve(data.pdf or [])
  480. .catch (response) ->
  481. error = response.data
  482. deferred.reject(error)
  483. return deferred.promise
  484. syncToCode: (position, options = {}) ->
  485. deferred = $q.defer()
  486. if !position?
  487. deferred.reject()
  488. return deferred.promise
  489. # FIXME: this actually works better if it's halfway across the
  490. # page (or the visible part of the page). Synctex doesn't
  491. # always find the right place in the file when the point is at
  492. # the edge of the page, it sometimes returns the start of the
  493. # next paragraph instead.
  494. h = position.offset.left
  495. # Compute the vertical position to pass to synctex, which
  496. # works with coordinates increasing from the top of the page
  497. # down. This matches the browser's DOM coordinate of the
  498. # click point, but the pdf position is measured from the
  499. # bottom of the page so we need to invert it.
  500. if options.fromPdfPosition and position.pageSize?.height?
  501. v = (position.pageSize.height - position.offset.top) or 0 # measure from pdf point (inverted)
  502. else
  503. v = position.offset.top or 0 # measure from html click position
  504. # It's not clear exactly where we should sync to if it wasn't directly
  505. # clicked on, but a little bit down from the very top seems best.
  506. if options.includeVisualOffset
  507. v += 72 # use the same value as in pdfViewer highlighting visual offset
  508. $http({
  509. url: "/project/#{ide.project_id}/sync/pdf",
  510. method: "GET",
  511. params: {
  512. page: position.page + 1
  513. h: h.toFixed(2)
  514. v: v.toFixed(2)
  515. clsiserverid:ide.clsiServerId
  516. }
  517. })
  518. .then (response) ->
  519. { data } = response
  520. if data.code? and data.code.length > 0
  521. doc = ide.fileTreeManager.findEntityByPath(data.code[0].file)
  522. return if !doc?
  523. deferred.resolve({doc: doc, line: data.code[0].line})
  524. .catch (response) ->
  525. error = response.data
  526. deferred.reject(error)
  527. return deferred.promise
  528. return synctex
  529. ]
  530. App.controller "PdfSynctexController", ["$scope", "synctex", "ide", ($scope, synctex, ide) ->
  531. @cursorPosition = null
  532. ide.$scope.$on "cursor:editor:update", (event, @cursorPosition) =>
  533. $scope.syncToPdf = () =>
  534. return if !@cursorPosition?
  535. synctex
  536. .syncToPdf(@cursorPosition)
  537. .then (highlights) ->
  538. $scope.pdf.highlights = highlights
  539. $scope.syncToCode = () ->
  540. synctex
  541. .syncToCode($scope.pdf.position, includeVisualOffset: true, fromPdfPosition: true)
  542. .then (data) ->
  543. {doc, line} = data
  544. ide.editorManager.openDoc(doc, gotoLine: line)
  545. ]
  546. App.controller "PdfLogEntryController", ["$scope", "ide", "event_tracking", ($scope, ide, event_tracking) ->
  547. $scope.openInEditor = (entry) ->
  548. event_tracking.sendMBOnce "logs-jump-to-location-once"
  549. entity = ide.fileTreeManager.findEntityByPath(entry.file)
  550. return if !entity? or entity.type != "doc"
  551. if entry.line?
  552. line = entry.line
  553. if entry.column?
  554. column = entry.column
  555. ide.editorManager.openDoc(entity, gotoLine: line, gotoColumn: column)
  556. ]
  557. App.controller 'ClearCacheModalController', ["$scope", "$modalInstance", ($scope, $modalInstance) ->
  558. $scope.state =
  559. inflight: false
  560. $scope.clear = () ->
  561. $scope.state.inflight = true
  562. $scope
  563. .clearCache()
  564. .then () ->
  565. $scope.state.inflight = false
  566. $modalInstance.close()
  567. $scope.cancel = () ->
  568. $modalInstance.dismiss('cancel')
  569. ]