PdfController.coffee 23 KB

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