PdfController.coffee 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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. $scope.trackLogHintsLearnMore = () ->
  17. event_tracking.sendCountly "logs-hints-learn-more"
  18. trackLogHintsFeedback = (isPositive, hintId) ->
  19. event_tracking.sendCountly "log-hints-feedback", { isPositive, hintId }
  20. $scope.trackLogHintsPositiveFeedback = (hintId) -> trackLogHintsFeedback true, hintId
  21. $scope.trackLogHintsNegativeFeedback = (hintId) -> trackLogHintsFeedback false, hintId
  22. if ace.require("ace/lib/useragent").isMac
  23. $scope.modifierKey = "Cmd"
  24. else
  25. $scope.modifierKey = "Ctrl"
  26. # utility for making a query string from a hash, could use jquery $.param
  27. createQueryString = (args) ->
  28. qs_args = ("#{k}=#{v}" for k, v of args)
  29. if qs_args.length then "?" + qs_args.join("&") else ""
  30. $scope.stripHTMLFromString = (htmlStr) ->
  31. tmp = document.createElement("DIV")
  32. tmp.innerHTML = htmlStr
  33. return tmp.textContent || tmp.innerText || ""
  34. $scope.$on "project:joined", () ->
  35. return if !autoCompile
  36. autoCompile = false
  37. $scope.recompile(isAutoCompile: true)
  38. $scope.hasPremiumCompile = $scope.project.features.compileGroup == "priority"
  39. $scope.$on "pdf:error:display", () ->
  40. $scope.pdf.view = 'errors'
  41. $scope.pdf.renderingError = true
  42. $scope.draft = localStorage("draft:#{$scope.project_id}") or false
  43. $scope.$watch "draft", (new_value, old_value) ->
  44. if new_value? and old_value != new_value
  45. localStorage("draft:#{$scope.project_id}", new_value)
  46. sendCompileRequest = (options = {}) ->
  47. url = "/project/#{$scope.project_id}/compile"
  48. params = {}
  49. if options.isAutoCompile
  50. params["auto_compile"]=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. # Save all downloads as files
  120. qs.popupDownload = true
  121. $scope.pdf.downloadUrl = "/project/#{$scope.project_id}/output/output.pdf" + createQueryString(qs)
  122. fetchLogs(fileByPath['output.log'], fileByPath['output.blg'])
  123. IGNORE_FILES = ["output.fls", "output.fdb_latexmk"]
  124. $scope.pdf.outputFiles = []
  125. if !response.outputFiles?
  126. return
  127. for file in response.outputFiles
  128. if IGNORE_FILES.indexOf(file.path) == -1
  129. # Turn 'output.blg' into 'blg file'.
  130. if file.path.match(/^output\./)
  131. file.name = "#{file.path.replace(/^output\./, "")} file"
  132. else
  133. file.name = file.path
  134. qs = {}
  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}(-[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. event_tracking.sendCountly "editor-recompile", options
  218. return if $scope.pdf.compiling
  219. $scope.pdf.compiling = true
  220. ide.$scope.$broadcast("flush-changes")
  221. options.rootDocOverride_id = getRootDocOverride_id()
  222. sendCompileRequest(options)
  223. .success (data) ->
  224. $scope.pdf.view = "pdf"
  225. $scope.pdf.compiling = false
  226. parseCompileResponse(data)
  227. .error () ->
  228. $scope.pdf.compiling = false
  229. $scope.pdf.renderingError = false
  230. $scope.pdf.error = true
  231. $scope.pdf.view = 'errors'
  232. # This needs to be public.
  233. ide.$scope.recompile = $scope.recompile
  234. # This method is a simply wrapper and exists only for tracking purposes.
  235. ide.$scope.recompileViaKey = () ->
  236. $scope.recompile { keyShortcut: true }
  237. $scope.clearCache = () ->
  238. $http {
  239. url: "/project/#{$scope.project_id}/output"
  240. method: "DELETE"
  241. params:
  242. clsiserverid:ide.clsiServerId
  243. headers:
  244. "X-Csrf-Token": window.csrfToken
  245. }
  246. $scope.toggleLogs = () ->
  247. $scope.shouldShowLogs = !$scope.shouldShowLogs
  248. event_tracking.sendCountly "ide-open-logs" if $scope.shouldShowLogs
  249. $scope.showPdf = () ->
  250. $scope.pdf.view = "pdf"
  251. $scope.shouldShowLogs = false
  252. $scope.toggleRawLog = () ->
  253. $scope.pdf.showRawLog = !$scope.pdf.showRawLog
  254. event_tracking.sendCountly "logs-view-raw" if $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. }
  317. })
  318. .success (data) ->
  319. deferred.resolve(data.pdf or [])
  320. .error (error) ->
  321. deferred.reject(error)
  322. return deferred.promise
  323. syncToCode: (position, options = {}) ->
  324. deferred = $q.defer()
  325. if !position?
  326. deferred.reject()
  327. return deferred.promise
  328. # FIXME: this actually works better if it's halfway across the
  329. # page (or the visible part of the page). Synctex doesn't
  330. # always find the right place in the file when the point is at
  331. # the edge of the page, it sometimes returns the start of the
  332. # next paragraph instead.
  333. h = position.offset.left
  334. # Compute the vertical position to pass to synctex, which
  335. # works with coordinates increasing from the top of the page
  336. # down. This matches the browser's DOM coordinate of the
  337. # click point, but the pdf position is measured from the
  338. # bottom of the page so we need to invert it.
  339. if options.fromPdfPosition and position.pageSize?.height?
  340. v = (position.pageSize.height - position.offset.top) or 0 # measure from pdf point (inverted)
  341. else
  342. v = position.offset.top or 0 # measure from html click position
  343. # It's not clear exactly where we should sync to if it wasn't directly
  344. # clicked on, but a little bit down from the very top seems best.
  345. if options.includeVisualOffset
  346. v += 72 # use the same value as in pdfViewer highlighting visual offset
  347. $http({
  348. url: "/project/#{ide.project_id}/sync/pdf",
  349. method: "GET",
  350. params: {
  351. page: position.page + 1
  352. h: h.toFixed(2)
  353. v: v.toFixed(2)
  354. clsiserverid:ide.clsiServerId
  355. }
  356. })
  357. .success (data) ->
  358. if data.code? and data.code.length > 0
  359. doc = ide.fileTreeManager.findEntityByPath(data.code[0].file)
  360. return if !doc?
  361. deferred.resolve({doc: doc, line: data.code[0].line})
  362. .error (error) ->
  363. deferred.reject(error)
  364. return deferred.promise
  365. return synctex
  366. ]
  367. App.controller "PdfSynctexController", ["$scope", "synctex", "ide", ($scope, synctex, ide) ->
  368. @cursorPosition = null
  369. ide.$scope.$on "cursor:editor:update", (event, @cursorPosition) =>
  370. $scope.syncToPdf = () =>
  371. return if !@cursorPosition?
  372. synctex
  373. .syncToPdf(@cursorPosition)
  374. .then (highlights) ->
  375. $scope.pdf.highlights = highlights
  376. $scope.syncToCode = () ->
  377. synctex
  378. .syncToCode($scope.pdf.position, includeVisualOffset: true, fromPdfPosition: true)
  379. .then (data) ->
  380. {doc, line} = data
  381. ide.editorManager.openDoc(doc, gotoLine: line)
  382. ]
  383. App.controller "PdfLogEntryController", ["$scope", "ide", "event_tracking", ($scope, ide, event_tracking) ->
  384. $scope.openInEditor = (entry) ->
  385. event_tracking.sendCountly 'logs-jump-to-location'
  386. entity = ide.fileTreeManager.findEntityByPath(entry.file)
  387. return if !entity? or entity.type != "doc"
  388. if entry.line?
  389. line = entry.line
  390. ide.editorManager.openDoc(entity, gotoLine: line)
  391. ]
  392. App.controller 'ClearCacheModalController', ["$scope", "$modalInstance", ($scope, $modalInstance) ->
  393. $scope.state =
  394. inflight: false
  395. $scope.clear = () ->
  396. $scope.state.inflight = true
  397. $scope
  398. .clearCache()
  399. .then () ->
  400. $scope.state.inflight = false
  401. $modalInstance.close()
  402. $scope.cancel = () ->
  403. $modalInstance.dismiss('cancel')
  404. ]