PdfController.js 33 KB

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