PdfController.coffee 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  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. AUTO_COMPILE_MAX_WAIT = 5000
  9. # We add a 1 second debounce to sending user changes to server if they aren't
  10. # collaborating with anyone. This needs to be higher than that, and allow for
  11. # client to server latency, otherwise we compile before the op reaches the server
  12. # and then again on ack.
  13. AUTO_COMPILE_DEBOUNCE = 2000
  14. App.controller "PdfController", ($scope, $http, ide, $modal, synctex, event_tracking, logHintsFeedback, localStorage) ->
  15. # enable per-user containers by default
  16. perUserCompile = true
  17. autoCompile = true
  18. # pdf.view = uncompiled | pdf | errors
  19. $scope.pdf.view = if $scope?.pdf?.url then 'pdf' else 'uncompiled'
  20. $scope.shouldShowLogs = false
  21. $scope.wikiEnabled = window.wikiEnabled;
  22. # view logic to check whether the files dropdown should "drop up" or "drop down"
  23. $scope.shouldDropUp = false
  24. logsContainerEl = document.querySelector ".pdf-logs"
  25. filesDropdownEl = logsContainerEl?.querySelector ".files-dropdown"
  26. # get the top coordinate of the files dropdown as a ratio (to the logs container height)
  27. # logs container supports scrollable content, so it's possible that ratio > 1.
  28. getFilesDropdownTopCoordAsRatio = () ->
  29. filesDropdownEl?.getBoundingClientRect().top / logsContainerEl?.getBoundingClientRect().height
  30. $scope.$watch "shouldShowLogs", (shouldShow) ->
  31. if shouldShow
  32. $scope.$applyAsync () ->
  33. $scope.shouldDropUp = getFilesDropdownTopCoordAsRatio() > 0.65
  34. # log hints tracking
  35. $scope.logHintsNegFeedbackValues = logHintsFeedback.feedbackOpts
  36. $scope.trackLogHintsLearnMore = () ->
  37. event_tracking.sendMB "logs-hints-learn-more"
  38. trackLogHintsFeedback = (isPositive, hintId) ->
  39. event_tracking.send "log-hints", (if isPositive then "feedback-positive" else "feedback-negative"), hintId
  40. event_tracking.sendMB (if isPositive then "log-hints-feedback-positive" else "log-hints-feedback-negative"), { hintId }
  41. $scope.trackLogHintsNegFeedbackDetails = (hintId, feedbackOpt, feedbackOtherVal) ->
  42. logHintsFeedback.submitFeedback hintId, feedbackOpt, feedbackOtherVal
  43. $scope.trackLogHintsPositiveFeedback = (hintId) -> trackLogHintsFeedback true, hintId
  44. $scope.trackLogHintsNegativeFeedback = (hintId) -> trackLogHintsFeedback false, hintId
  45. if ace.require("ace/lib/useragent").isMac
  46. $scope.modifierKey = "Cmd"
  47. else
  48. $scope.modifierKey = "Ctrl"
  49. # utility for making a query string from a hash, could use jquery $.param
  50. createQueryString = (args) ->
  51. qs_args = ("#{k}=#{v}" for k, v of args)
  52. if qs_args.length then "?" + qs_args.join("&") else ""
  53. $scope.stripHTMLFromString = (htmlStr) ->
  54. tmp = document.createElement("DIV")
  55. tmp.innerHTML = htmlStr
  56. return tmp.textContent || tmp.innerText || ""
  57. $scope.$on "project:joined", () ->
  58. return if !autoCompile
  59. autoCompile = false
  60. $scope.recompile(isAutoCompileOnLoad: true)
  61. $scope.hasPremiumCompile = $scope.project.features.compileGroup == "priority"
  62. $scope.$on "pdf:error:display", () ->
  63. $scope.pdf.view = 'errors'
  64. $scope.pdf.renderingError = true
  65. autoCompileInterval = null
  66. autoCompileIfReady = () ->
  67. if $scope.pdf.compiling
  68. return
  69. # Only checking linting if syntaxValidation is on and visible to the user
  70. autoCompileLintingError = ide.$scope.hasLintingError and ide.$scope.settings.syntaxValidation
  71. if $scope.autoCompileLintingError != autoCompileLintingError
  72. $scope.$apply () ->
  73. $scope.autoCompileLintingError = autoCompileLintingError
  74. # We've likely been waiting a while until the user fixed the linting, but we
  75. # don't want to compile as soon as it is fixed, so reset the timeout.
  76. $scope.startedTryingAutoCompileAt = Date.now()
  77. $scope.docLastChangedAt = Date.now()
  78. if autoCompileLintingError
  79. return
  80. # If there's a longish compile, don't compile immediately after if user is still typing
  81. startedTryingAt = Math.max($scope.startedTryingAutoCompileAt, $scope.lastFinishedCompileAt || 0)
  82. timeSinceStartedTrying = Date.now() - startedTryingAt
  83. timeSinceLastChange = Date.now() - $scope.docLastChangedAt
  84. shouldCompile = false
  85. if timeSinceLastChange > AUTO_COMPILE_DEBOUNCE # Don't compile in the middle of the user typing
  86. shouldCompile = true
  87. else if timeSinceStartedTrying > AUTO_COMPILE_MAX_WAIT # Unless they type for a long time
  88. shouldCompile = true
  89. else if timeSinceStartedTrying < 0 or timeSinceLastChange < 0
  90. # If time is non-monotonic, assume that the user's system clock has been
  91. # changed and continue with compile
  92. shouldCompile = true
  93. if shouldCompile
  94. triggerAutoCompile()
  95. triggerAutoCompile = () ->
  96. $scope.recompile(isAutoCompileOnChange: true)
  97. startTryingAutoCompile = () ->
  98. return if autoCompileInterval?
  99. $scope.startedTryingAutoCompileAt = Date.now()
  100. autoCompileInterval = setInterval autoCompileIfReady, 200
  101. stopTryingAutoCompile = () ->
  102. clearInterval autoCompileInterval
  103. autoCompileInterval = null
  104. $scope.$watch "uncompiledChanges", (uncompiledChanges) ->
  105. if uncompiledChanges
  106. startTryingAutoCompile()
  107. else
  108. stopTryingAutoCompile()
  109. $scope.uncompiledChanges = false
  110. recalculateUncompiledChanges = () ->
  111. if $scope.ui.pdfHidden
  112. # Don't bother auto-compiling if pdf isn't visible
  113. $scope.uncompiledChanges = false
  114. else if !$scope.docLastChangedAt?
  115. $scope.uncompiledChanges = false
  116. else if !$scope.lastStartedCompileAt? or $scope.docLastChangedAt > $scope.lastStartedCompileAt
  117. $scope.uncompiledChanges = true
  118. else
  119. $scope.uncompiledChanges = false
  120. _updateDocLastChangedAt = () ->
  121. $scope.docLastChangedAt = Date.now()
  122. recalculateUncompiledChanges()
  123. onDocChanged = () ->
  124. $scope.autoCompileLintingError = false
  125. _updateDocLastChangedAt()
  126. onDocSaved = () ->
  127. # We use the save as a trigger too, to account for the delay between the client
  128. # and server. Otherwise, we might have compiled after the user made
  129. # the change on the client, but before the server had it.
  130. _updateDocLastChangedAt()
  131. onCompilingStateChanged = (compiling) ->
  132. recalculateUncompiledChanges()
  133. autoCompileListeners = []
  134. toggleAutoCompile = (enabling) ->
  135. if enabling
  136. autoCompileListeners = [
  137. ide.$scope.$on "doc:changed", onDocChanged
  138. ide.$scope.$on "doc:saved", onDocSaved
  139. $scope.$watch "pdf.compiling", onCompilingStateChanged
  140. ]
  141. else
  142. for unbind in autoCompileListeners
  143. unbind()
  144. autoCompileListeners = []
  145. $scope.autoCompileLintingError = false
  146. $scope.autocompile_enabled = localStorage("autocompile_enabled:#{$scope.project_id}") or false
  147. $scope.$watch "autocompile_enabled", (newValue, oldValue) ->
  148. if newValue? and oldValue != newValue
  149. localStorage("autocompile_enabled:#{$scope.project_id}", newValue)
  150. toggleAutoCompile(newValue)
  151. event_tracking.sendMB "autocompile-setting-changed", { value: newValue }
  152. if $scope.autocompile_enabled
  153. toggleAutoCompile(true)
  154. # abort compile if syntax checks fail
  155. $scope.stop_on_validation_error = localStorage("stop_on_validation_error:#{$scope.project_id}")
  156. $scope.stop_on_validation_error ?= true # turn on for all users by default
  157. $scope.$watch "stop_on_validation_error", (new_value, old_value) ->
  158. if new_value? and old_value != new_value
  159. localStorage("stop_on_validation_error:#{$scope.project_id}", new_value)
  160. $scope.draft = localStorage("draft:#{$scope.project_id}") or false
  161. $scope.$watch "draft", (new_value, old_value) ->
  162. if new_value? and old_value != new_value
  163. localStorage("draft:#{$scope.project_id}", new_value)
  164. sendCompileRequest = (options = {}) ->
  165. url = "/project/#{$scope.project_id}/compile"
  166. params = {}
  167. if options.isAutoCompileOnLoad or options.isAutoCompileOnChange
  168. params["auto_compile"]=true
  169. # if the previous run was a check, clear the error logs
  170. $scope.pdf.logEntries = [] if $scope.check
  171. # keep track of whether this is a compile or check
  172. $scope.check = if options.check then true else false
  173. event_tracking.sendMB "syntax-check-request" if options.check
  174. # send appropriate check type to clsi
  175. checkType = switch
  176. when $scope.check then "validate" # validate only
  177. when options.try then "silent" # allow use to try compile once
  178. when $scope.stop_on_validation_error then "error" # try to compile
  179. else "silent" # ignore errors
  180. return $http.post url, {
  181. rootDoc_id: options.rootDocOverride_id or null
  182. draft: $scope.draft
  183. check: checkType
  184. # use incremental compile for all users but revert to a full
  185. # compile if there is a server error
  186. incrementalCompilesEnabled: not $scope.pdf.error
  187. _csrf: window.csrfToken
  188. }, {params: params}
  189. parseCompileResponse = (response) ->
  190. # keep last url
  191. last_pdf_url = $scope.pdf.url
  192. # Reset everything
  193. $scope.pdf.error = false
  194. $scope.pdf.timedout = false
  195. $scope.pdf.failure = false
  196. $scope.pdf.url = null
  197. $scope.pdf.clsiMaintenance = false
  198. $scope.pdf.tooRecentlyCompiled = false
  199. $scope.pdf.renderingError = false
  200. $scope.pdf.projectTooLarge = false
  201. $scope.pdf.compileTerminated = false
  202. $scope.pdf.compileExited = false
  203. $scope.pdf.failedCheck = false
  204. $scope.pdf.compileInProgress = false
  205. $scope.pdf.autoCompileDisabled = false
  206. # make a cache to look up files by name
  207. fileByPath = {}
  208. if response?.outputFiles?
  209. for file in response?.outputFiles
  210. fileByPath[file.path] = file
  211. # prepare query string
  212. qs = {}
  213. # add a query string parameter for the compile group
  214. if response.compileGroup?
  215. ide.compileGroup = qs.compileGroup = response.compileGroup
  216. # add a query string parameter for the clsi server id
  217. if response.clsiServerId?
  218. ide.clsiServerId = qs.clsiserverid = response.clsiServerId
  219. if response.status == "timedout"
  220. $scope.pdf.view = 'errors'
  221. $scope.pdf.timedout = true
  222. fetchLogs(fileByPath)
  223. else if response.status == "terminated"
  224. $scope.pdf.view = 'errors'
  225. $scope.pdf.compileTerminated = true
  226. fetchLogs(fileByPath)
  227. else if response.status in ["validation-fail", "validation-pass"]
  228. $scope.pdf.view = 'pdf'
  229. $scope.pdf.url = last_pdf_url
  230. $scope.shouldShowLogs = true
  231. $scope.pdf.failedCheck = true if response.status is "validation-fail"
  232. event_tracking.sendMB "syntax-check-#{response.status}"
  233. fetchLogs(fileByPath, { validation: true })
  234. else if response.status == "exited"
  235. $scope.pdf.view = 'pdf'
  236. $scope.pdf.compileExited = true
  237. $scope.pdf.url = last_pdf_url
  238. $scope.shouldShowLogs = true
  239. fetchLogs(fileByPath)
  240. else if response.status == "autocompile-backoff"
  241. if $scope.pdf.isAutoCompileOnLoad # initial autocompile
  242. $scope.pdf.view = 'uncompiled'
  243. else # background autocompile from typing
  244. $scope.pdf.view = 'errors'
  245. $scope.pdf.autoCompileDisabled = true
  246. $scope.autocompile_enabled = false # disable any further autocompiles
  247. event_tracking.sendMB "autocompile-rate-limited", {hasPremiumCompile: $scope.hasPremiumCompile}
  248. else if response.status == "project-too-large"
  249. $scope.pdf.view = 'errors'
  250. $scope.pdf.projectTooLarge = true
  251. else if response.status == "failure"
  252. $scope.pdf.view = 'errors'
  253. $scope.pdf.failure = true
  254. $scope.shouldShowLogs = true
  255. fetchLogs(fileByPath)
  256. else if response.status == 'clsi-maintenance'
  257. $scope.pdf.view = 'errors'
  258. $scope.pdf.clsiMaintenance = true
  259. else if response.status == "too-recently-compiled"
  260. $scope.pdf.view = 'errors'
  261. $scope.pdf.tooRecentlyCompiled = true
  262. else if response.status == "validation-problems"
  263. $scope.pdf.view = "validation-problems"
  264. $scope.pdf.validation = response.validationProblems
  265. $scope.shouldShowLogs = false
  266. else if response.status == "compile-in-progress"
  267. $scope.pdf.view = 'errors'
  268. $scope.pdf.compileInProgress = true
  269. else if response.status == "success"
  270. $scope.pdf.view = 'pdf'
  271. $scope.shouldShowLogs = false
  272. # define the base url. if the pdf file has a build number, pass it to the clsi in the url
  273. if fileByPath['output.pdf']?.url?
  274. $scope.pdf.url = fileByPath['output.pdf'].url
  275. else if fileByPath['output.pdf']?.build?
  276. build = fileByPath['output.pdf'].build
  277. $scope.pdf.url = "/project/#{$scope.project_id}/build/#{build}/output/output.pdf"
  278. else
  279. $scope.pdf.url = "/project/#{$scope.project_id}/output/output.pdf"
  280. # check if we need to bust cache (build id is unique so don't need it in that case)
  281. if not fileByPath['output.pdf']?.build?
  282. qs.cache_bust = "#{Date.now()}"
  283. # convert the qs hash into a query string and append it
  284. $scope.pdf.url += createQueryString qs
  285. # Save all downloads as files
  286. qs.popupDownload = true
  287. $scope.pdf.downloadUrl = "/project/#{$scope.project_id}/output/output.pdf" + createQueryString(qs)
  288. fetchLogs(fileByPath)
  289. IGNORE_FILES = ["output.fls", "output.fdb_latexmk"]
  290. $scope.pdf.outputFiles = []
  291. if !response.outputFiles?
  292. return
  293. # prepare list of output files for download dropdown
  294. qs = {}
  295. if response.clsiServerId?
  296. qs.clsiserverid = response.clsiServerId
  297. for file in response.outputFiles
  298. if IGNORE_FILES.indexOf(file.path) == -1
  299. isOutputFile = file.path.match(/^output\./)
  300. $scope.pdf.outputFiles.push {
  301. # Turn 'output.blg' into 'blg file'.
  302. name: if isOutputFile then "#{file.path.replace(/^output\./, "")} file" else file.path
  303. url: "/project/#{project_id}/output/#{file.path}" + createQueryString qs
  304. main: if isOutputFile then true else false
  305. }
  306. # sort the output files into order, main files first, then others
  307. $scope.pdf.outputFiles.sort (a,b) -> (b.main - a.main) || a.name.localeCompare(b.name)
  308. fetchLogs = (fileByPath, options) ->
  309. if options?.validation
  310. chktexFile = fileByPath['output.chktex']
  311. else
  312. logFile = fileByPath['output.log']
  313. blgFile = fileByPath['output.blg']
  314. getFile = (name, file) ->
  315. opts =
  316. method:"GET"
  317. params:
  318. compileGroup:ide.compileGroup
  319. clsiserverid:ide.clsiServerId
  320. if file?.url? # FIXME clean this up when we have file.urls out consistently
  321. opts.url = file.url
  322. else if file?.build?
  323. opts.url = "/project/#{$scope.project_id}/build/#{file.build}/output/#{name}"
  324. else
  325. opts.url = "/project/#{$scope.project_id}/output/#{name}"
  326. # check if we need to bust cache (build id is unique so don't need it in that case)
  327. if not file?.build?
  328. opts.params.cache_bust = "#{Date.now()}"
  329. return $http(opts)
  330. # accumulate the log entries
  331. logEntries =
  332. all: []
  333. errors: []
  334. warnings: []
  335. accumulateResults = (newEntries) ->
  336. for key in ['all', 'errors', 'warnings']
  337. if newEntries.type?
  338. entry.type = newEntries.type for entry in newEntries[key]
  339. logEntries[key] = logEntries[key].concat newEntries[key]
  340. # use the parsers for each file type
  341. processLog = (log) ->
  342. $scope.pdf.rawLog = log
  343. {errors, warnings, typesetting} = HumanReadableLogs.parse(log, ignoreDuplicates: true)
  344. all = [].concat errors, warnings, typesetting
  345. accumulateResults {all, errors, warnings}
  346. processChkTex = (log) ->
  347. errors = []
  348. warnings = []
  349. for line in log.split("\n")
  350. if m = line.match /^(\S+):(\d+):(\d+): (Error|Warning): (.*)/
  351. result = { file:m[1], line:m[2], column:m[3], level:m[4].toLowerCase(), message: "#{m[4]}: #{m[5]}"}
  352. if result.level is 'error'
  353. errors.push result
  354. else
  355. warnings.push result
  356. all = [].concat errors, warnings
  357. logHints = HumanReadableLogs.parse {type: "Syntax", all, errors, warnings}
  358. event_tracking.sendMB "syntax-check-return-count", {errors:errors.length, warnings:warnings.length}
  359. accumulateResults logHints
  360. processBiber = (log) ->
  361. {errors, warnings} = BibLogParser.parse(log, {})
  362. all = [].concat errors, warnings
  363. accumulateResults {type: "BibTeX", all, errors, warnings}
  364. # output the results
  365. handleError = () ->
  366. $scope.pdf.logEntries = []
  367. $scope.pdf.rawLog = ""
  368. annotateFiles = () ->
  369. $scope.pdf.logEntries = logEntries
  370. $scope.pdf.logEntryAnnotations = {}
  371. for entry in logEntries.all
  372. if entry.file?
  373. entry.file = normalizeFilePath(entry.file)
  374. entity = ide.fileTreeManager.findEntityByPath(entry.file)
  375. if entity?
  376. $scope.pdf.logEntryAnnotations[entity.id] ||= []
  377. $scope.pdf.logEntryAnnotations[entity.id].push {
  378. row: entry.line - 1
  379. type: if entry.level == "error" then "error" else "warning"
  380. text: entry.message
  381. }
  382. # retrieve the logfile and process it
  383. if logFile?
  384. response = getFile('output.log', logFile)
  385. .then (response) -> processLog(response.data)
  386. if blgFile? # retrieve the blg file if present
  387. response = response.then () ->
  388. getFile('output.blg', blgFile)
  389. .then(
  390. (response) -> processBiber(response.data),
  391. () -> true # ignore errors in biber file
  392. )
  393. if response?
  394. response.catch handleError
  395. else
  396. handleError()
  397. if chktexFile?
  398. getChkTex = () ->
  399. getFile('output.chktex', chktexFile)
  400. .then (response) -> processChkTex(response.data)
  401. # always retrieve the chktex file if present
  402. if response?
  403. response = response.then getChkTex, getChkTex
  404. else
  405. response = getChkTex()
  406. # display the combined result
  407. if response?
  408. response.finally annotateFiles
  409. getRootDocOverride_id = () ->
  410. doc = ide.editorManager.getCurrentDocValue()
  411. return null if !doc?
  412. for line in doc.split("\n")
  413. match = line.match /^[^%]*\\documentclass/
  414. if match
  415. return ide.editorManager.getCurrentDocId()
  416. return null
  417. normalizeFilePath = (path) ->
  418. path = path.replace(/^(.*)\/compiles\/[0-9a-f]{24}(-[0-9a-f]{24})?\/(\.\/)?/, "")
  419. path = path.replace(/^\/compile\//, "")
  420. rootDocDirname = ide.fileTreeManager.getRootDocDirname()
  421. if rootDocDirname?
  422. path = path.replace(/^\.\//, rootDocDirname + "/")
  423. return path
  424. $scope.recompile = (options = {}) ->
  425. return if $scope.pdf.compiling
  426. event_tracking.sendMBSampled "editor-recompile-sampled", options
  427. $scope.lastStartedCompileAt = Date.now()
  428. $scope.pdf.compiling = true
  429. $scope.pdf.isAutoCompileOnLoad = options?.isAutoCompileOnLoad # initial autocompile
  430. if options?.force
  431. # for forced compile, turn off validation check and ignore errors
  432. $scope.stop_on_validation_error = false
  433. $scope.shouldShowLogs = false # hide the logs while compiling
  434. event_tracking.sendMB "syntax-check-turn-off-checking"
  435. if options?.try
  436. $scope.shouldShowLogs = false # hide the logs while compiling
  437. event_tracking.sendMB "syntax-check-try-compile-anyway"
  438. ide.$scope.$broadcast("flush-changes")
  439. options.rootDocOverride_id = getRootDocOverride_id()
  440. sendCompileRequest(options)
  441. .then (response) ->
  442. { data } = response
  443. $scope.pdf.view = "pdf"
  444. $scope.pdf.compiling = false
  445. parseCompileResponse(data)
  446. .catch (response) ->
  447. { data, status } = response
  448. if status == 429
  449. $scope.pdf.rateLimited = true
  450. $scope.pdf.compiling = false
  451. $scope.pdf.renderingError = false
  452. $scope.pdf.error = true
  453. $scope.pdf.view = 'errors'
  454. .finally () ->
  455. $scope.lastFinishedCompileAt = Date.now()
  456. # This needs to be public.
  457. ide.$scope.recompile = $scope.recompile
  458. # This method is a simply wrapper and exists only for tracking purposes.
  459. ide.$scope.recompileViaKey = () ->
  460. $scope.recompile { keyShortcut: true }
  461. $scope.stop = () ->
  462. return if !$scope.pdf.compiling
  463. $http {
  464. url: "/project/#{$scope.project_id}/compile/stop"
  465. method: "POST"
  466. params:
  467. clsiserverid:ide.clsiServerId
  468. headers:
  469. "X-Csrf-Token": window.csrfToken
  470. }
  471. $scope.clearCache = () ->
  472. $http {
  473. url: "/project/#{$scope.project_id}/output"
  474. method: "DELETE"
  475. params:
  476. clsiserverid:ide.clsiServerId
  477. headers:
  478. "X-Csrf-Token": window.csrfToken
  479. }
  480. $scope.toggleLogs = () ->
  481. $scope.shouldShowLogs = !$scope.shouldShowLogs
  482. event_tracking.sendMBOnce "ide-open-logs-once" if $scope.shouldShowLogs
  483. $scope.showPdf = () ->
  484. $scope.pdf.view = "pdf"
  485. $scope.shouldShowLogs = false
  486. $scope.toggleRawLog = () ->
  487. $scope.pdf.showRawLog = !$scope.pdf.showRawLog
  488. event_tracking.sendMB "logs-view-raw" if $scope.pdf.showRawLog
  489. $scope.openClearCacheModal = () ->
  490. modalInstance = $modal.open(
  491. templateUrl: "clearCacheModalTemplate"
  492. controller: "ClearCacheModalController"
  493. scope: $scope
  494. )
  495. $scope.syncToCode = (position) ->
  496. synctex
  497. .syncToCode(position)
  498. .then (data) ->
  499. {doc, line} = data
  500. ide.editorManager.openDoc(doc, gotoLine: line)
  501. $scope.switchToFlatLayout = () ->
  502. $scope.ui.pdfLayout = 'flat'
  503. $scope.ui.view = 'pdf'
  504. ide.localStorage "pdf.layout", "flat"
  505. $scope.switchToSideBySideLayout = () ->
  506. $scope.ui.pdfLayout = 'sideBySide'
  507. $scope.ui.view = 'editor'
  508. localStorage "pdf.layout", "split"
  509. if pdfLayout = localStorage("pdf.layout")
  510. $scope.switchToSideBySideLayout() if pdfLayout == "split"
  511. $scope.switchToFlatLayout() if pdfLayout == "flat"
  512. else
  513. $scope.switchToSideBySideLayout()
  514. App.factory "synctex", ["ide", "$http", "$q", (ide, $http, $q) ->
  515. # enable per-user containers by default
  516. perUserCompile = true
  517. synctex =
  518. syncToPdf: (cursorPosition) ->
  519. deferred = $q.defer()
  520. doc_id = ide.editorManager.getCurrentDocId()
  521. if !doc_id?
  522. deferred.reject()
  523. return deferred.promise
  524. doc = ide.fileTreeManager.findEntityById(doc_id)
  525. if !doc?
  526. deferred.reject()
  527. return deferred.promise
  528. path = ide.fileTreeManager.getEntityPath(doc)
  529. if !path?
  530. deferred.reject()
  531. return deferred.promise
  532. # If the root file is folder/main.tex, then synctex sees the
  533. # path as folder/./main.tex
  534. rootDocDirname = ide.fileTreeManager.getRootDocDirname()
  535. if rootDocDirname? and rootDocDirname != ""
  536. path = path.replace(RegExp("^#{rootDocDirname}"), "#{rootDocDirname}/.")
  537. {row, column} = cursorPosition
  538. $http({
  539. url: "/project/#{ide.project_id}/sync/code",
  540. method: "GET",
  541. params: {
  542. file: path
  543. line: row + 1
  544. column: column
  545. clsiserverid:ide.clsiServerId
  546. }
  547. })
  548. .then (response) ->
  549. { data } = response
  550. deferred.resolve(data.pdf or [])
  551. .catch (response) ->
  552. error = response.data
  553. deferred.reject(error)
  554. return deferred.promise
  555. syncToCode: (position, options = {}) ->
  556. deferred = $q.defer()
  557. if !position?
  558. deferred.reject()
  559. return deferred.promise
  560. # FIXME: this actually works better if it's halfway across the
  561. # page (or the visible part of the page). Synctex doesn't
  562. # always find the right place in the file when the point is at
  563. # the edge of the page, it sometimes returns the start of the
  564. # next paragraph instead.
  565. h = position.offset.left
  566. # Compute the vertical position to pass to synctex, which
  567. # works with coordinates increasing from the top of the page
  568. # down. This matches the browser's DOM coordinate of the
  569. # click point, but the pdf position is measured from the
  570. # bottom of the page so we need to invert it.
  571. if options.fromPdfPosition and position.pageSize?.height?
  572. v = (position.pageSize.height - position.offset.top) or 0 # measure from pdf point (inverted)
  573. else
  574. v = position.offset.top or 0 # measure from html click position
  575. # It's not clear exactly where we should sync to if it wasn't directly
  576. # clicked on, but a little bit down from the very top seems best.
  577. if options.includeVisualOffset
  578. v += 72 # use the same value as in pdfViewer highlighting visual offset
  579. $http({
  580. url: "/project/#{ide.project_id}/sync/pdf",
  581. method: "GET",
  582. params: {
  583. page: position.page + 1
  584. h: h.toFixed(2)
  585. v: v.toFixed(2)
  586. clsiserverid:ide.clsiServerId
  587. }
  588. })
  589. .then (response) ->
  590. { data } = response
  591. if data.code? and data.code.length > 0
  592. doc = ide.fileTreeManager.findEntityByPath(data.code[0].file)
  593. return if !doc?
  594. deferred.resolve({doc: doc, line: data.code[0].line})
  595. .catch (response) ->
  596. error = response.data
  597. deferred.reject(error)
  598. return deferred.promise
  599. return synctex
  600. ]
  601. App.controller "PdfSynctexController", ["$scope", "synctex", "ide", ($scope, synctex, ide) ->
  602. @cursorPosition = null
  603. ide.$scope.$on "cursor:editor:update", (event, @cursorPosition) =>
  604. $scope.syncToPdf = () =>
  605. return if !@cursorPosition?
  606. synctex
  607. .syncToPdf(@cursorPosition)
  608. .then (highlights) ->
  609. $scope.pdf.highlights = highlights
  610. $scope.syncToCode = () ->
  611. synctex
  612. .syncToCode($scope.pdf.position, includeVisualOffset: true, fromPdfPosition: true)
  613. .then (data) ->
  614. {doc, line} = data
  615. ide.editorManager.openDoc(doc, gotoLine: line)
  616. ]
  617. App.controller "PdfLogEntryController", ["$scope", "ide", "event_tracking", ($scope, ide, event_tracking) ->
  618. $scope.openInEditor = (entry) ->
  619. event_tracking.sendMBOnce "logs-jump-to-location-once"
  620. entity = ide.fileTreeManager.findEntityByPath(entry.file)
  621. return if !entity? or entity.type != "doc"
  622. if entry.line?
  623. line = entry.line
  624. if entry.column?
  625. column = entry.column
  626. ide.editorManager.openDoc(entity, gotoLine: line, gotoColumn: column)
  627. ]
  628. App.controller 'ClearCacheModalController', ["$scope", "$modalInstance", ($scope, $modalInstance) ->
  629. $scope.state =
  630. inflight: false
  631. $scope.clear = () ->
  632. $scope.state.inflight = true
  633. $scope
  634. .clearCache()
  635. .then () ->
  636. $scope.state.inflight = false
  637. $modalInstance.close()
  638. $scope.cancel = () ->
  639. $modalInstance.dismiss('cancel')
  640. ]