PdfController.coffee 15 KB

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