PdfController.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230
  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.pdf.downloadUrl = null
  443. $scope.shouldShowLogs = true
  444. fetchLogs(fileByPath, { pdfDownloadDomain })
  445. } else if (response.status === 'clsi-maintenance') {
  446. $scope.pdf.view = 'errors'
  447. $scope.pdf.clsiMaintenance = true
  448. } else if (response.status === 'unavailable') {
  449. $scope.pdf.view = 'errors'
  450. $scope.pdf.clsiUnavailable = true
  451. } else if (response.status === 'too-recently-compiled') {
  452. $scope.pdf.view = 'errors'
  453. $scope.pdf.tooRecentlyCompiled = true
  454. } else if (response.status === 'validation-problems') {
  455. $scope.pdf.view = 'validation-problems'
  456. $scope.pdf.validation = response.validationProblems
  457. $scope.shouldShowLogs = false
  458. } else if (response.status === 'compile-in-progress') {
  459. $scope.pdf.view = 'errors'
  460. $scope.pdf.compileInProgress = true
  461. } else {
  462. // fall back to displaying an error
  463. $scope.pdf.view = 'errors'
  464. $scope.pdf.error = true
  465. }
  466. if (window.showNewLogsUI) {
  467. $scope.$applyAsync(() => {
  468. $scope.pdf.compileFailed = false
  469. // `$scope.clsiErrors` stores the error states nested within `$scope.pdf`
  470. // for use with React's <PreviewPane errors={$scope.clsiErrors}/>
  471. $scope.clsiErrors = Object.assign(
  472. {},
  473. $scope.pdf.error ? { error: true } : null,
  474. $scope.pdf.renderingError ? { renderingError: true } : null,
  475. $scope.pdf.clsiMaintenance ? { clsiMaintenance: true } : null,
  476. $scope.pdf.clsiUnavailable ? { clsiUnavailable: true } : null,
  477. $scope.pdf.tooRecentlyCompiled
  478. ? { tooRecentlyCompiled: true }
  479. : null,
  480. $scope.pdf.compileTerminated ? { compileTerminated: true } : null,
  481. $scope.pdf.rateLimited ? { rateLimited: true } : null,
  482. $scope.pdf.compileInProgress ? { compileInProgress: true } : null,
  483. $scope.pdf.timedout ? { timedout: true } : null,
  484. $scope.pdf.projectTooLarge ? { projectTooLarge: true } : null,
  485. $scope.pdf.autoCompileDisabled
  486. ? { autoCompileDisabled: true }
  487. : null,
  488. $scope.pdf.failure ? { failure: true } : null
  489. )
  490. if (
  491. $scope.pdf.view === 'errors' ||
  492. $scope.pdf.view === 'validation-problems'
  493. ) {
  494. $scope.shouldShowLogs = true
  495. $scope.pdf.compileFailed = true
  496. }
  497. })
  498. }
  499. const IGNORE_FILES = ['output.fls', 'output.fdb_latexmk']
  500. $scope.pdf.outputFiles = []
  501. if (response.outputFiles == null) {
  502. return
  503. }
  504. // prepare list of output files for download dropdown
  505. qs = {}
  506. if (response.clsiServerId != null) {
  507. qs.clsiserverid = response.clsiServerId
  508. }
  509. for (const file of response.outputFiles) {
  510. if (IGNORE_FILES.indexOf(file.path) === -1) {
  511. const isOutputFile = /^output\./.test(file.path)
  512. $scope.pdf.outputFiles.push({
  513. // Turn 'output.blg' into 'blg file'.
  514. name: isOutputFile
  515. ? `${file.path.replace(/^output\./, '')} file`
  516. : file.path,
  517. url: file.url + createQueryString(qs),
  518. main: !!isOutputFile,
  519. fileName: file.path,
  520. type: file.type,
  521. })
  522. }
  523. }
  524. // sort the output files into order, main files first, then others
  525. $scope.pdf.outputFiles.sort(
  526. (a, b) => b.main - a.main || a.name.localeCompare(b.name)
  527. )
  528. }
  529. function fetchLogs(fileByPath, options) {
  530. let blgFile, chktexFile, logFile
  531. if (options != null ? options.validation : undefined) {
  532. chktexFile = fileByPath['output.chktex']
  533. } else {
  534. logFile = fileByPath['output.log']
  535. blgFile = fileByPath['output.blg']
  536. }
  537. function getFile(name, file) {
  538. const opts = {
  539. method: 'GET',
  540. url: buildPdfDownloadUrl(options.pdfDownloadDomain, file.url),
  541. params: {
  542. compileGroup: ide.compileGroup,
  543. clsiserverid: ide.clsiServerId,
  544. },
  545. }
  546. return $http(opts)
  547. }
  548. // accumulate the log entries
  549. const logEntries = {
  550. all: [],
  551. errors: [],
  552. warnings: [],
  553. typesetting: [],
  554. }
  555. function accumulateResults(newEntries) {
  556. for (const key of ['all', 'errors', 'warnings', 'typesetting']) {
  557. if (newEntries[key]) {
  558. if (newEntries.type != null) {
  559. for (const entry of newEntries[key]) {
  560. entry.type = newEntries.type
  561. }
  562. }
  563. logEntries[key] = logEntries[key].concat(newEntries[key])
  564. }
  565. }
  566. }
  567. // use the parsers for each file type
  568. function processLog(log) {
  569. $scope.pdf.rawLog = log
  570. const { errors, warnings, typesetting } = HumanReadableLogs.parse(log, {
  571. ignoreDuplicates: true,
  572. })
  573. const all = [].concat(errors, warnings, typesetting)
  574. accumulateResults({ all, errors, warnings, typesetting })
  575. }
  576. function processChkTex(log) {
  577. const errors = []
  578. const warnings = []
  579. for (const line of log.split('\n')) {
  580. var m
  581. if ((m = line.match(/^(\S+):(\d+):(\d+): (Error|Warning): (.*)/))) {
  582. const result = {
  583. file: m[1],
  584. line: m[2],
  585. column: m[3],
  586. level: m[4].toLowerCase(),
  587. message: `${m[4]}: ${m[5]}`,
  588. }
  589. if (result.level === 'error') {
  590. errors.push(result)
  591. } else {
  592. warnings.push(result)
  593. }
  594. }
  595. }
  596. const all = [].concat(errors, warnings)
  597. const logHints = HumanReadableLogs.parse({
  598. type: 'Syntax',
  599. all,
  600. errors,
  601. warnings,
  602. })
  603. eventTracking.sendMB('syntax-check-return-count', {
  604. errors: errors.length,
  605. warnings: warnings.length,
  606. })
  607. accumulateResults(logHints)
  608. }
  609. function processBiber(log) {
  610. const { errors, warnings } = BibLogParser.parse(log, {})
  611. const all = [].concat(errors, warnings)
  612. accumulateResults({ type: 'BibTeX:', all, errors, warnings })
  613. }
  614. // output the results
  615. function handleError() {
  616. $scope.pdf.logEntries = {}
  617. $scope.pdf.rawLog = ''
  618. }
  619. function annotateFiles() {
  620. $scope.pdf.logEntries = logEntries
  621. $scope.pdf.logEntryAnnotations = {}
  622. for (const entry of logEntries.all) {
  623. if (entry.file != null) {
  624. entry.file = normalizeFilePath(entry.file)
  625. const entity = ide.fileTreeManager.findEntityByPath(entry.file)
  626. if (entity != null) {
  627. if (!$scope.pdf.logEntryAnnotations[entity.id]) {
  628. $scope.pdf.logEntryAnnotations[entity.id] = []
  629. }
  630. $scope.pdf.logEntryAnnotations[entity.id].push({
  631. row: entry.line - 1,
  632. type: entry.level === 'error' ? 'error' : 'warning',
  633. text: entry.message,
  634. })
  635. }
  636. }
  637. }
  638. }
  639. // retrieve the logfile and process it
  640. let response
  641. if (logFile != null) {
  642. response = getFile('output.log', logFile).then(response =>
  643. processLog(response.data)
  644. )
  645. if (blgFile != null) {
  646. // retrieve the blg file if present
  647. response = response.then(() =>
  648. getFile('output.blg', blgFile).then(
  649. response => processBiber(response.data),
  650. () => true
  651. )
  652. )
  653. }
  654. }
  655. if (response != null) {
  656. response.catch(handleError)
  657. } else {
  658. handleError()
  659. }
  660. if (chktexFile != null) {
  661. const getChkTex = () =>
  662. getFile('output.chktex', chktexFile).then(response =>
  663. processChkTex(response.data)
  664. )
  665. // always retrieve the chktex file if present
  666. if (response != null) {
  667. response = response.then(getChkTex, getChkTex)
  668. } else {
  669. response = getChkTex()
  670. }
  671. }
  672. // display the combined result
  673. if (response != null) {
  674. response.finally(() => {
  675. annotateFiles()
  676. sendCompileMetrics()
  677. })
  678. }
  679. }
  680. function sendCompileMetrics() {
  681. const hasCompiled =
  682. $scope.pdf.view !== 'errors' &&
  683. $scope.pdf.view !== 'validation-problems'
  684. if (hasCompiled && !window.user.alphaProgram) {
  685. const metadata = {
  686. errors: $scope.pdf.logEntries.errors.length,
  687. warnings: $scope.pdf.logEntries.warnings.length,
  688. typesetting: $scope.pdf.logEntries.typesetting.length,
  689. newLogsUI: window.showNewLogsUI,
  690. subvariant: window.showNewLogsUI ? window.logsUISubvariant : null,
  691. }
  692. eventTracking.sendMBSampled(
  693. 'compile-result',
  694. JSON.stringify(metadata),
  695. 0.01
  696. )
  697. }
  698. }
  699. function getRootDocOverrideId() {
  700. const rootDocId = $scope.project.rootDoc_id
  701. const currentDocId = ide.editorManager.getCurrentDocId()
  702. if (currentDocId === rootDocId) {
  703. return null // no need to override when in the root doc itself
  704. }
  705. const doc = ide.editorManager.getCurrentDocValue()
  706. if (doc == null) {
  707. return null
  708. }
  709. for (const line of doc.split('\n')) {
  710. if (/^[^%]*\\documentclass/.test(line)) {
  711. return ide.editorManager.getCurrentDocId()
  712. }
  713. }
  714. return null
  715. }
  716. function normalizeFilePath(path) {
  717. path = path.replace(
  718. /^(.*)\/compiles\/[0-9a-f]{24}(-[0-9a-f]{24})?\/(\.\/)?/,
  719. ''
  720. )
  721. path = path.replace(/^\/compile\//, '')
  722. const rootDocDirname = ide.fileTreeManager.getRootDocDirname()
  723. if (rootDocDirname != null) {
  724. path = path.replace(/^\.\//, rootDocDirname + '/')
  725. }
  726. return path
  727. }
  728. $scope.recompile = function (options) {
  729. if (options == null) {
  730. options = {}
  731. }
  732. if ($scope.pdf.compiling) {
  733. return
  734. }
  735. eventTracking.sendMBSampled('editor-recompile-sampled', options)
  736. $scope.lastStartedCompileAt = Date.now()
  737. $scope.pdf.compiling = true
  738. $scope.pdf.isAutoCompileOnLoad =
  739. options != null ? options.isAutoCompileOnLoad : undefined // initial autocompile
  740. if (options != null ? options.force : undefined) {
  741. // for forced compile, turn off validation check and ignore errors
  742. $scope.stop_on_validation_error = false
  743. $scope.shouldShowLogs = false // hide the logs while compiling
  744. eventTracking.sendMB('syntax-check-turn-off-checking')
  745. }
  746. if (options != null ? options.try : undefined) {
  747. $scope.shouldShowLogs = false // hide the logs while compiling
  748. eventTracking.sendMB('syntax-check-try-compile-anyway')
  749. }
  750. ide.$scope.$broadcast('flush-changes')
  751. options.rootDocOverride_id = getRootDocOverrideId()
  752. const t0 = performance.now()
  753. sendCompileRequest(options)
  754. .then(function (response) {
  755. const { data } = response
  756. const compileTimeClientE2E = performance.now() - t0
  757. $scope.$applyAsync(() => {
  758. $scope.pdf.view = 'pdf'
  759. $scope.pdf.compiling = false
  760. parseCompileResponse(data, compileTimeClientE2E)
  761. })
  762. })
  763. .catch(function (response) {
  764. const { status } = response
  765. $scope.$applyAsync(() => {
  766. if (status === 429) {
  767. $scope.pdf.rateLimited = true
  768. }
  769. $scope.pdf.compiling = false
  770. $scope.pdf.renderingError = false
  771. $scope.pdf.error = true
  772. $scope.pdf.view = 'errors'
  773. if (window.showNewLogsUI) {
  774. $scope.clsiErrors = { error: true }
  775. $scope.shouldShowLogs = true
  776. $scope.pdf.compileFailed = true
  777. }
  778. })
  779. })
  780. .finally(() => {
  781. $scope.$applyAsync(() => {
  782. $scope.lastFinishedCompileAt = Date.now()
  783. })
  784. })
  785. }
  786. // This needs to be public.
  787. ide.$scope.recompile = $scope.recompile
  788. // This method is a simply wrapper and exists only for tracking purposes.
  789. ide.$scope.recompileViaKey = function () {
  790. $scope.recompile({ keyShortcut: true })
  791. }
  792. $scope.stop = function () {
  793. if (!$scope.pdf.compiling) {
  794. return
  795. }
  796. return $http({
  797. url: `/project/${$scope.project_id}/compile/stop`,
  798. method: 'POST',
  799. params: {
  800. clsiserverid: ide.clsiServerId,
  801. },
  802. headers: {
  803. 'X-Csrf-Token': window.csrfToken,
  804. },
  805. })
  806. }
  807. $scope.clearCache = function () {
  808. $scope.pdf.clearingCache = true
  809. const deferred = $q.defer()
  810. // disable various download buttons
  811. $scope.pdf.url = null
  812. $scope.pdf.downloadUrl = null
  813. $scope.pdf.outputFiles = []
  814. $http({
  815. url: `/project/${$scope.project_id}/output`,
  816. method: 'DELETE',
  817. params: {
  818. clsiserverid: ide.clsiServerId,
  819. },
  820. headers: {
  821. 'X-Csrf-Token': window.csrfToken,
  822. },
  823. })
  824. .then(function (response) {
  825. $scope.pdf.clearingCache = false
  826. return deferred.resolve()
  827. })
  828. .catch(function (response) {
  829. console.error(response)
  830. const error = response.data
  831. $scope.pdf.clearingCache = false
  832. $scope.pdf.renderingError = false
  833. $scope.pdf.error = true
  834. $scope.pdf.view = 'errors'
  835. return deferred.reject(error)
  836. })
  837. return deferred.promise
  838. }
  839. $scope.recompileFromScratch = function () {
  840. $scope.pdf.compiling = true
  841. return $scope
  842. .clearCache()
  843. .then(() => {
  844. $scope.pdf.compiling = false
  845. $scope.recompile()
  846. })
  847. .catch(error => {
  848. console.error(error)
  849. })
  850. }
  851. $scope.toggleLogs = function () {
  852. $scope.$applyAsync(() => {
  853. $scope.shouldShowLogs = !$scope.shouldShowLogs
  854. if ($scope.shouldShowLogs) {
  855. eventTracking.sendMBOnce('ide-open-logs-once')
  856. }
  857. })
  858. }
  859. $scope.showPdf = function () {
  860. $scope.pdf.view = 'pdf'
  861. $scope.shouldShowLogs = false
  862. }
  863. $scope.toggleRawLog = function () {
  864. $scope.pdf.showRawLog = !$scope.pdf.showRawLog
  865. if ($scope.pdf.showRawLog) {
  866. eventTracking.sendMB('logs-view-raw')
  867. }
  868. }
  869. $scope.openClearCacheModal = function () {
  870. $modal.open({
  871. templateUrl: 'clearCacheModalTemplate',
  872. controller: 'ClearCacheModalController',
  873. scope: $scope,
  874. })
  875. }
  876. $scope.syncToCode = function (position) {
  877. synctex.syncToCode(position).then(function (data) {
  878. const { doc, line } = data
  879. ide.editorManager.openDoc(doc, { gotoLine: line })
  880. })
  881. }
  882. $scope.setAutoCompile = function (isOn) {
  883. $scope.$applyAsync(function () {
  884. $scope.autocompile_enabled = isOn
  885. })
  886. }
  887. $scope.setDraftMode = function (isOn) {
  888. $scope.$applyAsync(function () {
  889. $scope.draft = isOn
  890. })
  891. }
  892. $scope.setSyntaxCheck = function (isOn) {
  893. $scope.$applyAsync(function () {
  894. $scope.stop_on_validation_error = isOn
  895. })
  896. }
  897. $scope.runSyntaxCheckNow = function () {
  898. $scope.$applyAsync(function () {
  899. $scope.recompile({ check: true })
  900. })
  901. }
  902. $scope.openInEditor = function (entry) {
  903. let column, line
  904. eventTracking.sendMBOnce('logs-jump-to-location-once')
  905. const entity = ide.fileTreeManager.findEntityByPath(entry.file)
  906. if (entity == null || entity.type !== 'doc') {
  907. return
  908. }
  909. if (entry.line != null) {
  910. line = entry.line
  911. }
  912. if (entry.column != null) {
  913. column = entry.column
  914. }
  915. ide.editorManager.openDoc(entity, {
  916. gotoLine: line,
  917. gotoColumn: column,
  918. })
  919. }
  920. }
  921. )
  922. App.factory('synctex', function (ide, $http, $q) {
  923. const synctex = {
  924. syncToPdfInFlight: false,
  925. syncToCodeInFlight: false,
  926. syncToPdf(cursorPosition) {
  927. const deferred = $q.defer()
  928. const docId = ide.editorManager.getCurrentDocId()
  929. if (docId == null) {
  930. deferred.reject()
  931. return deferred.promise
  932. }
  933. const doc = ide.fileTreeManager.findEntityById(docId)
  934. if (doc == null) {
  935. deferred.reject()
  936. return deferred.promise
  937. }
  938. let path = ide.fileTreeManager.getEntityPath(doc)
  939. if (path == null) {
  940. deferred.reject()
  941. return deferred.promise
  942. }
  943. // If the root file is folder/main.tex, then synctex sees the
  944. // path as folder/./main.tex
  945. const rootDocDirname = ide.fileTreeManager.getRootDocDirname()
  946. if (rootDocDirname != null && rootDocDirname !== '') {
  947. path = path.replace(RegExp(`^${rootDocDirname}`), `${rootDocDirname}/.`)
  948. }
  949. const { row, column } = cursorPosition
  950. this.syncToPdfInFlight = true
  951. $http({
  952. url: `/project/${ide.project_id}/sync/code`,
  953. method: 'GET',
  954. params: {
  955. file: path,
  956. line: row + 1,
  957. column,
  958. clsiserverid: ide.clsiServerId,
  959. },
  960. })
  961. .then(response => {
  962. this.syncToPdfInFlight = false
  963. const { data } = response
  964. return deferred.resolve(data.pdf || [])
  965. })
  966. .catch(response => {
  967. this.syncToPdfInFlight = false
  968. const error = response.data
  969. return deferred.reject(error)
  970. })
  971. return deferred.promise
  972. },
  973. syncToCode(position, options) {
  974. if (options == null) {
  975. options = {}
  976. }
  977. const deferred = $q.defer()
  978. if (position == null) {
  979. deferred.reject()
  980. return deferred.promise
  981. }
  982. // FIXME: this actually works better if it's halfway across the
  983. // page (or the visible part of the page). Synctex doesn't
  984. // always find the right place in the file when the point is at
  985. // the edge of the page, it sometimes returns the start of the
  986. // next paragraph instead.
  987. const h = position.offset.left
  988. // Compute the vertical position to pass to synctex, which
  989. // works with coordinates increasing from the top of the page
  990. // down. This matches the browser's DOM coordinate of the
  991. // click point, but the pdf position is measured from the
  992. // bottom of the page so we need to invert it.
  993. let v
  994. if (
  995. options.fromPdfPosition &&
  996. (position.pageSize != null ? position.pageSize.height : undefined) !=
  997. null
  998. ) {
  999. v = position.pageSize.height - position.offset.top || 0 // measure from pdf point (inverted)
  1000. } else {
  1001. v = position.offset.top || 0 // measure from html click position
  1002. }
  1003. // It's not clear exactly where we should sync to if it wasn't directly
  1004. // clicked on, but a little bit down from the very top seems best.
  1005. if (options.includeVisualOffset) {
  1006. v += 72 // use the same value as in pdfViewer highlighting visual offset
  1007. }
  1008. this.syncToCodeInFlight = true
  1009. $http({
  1010. url: `/project/${ide.project_id}/sync/pdf`,
  1011. method: 'GET',
  1012. params: {
  1013. page: position.page + 1,
  1014. h: h.toFixed(2),
  1015. v: v.toFixed(2),
  1016. clsiserverid: ide.clsiServerId,
  1017. },
  1018. })
  1019. .then(response => {
  1020. this.syncToCodeInFlight = false
  1021. const { data } = response
  1022. if (
  1023. data.code != null &&
  1024. data.code.length > 0 &&
  1025. data.code[0].file !== ''
  1026. ) {
  1027. const doc = ide.fileTreeManager.findEntityByPath(data.code[0].file)
  1028. if (doc == null) {
  1029. deferred.reject()
  1030. }
  1031. return deferred.resolve({ doc, line: data.code[0].line })
  1032. } else if (data.code[0].file === '') {
  1033. ide.$scope.sync_tex_error = true
  1034. setTimeout(() => (ide.$scope.sync_tex_error = false), 4000)
  1035. }
  1036. })
  1037. .catch(response => {
  1038. this.syncToCodeInFlight = false
  1039. const error = response.data
  1040. return deferred.reject(error)
  1041. })
  1042. return deferred.promise
  1043. },
  1044. }
  1045. return synctex
  1046. })
  1047. App.controller('PdfSynctexController', function ($scope, synctex, ide) {
  1048. this.cursorPosition = null
  1049. $scope.$watch(
  1050. () => synctex.syncToPdfInFlight,
  1051. value => ($scope.syncToPdfInFlight = value)
  1052. )
  1053. $scope.$watch(
  1054. () => synctex.syncToCodeInFlight,
  1055. value => ($scope.syncToCodeInFlight = value)
  1056. )
  1057. ide.$scope.$on('cursor:editor:update', (event, cursorPosition) => {
  1058. this.cursorPosition = cursorPosition
  1059. })
  1060. $scope.syncToPdf = () => {
  1061. if (this.cursorPosition == null) {
  1062. return
  1063. }
  1064. synctex.syncToPdf(this.cursorPosition).then(highlights => {
  1065. $scope.pdf.highlights = highlights
  1066. })
  1067. }
  1068. ide.$scope.$on('cursor:editor:syncToPdf', $scope.syncToPdf)
  1069. $scope.syncToCode = function () {
  1070. synctex
  1071. .syncToCode($scope.pdf.position, {
  1072. includeVisualOffset: true,
  1073. fromPdfPosition: true,
  1074. })
  1075. .then(function (data) {
  1076. const { doc, line } = data
  1077. ide.editorManager.openDoc(doc, { gotoLine: line })
  1078. })
  1079. }
  1080. })
  1081. App.controller('ClearCacheModalController', function ($scope, $modalInstance) {
  1082. $scope.state = { error: false, inflight: false }
  1083. $scope.clear = function () {
  1084. $scope.state.inflight = true
  1085. $scope
  1086. .clearCache()
  1087. .then(function () {
  1088. $scope.state.inflight = false
  1089. $modalInstance.close()
  1090. })
  1091. .catch(function () {
  1092. $scope.state.error = true
  1093. $scope.state.inflight = false
  1094. })
  1095. }
  1096. $scope.cancel = () => $modalInstance.dismiss('cancel')
  1097. })
  1098. // Wrap React component as Angular component. Only needed for "top-level" component
  1099. App.component(
  1100. 'previewPane',
  1101. react2angular(
  1102. rootContext.use(PreviewPane),
  1103. Object.keys(PreviewPane.propTypes)
  1104. )
  1105. )