PdfController.js 37 KB

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