PdfController.js 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  1. import App from '../../../base'
  2. import HumanReadableLogs from '../../human-readable-logs/HumanReadableLogs'
  3. import BibLogParser from '../../log-parser/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 (
  252. window.user.alphaProgram ||
  253. window.user.betaProgram ||
  254. window.location.search.includes('file_line_errors=true')
  255. ) {
  256. params.file_line_errors = 'true'
  257. }
  258. // if the previous run was a check, clear the error logs
  259. if ($scope.check) {
  260. $scope.pdf.logEntries = {}
  261. }
  262. // keep track of whether this is a compile or check
  263. $scope.check = !!options.check
  264. if (options.check) {
  265. eventTracking.sendMB('syntax-check-request')
  266. }
  267. // send appropriate check type to clsi
  268. let checkType
  269. if ($scope.check) {
  270. checkType = 'validate' // validate only
  271. } else if (options.try) {
  272. checkType = 'silent' // allow use to try compile once
  273. } else if ($scope.stop_on_validation_error) {
  274. checkType = 'error' // try to compile
  275. } else {
  276. checkType = 'silent' // ignore errors
  277. }
  278. // FIXME: Temporarily disable syntax checking as it is causing
  279. // excessive support requests for projects migrated from v1
  280. // https://github.com/overleaf/sharelatex/issues/911
  281. if (checkType === 'error') {
  282. checkType = 'silent'
  283. }
  284. return $http.post(
  285. url,
  286. {
  287. rootDoc_id: options.rootDocOverride_id || null,
  288. draft: $scope.draft,
  289. check: checkType,
  290. // use incremental compile for all users but revert to a full
  291. // compile if there is a server error
  292. incrementalCompilesEnabled: !$scope.pdf.error,
  293. _csrf: window.csrfToken,
  294. },
  295. { params }
  296. )
  297. }
  298. function buildPdfDownloadUrl(pdfDownloadDomain, url) {
  299. if (pdfDownloadDomain) {
  300. return `${pdfDownloadDomain}${url}`
  301. } else {
  302. return url
  303. }
  304. }
  305. function noop() {}
  306. function parseCompileResponse(response, compileTimeClientE2E) {
  307. // keep last url
  308. const lastPdfUrl = $scope.pdf.url
  309. const { pdfDownloadDomain } = response
  310. // Reset everything
  311. $scope.pdf.error = false
  312. $scope.pdf.timedout = false
  313. $scope.pdf.failure = false
  314. $scope.pdf.url = null
  315. $scope.pdf.updateConsumedBandwidth = noop
  316. $scope.pdf.firstRenderDone = noop
  317. $scope.pdf.clsiMaintenance = false
  318. $scope.pdf.clsiUnavailable = false
  319. $scope.pdf.tooRecentlyCompiled = false
  320. $scope.pdf.renderingError = false
  321. $scope.pdf.projectTooLarge = false
  322. $scope.pdf.compileTerminated = false
  323. $scope.pdf.compileExited = false
  324. $scope.pdf.failedCheck = false
  325. $scope.pdf.compileInProgress = false
  326. $scope.pdf.autoCompileDisabled = false
  327. $scope.pdf.compileFailed = false
  328. // make a cache to look up files by name
  329. const fileByPath = {}
  330. if (response.outputFiles != null) {
  331. for (const file of response.outputFiles) {
  332. fileByPath[file.path] = file
  333. }
  334. }
  335. // prepare query string
  336. let qs = {}
  337. // add a query string parameter for the compile group
  338. if (response.compileGroup != null) {
  339. ide.compileGroup = qs.compileGroup = response.compileGroup
  340. }
  341. // add a query string parameter for the clsi server id
  342. if (response.clsiServerId != null) {
  343. ide.clsiServerId = qs.clsiserverid = response.clsiServerId
  344. }
  345. // TODO(das7pad): drop this hack once 2747f0d40af8729304 has landed in clsi
  346. if (response.status === 'success' && !fileByPath['output.pdf']) {
  347. response.status = 'failure'
  348. }
  349. if (response.status === 'success') {
  350. $scope.pdf.view = 'pdf'
  351. $scope.shouldShowLogs = false
  352. $scope.pdf.lastCompileTimestamp = Date.now()
  353. $scope.pdf.validation = {}
  354. $scope.pdf.url = buildPdfDownloadUrl(
  355. pdfDownloadDomain,
  356. fileByPath['output.pdf'].url
  357. )
  358. if (window.location.search.includes('verify_chunks=true')) {
  359. // Instruct the serviceWorker to verify composed ranges.
  360. qs.verify_chunks = 'true'
  361. }
  362. if (getMeta('ol-enablePdfCaching')) {
  363. // Tag traffic that uses the pdf caching logic.
  364. qs.enable_pdf_caching = 'true'
  365. }
  366. // convert the qs hash into a query string and append it
  367. $scope.pdf.url += createQueryString(qs)
  368. if (getMeta('ol-trackPdfDownload')) {
  369. const { firstRenderDone, updateConsumedBandwidth } = trackPdfDownload(
  370. response,
  371. compileTimeClientE2E
  372. )
  373. $scope.pdf.firstRenderDone = firstRenderDone
  374. $scope.pdf.updateConsumedBandwidth = updateConsumedBandwidth
  375. }
  376. // Save all downloads as files
  377. qs.popupDownload = true
  378. const { build: buildId } = fileByPath['output.pdf']
  379. $scope.pdf.downloadUrl =
  380. `/download/project/${$scope.project_id}/build/${buildId}/output/output.pdf` +
  381. createQueryString(qs)
  382. fetchLogs(fileByPath, { pdfDownloadDomain })
  383. } else if (response.status === 'timedout') {
  384. $scope.pdf.view = 'errors'
  385. $scope.pdf.timedout = true
  386. fetchLogs(fileByPath, { pdfDownloadDomain })
  387. if (
  388. !$scope.hasPremiumCompile &&
  389. ide.$scope.project.owner._id === ide.$scope.user.id
  390. ) {
  391. eventTracking.send(
  392. 'subscription-funnel',
  393. 'editor-click-feature',
  394. 'compile-timeout'
  395. )
  396. eventTracking.sendMB('paywall-prompt', {
  397. 'paywall-type': 'compile-timeout',
  398. })
  399. }
  400. } else if (response.status === 'terminated') {
  401. $scope.pdf.view = 'errors'
  402. $scope.pdf.compileTerminated = true
  403. fetchLogs(fileByPath, { pdfDownloadDomain })
  404. } else if (
  405. ['validation-fail', 'validation-pass'].includes(response.status)
  406. ) {
  407. $scope.pdf.view = 'pdf'
  408. $scope.pdf.url = lastPdfUrl
  409. $scope.shouldShowLogs = true
  410. if (response.status === 'validation-fail') {
  411. $scope.pdf.failedCheck = true
  412. }
  413. eventTracking.sendMB(`syntax-check-${response.status}`)
  414. fetchLogs(fileByPath, { validation: true, pdfDownloadDomain })
  415. } else if (response.status === 'exited') {
  416. $scope.pdf.view = 'pdf'
  417. $scope.pdf.compileExited = true
  418. $scope.pdf.url = lastPdfUrl
  419. $scope.shouldShowLogs = true
  420. fetchLogs(fileByPath, { pdfDownloadDomain })
  421. } else if (response.status === 'autocompile-backoff') {
  422. if ($scope.pdf.isAutoCompileOnLoad) {
  423. // initial autocompile
  424. $scope.pdf.view = 'uncompiled'
  425. } else {
  426. // background autocompile from typing
  427. $scope.pdf.view = 'errors'
  428. $scope.pdf.autoCompileDisabled = true
  429. $scope.autocompile_enabled = false // disable any further autocompiles
  430. eventTracking.sendMB('autocompile-rate-limited', {
  431. hasPremiumCompile: $scope.hasPremiumCompile,
  432. })
  433. }
  434. } else if (response.status === 'project-too-large') {
  435. $scope.pdf.view = 'errors'
  436. $scope.pdf.projectTooLarge = true
  437. } else if (response.status === 'failure') {
  438. $scope.pdf.view = 'errors'
  439. $scope.pdf.failure = true
  440. $scope.pdf.downloadUrl = null
  441. $scope.shouldShowLogs = true
  442. fetchLogs(fileByPath, { pdfDownloadDomain })
  443. } else if (response.status === 'clsi-maintenance') {
  444. $scope.pdf.view = 'errors'
  445. $scope.pdf.clsiMaintenance = true
  446. } else if (response.status === 'unavailable') {
  447. $scope.pdf.view = 'errors'
  448. $scope.pdf.clsiUnavailable = true
  449. } else if (response.status === 'too-recently-compiled') {
  450. $scope.pdf.view = 'errors'
  451. $scope.pdf.tooRecentlyCompiled = true
  452. } else if (response.status === 'validation-problems') {
  453. $scope.pdf.view = 'validation-problems'
  454. $scope.pdf.validation = response.validationProblems
  455. $scope.shouldShowLogs = false
  456. } else if (response.status === 'compile-in-progress') {
  457. $scope.pdf.view = 'errors'
  458. $scope.pdf.compileInProgress = true
  459. } else {
  460. // fall back to displaying an error
  461. $scope.pdf.view = 'errors'
  462. $scope.pdf.error = true
  463. }
  464. const IGNORE_FILES = ['output.fls', 'output.fdb_latexmk']
  465. $scope.pdf.outputFiles = []
  466. if (response.outputFiles == null) {
  467. return
  468. }
  469. // prepare list of output files for download dropdown
  470. qs = {}
  471. if (response.clsiServerId != null) {
  472. qs.clsiserverid = response.clsiServerId
  473. }
  474. for (const file of response.outputFiles) {
  475. if (IGNORE_FILES.indexOf(file.path) === -1) {
  476. const isOutputFile = /^output\./.test(file.path)
  477. $scope.pdf.outputFiles.push({
  478. // Turn 'output.blg' into 'blg file'.
  479. name: isOutputFile
  480. ? `${file.path.replace(/^output\./, '')} file`
  481. : file.path,
  482. url: file.url + createQueryString(qs),
  483. main: !!isOutputFile,
  484. fileName: file.path,
  485. type: file.type,
  486. })
  487. }
  488. }
  489. // sort the output files into order, main files first, then others
  490. $scope.pdf.outputFiles.sort(
  491. (a, b) => b.main - a.main || a.name.localeCompare(b.name)
  492. )
  493. }
  494. // In the existing compile UI, errors and validation problems are shown in the PDF pane, whereas in the new
  495. // one they're shown in the logs pane. This `$watch`er makes sure we change the view in the new logs UI.
  496. // This should be removed once we stop supporting the two different log UIs.
  497. if (window.showNewLogsUI) {
  498. $scope.$watch(
  499. () =>
  500. $scope.pdf.view === 'errors' ||
  501. $scope.pdf.view === 'validation-problems',
  502. newVal => {
  503. if (newVal) {
  504. $scope.shouldShowLogs = true
  505. $scope.pdf.compileFailed = true
  506. }
  507. }
  508. )
  509. }
  510. function fetchLogs(fileByPath, options) {
  511. let blgFile, chktexFile, logFile
  512. if (options != null ? options.validation : undefined) {
  513. chktexFile = fileByPath['output.chktex']
  514. } else {
  515. logFile = fileByPath['output.log']
  516. blgFile = fileByPath['output.blg']
  517. }
  518. function getFile(name, file) {
  519. const opts = {
  520. method: 'GET',
  521. url: buildPdfDownloadUrl(options.pdfDownloadDomain, file.url),
  522. params: {
  523. compileGroup: ide.compileGroup,
  524. clsiserverid: ide.clsiServerId,
  525. },
  526. }
  527. return $http(opts)
  528. }
  529. // accumulate the log entries
  530. const logEntries = {
  531. all: [],
  532. errors: [],
  533. warnings: [],
  534. typesetting: [],
  535. }
  536. function accumulateResults(newEntries) {
  537. for (const key of ['all', 'errors', 'warnings', 'typesetting']) {
  538. if (newEntries[key]) {
  539. if (newEntries.type != null) {
  540. for (const entry of newEntries[key]) {
  541. entry.type = newEntries.type
  542. }
  543. }
  544. logEntries[key] = logEntries[key].concat(newEntries[key])
  545. }
  546. }
  547. }
  548. // use the parsers for each file type
  549. function processLog(log) {
  550. $scope.pdf.rawLog = log
  551. const { errors, warnings, typesetting } = HumanReadableLogs.parse(log, {
  552. ignoreDuplicates: true,
  553. })
  554. const all = [].concat(errors, warnings, typesetting)
  555. accumulateResults({ all, errors, warnings, typesetting })
  556. }
  557. function processChkTex(log) {
  558. const errors = []
  559. const warnings = []
  560. for (const line of log.split('\n')) {
  561. var m
  562. if ((m = line.match(/^(\S+):(\d+):(\d+): (Error|Warning): (.*)/))) {
  563. const result = {
  564. file: m[1],
  565. line: m[2],
  566. column: m[3],
  567. level: m[4].toLowerCase(),
  568. message: `${m[4]}: ${m[5]}`,
  569. }
  570. if (result.level === 'error') {
  571. errors.push(result)
  572. } else {
  573. warnings.push(result)
  574. }
  575. }
  576. }
  577. const all = [].concat(errors, warnings)
  578. const logHints = HumanReadableLogs.parse({
  579. type: 'Syntax',
  580. all,
  581. errors,
  582. warnings,
  583. })
  584. eventTracking.sendMB('syntax-check-return-count', {
  585. errors: errors.length,
  586. warnings: warnings.length,
  587. })
  588. accumulateResults(logHints)
  589. }
  590. function processBiber(log) {
  591. const bibLogParser = new BibLogParser(log, {})
  592. const { errors, warnings } = bibLogParser.parse(log, {})
  593. const all = [].concat(errors, warnings)
  594. accumulateResults({ type: 'BibTeX:', all, errors, warnings })
  595. }
  596. // output the results
  597. function handleError() {
  598. $scope.pdf.logEntries = {}
  599. $scope.pdf.rawLog = ''
  600. }
  601. function annotateFiles() {
  602. $scope.pdf.logEntries = logEntries
  603. $scope.pdf.logEntryAnnotations = {}
  604. for (const entry of logEntries.all) {
  605. if (entry.file != null) {
  606. entry.file = normalizeFilePath(entry.file)
  607. const entity = ide.fileTreeManager.findEntityByPath(entry.file)
  608. if (entity != null) {
  609. if (!$scope.pdf.logEntryAnnotations[entity.id]) {
  610. $scope.pdf.logEntryAnnotations[entity.id] = []
  611. }
  612. $scope.pdf.logEntryAnnotations[entity.id].push({
  613. row: entry.line - 1,
  614. type: entry.level === 'error' ? 'error' : 'warning',
  615. text: entry.message,
  616. })
  617. }
  618. }
  619. }
  620. }
  621. // retrieve the logfile and process it
  622. let response
  623. if (logFile != null) {
  624. response = getFile('output.log', logFile).then(response =>
  625. processLog(response.data)
  626. )
  627. if (blgFile != null) {
  628. // retrieve the blg file if present
  629. response = response.then(() =>
  630. getFile('output.blg', blgFile).then(
  631. response => processBiber(response.data),
  632. () => true
  633. )
  634. )
  635. }
  636. }
  637. if (response != null) {
  638. response.catch(handleError)
  639. } else {
  640. handleError()
  641. }
  642. if (chktexFile != null) {
  643. const getChkTex = () =>
  644. getFile('output.chktex', chktexFile).then(response =>
  645. processChkTex(response.data)
  646. )
  647. // always retrieve the chktex file if present
  648. if (response != null) {
  649. response = response.then(getChkTex, getChkTex)
  650. } else {
  651. response = getChkTex()
  652. }
  653. }
  654. // display the combined result
  655. if (response != null) {
  656. response.finally(() => {
  657. annotateFiles()
  658. sendCompileMetrics()
  659. })
  660. }
  661. }
  662. function sendCompileMetrics() {
  663. const hasCompiled =
  664. $scope.pdf.view !== 'errors' &&
  665. $scope.pdf.view !== 'validation-problems'
  666. if (hasCompiled && !window.user.alphaProgram) {
  667. const metadata = {
  668. errors: $scope.pdf.logEntries.errors.length,
  669. warnings: $scope.pdf.logEntries.warnings.length,
  670. typesetting: $scope.pdf.logEntries.typesetting.length,
  671. newLogsUI: window.showNewLogsUI,
  672. subvariant: window.showNewLogsUI ? window.logsUISubvariant : null,
  673. }
  674. eventTracking.sendMBSampled('compile-result', metadata, 0.01)
  675. }
  676. }
  677. function getRootDocOverrideId() {
  678. const rootDocId = $scope.project.rootDoc_id
  679. const currentDocId = ide.editorManager.getCurrentDocId()
  680. if (currentDocId === rootDocId) {
  681. return null // no need to override when in the root doc itself
  682. }
  683. const doc = ide.editorManager.getCurrentDocValue()
  684. if (doc == null) {
  685. return null
  686. }
  687. for (const line of doc.split('\n')) {
  688. if (/^[^%]*\\documentclass/.test(line)) {
  689. return ide.editorManager.getCurrentDocId()
  690. }
  691. }
  692. return null
  693. }
  694. function normalizeFilePath(path) {
  695. path = path.replace(
  696. /^(.*)\/compiles\/[0-9a-f]{24}(-[0-9a-f]{24})?\/(\.\/)?/,
  697. ''
  698. )
  699. path = path.replace(/^\/compile\//, '')
  700. const rootDocDirname = ide.fileTreeManager.getRootDocDirname()
  701. if (rootDocDirname) {
  702. path = path.replace(/^\.\//, rootDocDirname + '/')
  703. } else {
  704. path = path.replace(/^\.\//, '')
  705. }
  706. return path
  707. }
  708. $scope.recompile = function (options) {
  709. if (options == null) {
  710. options = {}
  711. }
  712. if ($scope.pdf.compiling) {
  713. return
  714. }
  715. eventTracking.sendMBSampled('editor-recompile-sampled', options)
  716. $scope.lastStartedCompileAt = Date.now()
  717. $scope.pdf.compiling = true
  718. $scope.pdf.isAutoCompileOnLoad =
  719. options != null ? options.isAutoCompileOnLoad : undefined // initial autocompile
  720. if (options != null ? options.force : undefined) {
  721. // for forced compile, turn off validation check and ignore errors
  722. $scope.stop_on_validation_error = false
  723. $scope.shouldShowLogs = false // hide the logs while compiling
  724. eventTracking.sendMB('syntax-check-turn-off-checking')
  725. }
  726. if (options != null ? options.try : undefined) {
  727. $scope.shouldShowLogs = false // hide the logs while compiling
  728. eventTracking.sendMB('syntax-check-try-compile-anyway')
  729. }
  730. ide.$scope.$broadcast('flush-changes')
  731. options.rootDocOverride_id = getRootDocOverrideId()
  732. const t0 = performance.now()
  733. sendCompileRequest(options)
  734. .then(function (response) {
  735. const { data } = response
  736. const compileTimeClientE2E = performance.now() - t0
  737. $scope.pdf.view = 'pdf'
  738. $scope.pdf.compiling = false
  739. parseCompileResponse(data, compileTimeClientE2E)
  740. })
  741. .catch(function (response) {
  742. const { status } = response
  743. if (status === 429) {
  744. $scope.pdf.rateLimited = true
  745. }
  746. $scope.pdf.compiling = false
  747. $scope.pdf.renderingError = false
  748. $scope.pdf.error = true
  749. $scope.pdf.view = 'errors'
  750. })
  751. .finally(() => {
  752. $scope.lastFinishedCompileAt = Date.now()
  753. })
  754. }
  755. // This needs to be public.
  756. ide.$scope.recompile = $scope.recompile
  757. // This method is a simply wrapper and exists only for tracking purposes.
  758. ide.$scope.recompileViaKey = function () {
  759. $scope.recompile({ keyShortcut: true })
  760. }
  761. $scope.stop = function () {
  762. if (!$scope.pdf.compiling) {
  763. return
  764. }
  765. return $http({
  766. url: `/project/${$scope.project_id}/compile/stop`,
  767. method: 'POST',
  768. params: {
  769. clsiserverid: ide.clsiServerId,
  770. },
  771. headers: {
  772. 'X-Csrf-Token': window.csrfToken,
  773. },
  774. })
  775. }
  776. $scope.clearCache = function () {
  777. $scope.pdf.clearingCache = true
  778. const deferred = $q.defer()
  779. // disable various download buttons
  780. $scope.pdf.url = null
  781. $scope.pdf.downloadUrl = null
  782. $scope.pdf.outputFiles = []
  783. $http({
  784. url: `/project/${$scope.project_id}/output`,
  785. method: 'DELETE',
  786. params: {
  787. clsiserverid: ide.clsiServerId,
  788. },
  789. headers: {
  790. 'X-Csrf-Token': window.csrfToken,
  791. },
  792. })
  793. .then(function (response) {
  794. $scope.pdf.clearingCache = false
  795. return deferred.resolve()
  796. })
  797. .catch(function (response) {
  798. console.error(response)
  799. const error = response.data
  800. $scope.pdf.clearingCache = false
  801. $scope.pdf.renderingError = false
  802. $scope.pdf.error = true
  803. $scope.pdf.view = 'errors'
  804. return deferred.reject(error)
  805. })
  806. return deferred.promise
  807. }
  808. $scope.recompileFromScratch = function () {
  809. $scope.pdf.compiling = true
  810. return $scope
  811. .clearCache()
  812. .then(() => {
  813. $scope.pdf.compiling = false
  814. $scope.recompile()
  815. })
  816. .catch(error => {
  817. console.error(error)
  818. })
  819. }
  820. $scope.toggleLogs = function () {
  821. $scope.$applyAsync(() => {
  822. $scope.shouldShowLogs = !$scope.shouldShowLogs
  823. if ($scope.shouldShowLogs) {
  824. eventTracking.sendMBOnce('ide-open-logs-once')
  825. }
  826. })
  827. }
  828. $scope.showPdf = function () {
  829. $scope.pdf.view = 'pdf'
  830. $scope.shouldShowLogs = false
  831. }
  832. $scope.toggleRawLog = function () {
  833. $scope.pdf.showRawLog = !$scope.pdf.showRawLog
  834. if ($scope.pdf.showRawLog) {
  835. eventTracking.sendMB('logs-view-raw')
  836. }
  837. }
  838. $scope.openClearCacheModal = function () {
  839. $modal.open({
  840. templateUrl: 'clearCacheModalTemplate',
  841. controller: 'ClearCacheModalController',
  842. scope: $scope,
  843. })
  844. }
  845. $scope.syncToCode = function (position) {
  846. synctex.syncToCode(position).then(function (data) {
  847. const { doc, line } = data
  848. ide.editorManager.openDoc(doc, { gotoLine: line })
  849. })
  850. }
  851. $scope.setAutoCompile = function (isOn) {
  852. $scope.$applyAsync(function () {
  853. $scope.autocompile_enabled = isOn
  854. })
  855. }
  856. $scope.setDraftMode = function (isOn) {
  857. $scope.$applyAsync(function () {
  858. $scope.draft = isOn
  859. })
  860. }
  861. $scope.setSyntaxCheck = function (isOn) {
  862. $scope.$applyAsync(function () {
  863. $scope.stop_on_validation_error = isOn
  864. })
  865. }
  866. $scope.runSyntaxCheckNow = function () {
  867. $scope.$applyAsync(function () {
  868. $scope.recompile({ check: true })
  869. })
  870. }
  871. $scope.openInEditor = function (entry) {
  872. let column, line
  873. eventTracking.sendMBOnce('logs-jump-to-location-once')
  874. const entity = ide.fileTreeManager.findEntityByPath(entry.file)
  875. if (entity == null || entity.type !== 'doc') {
  876. return
  877. }
  878. if (entry.line != null) {
  879. line = entry.line
  880. }
  881. if (entry.column != null) {
  882. column = entry.column
  883. }
  884. ide.editorManager.openDoc(entity, {
  885. gotoLine: line,
  886. gotoColumn: column,
  887. })
  888. }
  889. }
  890. )
  891. App.controller('ClearCacheModalController', function ($scope, $modalInstance) {
  892. $scope.state = { error: false, inflight: false }
  893. $scope.clear = function () {
  894. $scope.state.inflight = true
  895. $scope
  896. .clearCache()
  897. .then(function () {
  898. $scope.state.inflight = false
  899. $modalInstance.close()
  900. })
  901. .catch(function () {
  902. $scope.state.error = true
  903. $scope.state.inflight = false
  904. })
  905. }
  906. $scope.cancel = () => $modalInstance.dismiss('cancel')
  907. })
  908. // Wrap React component as Angular component. Only needed for "top-level" component
  909. App.component(
  910. 'previewPane',
  911. react2angular(
  912. rootContext.use(PreviewPane),
  913. Object.keys(PreviewPane.propTypes)
  914. )
  915. )