PdfController.js 37 KB

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