PdfController.coffee 12 KB

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