PdfController.js 32 KB

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