PdfController.coffee 24 KB

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