PdfController.coffee 26 KB

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