PdfController.js 33 KB

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