PdfController.coffee 17 KB

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