PdfController.coffee 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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 null
  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. $scope.pdf.outputFiles.push {
  170. # Turn 'output.blg' into 'blg file'.
  171. name: if file.path.match(/^output\./) then "#{file.path.replace(/^output\./, "")} file" else file.path
  172. url: "/project/#{project_id}/output/#{file.path}" + createQueryString qs
  173. }
  174. fetchLogs = (fileByPath, options) ->
  175. if options?.validation
  176. chktexFile = fileByPath['output.chktex']
  177. else
  178. logFile = fileByPath['output.log']
  179. blgFile = fileByPath['output.blg']
  180. getFile = (name, file) ->
  181. opts =
  182. method:"GET"
  183. params:
  184. compileGroup:ide.compileGroup
  185. clsiserverid:ide.clsiServerId
  186. if file?.url? # FIXME clean this up when we have file.urls out consistently
  187. opts.url = file.url
  188. else if file?.build?
  189. opts.url = "/project/#{$scope.project_id}/build/#{file.build}/output/#{name}"
  190. else
  191. opts.url = "/project/#{$scope.project_id}/output/#{name}"
  192. # check if we need to bust cache (build id is unique so don't need it in that case)
  193. if not file?.build?
  194. opts.params.cache_bust = "#{Date.now()}"
  195. return $http(opts)
  196. # accumulate the log entries
  197. logEntries =
  198. all: []
  199. errors: []
  200. warnings: []
  201. accumulateResults = (newEntries) ->
  202. for key in ['all', 'errors', 'warnings']
  203. if newEntries.type?
  204. entry.type = newEntries.type for entry in newEntries[key]
  205. logEntries[key] = logEntries[key].concat newEntries[key]
  206. # use the parsers for each file type
  207. processLog = (log) ->
  208. $scope.pdf.rawLog = log
  209. {errors, warnings, typesetting} = HumanReadableLogs.parse(log, ignoreDuplicates: true)
  210. all = [].concat errors, warnings, typesetting
  211. accumulateResults {all, errors, warnings}
  212. processChkTex = (log) ->
  213. errors = []
  214. warnings = []
  215. for line in log.split("\n")
  216. if m = line.match /^(\S+):(\d+):(\d+): (Error|Warning): (.*)/
  217. result = { file:m[1], line:m[2], column:m[3], level:m[4].toLowerCase(), message: "#{m[4]}: #{m[5]}"}
  218. if result.level is 'error'
  219. errors.push result
  220. else
  221. warnings.push result
  222. all = [].concat errors, warnings
  223. logHints = HumanReadableLogs.parse {type: "Validation", all, errors, warnings}
  224. accumulateResults logHints
  225. processBiber = (log) ->
  226. {errors, warnings} = BibLogParser.parse(log, {})
  227. all = [].concat errors, warnings
  228. accumulateResults {type: "BibTeX", all, errors, warnings}
  229. # output the results
  230. handleError = () ->
  231. $scope.pdf.logEntries = []
  232. $scope.pdf.rawLog = ""
  233. annotateFiles = () ->
  234. $scope.pdf.logEntries = logEntries
  235. $scope.pdf.logEntryAnnotations = {}
  236. for entry in logEntries.all
  237. if entry.file?
  238. entry.file = normalizeFilePath(entry.file)
  239. entity = ide.fileTreeManager.findEntityByPath(entry.file)
  240. if entity?
  241. $scope.pdf.logEntryAnnotations[entity.id] ||= []
  242. $scope.pdf.logEntryAnnotations[entity.id].push {
  243. row: entry.line - 1
  244. type: if entry.level == "error" then "error" else "warning"
  245. text: entry.message
  246. }
  247. # retrieve the logfile and process it
  248. if logFile?
  249. response = getFile('output.log', logFile)
  250. .then (response) -> processLog(response.data)
  251. if blgFile? # retrieve the blg file if present
  252. response = response.then () ->
  253. getFile('output.blg', blgFile)
  254. .then(
  255. (response) -> processBiber(response.data),
  256. () -> true # ignore errors in biber file
  257. )
  258. if response?
  259. response.catch handleError
  260. else
  261. handleError()
  262. if chktexFile?
  263. getChkTex = () ->
  264. getFile('output.chktex', chktexFile)
  265. .then (response) -> processChkTex(response.data)
  266. # always retrieve the chktex file if present
  267. if response?
  268. response = response.then getChkTex, getChkTex
  269. else
  270. response = getChkTex()
  271. # display the combined result
  272. response.finally annotateFiles
  273. getRootDocOverride_id = () ->
  274. doc = ide.editorManager.getCurrentDocValue()
  275. return null if !doc?
  276. for line in doc.split("\n")
  277. match = line.match /^[^%]*\\documentclass/
  278. if match
  279. return ide.editorManager.getCurrentDocId()
  280. return null
  281. normalizeFilePath = (path) ->
  282. path = path.replace(/^(.*)\/compiles\/[0-9a-f]{24}(-[0-9a-f]{24})?\/(\.\/)?/, "")
  283. path = path.replace(/^\/compile\//, "")
  284. rootDocDirname = ide.fileTreeManager.getRootDocDirname()
  285. if rootDocDirname?
  286. path = path.replace(/^\.\//, rootDocDirname + "/")
  287. return path
  288. $scope.recompile = (options = {}) ->
  289. return if $scope.pdf.compiling
  290. event_tracking.sendMBSampled "editor-recompile-sampled", options
  291. $scope.pdf.compiling = true
  292. ide.$scope.$broadcast("flush-changes")
  293. options.rootDocOverride_id = getRootDocOverride_id()
  294. sendCompileRequest(options)
  295. .success (data) ->
  296. $scope.pdf.view = "pdf"
  297. $scope.pdf.compiling = false
  298. parseCompileResponse(data)
  299. .error () ->
  300. $scope.pdf.compiling = false
  301. $scope.pdf.renderingError = false
  302. $scope.pdf.error = true
  303. $scope.pdf.view = 'errors'
  304. # This needs to be public.
  305. ide.$scope.recompile = $scope.recompile
  306. # This method is a simply wrapper and exists only for tracking purposes.
  307. ide.$scope.recompileViaKey = () ->
  308. $scope.recompile { keyShortcut: true }
  309. $scope.stop = () ->
  310. return if !$scope.pdf.compiling
  311. $http {
  312. url: "/project/#{$scope.project_id}/compile/stop"
  313. method: "POST"
  314. params:
  315. clsiserverid:ide.clsiServerId
  316. headers:
  317. "X-Csrf-Token": window.csrfToken
  318. }
  319. $scope.clearCache = () ->
  320. $http {
  321. url: "/project/#{$scope.project_id}/output"
  322. method: "DELETE"
  323. params:
  324. clsiserverid:ide.clsiServerId
  325. headers:
  326. "X-Csrf-Token": window.csrfToken
  327. }
  328. $scope.toggleLogs = () ->
  329. $scope.shouldShowLogs = !$scope.shouldShowLogs
  330. event_tracking.sendMBOnce "ide-open-logs-once" if $scope.shouldShowLogs
  331. $scope.showPdf = () ->
  332. $scope.pdf.view = "pdf"
  333. $scope.shouldShowLogs = false
  334. $scope.toggleRawLog = () ->
  335. $scope.pdf.showRawLog = !$scope.pdf.showRawLog
  336. event_tracking.sendMB "logs-view-raw" if $scope.pdf.showRawLog
  337. $scope.openClearCacheModal = () ->
  338. modalInstance = $modal.open(
  339. templateUrl: "clearCacheModalTemplate"
  340. controller: "ClearCacheModalController"
  341. scope: $scope
  342. )
  343. $scope.syncToCode = (position) ->
  344. synctex
  345. .syncToCode(position)
  346. .then (data) ->
  347. {doc, line} = data
  348. ide.editorManager.openDoc(doc, gotoLine: line)
  349. $scope.switchToFlatLayout = () ->
  350. $scope.ui.pdfLayout = 'flat'
  351. $scope.ui.view = 'pdf'
  352. ide.localStorage "pdf.layout", "flat"
  353. $scope.switchToSideBySideLayout = () ->
  354. $scope.ui.pdfLayout = 'sideBySide'
  355. $scope.ui.view = 'editor'
  356. localStorage "pdf.layout", "split"
  357. if pdfLayout = localStorage("pdf.layout")
  358. $scope.switchToSideBySideLayout() if pdfLayout == "split"
  359. $scope.switchToFlatLayout() if pdfLayout == "flat"
  360. else
  361. $scope.switchToSideBySideLayout()
  362. $scope.startFreeTrial = (source) ->
  363. ga?('send', 'event', 'subscription-funnel', 'compile-timeout', source)
  364. event_tracking.sendMB "subscription-start-trial", { source }
  365. window.open("/user/subscription/new?planCode=student_free_trial_7_days")
  366. $scope.startedFreeTrial = true
  367. App.factory "synctex", ["ide", "$http", "$q", (ide, $http, $q) ->
  368. # enable per-user containers by default
  369. perUserCompile = true
  370. synctex =
  371. syncToPdf: (cursorPosition) ->
  372. deferred = $q.defer()
  373. doc_id = ide.editorManager.getCurrentDocId()
  374. if !doc_id?
  375. deferred.reject()
  376. return deferred.promise
  377. doc = ide.fileTreeManager.findEntityById(doc_id)
  378. if !doc?
  379. deferred.reject()
  380. return deferred.promise
  381. path = ide.fileTreeManager.getEntityPath(doc)
  382. if !path?
  383. deferred.reject()
  384. return deferred.promise
  385. # If the root file is folder/main.tex, then synctex sees the
  386. # path as folder/./main.tex
  387. rootDocDirname = ide.fileTreeManager.getRootDocDirname()
  388. if rootDocDirname? and rootDocDirname != ""
  389. path = path.replace(RegExp("^#{rootDocDirname}"), "#{rootDocDirname}/.")
  390. {row, column} = cursorPosition
  391. $http({
  392. url: "/project/#{ide.project_id}/sync/code",
  393. method: "GET",
  394. params: {
  395. file: path
  396. line: row + 1
  397. column: column
  398. clsiserverid:ide.clsiServerId
  399. }
  400. })
  401. .success (data) ->
  402. deferred.resolve(data.pdf or [])
  403. .error (error) ->
  404. deferred.reject(error)
  405. return deferred.promise
  406. syncToCode: (position, options = {}) ->
  407. deferred = $q.defer()
  408. if !position?
  409. deferred.reject()
  410. return deferred.promise
  411. # FIXME: this actually works better if it's halfway across the
  412. # page (or the visible part of the page). Synctex doesn't
  413. # always find the right place in the file when the point is at
  414. # the edge of the page, it sometimes returns the start of the
  415. # next paragraph instead.
  416. h = position.offset.left
  417. # Compute the vertical position to pass to synctex, which
  418. # works with coordinates increasing from the top of the page
  419. # down. This matches the browser's DOM coordinate of the
  420. # click point, but the pdf position is measured from the
  421. # bottom of the page so we need to invert it.
  422. if options.fromPdfPosition and position.pageSize?.height?
  423. v = (position.pageSize.height - position.offset.top) or 0 # measure from pdf point (inverted)
  424. else
  425. v = position.offset.top or 0 # measure from html click position
  426. # It's not clear exactly where we should sync to if it wasn't directly
  427. # clicked on, but a little bit down from the very top seems best.
  428. if options.includeVisualOffset
  429. v += 72 # use the same value as in pdfViewer highlighting visual offset
  430. $http({
  431. url: "/project/#{ide.project_id}/sync/pdf",
  432. method: "GET",
  433. params: {
  434. page: position.page + 1
  435. h: h.toFixed(2)
  436. v: v.toFixed(2)
  437. clsiserverid:ide.clsiServerId
  438. }
  439. })
  440. .success (data) ->
  441. if data.code? and data.code.length > 0
  442. doc = ide.fileTreeManager.findEntityByPath(data.code[0].file)
  443. return if !doc?
  444. deferred.resolve({doc: doc, line: data.code[0].line})
  445. .error (error) ->
  446. deferred.reject(error)
  447. return deferred.promise
  448. return synctex
  449. ]
  450. App.controller "PdfSynctexController", ["$scope", "synctex", "ide", ($scope, synctex, ide) ->
  451. @cursorPosition = null
  452. ide.$scope.$on "cursor:editor:update", (event, @cursorPosition) =>
  453. $scope.syncToPdf = () =>
  454. return if !@cursorPosition?
  455. synctex
  456. .syncToPdf(@cursorPosition)
  457. .then (highlights) ->
  458. $scope.pdf.highlights = highlights
  459. $scope.syncToCode = () ->
  460. synctex
  461. .syncToCode($scope.pdf.position, includeVisualOffset: true, fromPdfPosition: true)
  462. .then (data) ->
  463. {doc, line} = data
  464. ide.editorManager.openDoc(doc, gotoLine: line)
  465. ]
  466. App.controller "PdfLogEntryController", ["$scope", "ide", "event_tracking", ($scope, ide, event_tracking) ->
  467. $scope.openInEditor = (entry) ->
  468. event_tracking.sendMBOnce "logs-jump-to-location-once"
  469. entity = ide.fileTreeManager.findEntityByPath(entry.file)
  470. return if !entity? or entity.type != "doc"
  471. if entry.line?
  472. line = entry.line
  473. if entry.column?
  474. column = entry.column
  475. ide.editorManager.openDoc(entity, gotoLine: line, gotoColumn: column)
  476. ]
  477. App.controller 'ClearCacheModalController', ["$scope", "$modalInstance", ($scope, $modalInstance) ->
  478. $scope.state =
  479. inflight: false
  480. $scope.clear = () ->
  481. $scope.state.inflight = true
  482. $scope
  483. .clearCache()
  484. .then () ->
  485. $scope.state.inflight = false
  486. $modalInstance.close()
  487. $scope.cancel = () ->
  488. $modalInstance.dismiss('cancel')
  489. ]