PdfController.coffee 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. define [
  2. "base"
  3. "ace/ace"
  4. "ide/human-readable-logs/HumanReadableLogs"
  5. "libs/bib-log-parser"
  6. ], (App, Ace, HumanReadableLogs, BibLogParser) ->
  7. AUTO_COMPILE_MAX_WAIT = 5000
  8. # We add a 1 second debounce to sending user changes to server if they aren't
  9. # collaborating with anyone. This needs to be higher than that, and allow for
  10. # client to server latency, otherwise we compile before the op reaches the server
  11. # and then again on ack.
  12. AUTO_COMPILE_DEBOUNCE = 2000
  13. App.filter('trusted', ['$sce', ($sce)->
  14. return (url)-> return $sce.trustAsResourceUrl(url);
  15. ])
  16. App.controller "PdfController", ($scope, $http, ide, $modal, synctex, event_tracking, localStorage) ->
  17. # enable per-user containers by default
  18. perUserCompile = true
  19. autoCompile = true
  20. # pdf.view = uncompiled | pdf | errors
  21. $scope.pdf.view = if $scope?.pdf?.url then 'pdf' else 'uncompiled'
  22. $scope.shouldShowLogs = false
  23. $scope.wikiEnabled = window.wikiEnabled;
  24. # view logic to check whether the files dropdown should "drop up" or "drop down"
  25. $scope.shouldDropUp = false
  26. logsContainerEl = document.querySelector ".pdf-logs"
  27. filesDropdownEl = logsContainerEl?.querySelector ".files-dropdown"
  28. # get the top coordinate of the files dropdown as a ratio (to the logs container height)
  29. # logs container supports scrollable content, so it's possible that ratio > 1.
  30. getFilesDropdownTopCoordAsRatio = () ->
  31. filesDropdownEl?.getBoundingClientRect().top / logsContainerEl?.getBoundingClientRect().height
  32. $scope.$watch "shouldShowLogs", (shouldShow) ->
  33. if shouldShow
  34. $scope.$applyAsync () ->
  35. $scope.shouldDropUp = getFilesDropdownTopCoordAsRatio() > 0.65
  36. $scope.trackLogHintsLearnMore = () ->
  37. event_tracking.sendMB "logs-hints-learn-more"
  38. if ace.require("ace/lib/useragent").isMac
  39. $scope.modifierKey = "Cmd"
  40. else
  41. $scope.modifierKey = "Ctrl"
  42. # utility for making a query string from a hash, could use jquery $.param
  43. createQueryString = (args) ->
  44. qs_args = ("#{k}=#{v}" for k, v of args)
  45. if qs_args.length then "?" + qs_args.join("&") else ""
  46. $scope.stripHTMLFromString = (htmlStr) ->
  47. tmp = document.createElement("DIV")
  48. tmp.innerHTML = htmlStr
  49. return tmp.textContent || tmp.innerText || ""
  50. $scope.$on "project:joined", () ->
  51. return if !autoCompile
  52. autoCompile = false
  53. $scope.recompile(isAutoCompileOnLoad: true)
  54. $scope.hasPremiumCompile = $scope.project.features.compileGroup == "priority"
  55. $scope.$on "pdf:error:display", () ->
  56. $scope.pdf.view = 'errors'
  57. $scope.pdf.renderingError = true
  58. autoCompileInterval = null
  59. autoCompileIfReady = () ->
  60. if $scope.pdf.compiling
  61. return
  62. # Only checking linting if syntaxValidation is on and visible to the user
  63. autoCompileLintingError = ide.$scope.hasLintingError and ide.$scope.settings.syntaxValidation
  64. if $scope.autoCompileLintingError != autoCompileLintingError
  65. $scope.$apply () ->
  66. $scope.autoCompileLintingError = autoCompileLintingError
  67. # We've likely been waiting a while until the user fixed the linting, but we
  68. # don't want to compile as soon as it is fixed, so reset the timeout.
  69. $scope.startedTryingAutoCompileAt = Date.now()
  70. $scope.docLastChangedAt = Date.now()
  71. if autoCompileLintingError and $scope.stop_on_validation_error
  72. return
  73. # If there's a longish compile, don't compile immediately after if user is still typing
  74. startedTryingAt = Math.max($scope.startedTryingAutoCompileAt, $scope.lastFinishedCompileAt || 0)
  75. timeSinceStartedTrying = Date.now() - startedTryingAt
  76. timeSinceLastChange = Date.now() - $scope.docLastChangedAt
  77. shouldCompile = false
  78. if timeSinceLastChange > AUTO_COMPILE_DEBOUNCE # Don't compile in the middle of the user typing
  79. shouldCompile = true
  80. else if timeSinceStartedTrying > AUTO_COMPILE_MAX_WAIT # Unless they type for a long time
  81. shouldCompile = true
  82. else if timeSinceStartedTrying < 0 or timeSinceLastChange < 0
  83. # If time is non-monotonic, assume that the user's system clock has been
  84. # changed and continue with compile
  85. shouldCompile = true
  86. if shouldCompile
  87. triggerAutoCompile()
  88. triggerAutoCompile = () ->
  89. $scope.recompile(isAutoCompileOnChange: true)
  90. startTryingAutoCompile = () ->
  91. return if autoCompileInterval?
  92. $scope.startedTryingAutoCompileAt = Date.now()
  93. autoCompileInterval = setInterval autoCompileIfReady, 200
  94. stopTryingAutoCompile = () ->
  95. clearInterval autoCompileInterval
  96. autoCompileInterval = null
  97. $scope.$watch "uncompiledChanges", (uncompiledChanges) ->
  98. if uncompiledChanges
  99. startTryingAutoCompile()
  100. else
  101. stopTryingAutoCompile()
  102. $scope.uncompiledChanges = false
  103. recalculateUncompiledChanges = () ->
  104. if $scope.ui.pdfHidden
  105. # Don't bother auto-compiling if pdf isn't visible
  106. $scope.uncompiledChanges = false
  107. else if !$scope.docLastChangedAt?
  108. $scope.uncompiledChanges = false
  109. else if !$scope.lastStartedCompileAt? or $scope.docLastChangedAt > $scope.lastStartedCompileAt
  110. $scope.uncompiledChanges = true
  111. else
  112. $scope.uncompiledChanges = false
  113. _updateDocLastChangedAt = () ->
  114. $scope.docLastChangedAt = Date.now()
  115. recalculateUncompiledChanges()
  116. onDocChanged = () ->
  117. $scope.autoCompileLintingError = false
  118. _updateDocLastChangedAt()
  119. onDocSaved = () ->
  120. # We use the save as a trigger too, to account for the delay between the client
  121. # and server. Otherwise, we might have compiled after the user made
  122. # the change on the client, but before the server had it.
  123. _updateDocLastChangedAt()
  124. onCompilingStateChanged = (compiling) ->
  125. recalculateUncompiledChanges()
  126. autoCompileListeners = []
  127. toggleAutoCompile = (enabling) ->
  128. if enabling
  129. autoCompileListeners = [
  130. ide.$scope.$on "doc:changed", onDocChanged
  131. ide.$scope.$on "doc:saved", onDocSaved
  132. $scope.$watch "pdf.compiling", onCompilingStateChanged
  133. ]
  134. else
  135. for unbind in autoCompileListeners
  136. unbind()
  137. autoCompileListeners = []
  138. $scope.autoCompileLintingError = false
  139. $scope.autocompile_enabled = localStorage("autocompile_enabled:#{$scope.project_id}") or false
  140. $scope.$watch "autocompile_enabled", (newValue, oldValue) ->
  141. if newValue? and oldValue != newValue
  142. localStorage("autocompile_enabled:#{$scope.project_id}", newValue)
  143. toggleAutoCompile(newValue)
  144. event_tracking.sendMB "autocompile-setting-changed", { value: newValue }
  145. if $scope.autocompile_enabled
  146. toggleAutoCompile(true)
  147. # abort compile if syntax checks fail
  148. $scope.stop_on_validation_error = localStorage("stop_on_validation_error:#{$scope.project_id}")
  149. $scope.stop_on_validation_error ?= true # turn on for all users by default
  150. $scope.$watch "stop_on_validation_error", (new_value, old_value) ->
  151. if new_value? and old_value != new_value
  152. localStorage("stop_on_validation_error:#{$scope.project_id}", new_value)
  153. $scope.draft = localStorage("draft:#{$scope.project_id}") or false
  154. $scope.$watch "draft", (new_value, old_value) ->
  155. if new_value? and old_value != new_value
  156. localStorage("draft:#{$scope.project_id}", new_value)
  157. sendCompileRequest = (options = {}) ->
  158. url = "/project/#{$scope.project_id}/compile"
  159. params = {}
  160. if options.isAutoCompileOnLoad or options.isAutoCompileOnChange
  161. params["auto_compile"]=true
  162. # if the previous run was a check, clear the error logs
  163. $scope.pdf.logEntries = [] if $scope.check
  164. # keep track of whether this is a compile or check
  165. $scope.check = if options.check then true else false
  166. event_tracking.sendMB "syntax-check-request" if options.check
  167. # send appropriate check type to clsi
  168. checkType = switch
  169. when $scope.check then "validate" # validate only
  170. when options.try then "silent" # allow use to try compile once
  171. when $scope.stop_on_validation_error then "error" # try to compile
  172. else "silent" # ignore errors
  173. return $http.post url, {
  174. rootDoc_id: options.rootDocOverride_id or null
  175. draft: $scope.draft
  176. check: checkType
  177. # use incremental compile for all users but revert to a full
  178. # compile if there is a server error
  179. incrementalCompilesEnabled: not $scope.pdf.error
  180. _csrf: window.csrfToken
  181. }, {params: params}
  182. buildPdfDownloadUrl = (pdfDownloadDomain, path)->
  183. #we only download builds from compiles server for security reasons
  184. if pdfDownloadDomain? and path? and path.indexOf("build") != -1
  185. return "#{pdfDownloadDomain}#{path}"
  186. else
  187. return path
  188. parseCompileResponse = (response) ->
  189. # keep last url
  190. last_pdf_url = $scope.pdf.url
  191. pdfDownloadDomain = response.pdfDownloadDomain
  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, {pdfDownloadDomain:pdfDownloadDomain})
  223. else if response.status == "terminated"
  224. $scope.pdf.view = 'errors'
  225. $scope.pdf.compileTerminated = true
  226. fetchLogs(fileByPath, {pdfDownloadDomain:pdfDownloadDomain})
  227. else if response.status in ["validation-fail", "validation-pass"]
  228. $scope.pdf.view = 'pdf'
  229. $scope.pdf.url = buildPdfDownloadUrl pdfDownloadDomain, 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, pdfDownloadDomain:pdfDownloadDomain})
  234. else if response.status == "exited"
  235. $scope.pdf.view = 'pdf'
  236. $scope.pdf.compileExited = true
  237. $scope.pdf.url = buildPdfDownloadUrl pdfDownloadDomain, last_pdf_url
  238. $scope.shouldShowLogs = true
  239. fetchLogs(fileByPath, {pdfDownloadDomain:pdfDownloadDomain})
  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, {pdfDownloadDomain:pdfDownloadDomain})
  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 = buildPdfDownloadUrl pdfDownloadDomain, fileByPath['output.pdf'].url
  275. else if fileByPath['output.pdf']?.build?
  276. build = fileByPath['output.pdf'].build
  277. $scope.pdf.url = buildPdfDownloadUrl pdfDownloadDomain, "/project/#{$scope.project_id}/build/#{build}/output/output.pdf"
  278. else
  279. $scope.pdf.url = buildPdfDownloadUrl pdfDownloadDomain, "/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, {pdfDownloadDomain:pdfDownloadDomain})
  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 = /^output\./.test(file.path)
  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. opts.url = buildPdfDownloadUrl options.pdfDownloadDomain, opts.url
  330. return $http(opts)
  331. # accumulate the log entries
  332. logEntries =
  333. all: []
  334. errors: []
  335. warnings: []
  336. accumulateResults = (newEntries) ->
  337. for key in ['all', 'errors', 'warnings']
  338. if newEntries.type?
  339. entry.type = newEntries.type for entry in newEntries[key]
  340. logEntries[key] = logEntries[key].concat newEntries[key]
  341. # use the parsers for each file type
  342. processLog = (log) ->
  343. $scope.pdf.rawLog = log
  344. {errors, warnings, typesetting} = HumanReadableLogs.parse(log, ignoreDuplicates: true)
  345. all = [].concat errors, warnings, typesetting
  346. accumulateResults {all, errors, warnings}
  347. processChkTex = (log) ->
  348. errors = []
  349. warnings = []
  350. for line in log.split("\n")
  351. if m = line.match /^(\S+):(\d+):(\d+): (Error|Warning): (.*)/
  352. result = { file:m[1], line:m[2], column:m[3], level:m[4].toLowerCase(), message: "#{m[4]}: #{m[5]}"}
  353. if result.level is 'error'
  354. errors.push result
  355. else
  356. warnings.push result
  357. all = [].concat errors, warnings
  358. logHints = HumanReadableLogs.parse {type: "Syntax", all, errors, warnings}
  359. event_tracking.sendMB "syntax-check-return-count", {errors:errors.length, warnings:warnings.length}
  360. accumulateResults logHints
  361. processBiber = (log) ->
  362. {errors, warnings} = BibLogParser.parse(log, {})
  363. all = [].concat errors, warnings
  364. accumulateResults {type: "BibTeX", all, errors, warnings}
  365. # output the results
  366. handleError = () ->
  367. $scope.pdf.logEntries = []
  368. $scope.pdf.rawLog = ""
  369. annotateFiles = () ->
  370. $scope.pdf.logEntries = logEntries
  371. $scope.pdf.logEntryAnnotations = {}
  372. for entry in logEntries.all
  373. if entry.file?
  374. entry.file = normalizeFilePath(entry.file)
  375. entity = ide.fileTreeManager.findEntityByPath(entry.file)
  376. if entity?
  377. $scope.pdf.logEntryAnnotations[entity.id] ||= []
  378. $scope.pdf.logEntryAnnotations[entity.id].push {
  379. row: entry.line - 1
  380. type: if entry.level == "error" then "error" else "warning"
  381. text: entry.message
  382. }
  383. # retrieve the logfile and process it
  384. if logFile?
  385. response = getFile('output.log', logFile)
  386. .then (response) -> processLog(response.data)
  387. if blgFile? # retrieve the blg file if present
  388. response = response.then () ->
  389. getFile('output.blg', blgFile)
  390. .then(
  391. (response) -> processBiber(response.data),
  392. () -> true # ignore errors in biber file
  393. )
  394. if response?
  395. response.catch handleError
  396. else
  397. handleError()
  398. if chktexFile?
  399. getChkTex = () ->
  400. getFile('output.chktex', chktexFile)
  401. .then (response) -> processChkTex(response.data)
  402. # always retrieve the chktex file if present
  403. if response?
  404. response = response.then getChkTex, getChkTex
  405. else
  406. response = getChkTex()
  407. # display the combined result
  408. if response?
  409. response.finally annotateFiles
  410. getRootDocOverride_id = () ->
  411. doc = ide.editorManager.getCurrentDocValue()
  412. return null if !doc?
  413. for line in doc.split("\n")
  414. if /^[^%]*\\documentclass/.test(line)
  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. ide.$scope.$on "cursor:editor:syncToPdf", $scope.syncToPdf
  611. $scope.syncToCode = () ->
  612. synctex
  613. .syncToCode($scope.pdf.position, includeVisualOffset: true, fromPdfPosition: true)
  614. .then (data) ->
  615. {doc, line} = data
  616. ide.editorManager.openDoc(doc, gotoLine: line)
  617. ]
  618. App.controller "PdfLogEntryController", ["$scope", "ide", "event_tracking", ($scope, ide, event_tracking) ->
  619. $scope.openInEditor = (entry) ->
  620. event_tracking.sendMBOnce "logs-jump-to-location-once"
  621. entity = ide.fileTreeManager.findEntityByPath(entry.file)
  622. return if !entity? or entity.type != "doc"
  623. if entry.line?
  624. line = entry.line
  625. if entry.column?
  626. column = entry.column
  627. ide.editorManager.openDoc(entity, gotoLine: line, gotoColumn: column)
  628. ]
  629. App.controller 'ClearCacheModalController', ["$scope", "$modalInstance", ($scope, $modalInstance) ->
  630. $scope.state =
  631. inflight: false
  632. $scope.clear = () ->
  633. $scope.state.inflight = true
  634. $scope
  635. .clearCache()
  636. .then () ->
  637. $scope.state.inflight = false
  638. $modalInstance.close()
  639. $scope.cancel = () ->
  640. $modalInstance.dismiss('cancel')
  641. ]