PdfController.js 36 KB

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