PdfController.js 33 KB

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