PdfController.js 32 KB

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