PdfController.coffee 23 KB

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