PdfController.js 35 KB

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