PdfController.js 37 KB

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