PdfController.js 37 KB

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