PdfController.js 36 KB

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