PdfController.coffee 14 KB

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