PdfController.coffee 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  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. pdfDownloadDomain = response.pdfDownloadDomain
  193. # Reset everything
  194. $scope.pdf.error = false
  195. $scope.pdf.timedout = false
  196. $scope.pdf.failure = false
  197. $scope.pdf.url = null
  198. $scope.pdf.clsiMaintenance = false
  199. $scope.pdf.tooRecentlyCompiled = false
  200. $scope.pdf.renderingError = false
  201. $scope.pdf.projectTooLarge = false
  202. $scope.pdf.compileTerminated = false
  203. $scope.pdf.compileExited = false
  204. $scope.pdf.failedCheck = false
  205. $scope.pdf.compileInProgress = false
  206. $scope.pdf.autoCompileDisabled = false
  207. buildPdfDownloadUrl = (path)->
  208. if pdfDownloadDomain?
  209. return "#{pdfDownloadDomain}#{path}"
  210. else
  211. return path
  212. # make a cache to look up files by name
  213. fileByPath = {}
  214. if response?.outputFiles?
  215. for file in response?.outputFiles
  216. fileByPath[file.path] = file
  217. # prepare query string
  218. qs = {}
  219. # add a query string parameter for the compile group
  220. if response.compileGroup?
  221. ide.compileGroup = qs.compileGroup = response.compileGroup
  222. # add a query string parameter for the clsi server id
  223. if response.clsiServerId?
  224. ide.clsiServerId = qs.clsiserverid = response.clsiServerId
  225. if response.status == "timedout"
  226. $scope.pdf.view = 'errors'
  227. $scope.pdf.timedout = true
  228. fetchLogs(fileByPath)
  229. else if response.status == "terminated"
  230. $scope.pdf.view = 'errors'
  231. $scope.pdf.compileTerminated = true
  232. fetchLogs(fileByPath)
  233. else if response.status in ["validation-fail", "validation-pass"]
  234. $scope.pdf.view = 'pdf'
  235. $scope.pdf.url = buildPdfDownloadUrl last_pdf_url
  236. $scope.shouldShowLogs = true
  237. $scope.pdf.failedCheck = true if response.status is "validation-fail"
  238. event_tracking.sendMB "syntax-check-#{response.status}"
  239. fetchLogs(fileByPath, { validation: true })
  240. else if response.status == "exited"
  241. $scope.pdf.view = 'pdf'
  242. $scope.pdf.compileExited = true
  243. $scope.pdf.url = buildPdfDownloadUrl last_pdf_url
  244. $scope.shouldShowLogs = true
  245. fetchLogs(fileByPath)
  246. else if response.status == "autocompile-backoff"
  247. if $scope.pdf.isAutoCompileOnLoad # initial autocompile
  248. $scope.pdf.view = 'uncompiled'
  249. else # background autocompile from typing
  250. $scope.pdf.view = 'errors'
  251. $scope.pdf.autoCompileDisabled = true
  252. $scope.autocompile_enabled = false # disable any further autocompiles
  253. event_tracking.sendMB "autocompile-rate-limited", {hasPremiumCompile: $scope.hasPremiumCompile}
  254. else if response.status == "project-too-large"
  255. $scope.pdf.view = 'errors'
  256. $scope.pdf.projectTooLarge = true
  257. else if response.status == "failure"
  258. $scope.pdf.view = 'errors'
  259. $scope.pdf.failure = true
  260. $scope.shouldShowLogs = true
  261. fetchLogs(fileByPath)
  262. else if response.status == 'clsi-maintenance'
  263. $scope.pdf.view = 'errors'
  264. $scope.pdf.clsiMaintenance = true
  265. else if response.status == "too-recently-compiled"
  266. $scope.pdf.view = 'errors'
  267. $scope.pdf.tooRecentlyCompiled = true
  268. else if response.status == "validation-problems"
  269. $scope.pdf.view = "validation-problems"
  270. $scope.pdf.validation = response.validationProblems
  271. $scope.shouldShowLogs = false
  272. else if response.status == "compile-in-progress"
  273. $scope.pdf.view = 'errors'
  274. $scope.pdf.compileInProgress = true
  275. else if response.status == "success"
  276. $scope.pdf.view = 'pdf'
  277. $scope.shouldShowLogs = false
  278. # define the base url. if the pdf file has a build number, pass it to the clsi in the url
  279. if fileByPath['output.pdf']?.url?
  280. $scope.pdf.url = buildPdfDownloadUrl fileByPath['output.pdf'].url
  281. else if fileByPath['output.pdf']?.build?
  282. build = fileByPath['output.pdf'].build
  283. $scope.pdf.url = buildPdfDownloadUrl "/project/#{$scope.project_id}/build/#{build}/output/output.pdf"
  284. else
  285. $scope.pdf.url = buildPdfDownloadUrl "/project/#{$scope.project_id}/output/output.pdf"
  286. # check if we need to bust cache (build id is unique so don't need it in that case)
  287. if not fileByPath['output.pdf']?.build?
  288. qs.cache_bust = "#{Date.now()}"
  289. # convert the qs hash into a query string and append it
  290. $scope.pdf.url += createQueryString qs
  291. # Save all downloads as files
  292. qs.popupDownload = true
  293. $scope.pdf.downloadUrl = "/project/#{$scope.project_id}/output/output.pdf" + createQueryString(qs)
  294. fetchLogs(fileByPath)
  295. IGNORE_FILES = ["output.fls", "output.fdb_latexmk"]
  296. $scope.pdf.outputFiles = []
  297. if !response.outputFiles?
  298. return
  299. # prepare list of output files for download dropdown
  300. qs = {}
  301. if response.clsiServerId?
  302. qs.clsiserverid = response.clsiServerId
  303. for file in response.outputFiles
  304. if IGNORE_FILES.indexOf(file.path) == -1
  305. isOutputFile = file.path.match(/^output\./)
  306. $scope.pdf.outputFiles.push {
  307. # Turn 'output.blg' into 'blg file'.
  308. name: if isOutputFile then "#{file.path.replace(/^output\./, "")} file" else file.path
  309. url: "/project/#{project_id}/output/#{file.path}" + createQueryString qs
  310. main: if isOutputFile then true else false
  311. }
  312. # sort the output files into order, main files first, then others
  313. $scope.pdf.outputFiles.sort (a,b) -> (b.main - a.main) || a.name.localeCompare(b.name)
  314. fetchLogs = (fileByPath, options) ->
  315. if options?.validation
  316. chktexFile = fileByPath['output.chktex']
  317. else
  318. logFile = fileByPath['output.log']
  319. blgFile = fileByPath['output.blg']
  320. getFile = (name, file) ->
  321. opts =
  322. method:"GET"
  323. params:
  324. compileGroup:ide.compileGroup
  325. clsiserverid:ide.clsiServerId
  326. if file?.url? # FIXME clean this up when we have file.urls out consistently
  327. opts.url = file.url
  328. else if file?.build?
  329. opts.url = "/project/#{$scope.project_id}/build/#{file.build}/output/#{name}"
  330. else
  331. opts.url = "/project/#{$scope.project_id}/output/#{name}"
  332. # check if we need to bust cache (build id is unique so don't need it in that case)
  333. if not file?.build?
  334. opts.params.cache_bust = "#{Date.now()}"
  335. return $http(opts)
  336. # accumulate the log entries
  337. logEntries =
  338. all: []
  339. errors: []
  340. warnings: []
  341. accumulateResults = (newEntries) ->
  342. for key in ['all', 'errors', 'warnings']
  343. if newEntries.type?
  344. entry.type = newEntries.type for entry in newEntries[key]
  345. logEntries[key] = logEntries[key].concat newEntries[key]
  346. # use the parsers for each file type
  347. processLog = (log) ->
  348. $scope.pdf.rawLog = log
  349. {errors, warnings, typesetting} = HumanReadableLogs.parse(log, ignoreDuplicates: true)
  350. all = [].concat errors, warnings, typesetting
  351. accumulateResults {all, errors, warnings}
  352. processChkTex = (log) ->
  353. errors = []
  354. warnings = []
  355. for line in log.split("\n")
  356. if m = line.match /^(\S+):(\d+):(\d+): (Error|Warning): (.*)/
  357. result = { file:m[1], line:m[2], column:m[3], level:m[4].toLowerCase(), message: "#{m[4]}: #{m[5]}"}
  358. if result.level is 'error'
  359. errors.push result
  360. else
  361. warnings.push result
  362. all = [].concat errors, warnings
  363. logHints = HumanReadableLogs.parse {type: "Syntax", all, errors, warnings}
  364. event_tracking.sendMB "syntax-check-return-count", {errors:errors.length, warnings:warnings.length}
  365. accumulateResults logHints
  366. processBiber = (log) ->
  367. {errors, warnings} = BibLogParser.parse(log, {})
  368. all = [].concat errors, warnings
  369. accumulateResults {type: "BibTeX", all, errors, warnings}
  370. # output the results
  371. handleError = () ->
  372. $scope.pdf.logEntries = []
  373. $scope.pdf.rawLog = ""
  374. annotateFiles = () ->
  375. $scope.pdf.logEntries = logEntries
  376. $scope.pdf.logEntryAnnotations = {}
  377. for entry in logEntries.all
  378. if entry.file?
  379. entry.file = normalizeFilePath(entry.file)
  380. entity = ide.fileTreeManager.findEntityByPath(entry.file)
  381. if entity?
  382. $scope.pdf.logEntryAnnotations[entity.id] ||= []
  383. $scope.pdf.logEntryAnnotations[entity.id].push {
  384. row: entry.line - 1
  385. type: if entry.level == "error" then "error" else "warning"
  386. text: entry.message
  387. }
  388. # retrieve the logfile and process it
  389. if logFile?
  390. response = getFile('output.log', logFile)
  391. .then (response) -> processLog(response.data)
  392. if blgFile? # retrieve the blg file if present
  393. response = response.then () ->
  394. getFile('output.blg', blgFile)
  395. .then(
  396. (response) -> processBiber(response.data),
  397. () -> true # ignore errors in biber file
  398. )
  399. if response?
  400. response.catch handleError
  401. else
  402. handleError()
  403. if chktexFile?
  404. getChkTex = () ->
  405. getFile('output.chktex', chktexFile)
  406. .then (response) -> processChkTex(response.data)
  407. # always retrieve the chktex file if present
  408. if response?
  409. response = response.then getChkTex, getChkTex
  410. else
  411. response = getChkTex()
  412. # display the combined result
  413. if response?
  414. response.finally annotateFiles
  415. getRootDocOverride_id = () ->
  416. doc = ide.editorManager.getCurrentDocValue()
  417. return null if !doc?
  418. for line in doc.split("\n")
  419. match = line.match /^[^%]*\\documentclass/
  420. if match
  421. return ide.editorManager.getCurrentDocId()
  422. return null
  423. normalizeFilePath = (path) ->
  424. path = path.replace(/^(.*)\/compiles\/[0-9a-f]{24}(-[0-9a-f]{24})?\/(\.\/)?/, "")
  425. path = path.replace(/^\/compile\//, "")
  426. rootDocDirname = ide.fileTreeManager.getRootDocDirname()
  427. if rootDocDirname?
  428. path = path.replace(/^\.\//, rootDocDirname + "/")
  429. return path
  430. $scope.recompile = (options = {}) ->
  431. return if $scope.pdf.compiling
  432. event_tracking.sendMBSampled "editor-recompile-sampled", options
  433. $scope.lastStartedCompileAt = Date.now()
  434. $scope.pdf.compiling = true
  435. $scope.pdf.isAutoCompileOnLoad = options?.isAutoCompileOnLoad # initial autocompile
  436. if options?.force
  437. # for forced compile, turn off validation check and ignore errors
  438. $scope.stop_on_validation_error = false
  439. $scope.shouldShowLogs = false # hide the logs while compiling
  440. event_tracking.sendMB "syntax-check-turn-off-checking"
  441. if options?.try
  442. $scope.shouldShowLogs = false # hide the logs while compiling
  443. event_tracking.sendMB "syntax-check-try-compile-anyway"
  444. ide.$scope.$broadcast("flush-changes")
  445. options.rootDocOverride_id = getRootDocOverride_id()
  446. sendCompileRequest(options)
  447. .then (response) ->
  448. { data } = response
  449. $scope.pdf.view = "pdf"
  450. $scope.pdf.compiling = false
  451. parseCompileResponse(data)
  452. .catch (response) ->
  453. { data, status } = response
  454. if status == 429
  455. $scope.pdf.rateLimited = true
  456. $scope.pdf.compiling = false
  457. $scope.pdf.renderingError = false
  458. $scope.pdf.error = true
  459. $scope.pdf.view = 'errors'
  460. .finally () ->
  461. $scope.lastFinishedCompileAt = Date.now()
  462. # This needs to be public.
  463. ide.$scope.recompile = $scope.recompile
  464. # This method is a simply wrapper and exists only for tracking purposes.
  465. ide.$scope.recompileViaKey = () ->
  466. $scope.recompile { keyShortcut: true }
  467. $scope.stop = () ->
  468. return if !$scope.pdf.compiling
  469. $http {
  470. url: "/project/#{$scope.project_id}/compile/stop"
  471. method: "POST"
  472. params:
  473. clsiserverid:ide.clsiServerId
  474. headers:
  475. "X-Csrf-Token": window.csrfToken
  476. }
  477. $scope.clearCache = () ->
  478. $http {
  479. url: "/project/#{$scope.project_id}/output"
  480. method: "DELETE"
  481. params:
  482. clsiserverid:ide.clsiServerId
  483. headers:
  484. "X-Csrf-Token": window.csrfToken
  485. }
  486. $scope.toggleLogs = () ->
  487. $scope.shouldShowLogs = !$scope.shouldShowLogs
  488. event_tracking.sendMBOnce "ide-open-logs-once" if $scope.shouldShowLogs
  489. $scope.showPdf = () ->
  490. $scope.pdf.view = "pdf"
  491. $scope.shouldShowLogs = false
  492. $scope.toggleRawLog = () ->
  493. $scope.pdf.showRawLog = !$scope.pdf.showRawLog
  494. event_tracking.sendMB "logs-view-raw" if $scope.pdf.showRawLog
  495. $scope.openClearCacheModal = () ->
  496. modalInstance = $modal.open(
  497. templateUrl: "clearCacheModalTemplate"
  498. controller: "ClearCacheModalController"
  499. scope: $scope
  500. )
  501. $scope.syncToCode = (position) ->
  502. synctex
  503. .syncToCode(position)
  504. .then (data) ->
  505. {doc, line} = data
  506. ide.editorManager.openDoc(doc, gotoLine: line)
  507. $scope.switchToFlatLayout = () ->
  508. $scope.ui.pdfLayout = 'flat'
  509. $scope.ui.view = 'pdf'
  510. ide.localStorage "pdf.layout", "flat"
  511. $scope.switchToSideBySideLayout = () ->
  512. $scope.ui.pdfLayout = 'sideBySide'
  513. $scope.ui.view = 'editor'
  514. localStorage "pdf.layout", "split"
  515. if pdfLayout = localStorage("pdf.layout")
  516. $scope.switchToSideBySideLayout() if pdfLayout == "split"
  517. $scope.switchToFlatLayout() if pdfLayout == "flat"
  518. else
  519. $scope.switchToSideBySideLayout()
  520. App.factory "synctex", ["ide", "$http", "$q", (ide, $http, $q) ->
  521. # enable per-user containers by default
  522. perUserCompile = true
  523. synctex =
  524. syncToPdf: (cursorPosition) ->
  525. deferred = $q.defer()
  526. doc_id = ide.editorManager.getCurrentDocId()
  527. if !doc_id?
  528. deferred.reject()
  529. return deferred.promise
  530. doc = ide.fileTreeManager.findEntityById(doc_id)
  531. if !doc?
  532. deferred.reject()
  533. return deferred.promise
  534. path = ide.fileTreeManager.getEntityPath(doc)
  535. if !path?
  536. deferred.reject()
  537. return deferred.promise
  538. # If the root file is folder/main.tex, then synctex sees the
  539. # path as folder/./main.tex
  540. rootDocDirname = ide.fileTreeManager.getRootDocDirname()
  541. if rootDocDirname? and rootDocDirname != ""
  542. path = path.replace(RegExp("^#{rootDocDirname}"), "#{rootDocDirname}/.")
  543. {row, column} = cursorPosition
  544. $http({
  545. url: "/project/#{ide.project_id}/sync/code",
  546. method: "GET",
  547. params: {
  548. file: path
  549. line: row + 1
  550. column: column
  551. clsiserverid:ide.clsiServerId
  552. }
  553. })
  554. .then (response) ->
  555. { data } = response
  556. deferred.resolve(data.pdf or [])
  557. .catch (response) ->
  558. error = response.data
  559. deferred.reject(error)
  560. return deferred.promise
  561. syncToCode: (position, options = {}) ->
  562. deferred = $q.defer()
  563. if !position?
  564. deferred.reject()
  565. return deferred.promise
  566. # FIXME: this actually works better if it's halfway across the
  567. # page (or the visible part of the page). Synctex doesn't
  568. # always find the right place in the file when the point is at
  569. # the edge of the page, it sometimes returns the start of the
  570. # next paragraph instead.
  571. h = position.offset.left
  572. # Compute the vertical position to pass to synctex, which
  573. # works with coordinates increasing from the top of the page
  574. # down. This matches the browser's DOM coordinate of the
  575. # click point, but the pdf position is measured from the
  576. # bottom of the page so we need to invert it.
  577. if options.fromPdfPosition and position.pageSize?.height?
  578. v = (position.pageSize.height - position.offset.top) or 0 # measure from pdf point (inverted)
  579. else
  580. v = position.offset.top or 0 # measure from html click position
  581. # It's not clear exactly where we should sync to if it wasn't directly
  582. # clicked on, but a little bit down from the very top seems best.
  583. if options.includeVisualOffset
  584. v += 72 # use the same value as in pdfViewer highlighting visual offset
  585. $http({
  586. url: "/project/#{ide.project_id}/sync/pdf",
  587. method: "GET",
  588. params: {
  589. page: position.page + 1
  590. h: h.toFixed(2)
  591. v: v.toFixed(2)
  592. clsiserverid:ide.clsiServerId
  593. }
  594. })
  595. .then (response) ->
  596. { data } = response
  597. if data.code? and data.code.length > 0
  598. doc = ide.fileTreeManager.findEntityByPath(data.code[0].file)
  599. return if !doc?
  600. deferred.resolve({doc: doc, line: data.code[0].line})
  601. .catch (response) ->
  602. error = response.data
  603. deferred.reject(error)
  604. return deferred.promise
  605. return synctex
  606. ]
  607. App.controller "PdfSynctexController", ["$scope", "synctex", "ide", ($scope, synctex, ide) ->
  608. @cursorPosition = null
  609. ide.$scope.$on "cursor:editor:update", (event, @cursorPosition) =>
  610. $scope.syncToPdf = () =>
  611. return if !@cursorPosition?
  612. synctex
  613. .syncToPdf(@cursorPosition)
  614. .then (highlights) ->
  615. $scope.pdf.highlights = highlights
  616. $scope.syncToCode = () ->
  617. synctex
  618. .syncToCode($scope.pdf.position, includeVisualOffset: true, fromPdfPosition: true)
  619. .then (data) ->
  620. {doc, line} = data
  621. ide.editorManager.openDoc(doc, gotoLine: line)
  622. ]
  623. App.controller "PdfLogEntryController", ["$scope", "ide", "event_tracking", ($scope, ide, event_tracking) ->
  624. $scope.openInEditor = (entry) ->
  625. event_tracking.sendMBOnce "logs-jump-to-location-once"
  626. entity = ide.fileTreeManager.findEntityByPath(entry.file)
  627. return if !entity? or entity.type != "doc"
  628. if entry.line?
  629. line = entry.line
  630. if entry.column?
  631. column = entry.column
  632. ide.editorManager.openDoc(entity, gotoLine: line, gotoColumn: column)
  633. ]
  634. App.controller 'ClearCacheModalController', ["$scope", "$modalInstance", ($scope, $modalInstance) ->
  635. $scope.state =
  636. inflight: false
  637. $scope.clear = () ->
  638. $scope.state.inflight = true
  639. $scope
  640. .clearCache()
  641. .then () ->
  642. $scope.state.inflight = false
  643. $modalInstance.close()
  644. $scope.cancel = () ->
  645. $modalInstance.dismiss('cancel')
  646. ]