PdfController.coffee 22 KB

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