PdfController.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232
  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. 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. let setup = Promise.resolve()
  245. const params = {}
  246. if (options.isAutoCompileOnLoad || options.isAutoCompileOnChange) {
  247. params.auto_compile = true
  248. }
  249. if (getMeta('ol-enablePdfCaching')) {
  250. setup = waitForServiceWorker()
  251. params.enable_pdf_caching = true
  252. }
  253. // if the previous run was a check, clear the error logs
  254. if ($scope.check) {
  255. $scope.pdf.logEntries = {}
  256. }
  257. // keep track of whether this is a compile or check
  258. $scope.check = !!options.check
  259. if (options.check) {
  260. eventTracking.sendMB('syntax-check-request')
  261. }
  262. // send appropriate check type to clsi
  263. let checkType
  264. if ($scope.check) {
  265. checkType = 'validate' // validate only
  266. } else if (options.try) {
  267. checkType = 'silent' // allow use to try compile once
  268. } else if ($scope.stop_on_validation_error) {
  269. checkType = 'error' // try to compile
  270. } else {
  271. checkType = 'silent' // ignore errors
  272. }
  273. // FIXME: Temporarily disable syntax checking as it is causing
  274. // excessive support requests for projects migrated from v1
  275. // https://github.com/overleaf/sharelatex/issues/911
  276. if (checkType === 'error') {
  277. checkType = 'silent'
  278. }
  279. return setup.then(() =>
  280. $http.post(
  281. url,
  282. {
  283. rootDoc_id: options.rootDocOverride_id || null,
  284. draft: $scope.draft,
  285. check: checkType,
  286. // use incremental compile for all users but revert to a full
  287. // compile if there is a server error
  288. incrementalCompilesEnabled: !$scope.pdf.error,
  289. _csrf: window.csrfToken,
  290. },
  291. { params }
  292. )
  293. )
  294. }
  295. function buildPdfDownloadUrl(pdfDownloadDomain, url) {
  296. if (pdfDownloadDomain) {
  297. return `${pdfDownloadDomain}${url}`
  298. } else {
  299. return url
  300. }
  301. }
  302. function noop() {}
  303. function parseCompileResponse(response) {
  304. // keep last url
  305. const lastPdfUrl = $scope.pdf.url
  306. const { pdfDownloadDomain } = response
  307. // Reset everything
  308. $scope.pdf.error = false
  309. $scope.pdf.timedout = false
  310. $scope.pdf.failure = false
  311. $scope.pdf.url = null
  312. $scope.pdf.updateConsumedBandwidth = noop
  313. $scope.pdf.firstRenderDone = noop
  314. $scope.pdf.clsiMaintenance = false
  315. $scope.pdf.tooRecentlyCompiled = false
  316. $scope.pdf.renderingError = false
  317. $scope.pdf.projectTooLarge = false
  318. $scope.pdf.compileTerminated = false
  319. $scope.pdf.compileExited = false
  320. $scope.pdf.failedCheck = false
  321. $scope.pdf.compileInProgress = false
  322. $scope.pdf.autoCompileDisabled = false
  323. if (window.showNewLogsUI) {
  324. $scope.clsiErrors = {}
  325. }
  326. // make a cache to look up files by name
  327. const fileByPath = {}
  328. if (response.outputFiles != null) {
  329. for (const file of response.outputFiles) {
  330. fileByPath[file.path] = file
  331. }
  332. }
  333. // prepare query string
  334. let qs = {}
  335. // add a query string parameter for the compile group
  336. if (response.compileGroup != null) {
  337. ide.compileGroup = qs.compileGroup = response.compileGroup
  338. }
  339. // add a query string parameter for the clsi server id
  340. if (response.clsiServerId != null) {
  341. ide.clsiServerId = qs.clsiserverid = response.clsiServerId
  342. }
  343. // TODO(das7pad): drop this hack once 2747f0d40af8729304 has landed in clsi
  344. if (response.status === 'success' && !fileByPath['output.pdf']) {
  345. response.status = 'failure'
  346. }
  347. if (response.status === 'success') {
  348. $scope.pdf.view = 'pdf'
  349. $scope.shouldShowLogs = false
  350. $scope.pdf.lastCompileTimestamp = Date.now()
  351. $scope.pdf.validation = {}
  352. $scope.pdf.url = buildPdfDownloadUrl(
  353. pdfDownloadDomain,
  354. fileByPath['output.pdf'].url
  355. )
  356. // convert the qs hash into a query string and append it
  357. $scope.pdf.url += createQueryString(qs)
  358. const {
  359. onFirstRenderDone,
  360. firstRenderDone,
  361. updateConsumedBandwidth,
  362. } = trackPDFDownload()
  363. $scope.pdf.firstRenderDone = firstRenderDone
  364. $scope.pdf.updateConsumedBandwidth = updateConsumedBandwidth
  365. const { serviceWorkerMetrics } = response
  366. onFirstRenderDone.then(({ latencyFetch, latencyRender }) => {
  367. sl_console.log(
  368. JSON.stringify({
  369. latencyFetch,
  370. latencyRender,
  371. totalBandwidthReportedByPdfJs,
  372. serviceWorkerMetrics,
  373. })
  374. )
  375. })
  376. // Save all downloads as files
  377. qs.popupDownload = true
  378. const { build: buildId } = fileByPath['output.pdf']
  379. $scope.pdf.downloadUrl =
  380. `/download/project/${$scope.project_id}/build/${buildId}/output/output.pdf` +
  381. createQueryString(qs)
  382. fetchLogs(fileByPath, { pdfDownloadDomain })
  383. } else if (response.status === 'timedout') {
  384. $scope.pdf.view = 'errors'
  385. $scope.pdf.timedout = true
  386. fetchLogs(fileByPath, { pdfDownloadDomain })
  387. if (
  388. !$scope.hasPremiumCompile &&
  389. ide.$scope.project.owner._id === ide.$scope.user.id
  390. ) {
  391. eventTracking.send(
  392. 'subscription-funnel',
  393. 'editor-click-feature',
  394. 'compile-timeout'
  395. )
  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.autoCompileDisabled ? { autoCompileDisabled: true } : null
  476. )
  477. if (
  478. $scope.pdf.view === 'errors' ||
  479. $scope.pdf.view === 'validation-problems'
  480. ) {
  481. $scope.shouldShowLogs = true
  482. $scope.pdf.compileFailed = true
  483. }
  484. }
  485. const IGNORE_FILES = ['output.fls', 'output.fdb_latexmk']
  486. $scope.pdf.outputFiles = []
  487. if (response.outputFiles == null) {
  488. return
  489. }
  490. // prepare list of output files for download dropdown
  491. qs = {}
  492. if (response.clsiServerId != null) {
  493. qs.clsiserverid = response.clsiServerId
  494. }
  495. for (const file of response.outputFiles) {
  496. if (IGNORE_FILES.indexOf(file.path) === -1) {
  497. const isOutputFile = /^output\./.test(file.path)
  498. $scope.pdf.outputFiles.push({
  499. // Turn 'output.blg' into 'blg file'.
  500. name: isOutputFile
  501. ? `${file.path.replace(/^output\./, '')} file`
  502. : file.path,
  503. url: file.url + createQueryString(qs),
  504. main: !!isOutputFile,
  505. fileName: file.path,
  506. type: file.type,
  507. })
  508. }
  509. }
  510. // sort the output files into order, main files first, then others
  511. $scope.pdf.outputFiles.sort(
  512. (a, b) => b.main - a.main || a.name.localeCompare(b.name)
  513. )
  514. }
  515. let totalBandwidthReportedByPdfJs = 0
  516. function trackPDFDownload() {
  517. const t0 = performance.now()
  518. let bandwidth = 0
  519. function firstRenderDone({ timePDFFetched, timePDFRendered }) {
  520. const latencyFetch = timePDFFetched - t0
  521. // The renderer does not yield in case the browser tab is hidden.
  522. // It will yield when the browser tab is visible again.
  523. // This will skew our performance metrics for rendering!
  524. const latencyRender = timePDFRendered - t0
  525. done({ latencyFetch, latencyRender })
  526. }
  527. function updateConsumedBandwidth(bytes) {
  528. totalBandwidthReportedByPdfJs += bytes - bandwidth
  529. bandwidth = bytes
  530. }
  531. let done
  532. const onFirstRenderDone = new Promise(resolve => {
  533. done = resolve
  534. })
  535. return {
  536. onFirstRenderDone,
  537. firstRenderDone,
  538. updateConsumedBandwidth,
  539. }
  540. }
  541. function fetchLogs(fileByPath, options) {
  542. let blgFile, chktexFile, logFile
  543. if (options != null ? options.validation : undefined) {
  544. chktexFile = fileByPath['output.chktex']
  545. } else {
  546. logFile = fileByPath['output.log']
  547. blgFile = fileByPath['output.blg']
  548. }
  549. function getFile(name, file) {
  550. const opts = {
  551. method: 'GET',
  552. url: buildPdfDownloadUrl(options.pdfDownloadDomain, file.url),
  553. params: {
  554. compileGroup: ide.compileGroup,
  555. clsiserverid: ide.clsiServerId,
  556. },
  557. }
  558. return $http(opts)
  559. }
  560. // accumulate the log entries
  561. const logEntries = {
  562. all: [],
  563. errors: [],
  564. warnings: [],
  565. typesetting: [],
  566. }
  567. function accumulateResults(newEntries) {
  568. for (const key of ['all', 'errors', 'warnings', 'typesetting']) {
  569. if (newEntries[key]) {
  570. if (newEntries.type != null) {
  571. for (const entry of newEntries[key]) {
  572. entry.type = newEntries.type
  573. }
  574. }
  575. logEntries[key] = logEntries[key].concat(newEntries[key])
  576. }
  577. }
  578. }
  579. // use the parsers for each file type
  580. function processLog(log) {
  581. $scope.pdf.rawLog = log
  582. const { errors, warnings, typesetting } = HumanReadableLogs.parse(log, {
  583. ignoreDuplicates: true,
  584. })
  585. const all = [].concat(errors, warnings, typesetting)
  586. accumulateResults({ all, errors, warnings, typesetting })
  587. }
  588. function processChkTex(log) {
  589. const errors = []
  590. const warnings = []
  591. for (const line of log.split('\n')) {
  592. var m
  593. if ((m = line.match(/^(\S+):(\d+):(\d+): (Error|Warning): (.*)/))) {
  594. const result = {
  595. file: m[1],
  596. line: m[2],
  597. column: m[3],
  598. level: m[4].toLowerCase(),
  599. message: `${m[4]}: ${m[5]}`,
  600. }
  601. if (result.level === 'error') {
  602. errors.push(result)
  603. } else {
  604. warnings.push(result)
  605. }
  606. }
  607. }
  608. const all = [].concat(errors, warnings)
  609. const logHints = HumanReadableLogs.parse({
  610. type: 'Syntax',
  611. all,
  612. errors,
  613. warnings,
  614. })
  615. eventTracking.sendMB('syntax-check-return-count', {
  616. errors: errors.length,
  617. warnings: warnings.length,
  618. })
  619. accumulateResults(logHints)
  620. }
  621. function processBiber(log) {
  622. const { errors, warnings } = BibLogParser.parse(log, {})
  623. const all = [].concat(errors, warnings)
  624. accumulateResults({ type: 'BibTeX:', all, errors, warnings })
  625. }
  626. // output the results
  627. function handleError() {
  628. $scope.pdf.logEntries = {}
  629. $scope.pdf.rawLog = ''
  630. }
  631. function annotateFiles() {
  632. $scope.pdf.logEntries = logEntries
  633. $scope.pdf.logEntryAnnotations = {}
  634. for (const entry of logEntries.all) {
  635. if (entry.file != null) {
  636. entry.file = normalizeFilePath(entry.file)
  637. const entity = ide.fileTreeManager.findEntityByPath(entry.file)
  638. if (entity != null) {
  639. if (!$scope.pdf.logEntryAnnotations[entity.id]) {
  640. $scope.pdf.logEntryAnnotations[entity.id] = []
  641. }
  642. $scope.pdf.logEntryAnnotations[entity.id].push({
  643. row: entry.line - 1,
  644. type: entry.level === 'error' ? 'error' : 'warning',
  645. text: entry.message,
  646. })
  647. }
  648. }
  649. }
  650. }
  651. // retrieve the logfile and process it
  652. let response
  653. if (logFile != null) {
  654. response = getFile('output.log', logFile).then(response =>
  655. processLog(response.data)
  656. )
  657. if (blgFile != null) {
  658. // retrieve the blg file if present
  659. response = response.then(() =>
  660. getFile('output.blg', blgFile).then(
  661. response => processBiber(response.data),
  662. () => true
  663. )
  664. )
  665. }
  666. }
  667. if (response != null) {
  668. response.catch(handleError)
  669. } else {
  670. handleError()
  671. }
  672. if (chktexFile != null) {
  673. const getChkTex = () =>
  674. getFile('output.chktex', chktexFile).then(response =>
  675. processChkTex(response.data)
  676. )
  677. // always retrieve the chktex file if present
  678. if (response != null) {
  679. response = response.then(getChkTex, getChkTex)
  680. } else {
  681. response = getChkTex()
  682. }
  683. }
  684. // display the combined result
  685. if (response != null) {
  686. response.finally(() => {
  687. annotateFiles()
  688. sendCompileMetrics()
  689. })
  690. }
  691. }
  692. function sendCompileMetrics() {
  693. const hasCompiled =
  694. $scope.pdf.view !== 'errors' &&
  695. $scope.pdf.view !== 'validation-problems'
  696. if (hasCompiled && !window.user.alphaProgram) {
  697. const metadata = {
  698. errors: $scope.pdf.logEntries.errors.length,
  699. warnings: $scope.pdf.logEntries.warnings.length,
  700. typesetting: $scope.pdf.logEntries.typesetting.length,
  701. newLogsUI: window.showNewLogsUI,
  702. subvariant: window.showNewLogsUI ? window.logsUISubvariant : null,
  703. }
  704. eventTracking.sendMBSampled(
  705. 'compile-result',
  706. JSON.stringify(metadata),
  707. 0.01
  708. )
  709. }
  710. }
  711. function getRootDocOverrideId() {
  712. const rootDocId = $scope.project.rootDoc_id
  713. const currentDocId = ide.editorManager.getCurrentDocId()
  714. if (currentDocId === rootDocId) {
  715. return null // no need to override when in the root doc itself
  716. }
  717. const doc = ide.editorManager.getCurrentDocValue()
  718. if (doc == null) {
  719. return null
  720. }
  721. for (const line of doc.split('\n')) {
  722. if (/^[^%]*\\documentclass/.test(line)) {
  723. return ide.editorManager.getCurrentDocId()
  724. }
  725. }
  726. return null
  727. }
  728. function normalizeFilePath(path) {
  729. path = path.replace(
  730. /^(.*)\/compiles\/[0-9a-f]{24}(-[0-9a-f]{24})?\/(\.\/)?/,
  731. ''
  732. )
  733. path = path.replace(/^\/compile\//, '')
  734. const rootDocDirname = ide.fileTreeManager.getRootDocDirname()
  735. if (rootDocDirname != null) {
  736. path = path.replace(/^\.\//, rootDocDirname + '/')
  737. }
  738. return path
  739. }
  740. $scope.recompile = function (options) {
  741. if (options == null) {
  742. options = {}
  743. }
  744. if ($scope.pdf.compiling) {
  745. return
  746. }
  747. eventTracking.sendMBSampled('editor-recompile-sampled', options)
  748. $scope.lastStartedCompileAt = Date.now()
  749. $scope.pdf.compiling = true
  750. $scope.pdf.isAutoCompileOnLoad =
  751. options != null ? options.isAutoCompileOnLoad : undefined // initial autocompile
  752. if (options != null ? options.force : undefined) {
  753. // for forced compile, turn off validation check and ignore errors
  754. $scope.stop_on_validation_error = false
  755. $scope.shouldShowLogs = false // hide the logs while compiling
  756. eventTracking.sendMB('syntax-check-turn-off-checking')
  757. }
  758. if (options != null ? options.try : undefined) {
  759. $scope.shouldShowLogs = false // hide the logs while compiling
  760. eventTracking.sendMB('syntax-check-try-compile-anyway')
  761. }
  762. ide.$scope.$broadcast('flush-changes')
  763. options.rootDocOverride_id = getRootDocOverrideId()
  764. sendCompileRequest(options)
  765. .then(function (response) {
  766. const { data } = response
  767. $scope.pdf.view = 'pdf'
  768. $scope.pdf.compiling = false
  769. parseCompileResponse(data)
  770. })
  771. .catch(function (response) {
  772. const { status } = response
  773. if (status === 429) {
  774. $scope.pdf.rateLimited = true
  775. }
  776. $scope.pdf.compiling = false
  777. $scope.pdf.renderingError = false
  778. $scope.pdf.error = true
  779. $scope.pdf.view = 'errors'
  780. if (window.showNewLogsUI) {
  781. $scope.clsiErrors = { error: true }
  782. $scope.shouldShowLogs = true
  783. $scope.pdf.compileFailed = true
  784. }
  785. })
  786. .finally(() => {
  787. $scope.lastFinishedCompileAt = Date.now()
  788. })
  789. }
  790. // This needs to be public.
  791. ide.$scope.recompile = $scope.recompile
  792. // This method is a simply wrapper and exists only for tracking purposes.
  793. ide.$scope.recompileViaKey = function () {
  794. $scope.recompile({ keyShortcut: true })
  795. }
  796. $scope.stop = function () {
  797. if (!$scope.pdf.compiling) {
  798. return
  799. }
  800. return $http({
  801. url: `/project/${$scope.project_id}/compile/stop`,
  802. method: 'POST',
  803. params: {
  804. clsiserverid: ide.clsiServerId,
  805. },
  806. headers: {
  807. 'X-Csrf-Token': window.csrfToken,
  808. },
  809. })
  810. }
  811. $scope.clearCache = function () {
  812. $scope.pdf.clearingCache = true
  813. const deferred = $q.defer()
  814. // disable various download buttons
  815. $scope.pdf.url = null
  816. $scope.pdf.downloadUrl = null
  817. $scope.pdf.outputFiles = []
  818. $http({
  819. url: `/project/${$scope.project_id}/output`,
  820. method: 'DELETE',
  821. params: {
  822. clsiserverid: ide.clsiServerId,
  823. },
  824. headers: {
  825. 'X-Csrf-Token': window.csrfToken,
  826. },
  827. })
  828. .then(function (response) {
  829. $scope.pdf.clearingCache = false
  830. return deferred.resolve()
  831. })
  832. .catch(function (response) {
  833. console.error(response)
  834. const error = response.data
  835. $scope.pdf.clearingCache = false
  836. $scope.pdf.renderingError = false
  837. $scope.pdf.error = true
  838. $scope.pdf.view = 'errors'
  839. return deferred.reject(error)
  840. })
  841. return deferred.promise
  842. }
  843. $scope.recompileFromScratch = function () {
  844. $scope.pdf.compiling = true
  845. return $scope
  846. .clearCache()
  847. .then(() => {
  848. $scope.pdf.compiling = false
  849. $scope.recompile()
  850. })
  851. .catch(error => {
  852. console.error(error)
  853. })
  854. }
  855. $scope.toggleLogs = function () {
  856. $scope.$applyAsync(() => {
  857. $scope.shouldShowLogs = !$scope.shouldShowLogs
  858. if ($scope.shouldShowLogs) {
  859. eventTracking.sendMBOnce('ide-open-logs-once')
  860. }
  861. })
  862. }
  863. $scope.showPdf = function () {
  864. $scope.pdf.view = 'pdf'
  865. $scope.shouldShowLogs = false
  866. }
  867. $scope.toggleRawLog = function () {
  868. $scope.pdf.showRawLog = !$scope.pdf.showRawLog
  869. if ($scope.pdf.showRawLog) {
  870. eventTracking.sendMB('logs-view-raw')
  871. }
  872. }
  873. $scope.openClearCacheModal = function () {
  874. $modal.open({
  875. templateUrl: 'clearCacheModalTemplate',
  876. controller: 'ClearCacheModalController',
  877. scope: $scope,
  878. })
  879. }
  880. $scope.syncToCode = function (position) {
  881. synctex.syncToCode(position).then(function (data) {
  882. const { doc, line } = data
  883. ide.editorManager.openDoc(doc, { gotoLine: line })
  884. })
  885. }
  886. $scope.setAutoCompile = function (isOn) {
  887. $scope.$applyAsync(function () {
  888. $scope.autocompile_enabled = isOn
  889. })
  890. }
  891. $scope.setDraftMode = function (isOn) {
  892. $scope.$applyAsync(function () {
  893. $scope.draft = isOn
  894. })
  895. }
  896. $scope.setSyntaxCheck = function (isOn) {
  897. $scope.$applyAsync(function () {
  898. $scope.stop_on_validation_error = isOn
  899. })
  900. }
  901. $scope.runSyntaxCheckNow = function () {
  902. $scope.$applyAsync(function () {
  903. $scope.recompile({ check: true })
  904. })
  905. }
  906. $scope.openInEditor = function (entry) {
  907. let column, line
  908. eventTracking.sendMBOnce('logs-jump-to-location-once')
  909. const entity = ide.fileTreeManager.findEntityByPath(entry.file)
  910. if (entity == null || entity.type !== 'doc') {
  911. return
  912. }
  913. if (entry.line != null) {
  914. line = entry.line
  915. }
  916. if (entry.column != null) {
  917. column = entry.column
  918. }
  919. ide.editorManager.openDoc(entity, {
  920. gotoLine: line,
  921. gotoColumn: column,
  922. })
  923. }
  924. }
  925. )
  926. App.factory('synctex', function (ide, $http, $q) {
  927. const synctex = {
  928. syncToPdfInFlight: false,
  929. syncToCodeInFlight: false,
  930. syncToPdf(cursorPosition) {
  931. const deferred = $q.defer()
  932. const docId = ide.editorManager.getCurrentDocId()
  933. if (docId == null) {
  934. deferred.reject()
  935. return deferred.promise
  936. }
  937. const doc = ide.fileTreeManager.findEntityById(docId)
  938. if (doc == null) {
  939. deferred.reject()
  940. return deferred.promise
  941. }
  942. let path = ide.fileTreeManager.getEntityPath(doc)
  943. if (path == null) {
  944. deferred.reject()
  945. return deferred.promise
  946. }
  947. // If the root file is folder/main.tex, then synctex sees the
  948. // path as folder/./main.tex
  949. const rootDocDirname = ide.fileTreeManager.getRootDocDirname()
  950. if (rootDocDirname != null && rootDocDirname !== '') {
  951. path = path.replace(RegExp(`^${rootDocDirname}`), `${rootDocDirname}/.`)
  952. }
  953. const { row, column } = cursorPosition
  954. this.syncToPdfInFlight = true
  955. $http({
  956. url: `/project/${ide.project_id}/sync/code`,
  957. method: 'GET',
  958. params: {
  959. file: path,
  960. line: row + 1,
  961. column,
  962. clsiserverid: ide.clsiServerId,
  963. },
  964. })
  965. .then(response => {
  966. this.syncToPdfInFlight = false
  967. const { data } = response
  968. return deferred.resolve(data.pdf || [])
  969. })
  970. .catch(response => {
  971. this.syncToPdfInFlight = false
  972. const error = response.data
  973. return deferred.reject(error)
  974. })
  975. return deferred.promise
  976. },
  977. syncToCode(position, options) {
  978. if (options == null) {
  979. options = {}
  980. }
  981. const deferred = $q.defer()
  982. if (position == null) {
  983. deferred.reject()
  984. return deferred.promise
  985. }
  986. // FIXME: this actually works better if it's halfway across the
  987. // page (or the visible part of the page). Synctex doesn't
  988. // always find the right place in the file when the point is at
  989. // the edge of the page, it sometimes returns the start of the
  990. // next paragraph instead.
  991. const h = position.offset.left
  992. // Compute the vertical position to pass to synctex, which
  993. // works with coordinates increasing from the top of the page
  994. // down. This matches the browser's DOM coordinate of the
  995. // click point, but the pdf position is measured from the
  996. // bottom of the page so we need to invert it.
  997. let v
  998. if (
  999. options.fromPdfPosition &&
  1000. (position.pageSize != null ? position.pageSize.height : undefined) !=
  1001. null
  1002. ) {
  1003. v = position.pageSize.height - position.offset.top || 0 // measure from pdf point (inverted)
  1004. } else {
  1005. v = position.offset.top || 0 // measure from html click position
  1006. }
  1007. // It's not clear exactly where we should sync to if it wasn't directly
  1008. // clicked on, but a little bit down from the very top seems best.
  1009. if (options.includeVisualOffset) {
  1010. v += 72 // use the same value as in pdfViewer highlighting visual offset
  1011. }
  1012. this.syncToCodeInFlight = true
  1013. $http({
  1014. url: `/project/${ide.project_id}/sync/pdf`,
  1015. method: 'GET',
  1016. params: {
  1017. page: position.page + 1,
  1018. h: h.toFixed(2),
  1019. v: v.toFixed(2),
  1020. clsiserverid: ide.clsiServerId,
  1021. },
  1022. })
  1023. .then(response => {
  1024. this.syncToCodeInFlight = false
  1025. const { data } = response
  1026. if (
  1027. data.code != null &&
  1028. data.code.length > 0 &&
  1029. data.code[0].file !== ''
  1030. ) {
  1031. const doc = ide.fileTreeManager.findEntityByPath(data.code[0].file)
  1032. if (doc == null) {
  1033. deferred.reject()
  1034. }
  1035. return deferred.resolve({ doc, line: data.code[0].line })
  1036. } else if (data.code[0].file === '') {
  1037. ide.$scope.sync_tex_error = true
  1038. setTimeout(() => (ide.$scope.sync_tex_error = false), 4000)
  1039. }
  1040. })
  1041. .catch(response => {
  1042. this.syncToCodeInFlight = false
  1043. const error = response.data
  1044. return deferred.reject(error)
  1045. })
  1046. return deferred.promise
  1047. },
  1048. }
  1049. return synctex
  1050. })
  1051. App.controller('PdfSynctexController', function ($scope, synctex, ide) {
  1052. this.cursorPosition = null
  1053. $scope.$watch(
  1054. () => synctex.syncToPdfInFlight,
  1055. value => ($scope.syncToPdfInFlight = value)
  1056. )
  1057. $scope.$watch(
  1058. () => synctex.syncToCodeInFlight,
  1059. value => ($scope.syncToCodeInFlight = value)
  1060. )
  1061. ide.$scope.$on('cursor:editor:update', (event, cursorPosition) => {
  1062. this.cursorPosition = cursorPosition
  1063. })
  1064. $scope.syncToPdf = () => {
  1065. if (this.cursorPosition == null) {
  1066. return
  1067. }
  1068. synctex.syncToPdf(this.cursorPosition).then(highlights => {
  1069. $scope.pdf.highlights = highlights
  1070. })
  1071. }
  1072. ide.$scope.$on('cursor:editor:syncToPdf', $scope.syncToPdf)
  1073. $scope.syncToCode = function () {
  1074. synctex
  1075. .syncToCode($scope.pdf.position, {
  1076. includeVisualOffset: true,
  1077. fromPdfPosition: true,
  1078. })
  1079. .then(function (data) {
  1080. const { doc, line } = data
  1081. ide.editorManager.openDoc(doc, { gotoLine: line })
  1082. })
  1083. }
  1084. })
  1085. App.controller('ClearCacheModalController', function ($scope, $modalInstance) {
  1086. $scope.state = { error: false, inflight: false }
  1087. $scope.clear = function () {
  1088. $scope.state.inflight = true
  1089. $scope
  1090. .clearCache()
  1091. .then(function () {
  1092. $scope.state.inflight = false
  1093. $modalInstance.close()
  1094. })
  1095. .catch(function () {
  1096. $scope.state.error = true
  1097. $scope.state.inflight = false
  1098. })
  1099. }
  1100. $scope.cancel = () => $modalInstance.dismiss('cancel')
  1101. })
  1102. // Wrap React component as Angular component. Only needed for "top-level" component
  1103. App.component(
  1104. 'previewPane',
  1105. react2angular(
  1106. rootContext.use(PreviewPane),
  1107. Object.keys(PreviewPane.propTypes)
  1108. )
  1109. )