PdfController.js 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  1. import App from '../../../base'
  2. import HumanReadableLogs from '../../human-readable-logs/HumanReadableLogs'
  3. import BibLogParser from 'libs/bib-log-parser'
  4. import 'ace/ace'
  5. const AUTO_COMPILE_MAX_WAIT = 5000
  6. // We add a 1 second debounce to sending user changes to server if they aren't
  7. // collaborating with anyone. This needs to be higher than that, and allow for
  8. // client to server latency, otherwise we compile before the op reaches the server
  9. // and then again on ack.
  10. const AUTO_COMPILE_DEBOUNCE = 2000
  11. App.filter('trusted', $sce => url => $sce.trustAsResourceUrl(url))
  12. App.controller('PdfController', function(
  13. $scope,
  14. $http,
  15. ide,
  16. $modal,
  17. synctex,
  18. eventTracking,
  19. localStorage
  20. ) {
  21. let autoCompile = true
  22. // pdf.view = uncompiled | pdf | errors
  23. $scope.pdf.view = $scope.pdf.url ? 'pdf' : 'uncompiled'
  24. $scope.shouldShowLogs = false
  25. $scope.wikiEnabled = window.wikiEnabled
  26. // view logic to check whether the files dropdown should "drop up" or "drop down"
  27. $scope.shouldDropUp = false
  28. const logsContainerEl = document.querySelector('.pdf-logs')
  29. const filesDropdownEl =
  30. logsContainerEl && logsContainerEl.querySelector('.files-dropdown')
  31. // get the top coordinate of the files dropdown as a ratio (to the logs container height)
  32. // logs container supports scrollable content, so it's possible that ratio > 1.
  33. function getFilesDropdownTopCoordAsRatio() {
  34. if (filesDropdownEl == null || logsContainerEl == null) {
  35. return 0
  36. }
  37. return (
  38. filesDropdownEl.getBoundingClientRect().top /
  39. logsContainerEl.getBoundingClientRect().height
  40. )
  41. }
  42. $scope.$watch('shouldShowLogs', shouldShow => {
  43. if (shouldShow) {
  44. $scope.$applyAsync(() => {
  45. $scope.shouldDropUp = getFilesDropdownTopCoordAsRatio() > 0.65
  46. })
  47. }
  48. })
  49. $scope.trackLogHintsLearnMore = function() {
  50. eventTracking.sendMB('logs-hints-learn-more')
  51. }
  52. if (ace.require('ace/lib/useragent').isMac) {
  53. $scope.modifierKey = 'Cmd'
  54. } else {
  55. $scope.modifierKey = 'Ctrl'
  56. }
  57. // utility for making a query string from a hash, could use jquery $.param
  58. function createQueryString(args) {
  59. const qsArgs = []
  60. for (const k in args) {
  61. const v = args[k]
  62. qsArgs.push(`${k}=${v}`)
  63. }
  64. if (qsArgs.length) {
  65. return `?${qsArgs.join('&')}`
  66. } else {
  67. return ''
  68. }
  69. }
  70. $scope.stripHTMLFromString = function(htmlStr) {
  71. const tmp = document.createElement('DIV')
  72. tmp.innerHTML = htmlStr
  73. return tmp.textContent || tmp.innerText || ''
  74. }
  75. $scope.$on('project:joined', () => {
  76. if (!autoCompile) {
  77. return
  78. }
  79. autoCompile = false
  80. $scope.recompile({ isAutoCompileOnLoad: true })
  81. $scope.hasPremiumCompile =
  82. $scope.project.features.compileGroup === 'priority'
  83. })
  84. $scope.$on('pdf:error:display', function() {
  85. $scope.pdf.view = 'errors'
  86. $scope.pdf.renderingError = true
  87. })
  88. let autoCompileInterval = null
  89. function autoCompileIfReady() {
  90. if (
  91. $scope.pdf.compiling ||
  92. !$scope.autocompile_enabled ||
  93. !$scope.pdf.uncompiled
  94. ) {
  95. return
  96. }
  97. // Only checking linting if syntaxValidation is on and visible to the user
  98. const autoCompileLintingError =
  99. ide.$scope.hasLintingError && ide.$scope.settings.syntaxValidation
  100. if ($scope.autoCompileLintingError !== autoCompileLintingError) {
  101. $scope.$apply(() => {
  102. $scope.autoCompileLintingError = autoCompileLintingError
  103. // We've likely been waiting a while until the user fixed the linting, but we
  104. // don't want to compile as soon as it is fixed, so reset the timeout.
  105. $scope.startedTryingAutoCompileAt = Date.now()
  106. $scope.docLastChangedAt = Date.now()
  107. })
  108. }
  109. if (autoCompileLintingError && $scope.stop_on_validation_error) {
  110. return
  111. }
  112. // If there's a longish compile, don't compile immediately after if user is still typing
  113. const startedTryingAt = Math.max(
  114. $scope.startedTryingAutoCompileAt,
  115. $scope.lastFinishedCompileAt || 0
  116. )
  117. const timeSinceStartedTrying = Date.now() - startedTryingAt
  118. const timeSinceLastChange = Date.now() - $scope.docLastChangedAt
  119. let shouldCompile = false
  120. if (timeSinceLastChange > AUTO_COMPILE_DEBOUNCE) {
  121. // Don't compile in the middle of the user typing
  122. shouldCompile = true
  123. } else if (timeSinceStartedTrying > AUTO_COMPILE_MAX_WAIT) {
  124. // Unless they type for a long time
  125. shouldCompile = true
  126. } else if (timeSinceStartedTrying < 0 || timeSinceLastChange < 0) {
  127. // If time is non-monotonic, assume that the user's system clock has been
  128. // changed and continue with compile
  129. shouldCompile = true
  130. }
  131. if (shouldCompile) {
  132. return triggerAutoCompile()
  133. }
  134. }
  135. function triggerAutoCompile() {
  136. $scope.recompile({ isAutoCompileOnChange: true })
  137. }
  138. function startTryingAutoCompile() {
  139. if (autoCompileInterval != null) {
  140. return
  141. }
  142. $scope.startedTryingAutoCompileAt = Date.now()
  143. autoCompileInterval = setInterval(autoCompileIfReady, 200)
  144. }
  145. function stopTryingAutoCompile() {
  146. clearInterval(autoCompileInterval)
  147. autoCompileInterval = null
  148. }
  149. $scope.changesToAutoCompile = false
  150. $scope.$watch('pdf.uncompiled', uncompiledChanges => {
  151. // don't autocompile if disabled or the pdf is not visible
  152. if (
  153. $scope.pdf.uncompiled &&
  154. $scope.autocompile_enabled &&
  155. !$scope.ui.pdfHidden
  156. ) {
  157. $scope.changesToAutoCompile = true
  158. startTryingAutoCompile()
  159. } else {
  160. $scope.changesToAutoCompile = false
  161. stopTryingAutoCompile()
  162. }
  163. })
  164. function recalculateUncompiledChanges() {
  165. if ($scope.docLastChangedAt == null) {
  166. $scope.pdf.uncompiled = false
  167. } else if (
  168. $scope.lastStartedCompileAt == null ||
  169. $scope.docLastChangedAt > $scope.lastStartedCompileAt
  170. ) {
  171. $scope.pdf.uncompiled = true
  172. } else {
  173. $scope.pdf.uncompiled = false
  174. }
  175. }
  176. function _updateDocLastChangedAt() {
  177. $scope.docLastChangedAt = Date.now()
  178. recalculateUncompiledChanges()
  179. }
  180. function onDocChanged() {
  181. $scope.autoCompileLintingError = false
  182. _updateDocLastChangedAt()
  183. }
  184. function onDocSaved() {
  185. // We use the save as a trigger too, to account for the delay between the client
  186. // and server. Otherwise, we might have compiled after the user made
  187. // the change on the client, but before the server had it.
  188. _updateDocLastChangedAt()
  189. }
  190. function onCompilingStateChanged(compiling) {
  191. recalculateUncompiledChanges()
  192. }
  193. ide.$scope.$on('doc:changed', onDocChanged)
  194. ide.$scope.$on('doc:saved', onDocSaved)
  195. $scope.$watch('pdf.compiling', onCompilingStateChanged)
  196. $scope.autocompile_enabled =
  197. localStorage(`autocompile_enabled:${$scope.project_id}`) || false
  198. $scope.$watch('autocompile_enabled', (newValue, oldValue) => {
  199. if (newValue != null && oldValue !== newValue) {
  200. if (newValue === true) {
  201. autoCompileIfReady()
  202. }
  203. localStorage(`autocompile_enabled:${$scope.project_id}`, newValue)
  204. eventTracking.sendMB('autocompile-setting-changed', {
  205. value: newValue
  206. })
  207. }
  208. })
  209. // abort compile if syntax checks fail
  210. $scope.stop_on_validation_error = localStorage(
  211. `stop_on_validation_error:${$scope.project_id}`
  212. )
  213. if ($scope.stop_on_validation_error == null) {
  214. $scope.stop_on_validation_error = true
  215. }
  216. // turn on for all users by default
  217. $scope.$watch('stop_on_validation_error', (newValue, oldValue) => {
  218. if (newValue != null && oldValue !== newValue) {
  219. localStorage(`stop_on_validation_error:${$scope.project_id}`, newValue)
  220. }
  221. })
  222. $scope.draft = localStorage(`draft:${$scope.project_id}`) || false
  223. $scope.$watch('draft', (newValue, oldValue) => {
  224. if (newValue != null && oldValue !== newValue) {
  225. localStorage(`draft:${$scope.project_id}`, newValue)
  226. }
  227. })
  228. function sendCompileRequest(options) {
  229. if (options == null) {
  230. options = {}
  231. }
  232. const url = `/project/${$scope.project_id}/compile`
  233. const params = {}
  234. if (options.isAutoCompileOnLoad || options.isAutoCompileOnChange) {
  235. params['auto_compile'] = true
  236. }
  237. // if the previous run was a check, clear the error logs
  238. if ($scope.check) {
  239. $scope.pdf.logEntries = []
  240. }
  241. // keep track of whether this is a compile or check
  242. $scope.check = !!options.check
  243. if (options.check) {
  244. eventTracking.sendMB('syntax-check-request')
  245. }
  246. // send appropriate check type to clsi
  247. let checkType
  248. if ($scope.check) {
  249. checkType = 'validate' // validate only
  250. } else if (options.try) {
  251. checkType = 'silent' // allow use to try compile once
  252. } else if ($scope.stop_on_validation_error) {
  253. checkType = 'error' // try to compile
  254. } else {
  255. checkType = 'silent' // ignore errors
  256. }
  257. // FIXME: Temporarily disable syntax checking as it is causing
  258. // excessive support requests for projects migrated from v1
  259. // https://github.com/overleaf/sharelatex/issues/911
  260. if (checkType === 'error') {
  261. checkType = 'silent'
  262. }
  263. return $http.post(
  264. url,
  265. {
  266. rootDoc_id: options.rootDocOverride_id || null,
  267. draft: $scope.draft,
  268. check: checkType,
  269. // use incremental compile for all users but revert to a full
  270. // compile if there is a server error
  271. incrementalCompilesEnabled: !$scope.pdf.error,
  272. _csrf: window.csrfToken
  273. },
  274. { params }
  275. )
  276. }
  277. function buildPdfDownloadUrl(pdfDownloadDomain, path) {
  278. // we only download builds from compiles server for security reasons
  279. if (
  280. pdfDownloadDomain != null &&
  281. path != null &&
  282. path.indexOf('build') !== -1
  283. ) {
  284. return `${pdfDownloadDomain}${path}`
  285. } else {
  286. return path
  287. }
  288. }
  289. function parseCompileResponse(response) {
  290. // keep last url
  291. const lastPdfUrl = $scope.pdf.url
  292. const { pdfDownloadDomain } = response
  293. // Reset everything
  294. $scope.pdf.error = false
  295. $scope.pdf.timedout = false
  296. $scope.pdf.failure = false
  297. $scope.pdf.url = null
  298. $scope.pdf.clsiMaintenance = false
  299. $scope.pdf.tooRecentlyCompiled = false
  300. $scope.pdf.renderingError = false
  301. $scope.pdf.projectTooLarge = false
  302. $scope.pdf.compileTerminated = false
  303. $scope.pdf.compileExited = false
  304. $scope.pdf.failedCheck = false
  305. $scope.pdf.compileInProgress = false
  306. $scope.pdf.autoCompileDisabled = false
  307. // make a cache to look up files by name
  308. const fileByPath = {}
  309. if (response.outputFiles != null) {
  310. for (const file of response.outputFiles) {
  311. fileByPath[file.path] = file
  312. }
  313. }
  314. // prepare query string
  315. let qs = {}
  316. // add a query string parameter for the compile group
  317. if (response.compileGroup != null) {
  318. ide.compileGroup = qs.compileGroup = response.compileGroup
  319. }
  320. // add a query string parameter for the clsi server id
  321. if (response.clsiServerId != null) {
  322. ide.clsiServerId = qs.clsiserverid = response.clsiServerId
  323. }
  324. if (response.status === 'timedout') {
  325. $scope.pdf.view = 'errors'
  326. $scope.pdf.timedout = true
  327. fetchLogs(fileByPath, { pdfDownloadDomain })
  328. if (
  329. !$scope.hasPremiumCompile &&
  330. ide.$scope.project.owner._id === ide.$scope.user.id
  331. ) {
  332. eventTracking.send(
  333. 'subscription-funnel',
  334. 'editor-click-feature',
  335. 'compile-timeout'
  336. )
  337. }
  338. } else if (response.status === 'terminated') {
  339. $scope.pdf.view = 'errors'
  340. $scope.pdf.compileTerminated = true
  341. fetchLogs(fileByPath, { pdfDownloadDomain })
  342. } else if (
  343. ['validation-fail', 'validation-pass'].includes(response.status)
  344. ) {
  345. $scope.pdf.view = 'pdf'
  346. $scope.pdf.url = buildPdfDownloadUrl(pdfDownloadDomain, lastPdfUrl)
  347. $scope.shouldShowLogs = true
  348. if (response.status === 'validation-fail') {
  349. $scope.pdf.failedCheck = true
  350. }
  351. eventTracking.sendMB(`syntax-check-${response.status}`)
  352. fetchLogs(fileByPath, { validation: true, pdfDownloadDomain })
  353. } else if (response.status === 'exited') {
  354. $scope.pdf.view = 'pdf'
  355. $scope.pdf.compileExited = true
  356. $scope.pdf.url = buildPdfDownloadUrl(pdfDownloadDomain, lastPdfUrl)
  357. $scope.shouldShowLogs = true
  358. fetchLogs(fileByPath, { pdfDownloadDomain })
  359. } else if (response.status === 'autocompile-backoff') {
  360. if ($scope.pdf.isAutoCompileOnLoad) {
  361. // initial autocompile
  362. $scope.pdf.view = 'uncompiled'
  363. } else {
  364. // background autocompile from typing
  365. $scope.pdf.view = 'errors'
  366. $scope.pdf.autoCompileDisabled = true
  367. $scope.autocompile_enabled = false // disable any further autocompiles
  368. eventTracking.sendMB('autocompile-rate-limited', {
  369. hasPremiumCompile: $scope.hasPremiumCompile
  370. })
  371. }
  372. } else if (response.status === 'project-too-large') {
  373. $scope.pdf.view = 'errors'
  374. $scope.pdf.projectTooLarge = true
  375. } else if (response.status === 'failure') {
  376. $scope.pdf.view = 'errors'
  377. $scope.pdf.failure = true
  378. $scope.shouldShowLogs = true
  379. fetchLogs(fileByPath, { pdfDownloadDomain })
  380. } else if (response.status === 'clsi-maintenance') {
  381. $scope.pdf.view = 'errors'
  382. $scope.pdf.clsiMaintenance = true
  383. } else if (response.status === 'too-recently-compiled') {
  384. $scope.pdf.view = 'errors'
  385. $scope.pdf.tooRecentlyCompiled = true
  386. } else if (response.status === 'validation-problems') {
  387. $scope.pdf.view = 'validation-problems'
  388. $scope.pdf.validation = response.validationProblems
  389. $scope.shouldShowLogs = false
  390. } else if (response.status === 'compile-in-progress') {
  391. $scope.pdf.view = 'errors'
  392. $scope.pdf.compileInProgress = true
  393. } else if (response.status === 'success') {
  394. $scope.pdf.view = 'pdf'
  395. $scope.shouldShowLogs = false
  396. // define the base url. if the pdf file has a build number, pass it to the clsi in the url
  397. if (fileByPath['output.pdf'] && fileByPath['output.pdf'].url) {
  398. $scope.pdf.url = buildPdfDownloadUrl(
  399. pdfDownloadDomain,
  400. fileByPath['output.pdf'].url
  401. )
  402. } else if (fileByPath['output.pdf'] && fileByPath['output.pdf'].build) {
  403. const { build } = fileByPath['output.pdf']
  404. $scope.pdf.url = buildPdfDownloadUrl(
  405. pdfDownloadDomain,
  406. `/project/${$scope.project_id}/build/${build}/output/output.pdf`
  407. )
  408. } else {
  409. $scope.pdf.url = buildPdfDownloadUrl(
  410. pdfDownloadDomain,
  411. `/project/${$scope.project_id}/output/output.pdf`
  412. )
  413. }
  414. // check if we need to bust cache (build id is unique so don't need it in that case)
  415. if (!(fileByPath['output.pdf'] && fileByPath['output.pdf'].build)) {
  416. qs.cache_bust = `${Date.now()}`
  417. }
  418. // convert the qs hash into a query string and append it
  419. $scope.pdf.url += createQueryString(qs)
  420. // Save all downloads as files
  421. qs.popupDownload = true
  422. // Pass build id to download if we have it
  423. let buildId = null
  424. if (fileByPath['output.pdf'] && fileByPath['output.pdf'].build) {
  425. buildId = fileByPath['output.pdf'].build
  426. }
  427. $scope.pdf.downloadUrl =
  428. `/download/project/${$scope.project_id}${
  429. buildId ? '/build/' + buildId : ''
  430. }/output/output.pdf` + createQueryString(qs)
  431. fetchLogs(fileByPath, { pdfDownloadDomain })
  432. }
  433. const IGNORE_FILES = ['output.fls', 'output.fdb_latexmk']
  434. $scope.pdf.outputFiles = []
  435. if (response.outputFiles == null) {
  436. return
  437. }
  438. // prepare list of output files for download dropdown
  439. qs = {}
  440. if (response.clsiServerId != null) {
  441. qs.clsiserverid = response.clsiServerId
  442. }
  443. for (const file of response.outputFiles) {
  444. if (IGNORE_FILES.indexOf(file.path) === -1) {
  445. const isOutputFile = /^output\./.test(file.path)
  446. $scope.pdf.outputFiles.push({
  447. // Turn 'output.blg' into 'blg file'.
  448. name: isOutputFile
  449. ? `${file.path.replace(/^output\./, '')} file`
  450. : file.path,
  451. url:
  452. `/project/${$scope.project_id}/output/${file.path}` +
  453. createQueryString(qs),
  454. main: !!isOutputFile
  455. })
  456. }
  457. }
  458. // sort the output files into order, main files first, then others
  459. $scope.pdf.outputFiles.sort(
  460. (a, b) => b.main - a.main || a.name.localeCompare(b.name)
  461. )
  462. }
  463. function fetchLogs(fileByPath, options) {
  464. let blgFile, chktexFile, logFile
  465. if (options != null ? options.validation : undefined) {
  466. chktexFile = fileByPath['output.chktex']
  467. } else {
  468. logFile = fileByPath['output.log']
  469. blgFile = fileByPath['output.blg']
  470. }
  471. function getFile(name, file) {
  472. const opts = {
  473. method: 'GET',
  474. params: {
  475. compileGroup: ide.compileGroup,
  476. clsiserverid: ide.clsiServerId
  477. }
  478. }
  479. if (file && file.url) {
  480. // FIXME clean this up when we have file.urls out consistently
  481. opts.url = file.url
  482. } else if (file && file.build) {
  483. opts.url = `/project/${$scope.project_id}/build/${
  484. file.build
  485. }/output/${name}`
  486. } else {
  487. opts.url = `/project/${$scope.project_id}/output/${name}`
  488. }
  489. // check if we need to bust cache (build id is unique so don't need it in that case)
  490. if (!(file && file.build)) {
  491. opts.params.cache_bust = `${Date.now()}`
  492. }
  493. opts.url = buildPdfDownloadUrl(options.pdfDownloadDomain, opts.url)
  494. return $http(opts)
  495. }
  496. // accumulate the log entries
  497. const logEntries = {
  498. all: [],
  499. errors: [],
  500. warnings: []
  501. }
  502. function accumulateResults(newEntries) {
  503. for (let key of ['all', 'errors', 'warnings']) {
  504. if (newEntries.type != null) {
  505. for (let entry of newEntries[key]) {
  506. entry.type = newEntries.type
  507. }
  508. }
  509. logEntries[key] = logEntries[key].concat(newEntries[key])
  510. }
  511. }
  512. // use the parsers for each file type
  513. function processLog(log) {
  514. $scope.pdf.rawLog = log
  515. const { errors, warnings, typesetting } = HumanReadableLogs.parse(log, {
  516. ignoreDuplicates: true
  517. })
  518. const all = [].concat(errors, warnings, typesetting)
  519. accumulateResults({ all, errors, warnings })
  520. }
  521. function processChkTex(log) {
  522. const errors = []
  523. const warnings = []
  524. for (let line of log.split('\n')) {
  525. var m
  526. if ((m = line.match(/^(\S+):(\d+):(\d+): (Error|Warning): (.*)/))) {
  527. const result = {
  528. file: m[1],
  529. line: m[2],
  530. column: m[3],
  531. level: m[4].toLowerCase(),
  532. message: `${m[4]}: ${m[5]}`
  533. }
  534. if (result.level === 'error') {
  535. errors.push(result)
  536. } else {
  537. warnings.push(result)
  538. }
  539. }
  540. }
  541. const all = [].concat(errors, warnings)
  542. const logHints = HumanReadableLogs.parse({
  543. type: 'Syntax',
  544. all,
  545. errors,
  546. warnings
  547. })
  548. eventTracking.sendMB('syntax-check-return-count', {
  549. errors: errors.length,
  550. warnings: warnings.length
  551. })
  552. accumulateResults(logHints)
  553. }
  554. function processBiber(log) {
  555. const { errors, warnings } = BibLogParser.parse(log, {})
  556. const all = [].concat(errors, warnings)
  557. accumulateResults({ type: 'BibTeX', all, errors, warnings })
  558. }
  559. // output the results
  560. function handleError() {
  561. $scope.pdf.logEntries = []
  562. $scope.pdf.rawLog = ''
  563. }
  564. function annotateFiles() {
  565. $scope.pdf.logEntries = logEntries
  566. $scope.pdf.logEntryAnnotations = {}
  567. for (const entry of logEntries.all) {
  568. if (entry.file != null) {
  569. entry.file = normalizeFilePath(entry.file)
  570. const entity = ide.fileTreeManager.findEntityByPath(entry.file)
  571. if (entity != null) {
  572. if (!$scope.pdf.logEntryAnnotations[entity.id]) {
  573. $scope.pdf.logEntryAnnotations[entity.id] = []
  574. }
  575. $scope.pdf.logEntryAnnotations[entity.id].push({
  576. row: entry.line - 1,
  577. type: entry.level === 'error' ? 'error' : 'warning',
  578. text: entry.message
  579. })
  580. }
  581. }
  582. }
  583. }
  584. // retrieve the logfile and process it
  585. let response
  586. if (logFile != null) {
  587. response = getFile('output.log', logFile).then(response =>
  588. processLog(response.data)
  589. )
  590. if (blgFile != null) {
  591. // retrieve the blg file if present
  592. response = response.then(() =>
  593. getFile('output.blg', blgFile).then(
  594. response => processBiber(response.data),
  595. () => true
  596. )
  597. )
  598. }
  599. }
  600. if (response != null) {
  601. response.catch(handleError)
  602. } else {
  603. handleError()
  604. }
  605. if (chktexFile != null) {
  606. const getChkTex = () =>
  607. getFile('output.chktex', chktexFile).then(response =>
  608. processChkTex(response.data)
  609. )
  610. // always retrieve the chktex file if present
  611. if (response != null) {
  612. response = response.then(getChkTex, getChkTex)
  613. } else {
  614. response = getChkTex()
  615. }
  616. }
  617. // display the combined result
  618. if (response != null) {
  619. response.finally(annotateFiles)
  620. }
  621. }
  622. function getRootDocOverrideId() {
  623. const doc = ide.editorManager.getCurrentDocValue()
  624. if (doc == null) {
  625. return null
  626. }
  627. for (let line of doc.split('\n')) {
  628. if (/^[^%]*\\documentclass/.test(line)) {
  629. return ide.editorManager.getCurrentDocId()
  630. }
  631. }
  632. return null
  633. }
  634. function normalizeFilePath(path) {
  635. path = path.replace(
  636. /^(.*)\/compiles\/[0-9a-f]{24}(-[0-9a-f]{24})?\/(\.\/)?/,
  637. ''
  638. )
  639. path = path.replace(/^\/compile\//, '')
  640. const rootDocDirname = ide.fileTreeManager.getRootDocDirname()
  641. if (rootDocDirname != null) {
  642. path = path.replace(/^\.\//, rootDocDirname + '/')
  643. }
  644. return path
  645. }
  646. $scope.recompile = function(options) {
  647. if (options == null) {
  648. options = {}
  649. }
  650. if ($scope.pdf.compiling) {
  651. return
  652. }
  653. eventTracking.sendMBSampled('editor-recompile-sampled', options)
  654. $scope.lastStartedCompileAt = Date.now()
  655. $scope.pdf.compiling = true
  656. $scope.pdf.isAutoCompileOnLoad =
  657. options != null ? options.isAutoCompileOnLoad : undefined // initial autocompile
  658. if (options != null ? options.force : undefined) {
  659. // for forced compile, turn off validation check and ignore errors
  660. $scope.stop_on_validation_error = false
  661. $scope.shouldShowLogs = false // hide the logs while compiling
  662. eventTracking.sendMB('syntax-check-turn-off-checking')
  663. }
  664. if (options != null ? options.try : undefined) {
  665. $scope.shouldShowLogs = false // hide the logs while compiling
  666. eventTracking.sendMB('syntax-check-try-compile-anyway')
  667. }
  668. ide.$scope.$broadcast('flush-changes')
  669. options.rootDocOverride_id = getRootDocOverrideId()
  670. sendCompileRequest(options)
  671. .then(function(response) {
  672. const { data } = response
  673. $scope.pdf.view = 'pdf'
  674. $scope.pdf.compiling = false
  675. parseCompileResponse(data)
  676. })
  677. .catch(function(response) {
  678. const { status } = response
  679. if (status === 429) {
  680. $scope.pdf.rateLimited = true
  681. }
  682. $scope.pdf.compiling = false
  683. $scope.pdf.renderingError = false
  684. $scope.pdf.error = true
  685. $scope.pdf.view = 'errors'
  686. })
  687. .finally(() => {
  688. $scope.lastFinishedCompileAt = Date.now()
  689. })
  690. }
  691. // This needs to be public.
  692. ide.$scope.recompile = $scope.recompile
  693. // This method is a simply wrapper and exists only for tracking purposes.
  694. ide.$scope.recompileViaKey = function() {
  695. $scope.recompile({ keyShortcut: true })
  696. }
  697. $scope.stop = function() {
  698. if (!$scope.pdf.compiling) {
  699. return
  700. }
  701. return $http({
  702. url: `/project/${$scope.project_id}/compile/stop`,
  703. method: 'POST',
  704. params: {
  705. clsiserverid: ide.clsiServerId
  706. },
  707. headers: {
  708. 'X-Csrf-Token': window.csrfToken
  709. }
  710. })
  711. }
  712. $scope.clearCache = function() {
  713. return $http({
  714. url: `/project/${$scope.project_id}/output`,
  715. method: 'DELETE',
  716. params: {
  717. clsiserverid: ide.clsiServerId
  718. },
  719. headers: {
  720. 'X-Csrf-Token': window.csrfToken
  721. }
  722. })
  723. }
  724. $scope.toggleLogs = function() {
  725. $scope.shouldShowLogs = !$scope.shouldShowLogs
  726. if ($scope.shouldShowLogs) {
  727. eventTracking.sendMBOnce('ide-open-logs-once')
  728. }
  729. }
  730. $scope.showPdf = function() {
  731. $scope.pdf.view = 'pdf'
  732. $scope.shouldShowLogs = false
  733. }
  734. $scope.toggleRawLog = function() {
  735. $scope.pdf.showRawLog = !$scope.pdf.showRawLog
  736. if ($scope.pdf.showRawLog) {
  737. eventTracking.sendMB('logs-view-raw')
  738. }
  739. }
  740. $scope.openClearCacheModal = function() {
  741. $modal.open({
  742. templateUrl: 'clearCacheModalTemplate',
  743. controller: 'ClearCacheModalController',
  744. scope: $scope
  745. })
  746. }
  747. $scope.syncToCode = function(position) {
  748. synctex.syncToCode(position).then(function(data) {
  749. const { doc, line } = data
  750. ide.editorManager.openDoc(doc, { gotoLine: line })
  751. })
  752. }
  753. })
  754. App.factory('synctex', function(ide, $http, $q) {
  755. const synctex = {
  756. syncToPdf(cursorPosition) {
  757. const deferred = $q.defer()
  758. const docId = ide.editorManager.getCurrentDocId()
  759. if (docId == null) {
  760. deferred.reject()
  761. return deferred.promise
  762. }
  763. const doc = ide.fileTreeManager.findEntityById(docId)
  764. if (doc == null) {
  765. deferred.reject()
  766. return deferred.promise
  767. }
  768. let path = ide.fileTreeManager.getEntityPath(doc)
  769. if (path == null) {
  770. deferred.reject()
  771. return deferred.promise
  772. }
  773. // If the root file is folder/main.tex, then synctex sees the
  774. // path as folder/./main.tex
  775. const rootDocDirname = ide.fileTreeManager.getRootDocDirname()
  776. if (rootDocDirname != null && rootDocDirname !== '') {
  777. path = path.replace(RegExp(`^${rootDocDirname}`), `${rootDocDirname}/.`)
  778. }
  779. const { row, column } = cursorPosition
  780. $http({
  781. url: `/project/${ide.project_id}/sync/code`,
  782. method: 'GET',
  783. params: {
  784. file: path,
  785. line: row + 1,
  786. column,
  787. clsiserverid: ide.clsiServerId
  788. }
  789. })
  790. .then(function(response) {
  791. const { data } = response
  792. return deferred.resolve(data.pdf || [])
  793. })
  794. .catch(function(response) {
  795. const error = response.data
  796. return deferred.reject(error)
  797. })
  798. return deferred.promise
  799. },
  800. syncToCode(position, options) {
  801. if (options == null) {
  802. options = {}
  803. }
  804. const deferred = $q.defer()
  805. if (position == null) {
  806. deferred.reject()
  807. return deferred.promise
  808. }
  809. // FIXME: this actually works better if it's halfway across the
  810. // page (or the visible part of the page). Synctex doesn't
  811. // always find the right place in the file when the point is at
  812. // the edge of the page, it sometimes returns the start of the
  813. // next paragraph instead.
  814. const h = position.offset.left
  815. // Compute the vertical position to pass to synctex, which
  816. // works with coordinates increasing from the top of the page
  817. // down. This matches the browser's DOM coordinate of the
  818. // click point, but the pdf position is measured from the
  819. // bottom of the page so we need to invert it.
  820. let v
  821. if (
  822. options.fromPdfPosition &&
  823. (position.pageSize != null ? position.pageSize.height : undefined) !=
  824. null
  825. ) {
  826. v = position.pageSize.height - position.offset.top || 0 // measure from pdf point (inverted)
  827. } else {
  828. v = position.offset.top || 0 // measure from html click position
  829. }
  830. // It's not clear exactly where we should sync to if it wasn't directly
  831. // clicked on, but a little bit down from the very top seems best.
  832. if (options.includeVisualOffset) {
  833. v += 72 // use the same value as in pdfViewer highlighting visual offset
  834. }
  835. $http({
  836. url: `/project/${ide.project_id}/sync/pdf`,
  837. method: 'GET',
  838. params: {
  839. page: position.page + 1,
  840. h: h.toFixed(2),
  841. v: v.toFixed(2),
  842. clsiserverid: ide.clsiServerId
  843. }
  844. })
  845. .then(function(response) {
  846. const { data } = response
  847. if (
  848. data.code != null &&
  849. data.code.length > 0 &&
  850. data.code[0].file !== ''
  851. ) {
  852. const doc = ide.fileTreeManager.findEntityByPath(data.code[0].file)
  853. if (doc == null) {
  854. return
  855. }
  856. return deferred.resolve({ doc, line: data.code[0].line })
  857. } else if (data.code[0].file === '') {
  858. ide.$scope.sync_tex_error = true
  859. setTimeout(() => (ide.$scope.sync_tex_error = false), 4000)
  860. }
  861. })
  862. .catch(function(response) {
  863. const error = response.data
  864. return deferred.reject(error)
  865. })
  866. return deferred.promise
  867. }
  868. }
  869. return synctex
  870. })
  871. App.controller('PdfSynctexController', function($scope, synctex, ide) {
  872. this.cursorPosition = null
  873. ide.$scope.$on('cursor:editor:update', (event, cursorPosition) => {
  874. this.cursorPosition = cursorPosition
  875. })
  876. $scope.syncToPdf = () => {
  877. if (this.cursorPosition == null) {
  878. return
  879. }
  880. synctex.syncToPdf(this.cursorPosition).then(highlights => {
  881. $scope.pdf.highlights = highlights
  882. })
  883. }
  884. ide.$scope.$on('cursor:editor:syncToPdf', $scope.syncToPdf)
  885. $scope.syncToCode = function() {
  886. synctex
  887. .syncToCode($scope.pdf.position, {
  888. includeVisualOffset: true,
  889. fromPdfPosition: true
  890. })
  891. .then(function(data) {
  892. const { doc, line } = data
  893. ide.editorManager.openDoc(doc, { gotoLine: line })
  894. })
  895. }
  896. })
  897. App.controller('PdfLogEntryController', function($scope, ide, eventTracking) {
  898. $scope.openInEditor = function(entry) {
  899. let column, line
  900. eventTracking.sendMBOnce('logs-jump-to-location-once')
  901. const entity = ide.fileTreeManager.findEntityByPath(entry.file)
  902. if (entity == null || entity.type !== 'doc') {
  903. return
  904. }
  905. if (entry.line != null) {
  906. line = entry.line
  907. }
  908. if (entry.column != null) {
  909. column = entry.column
  910. }
  911. ide.editorManager.openDoc(entity, {
  912. gotoLine: line,
  913. gotoColumn: column
  914. })
  915. }
  916. })
  917. App.controller('ClearCacheModalController', function($scope, $modalInstance) {
  918. $scope.state = { inflight: false }
  919. $scope.clear = function() {
  920. $scope.state.inflight = true
  921. $scope.clearCache().then(function() {
  922. $scope.state.inflight = false
  923. $modalInstance.close()
  924. })
  925. }
  926. $scope.cancel = () => $modalInstance.dismiss('cancel')
  927. })