PdfController.coffee 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. define [
  2. "base"
  3. "ace/ace"
  4. "libs/latex-log-parser"
  5. "libs/bib-log-parser"
  6. ], (App, Ace, LogParser, BibLogParser) ->
  7. App.controller "PdfController", ($scope, $http, ide, $modal, synctex, event_tracking, localStorage) ->
  8. # enable per-user containers if querystring includes isolated=true
  9. perUserCompile = window.location?.search?.match(/isolated=true/)? or undefined
  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. qs_args = ("#{k}=#{v}" for k, v of qs)
  108. $scope.pdf.qs = if qs_args.length then "?" + qs_args.join("&") else ""
  109. $scope.pdf.url += $scope.pdf.qs
  110. $scope.pdf.downloadUrl = "/Project/#{$scope.project_id}/output/output.pdf" + $scope.pdf.qs
  111. fetchLogs(fileByPath['output.log'], fileByPath['output.blg'])
  112. IGNORE_FILES = ["output.fls", "output.fdb_latexmk"]
  113. $scope.pdf.outputFiles = []
  114. if !response.outputFiles?
  115. return
  116. for file in response.outputFiles
  117. if IGNORE_FILES.indexOf(file.path) == -1
  118. # Turn 'output.blg' into 'blg file'.
  119. if file.path.match(/^output\./)
  120. file.name = "#{file.path.replace(/^output\./, "")} file"
  121. else
  122. file.name = file.path
  123. if not file.url?
  124. file.url = "/project/#{project_id}/output/#{file.path}"
  125. if response.clsiServerId?
  126. file.url = file.url + "?clsiserverid=#{response.clsiServerId}"
  127. $scope.pdf.outputFiles.push file
  128. fetchLogs = (logFile, blgFile) ->
  129. getFile = (name, file) ->
  130. opts =
  131. method:"GET"
  132. params:
  133. clsiserverid:ide.clsiServerId
  134. if file.url? # FIXME clean this up when we have file.urls out consistently
  135. opts.url = file.url
  136. else if file?.build?
  137. opts.url = "/project/#{$scope.project_id}/build/#{file.build}/output/#{name}"
  138. else
  139. opts.url = "/project/#{$scope.project_id}/output/#{name}"
  140. return $http(opts)
  141. # accumulate the log entries
  142. logEntries =
  143. all: []
  144. errors: []
  145. warnings: []
  146. accumulateResults = (newEntries) ->
  147. for key in ['all', 'errors', 'warnings']
  148. logEntries[key] = logEntries[key].concat newEntries[key]
  149. # use the parsers for each file type
  150. processLog = (log) ->
  151. $scope.pdf.rawLog = log
  152. {errors, warnings, typesetting} = LogParser.parse(log, ignoreDuplicates: true)
  153. all = [].concat errors, warnings, typesetting
  154. accumulateResults {all, errors, warnings}
  155. processBiber = (log) ->
  156. {errors, warnings} = BibLogParser.parse(log, {})
  157. all = [].concat errors, warnings
  158. accumulateResults {all, errors, warnings}
  159. # output the results
  160. handleError = () ->
  161. $scope.pdf.logEntries = []
  162. $scope.pdf.rawLog = ""
  163. annotateFiles = () ->
  164. $scope.pdf.logEntries = logEntries
  165. $scope.pdf.logEntryAnnotations = {}
  166. for entry in logEntries.all
  167. if entry.file?
  168. entry.file = normalizeFilePath(entry.file)
  169. entity = ide.fileTreeManager.findEntityByPath(entry.file)
  170. if entity?
  171. $scope.pdf.logEntryAnnotations[entity.id] ||= []
  172. $scope.pdf.logEntryAnnotations[entity.id].push {
  173. row: entry.line - 1
  174. type: if entry.level == "error" then "error" else "warning"
  175. text: entry.message
  176. }
  177. # retrieve the logfile and process it
  178. response = getFile('output.log', logFile)
  179. .success processLog
  180. .error handleError
  181. if blgFile? # retrieve the blg file if present
  182. response.success () ->
  183. getFile('output.blg', blgFile)
  184. # ignore errors in biber file
  185. .success processBiber
  186. # display the combined result
  187. .then annotateFiles
  188. else # otherwise just display the result
  189. response.success annotateFiles
  190. getRootDocOverride_id = () ->
  191. doc = ide.editorManager.getCurrentDocValue()
  192. return null if !doc?
  193. for line in doc.split("\n")
  194. match = line.match /^[^%]*\\documentclass/
  195. if match
  196. return ide.editorManager.getCurrentDocId()
  197. return null
  198. normalizeFilePath = (path) ->
  199. path = path.replace(/^(.*)\/compiles\/[0-9a-f]{24}\/(\.\/)?/, "")
  200. path = path.replace(/^\/compile\//, "")
  201. rootDocDirname = ide.fileTreeManager.getRootDocDirname()
  202. if rootDocDirname?
  203. path = path.replace(/^\.\//, rootDocDirname + "/")
  204. return path
  205. $scope.recompile = (options = {}) ->
  206. return if $scope.pdf.compiling
  207. $scope.pdf.compiling = true
  208. ide.$scope.$broadcast("flush-changes")
  209. options.rootDocOverride_id = getRootDocOverride_id()
  210. sendCompileRequest(options)
  211. .success (data) ->
  212. $scope.pdf.view = "pdf"
  213. $scope.pdf.compiling = false
  214. parseCompileResponse(data)
  215. .error () ->
  216. $scope.pdf.compiling = false
  217. $scope.pdf.renderingError = false
  218. $scope.pdf.error = true
  219. $scope.pdf.view = 'errors'
  220. # This needs to be public.
  221. ide.$scope.recompile = $scope.recompile
  222. $scope.clearCache = () ->
  223. $http {
  224. url: "/project/#{$scope.project_id}/output"
  225. method: "DELETE"
  226. params:
  227. clsiserverid:ide.clsiServerId
  228. isolated: perUserCompile
  229. headers:
  230. "X-Csrf-Token": window.csrfToken
  231. }
  232. $scope.toggleLogs = () ->
  233. $scope.shouldShowLogs = !$scope.shouldShowLogs
  234. $scope.showPdf = () ->
  235. $scope.pdf.view = "pdf"
  236. $scope.shouldShowLogs = false
  237. $scope.toggleRawLog = () ->
  238. $scope.pdf.showRawLog = !$scope.pdf.showRawLog
  239. $scope.openClearCacheModal = () ->
  240. modalInstance = $modal.open(
  241. templateUrl: "clearCacheModalTemplate"
  242. controller: "ClearCacheModalController"
  243. scope: $scope
  244. )
  245. $scope.syncToCode = (position) ->
  246. synctex
  247. .syncToCode(position)
  248. .then (data) ->
  249. {doc, line} = data
  250. ide.editorManager.openDoc(doc, gotoLine: line)
  251. $scope.switchToFlatLayout = () ->
  252. $scope.ui.pdfLayout = 'flat'
  253. $scope.ui.view = 'pdf'
  254. ide.localStorage "pdf.layout", "flat"
  255. $scope.switchToSideBySideLayout = () ->
  256. $scope.ui.pdfLayout = 'sideBySide'
  257. $scope.ui.view = 'editor'
  258. localStorage "pdf.layout", "split"
  259. if pdfLayout = localStorage("pdf.layout")
  260. $scope.switchToSideBySideLayout() if pdfLayout == "split"
  261. $scope.switchToFlatLayout() if pdfLayout == "flat"
  262. else
  263. $scope.switchToSideBySideLayout()
  264. $scope.startFreeTrial = (source) ->
  265. ga?('send', 'event', 'subscription-funnel', 'compile-timeout', source)
  266. window.open("/user/subscription/new?planCode=student_free_trial_7_days")
  267. $scope.startedFreeTrial = true
  268. App.factory "synctex", ["ide", "$http", "$q", (ide, $http, $q) ->
  269. # enable per-user containers if querystring includes isolated=true
  270. perUserCompile = window.location?.search?.match(/isolated=true/)? or undefined
  271. synctex =
  272. syncToPdf: (cursorPosition) ->
  273. deferred = $q.defer()
  274. doc_id = ide.editorManager.getCurrentDocId()
  275. if !doc_id?
  276. deferred.reject()
  277. return deferred.promise
  278. doc = ide.fileTreeManager.findEntityById(doc_id)
  279. if !doc?
  280. deferred.reject()
  281. return deferred.promise
  282. path = ide.fileTreeManager.getEntityPath(doc)
  283. if !path?
  284. deferred.reject()
  285. return deferred.promise
  286. # If the root file is folder/main.tex, then synctex sees the
  287. # path as folder/./main.tex
  288. rootDocDirname = ide.fileTreeManager.getRootDocDirname()
  289. if rootDocDirname? and rootDocDirname != ""
  290. path = path.replace(RegExp("^#{rootDocDirname}"), "#{rootDocDirname}/.")
  291. {row, column} = cursorPosition
  292. $http({
  293. url: "/project/#{ide.project_id}/sync/code",
  294. method: "GET",
  295. params: {
  296. file: path
  297. line: row + 1
  298. column: column
  299. clsiserverid:ide.clsiServerId
  300. isolated: perUserCompile
  301. }
  302. })
  303. .success (data) ->
  304. deferred.resolve(data.pdf or [])
  305. .error (error) ->
  306. deferred.reject(error)
  307. return deferred.promise
  308. syncToCode: (position, options = {}) ->
  309. deferred = $q.defer()
  310. if !position?
  311. deferred.reject()
  312. return deferred.promise
  313. # FIXME: this actually works better if it's halfway across the
  314. # page (or the visible part of the page). Synctex doesn't
  315. # always find the right place in the file when the point is at
  316. # the edge of the page, it sometimes returns the start of the
  317. # next paragraph instead.
  318. h = position.offset.left
  319. # Compute the vertical position to pass to synctex, which
  320. # works with coordinates increasing from the top of the page
  321. # down. This matches the browser's DOM coordinate of the
  322. # click point, but the pdf position is measured from the
  323. # bottom of the page so we need to invert it.
  324. if options.fromPdfPosition and position.pageSize?.height?
  325. v = (position.pageSize.height - position.offset.top) or 0 # measure from pdf point (inverted)
  326. else
  327. v = position.offset.top or 0 # measure from html click position
  328. # It's not clear exactly where we should sync to if it wasn't directly
  329. # clicked on, but a little bit down from the very top seems best.
  330. if options.includeVisualOffset
  331. v += 72 # use the same value as in pdfViewer highlighting visual offset
  332. $http({
  333. url: "/project/#{ide.project_id}/sync/pdf",
  334. method: "GET",
  335. params: {
  336. page: position.page + 1
  337. h: h.toFixed(2)
  338. v: v.toFixed(2)
  339. clsiserverid:ide.clsiServerId
  340. isolated: perUserCompile
  341. }
  342. })
  343. .success (data) ->
  344. if data.code? and data.code.length > 0
  345. doc = ide.fileTreeManager.findEntityByPath(data.code[0].file)
  346. return if !doc?
  347. deferred.resolve({doc: doc, line: data.code[0].line})
  348. .error (error) ->
  349. deferred.reject(error)
  350. return deferred.promise
  351. return synctex
  352. ]
  353. App.controller "PdfSynctexController", ["$scope", "synctex", "ide", ($scope, synctex, ide) ->
  354. @cursorPosition = null
  355. ide.$scope.$on "cursor:editor:update", (event, @cursorPosition) =>
  356. $scope.syncToPdf = () =>
  357. return if !@cursorPosition?
  358. synctex
  359. .syncToPdf(@cursorPosition)
  360. .then (highlights) ->
  361. $scope.pdf.highlights = highlights
  362. $scope.syncToCode = () ->
  363. synctex
  364. .syncToCode($scope.pdf.position, includeVisualOffset: true, fromPdfPosition: true)
  365. .then (data) ->
  366. {doc, line} = data
  367. ide.editorManager.openDoc(doc, gotoLine: line)
  368. ]
  369. App.controller "PdfLogEntryController", ["$scope", "ide", ($scope, ide) ->
  370. $scope.openInEditor = (entry) ->
  371. entity = ide.fileTreeManager.findEntityByPath(entry.file)
  372. return if !entity? or entity.type != "doc"
  373. if entry.line?
  374. line = entry.line
  375. ide.editorManager.openDoc(entity, gotoLine: line)
  376. ]
  377. App.controller 'ClearCacheModalController', ["$scope", "$modalInstance", ($scope, $modalInstance) ->
  378. $scope.state =
  379. inflight: false
  380. $scope.clear = () ->
  381. $scope.state.inflight = true
  382. $scope
  383. .clearCache()
  384. .then () ->
  385. $scope.state.inflight = false
  386. $modalInstance.close()
  387. $scope.cancel = () ->
  388. $modalInstance.dismiss('cancel')
  389. ]