PdfController.coffee 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. define [
  2. "base"
  3. "libs/latex-log-parser"
  4. "libs/bib-log-parser"
  5. ], (App, LogParser, BibLogParser) ->
  6. App.controller "PdfController", ($scope, $http, ide, $modal, synctex, event_tracking, localStorage) ->
  7. # enable per-user containers if querystring includes isolated=true
  8. perUserCompile = window.location?.search?.match(/isolated=true/)? or undefined
  9. autoCompile = true
  10. # pdf.view = uncompiled | pdf | errors
  11. $scope.pdf.view = if $scope?.pdf?.url then 'pdf' else 'uncompiled'
  12. $scope.shouldShowLogs = false
  13. $scope.$on "project:joined", () ->
  14. return if !autoCompile
  15. autoCompile = false
  16. $scope.recompile(isAutoCompile: true)
  17. $scope.hasPremiumCompile = $scope.project.features.compileGroup == "priority"
  18. $scope.$on "pdf:error:display", () ->
  19. $scope.pdf.view = 'errors'
  20. $scope.pdf.renderingError = true
  21. $scope.draft = localStorage("draft:#{$scope.project_id}") or false
  22. $scope.$watch "draft", (new_value, old_value) ->
  23. if new_value? and old_value != new_value
  24. localStorage("draft:#{$scope.project_id}", new_value)
  25. sendCompileRequest = (options = {}) ->
  26. url = "/project/#{$scope.project_id}/compile"
  27. params = {}
  28. if options.isAutoCompile
  29. params["auto_compile"]=true
  30. if perUserCompile # send ?isolated=true for per-user compiles
  31. params["isolated"] = true
  32. return $http.post url, {
  33. rootDoc_id: options.rootDocOverride_id or null
  34. draft: $scope.draft
  35. _csrf: window.csrfToken
  36. }, {params: params}
  37. parseCompileResponse = (response) ->
  38. # Reset everything
  39. $scope.pdf.error = false
  40. $scope.pdf.timedout = false
  41. $scope.pdf.failure = false
  42. $scope.pdf.url = null
  43. $scope.pdf.clsiMaintenance = false
  44. $scope.pdf.tooRecentlyCompiled = false
  45. $scope.pdf.renderingError = false
  46. $scope.pdf.projectTooLarge = false
  47. # make a cache to look up files by name
  48. fileByPath = {}
  49. if response?.outputFiles?
  50. for file in response?.outputFiles
  51. fileByPath[file.path] = file
  52. if response.status == "timedout"
  53. $scope.pdf.view = 'errors'
  54. $scope.pdf.timedout = true
  55. else if response.status == "autocompile-backoff"
  56. $scope.pdf.view = 'uncompiled'
  57. else if response.status == "project-too-large"
  58. $scope.pdf.view = 'errors'
  59. $scope.pdf.projectTooLarge = true
  60. else if response.status == "failure"
  61. $scope.pdf.view = 'errors'
  62. $scope.pdf.failure = true
  63. $scope.shouldShowLogs = true
  64. fetchLogs(fileByPath['output.log'], fileByPath['output.blg'])
  65. else if response.status == 'clsi-maintenance'
  66. $scope.pdf.view = 'errors'
  67. $scope.pdf.clsiMaintenance = true
  68. else if response.status == "too-recently-compiled"
  69. $scope.pdf.view = 'errors'
  70. $scope.pdf.tooRecentlyCompiled = true
  71. else if response.status == "validation-problems"
  72. $scope.pdf.view = "validation-problems"
  73. $scope.pdf.validation = response.validationProblems
  74. else if response.status == "success"
  75. $scope.pdf.view = 'pdf'
  76. $scope.shouldShowLogs = false
  77. # prepare query string
  78. qs = {}
  79. # define the base url. if the pdf file has a build number, pass it to the clsi in the url
  80. if fileByPath['output.pdf']?.url?
  81. $scope.pdf.url = fileByPath['output.pdf'].url
  82. else if fileByPath['output.pdf']?.build?
  83. build = fileByPath['output.pdf'].build
  84. $scope.pdf.url = "/project/#{$scope.project_id}/build/#{build}/output/output.pdf"
  85. else
  86. $scope.pdf.url = "/project/#{$scope.project_id}/output/output.pdf"
  87. # check if we need to bust cache (build id is unique so don't need it in that case)
  88. if not fileByPath['output.pdf']?.build?
  89. qs.cache_bust = "#{Date.now()}"
  90. # add a query string parameter for the compile group
  91. if response.compileGroup?
  92. $scope.pdf.compileGroup = response.compileGroup
  93. qs.compileGroup = "#{$scope.pdf.compileGroup}"
  94. if response.clsiServerId?
  95. qs.clsiserverid = response.clsiServerId
  96. ide.clsiServerId = response.clsiServerId
  97. # convert the qs hash into a query string and append it
  98. qs_args = ("#{k}=#{v}" for k, v of qs)
  99. $scope.pdf.qs = if qs_args.length then "?" + qs_args.join("&") else ""
  100. $scope.pdf.url += $scope.pdf.qs
  101. $scope.pdf.downloadUrl = "/Project/#{$scope.project_id}/output/output.pdf" + $scope.pdf.qs
  102. fetchLogs(fileByPath['output.log'], fileByPath['output.blg'])
  103. IGNORE_FILES = ["output.fls", "output.fdb_latexmk"]
  104. $scope.pdf.outputFiles = []
  105. if !response.outputFiles?
  106. return
  107. for file in response.outputFiles
  108. if IGNORE_FILES.indexOf(file.path) == -1
  109. # Turn 'output.blg' into 'blg file'.
  110. if file.path.match(/^output\./)
  111. file.name = "#{file.path.replace(/^output\./, "")} file"
  112. else
  113. file.name = file.path
  114. if not file.url?
  115. file.url = "/project/#{project_id}/output/#{file.path}"
  116. if response.clsiServerId?
  117. file.url = file.url + "?clsiserverid=#{response.clsiServerId}"
  118. $scope.pdf.outputFiles.push file
  119. fetchLogs = (logFile, blgFile) ->
  120. getFile = (name, file) ->
  121. opts =
  122. method:"GET"
  123. params:
  124. clsiserverid:ide.clsiServerId
  125. if file.url? # FIXME clean this up when we have file.urls out consistently
  126. opts.url = file.url
  127. else if file?.build?
  128. opts.url = "/project/#{$scope.project_id}/build/#{file.build}/output/#{name}"
  129. else
  130. opts.url = "/project/#{$scope.project_id}/output/#{name}"
  131. return $http(opts)
  132. # accumulate the log entries
  133. logEntries =
  134. all: []
  135. errors: []
  136. warnings: []
  137. accumulateResults = (newEntries) ->
  138. for key in ['all', 'errors', 'warnings']
  139. logEntries[key] = logEntries[key].concat newEntries[key]
  140. # use the parsers for each file type
  141. processLog = (log) ->
  142. $scope.pdf.rawLog = log
  143. {errors, warnings, typesetting} = LogParser.parse(log, ignoreDuplicates: true)
  144. all = [].concat errors, warnings, typesetting
  145. accumulateResults {all, errors, warnings}
  146. processBiber = (log) ->
  147. {errors, warnings} = BibLogParser.parse(log, {})
  148. all = [].concat errors, warnings
  149. accumulateResults {all, errors, warnings}
  150. # output the results
  151. handleError = () ->
  152. $scope.pdf.logEntries = []
  153. $scope.pdf.rawLog = ""
  154. annotateFiles = () ->
  155. $scope.pdf.logEntries = logEntries
  156. $scope.pdf.logEntryAnnotations = {}
  157. for entry in logEntries.all
  158. if entry.file?
  159. entry.file = normalizeFilePath(entry.file)
  160. entity = ide.fileTreeManager.findEntityByPath(entry.file)
  161. if entity?
  162. $scope.pdf.logEntryAnnotations[entity.id] ||= []
  163. $scope.pdf.logEntryAnnotations[entity.id].push {
  164. row: entry.line - 1
  165. type: if entry.level == "error" then "error" else "warning"
  166. text: entry.message
  167. }
  168. # retrieve the logfile and process it
  169. response = getFile('output.log', logFile)
  170. .success processLog
  171. .error handleError
  172. if blgFile? # retrieve the blg file if present
  173. response.success () ->
  174. getFile('output.blg', blgFile)
  175. # ignore errors in biber file
  176. .success processBiber
  177. # display the combined result
  178. .then annotateFiles
  179. else # otherwise just display the result
  180. response.success annotateFiles
  181. getRootDocOverride_id = () ->
  182. doc = ide.editorManager.getCurrentDocValue()
  183. return null if !doc?
  184. for line in doc.split("\n")
  185. match = line.match /^[^%]*\\documentclass/
  186. if match
  187. return ide.editorManager.getCurrentDocId()
  188. return null
  189. normalizeFilePath = (path) ->
  190. path = path.replace(/^(.*)\/compiles\/[0-9a-f]{24}\/(\.\/)?/, "")
  191. path = path.replace(/^\/compile\//, "")
  192. rootDocDirname = ide.fileTreeManager.getRootDocDirname()
  193. if rootDocDirname?
  194. path = path.replace(/^\.\//, rootDocDirname + "/")
  195. return path
  196. $scope.recompile = (options = {}) ->
  197. return if $scope.pdf.compiling
  198. $scope.pdf.compiling = true
  199. ide.$scope.$broadcast("flush-changes")
  200. options.rootDocOverride_id = getRootDocOverride_id()
  201. sendCompileRequest(options)
  202. .success (data) ->
  203. $scope.pdf.view = "pdf"
  204. $scope.pdf.compiling = false
  205. parseCompileResponse(data)
  206. .error () ->
  207. $scope.pdf.compiling = false
  208. $scope.pdf.renderingError = false
  209. $scope.pdf.error = true
  210. $scope.pdf.view = 'errors'
  211. # This needs to be public.
  212. ide.$scope.recompile = $scope.recompile
  213. $scope.clearCache = () ->
  214. $http {
  215. url: "/project/#{$scope.project_id}/output"
  216. method: "DELETE"
  217. params:
  218. clsiserverid:ide.clsiServerId
  219. isolated: perUserCompile
  220. headers:
  221. "X-Csrf-Token": window.csrfToken
  222. }
  223. $scope.toggleLogs = () ->
  224. $scope.shouldShowLogs = !$scope.shouldShowLogs
  225. $scope.showPdf = () ->
  226. $scope.pdf.view = "pdf"
  227. $scope.shouldShowLogs = false
  228. $scope.toggleRawLog = () ->
  229. $scope.pdf.showRawLog = !$scope.pdf.showRawLog
  230. $scope.openClearCacheModal = () ->
  231. modalInstance = $modal.open(
  232. templateUrl: "clearCacheModalTemplate"
  233. controller: "ClearCacheModalController"
  234. scope: $scope
  235. )
  236. $scope.syncToCode = (position) ->
  237. synctex
  238. .syncToCode(position)
  239. .then (data) ->
  240. {doc, line} = data
  241. ide.editorManager.openDoc(doc, gotoLine: line)
  242. $scope.switchToFlatLayout = () ->
  243. $scope.ui.pdfLayout = 'flat'
  244. $scope.ui.view = 'pdf'
  245. ide.localStorage "pdf.layout", "flat"
  246. $scope.switchToSideBySideLayout = () ->
  247. $scope.ui.pdfLayout = 'sideBySide'
  248. $scope.ui.view = 'editor'
  249. localStorage "pdf.layout", "split"
  250. if pdfLayout = localStorage("pdf.layout")
  251. $scope.switchToSideBySideLayout() if pdfLayout == "split"
  252. $scope.switchToFlatLayout() if pdfLayout == "flat"
  253. else
  254. $scope.switchToSideBySideLayout()
  255. $scope.startFreeTrial = (source) ->
  256. ga?('send', 'event', 'subscription-funnel', 'compile-timeout', source)
  257. window.open("/user/subscription/new?planCode=student_free_trial_7_days")
  258. $scope.startedFreeTrial = true
  259. App.factory "synctex", ["ide", "$http", "$q", (ide, $http, $q) ->
  260. # enable per-user containers if querystring includes isolated=true
  261. perUserCompile = window.location?.search?.match(/isolated=true/)? or undefined
  262. synctex =
  263. syncToPdf: (cursorPosition) ->
  264. deferred = $q.defer()
  265. doc_id = ide.editorManager.getCurrentDocId()
  266. if !doc_id?
  267. deferred.reject()
  268. return deferred.promise
  269. doc = ide.fileTreeManager.findEntityById(doc_id)
  270. if !doc?
  271. deferred.reject()
  272. return deferred.promise
  273. path = ide.fileTreeManager.getEntityPath(doc)
  274. if !path?
  275. deferred.reject()
  276. return deferred.promise
  277. # If the root file is folder/main.tex, then synctex sees the
  278. # path as folder/./main.tex
  279. rootDocDirname = ide.fileTreeManager.getRootDocDirname()
  280. if rootDocDirname? and rootDocDirname != ""
  281. path = path.replace(RegExp("^#{rootDocDirname}"), "#{rootDocDirname}/.")
  282. {row, column} = cursorPosition
  283. $http({
  284. url: "/project/#{ide.project_id}/sync/code",
  285. method: "GET",
  286. params: {
  287. file: path
  288. line: row + 1
  289. column: column
  290. clsiserverid:ide.clsiServerId
  291. isolated: perUserCompile
  292. }
  293. })
  294. .success (data) ->
  295. deferred.resolve(data.pdf or [])
  296. .error (error) ->
  297. deferred.reject(error)
  298. return deferred.promise
  299. syncToCode: (position, options = {}) ->
  300. deferred = $q.defer()
  301. if !position?
  302. deferred.reject()
  303. return deferred.promise
  304. # FIXME: this actually works better if it's halfway across the
  305. # page (or the visible part of the page). Synctex doesn't
  306. # always find the right place in the file when the point is at
  307. # the edge of the page, it sometimes returns the start of the
  308. # next paragraph instead.
  309. h = position.offset.left
  310. # Compute the vertical position to pass to synctex, which
  311. # works with coordinates increasing from the top of the page
  312. # down. This matches the browser's DOM coordinate of the
  313. # click point, but the pdf position is measured from the
  314. # bottom of the page so we need to invert it.
  315. if options.fromPdfPosition and position.pageSize?.height?
  316. v = (position.pageSize.height - position.offset.top) or 0 # measure from pdf point (inverted)
  317. else
  318. v = position.offset.top or 0 # measure from html click position
  319. # It's not clear exactly where we should sync to if it wasn't directly
  320. # clicked on, but a little bit down from the very top seems best.
  321. if options.includeVisualOffset
  322. v += 72 # use the same value as in pdfViewer highlighting visual offset
  323. $http({
  324. url: "/project/#{ide.project_id}/sync/pdf",
  325. method: "GET",
  326. params: {
  327. page: position.page + 1
  328. h: h.toFixed(2)
  329. v: v.toFixed(2)
  330. clsiserverid:ide.clsiServerId
  331. isolated: perUserCompile
  332. }
  333. })
  334. .success (data) ->
  335. if data.code? and data.code.length > 0
  336. doc = ide.fileTreeManager.findEntityByPath(data.code[0].file)
  337. return if !doc?
  338. deferred.resolve({doc: doc, line: data.code[0].line})
  339. .error (error) ->
  340. deferred.reject(error)
  341. return deferred.promise
  342. return synctex
  343. ]
  344. App.controller "PdfSynctexController", ["$scope", "synctex", "ide", ($scope, synctex, ide) ->
  345. @cursorPosition = null
  346. ide.$scope.$on "cursor:editor:update", (event, @cursorPosition) =>
  347. $scope.syncToPdf = () =>
  348. return if !@cursorPosition?
  349. synctex
  350. .syncToPdf(@cursorPosition)
  351. .then (highlights) ->
  352. $scope.pdf.highlights = highlights
  353. $scope.syncToCode = () ->
  354. synctex
  355. .syncToCode($scope.pdf.position, includeVisualOffset: true, fromPdfPosition: true)
  356. .then (data) ->
  357. {doc, line} = data
  358. ide.editorManager.openDoc(doc, gotoLine: line)
  359. ]
  360. App.controller "PdfLogEntryController", ["$scope", "ide", ($scope, ide) ->
  361. $scope.openInEditor = (entry) ->
  362. entity = ide.fileTreeManager.findEntityByPath(entry.file)
  363. return if !entity? or entity.type != "doc"
  364. if entry.line?
  365. line = entry.line
  366. ide.editorManager.openDoc(entity, gotoLine: line)
  367. ]
  368. App.controller 'ClearCacheModalController', ["$scope", "$modalInstance", ($scope, $modalInstance) ->
  369. $scope.state =
  370. inflight: false
  371. $scope.clear = () ->
  372. $scope.state.inflight = true
  373. $scope
  374. .clearCache()
  375. .then () ->
  376. $scope.state.inflight = false
  377. $modalInstance.close()
  378. $scope.cancel = () ->
  379. $modalInstance.dismiss('cancel')
  380. ]