PdfController.js 38 KB

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