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