PdfController.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  1. import App from '../../../base'
  2. import HumanReadableLogs from '../../human-readable-logs/HumanReadableLogs'
  3. import BibLogParser from '../../../vendor/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 (
  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 { errors, warnings } = BibLogParser.parse(log, {})
  592. const all = [].concat(errors, warnings)
  593. accumulateResults({ type: 'BibTeX:', all, errors, warnings })
  594. }
  595. // output the results
  596. function handleError() {
  597. $scope.pdf.logEntries = {}
  598. $scope.pdf.rawLog = ''
  599. }
  600. function annotateFiles() {
  601. $scope.pdf.logEntries = logEntries
  602. $scope.pdf.logEntryAnnotations = {}
  603. for (const entry of logEntries.all) {
  604. if (entry.file != null) {
  605. entry.file = normalizeFilePath(entry.file)
  606. const entity = ide.fileTreeManager.findEntityByPath(entry.file)
  607. if (entity != null) {
  608. if (!$scope.pdf.logEntryAnnotations[entity.id]) {
  609. $scope.pdf.logEntryAnnotations[entity.id] = []
  610. }
  611. $scope.pdf.logEntryAnnotations[entity.id].push({
  612. row: entry.line - 1,
  613. type: entry.level === 'error' ? 'error' : 'warning',
  614. text: entry.message,
  615. })
  616. }
  617. }
  618. }
  619. }
  620. // retrieve the logfile and process it
  621. let response
  622. if (logFile != null) {
  623. response = getFile('output.log', logFile).then(response =>
  624. processLog(response.data)
  625. )
  626. if (blgFile != null) {
  627. // retrieve the blg file if present
  628. response = response.then(() =>
  629. getFile('output.blg', blgFile).then(
  630. response => processBiber(response.data),
  631. () => true
  632. )
  633. )
  634. }
  635. }
  636. if (response != null) {
  637. response.catch(handleError)
  638. } else {
  639. handleError()
  640. }
  641. if (chktexFile != null) {
  642. const getChkTex = () =>
  643. getFile('output.chktex', chktexFile).then(response =>
  644. processChkTex(response.data)
  645. )
  646. // always retrieve the chktex file if present
  647. if (response != null) {
  648. response = response.then(getChkTex, getChkTex)
  649. } else {
  650. response = getChkTex()
  651. }
  652. }
  653. // display the combined result
  654. if (response != null) {
  655. response.finally(() => {
  656. annotateFiles()
  657. sendCompileMetrics()
  658. })
  659. }
  660. }
  661. function sendCompileMetrics() {
  662. const hasCompiled =
  663. $scope.pdf.view !== 'errors' &&
  664. $scope.pdf.view !== 'validation-problems'
  665. if (hasCompiled && !window.user.alphaProgram) {
  666. const metadata = {
  667. errors: $scope.pdf.logEntries.errors.length,
  668. warnings: $scope.pdf.logEntries.warnings.length,
  669. typesetting: $scope.pdf.logEntries.typesetting.length,
  670. newLogsUI: window.showNewLogsUI,
  671. subvariant: window.showNewLogsUI ? window.logsUISubvariant : null,
  672. }
  673. eventTracking.sendMBSampled('compile-result', metadata, 0.01)
  674. }
  675. }
  676. function getRootDocOverrideId() {
  677. const rootDocId = $scope.project.rootDoc_id
  678. const currentDocId = ide.editorManager.getCurrentDocId()
  679. if (currentDocId === rootDocId) {
  680. return null // no need to override when in the root doc itself
  681. }
  682. const doc = ide.editorManager.getCurrentDocValue()
  683. if (doc == null) {
  684. return null
  685. }
  686. for (const line of doc.split('\n')) {
  687. if (/^[^%]*\\documentclass/.test(line)) {
  688. return ide.editorManager.getCurrentDocId()
  689. }
  690. }
  691. return null
  692. }
  693. function normalizeFilePath(path) {
  694. path = path.replace(
  695. /^(.*)\/compiles\/[0-9a-f]{24}(-[0-9a-f]{24})?\/(\.\/)?/,
  696. ''
  697. )
  698. path = path.replace(/^\/compile\//, '')
  699. const rootDocDirname = ide.fileTreeManager.getRootDocDirname()
  700. if (rootDocDirname) {
  701. path = path.replace(/^\.\//, rootDocDirname + '/')
  702. } else {
  703. path = path.replace(/^\.\//, '')
  704. }
  705. return path
  706. }
  707. $scope.recompile = function (options) {
  708. if (options == null) {
  709. options = {}
  710. }
  711. if ($scope.pdf.compiling) {
  712. return
  713. }
  714. eventTracking.sendMBSampled('editor-recompile-sampled', options)
  715. $scope.lastStartedCompileAt = Date.now()
  716. $scope.pdf.compiling = true
  717. $scope.pdf.isAutoCompileOnLoad =
  718. options != null ? options.isAutoCompileOnLoad : undefined // initial autocompile
  719. if (options != null ? options.force : undefined) {
  720. // for forced compile, turn off validation check and ignore errors
  721. $scope.stop_on_validation_error = false
  722. $scope.shouldShowLogs = false // hide the logs while compiling
  723. eventTracking.sendMB('syntax-check-turn-off-checking')
  724. }
  725. if (options != null ? options.try : undefined) {
  726. $scope.shouldShowLogs = false // hide the logs while compiling
  727. eventTracking.sendMB('syntax-check-try-compile-anyway')
  728. }
  729. ide.$scope.$broadcast('flush-changes')
  730. options.rootDocOverride_id = getRootDocOverrideId()
  731. const t0 = performance.now()
  732. sendCompileRequest(options)
  733. .then(function (response) {
  734. const { data } = response
  735. const compileTimeClientE2E = performance.now() - t0
  736. $scope.pdf.view = 'pdf'
  737. $scope.pdf.compiling = false
  738. parseCompileResponse(data, compileTimeClientE2E)
  739. })
  740. .catch(function (response) {
  741. const { status } = response
  742. if (status === 429) {
  743. $scope.pdf.rateLimited = true
  744. }
  745. $scope.pdf.compiling = false
  746. $scope.pdf.renderingError = false
  747. $scope.pdf.error = true
  748. $scope.pdf.view = 'errors'
  749. })
  750. .finally(() => {
  751. $scope.lastFinishedCompileAt = Date.now()
  752. })
  753. }
  754. // This needs to be public.
  755. ide.$scope.recompile = $scope.recompile
  756. // This method is a simply wrapper and exists only for tracking purposes.
  757. ide.$scope.recompileViaKey = function () {
  758. $scope.recompile({ keyShortcut: true })
  759. }
  760. $scope.stop = function () {
  761. if (!$scope.pdf.compiling) {
  762. return
  763. }
  764. return $http({
  765. url: `/project/${$scope.project_id}/compile/stop`,
  766. method: 'POST',
  767. params: {
  768. clsiserverid: ide.clsiServerId,
  769. },
  770. headers: {
  771. 'X-Csrf-Token': window.csrfToken,
  772. },
  773. })
  774. }
  775. $scope.clearCache = function () {
  776. $scope.pdf.clearingCache = true
  777. const deferred = $q.defer()
  778. // disable various download buttons
  779. $scope.pdf.url = null
  780. $scope.pdf.downloadUrl = null
  781. $scope.pdf.outputFiles = []
  782. $http({
  783. url: `/project/${$scope.project_id}/output`,
  784. method: 'DELETE',
  785. params: {
  786. clsiserverid: ide.clsiServerId,
  787. },
  788. headers: {
  789. 'X-Csrf-Token': window.csrfToken,
  790. },
  791. })
  792. .then(function (response) {
  793. $scope.pdf.clearingCache = false
  794. return deferred.resolve()
  795. })
  796. .catch(function (response) {
  797. console.error(response)
  798. const error = response.data
  799. $scope.pdf.clearingCache = false
  800. $scope.pdf.renderingError = false
  801. $scope.pdf.error = true
  802. $scope.pdf.view = 'errors'
  803. return deferred.reject(error)
  804. })
  805. return deferred.promise
  806. }
  807. $scope.recompileFromScratch = function () {
  808. $scope.pdf.compiling = true
  809. return $scope
  810. .clearCache()
  811. .then(() => {
  812. $scope.pdf.compiling = false
  813. $scope.recompile()
  814. })
  815. .catch(error => {
  816. console.error(error)
  817. })
  818. }
  819. $scope.toggleLogs = function () {
  820. $scope.$applyAsync(() => {
  821. $scope.shouldShowLogs = !$scope.shouldShowLogs
  822. if ($scope.shouldShowLogs) {
  823. eventTracking.sendMBOnce('ide-open-logs-once')
  824. }
  825. })
  826. }
  827. $scope.showPdf = function () {
  828. $scope.pdf.view = 'pdf'
  829. $scope.shouldShowLogs = false
  830. }
  831. $scope.toggleRawLog = function () {
  832. $scope.pdf.showRawLog = !$scope.pdf.showRawLog
  833. if ($scope.pdf.showRawLog) {
  834. eventTracking.sendMB('logs-view-raw')
  835. }
  836. }
  837. $scope.openClearCacheModal = function () {
  838. $modal.open({
  839. templateUrl: 'clearCacheModalTemplate',
  840. controller: 'ClearCacheModalController',
  841. scope: $scope,
  842. })
  843. }
  844. $scope.syncToCode = function (position) {
  845. synctex.syncToCode(position).then(function (data) {
  846. const { doc, line } = data
  847. ide.editorManager.openDoc(doc, { gotoLine: line })
  848. })
  849. }
  850. $scope.setAutoCompile = function (isOn) {
  851. $scope.$applyAsync(function () {
  852. $scope.autocompile_enabled = isOn
  853. })
  854. }
  855. $scope.setDraftMode = function (isOn) {
  856. $scope.$applyAsync(function () {
  857. $scope.draft = isOn
  858. })
  859. }
  860. $scope.setSyntaxCheck = function (isOn) {
  861. $scope.$applyAsync(function () {
  862. $scope.stop_on_validation_error = isOn
  863. })
  864. }
  865. $scope.runSyntaxCheckNow = function () {
  866. $scope.$applyAsync(function () {
  867. $scope.recompile({ check: true })
  868. })
  869. }
  870. $scope.openInEditor = function (entry) {
  871. let column, line
  872. eventTracking.sendMBOnce('logs-jump-to-location-once')
  873. const entity = ide.fileTreeManager.findEntityByPath(entry.file)
  874. if (entity == null || entity.type !== 'doc') {
  875. return
  876. }
  877. if (entry.line != null) {
  878. line = entry.line
  879. }
  880. if (entry.column != null) {
  881. column = entry.column
  882. }
  883. ide.editorManager.openDoc(entity, {
  884. gotoLine: line,
  885. gotoColumn: column,
  886. })
  887. }
  888. }
  889. )
  890. App.controller('ClearCacheModalController', function ($scope, $modalInstance) {
  891. $scope.state = { error: false, inflight: false }
  892. $scope.clear = function () {
  893. $scope.state.inflight = true
  894. $scope
  895. .clearCache()
  896. .then(function () {
  897. $scope.state.inflight = false
  898. $modalInstance.close()
  899. })
  900. .catch(function () {
  901. $scope.state.error = true
  902. $scope.state.inflight = false
  903. })
  904. }
  905. $scope.cancel = () => $modalInstance.dismiss('cancel')
  906. })
  907. // Wrap React component as Angular component. Only needed for "top-level" component
  908. App.component(
  909. 'previewPane',
  910. react2angular(
  911. rootContext.use(PreviewPane),
  912. Object.keys(PreviewPane.propTypes)
  913. )
  914. )