PdfController.js 31 KB

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