PdfController.coffee 13 KB

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