PdfController.js 37 KB

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