PdfController.coffee 15 KB

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