PdfController.coffee 17 KB

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