PdfController.coffee 15 KB

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