PdfController.coffee 26 KB

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