PdfController.js 37 KB

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