PdfController.js 31 KB

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