PdfController.js 34 KB

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