PdfController.coffee 19 KB

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