PdfController.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  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(() => {
  629. annotateFiles()
  630. sendCompileMetrics()
  631. })
  632. }
  633. }
  634. function sendCompileMetrics() {
  635. const hasCompiled =
  636. $scope.pdf.view !== 'errors' && $scope.pdf.view !== 'validation-problems'
  637. const sendMetricsForUser =
  638. window.user.betaProgram && !window.user.alphaProgram
  639. if (hasCompiled && sendMetricsForUser) {
  640. const metadata = {
  641. errors: $scope.pdf.logEntries.errors.length,
  642. warnings: $scope.pdf.logEntries.warnings.length,
  643. typesetting: $scope.pdf.logEntries.typesetting.length,
  644. newLogsUI: window.showNewLogsUI
  645. }
  646. eventTracking.sendMBSampled(
  647. 'compile-result',
  648. JSON.stringify(metadata),
  649. 0.05
  650. )
  651. }
  652. }
  653. function getRootDocOverrideId() {
  654. const rootDocId = $scope.project.rootDoc_id
  655. const currentDocId = ide.editorManager.getCurrentDocId()
  656. if (currentDocId === rootDocId) {
  657. return null // no need to override when in the root doc itself
  658. }
  659. const doc = ide.editorManager.getCurrentDocValue()
  660. if (doc == null) {
  661. return null
  662. }
  663. for (let line of doc.split('\n')) {
  664. if (/^[^%]*\\documentclass/.test(line)) {
  665. return ide.editorManager.getCurrentDocId()
  666. }
  667. }
  668. return null
  669. }
  670. function normalizeFilePath(path) {
  671. path = path.replace(
  672. /^(.*)\/compiles\/[0-9a-f]{24}(-[0-9a-f]{24})?\/(\.\/)?/,
  673. ''
  674. )
  675. path = path.replace(/^\/compile\//, '')
  676. const rootDocDirname = ide.fileTreeManager.getRootDocDirname()
  677. if (rootDocDirname != null) {
  678. path = path.replace(/^\.\//, rootDocDirname + '/')
  679. }
  680. return path
  681. }
  682. $scope.recompile = function(options) {
  683. if (options == null) {
  684. options = {}
  685. }
  686. if ($scope.pdf.compiling) {
  687. return
  688. }
  689. eventTracking.sendMBSampled('editor-recompile-sampled', options)
  690. $scope.lastStartedCompileAt = Date.now()
  691. $scope.pdf.compiling = true
  692. $scope.pdf.isAutoCompileOnLoad =
  693. options != null ? options.isAutoCompileOnLoad : undefined // initial autocompile
  694. if (options != null ? options.force : undefined) {
  695. // for forced compile, turn off validation check and ignore errors
  696. $scope.stop_on_validation_error = false
  697. $scope.shouldShowLogs = false // hide the logs while compiling
  698. eventTracking.sendMB('syntax-check-turn-off-checking')
  699. }
  700. if (options != null ? options.try : undefined) {
  701. $scope.shouldShowLogs = false // hide the logs while compiling
  702. eventTracking.sendMB('syntax-check-try-compile-anyway')
  703. }
  704. ide.$scope.$broadcast('flush-changes')
  705. options.rootDocOverride_id = getRootDocOverrideId()
  706. sendCompileRequest(options)
  707. .then(function(response) {
  708. const { data } = response
  709. $scope.pdf.view = 'pdf'
  710. $scope.pdf.compiling = false
  711. parseCompileResponse(data)
  712. })
  713. .catch(function(response) {
  714. const { status } = response
  715. if (status === 429) {
  716. $scope.pdf.rateLimited = true
  717. }
  718. $scope.pdf.compiling = false
  719. $scope.pdf.renderingError = false
  720. $scope.pdf.error = true
  721. $scope.pdf.view = 'errors'
  722. if (window.showNewLogsUI) {
  723. $scope.clsiErrors = { error: true }
  724. $scope.shouldShowLogs = true
  725. $scope.pdf.compileFailed = true
  726. }
  727. })
  728. .finally(() => {
  729. $scope.lastFinishedCompileAt = Date.now()
  730. })
  731. }
  732. // This needs to be public.
  733. ide.$scope.recompile = $scope.recompile
  734. // This method is a simply wrapper and exists only for tracking purposes.
  735. ide.$scope.recompileViaKey = function() {
  736. $scope.recompile({ keyShortcut: true })
  737. }
  738. $scope.stop = function() {
  739. if (!$scope.pdf.compiling) {
  740. return
  741. }
  742. return $http({
  743. url: `/project/${$scope.project_id}/compile/stop`,
  744. method: 'POST',
  745. params: {
  746. clsiserverid: ide.clsiServerId
  747. },
  748. headers: {
  749. 'X-Csrf-Token': window.csrfToken
  750. }
  751. })
  752. }
  753. $scope.clearCache = function() {
  754. $scope.pdf.clearingCache = true
  755. const deferred = $q.defer()
  756. // disable various download buttons
  757. $scope.pdf.url = null
  758. $scope.pdf.downloadUrl = null
  759. $scope.pdf.outputFiles = []
  760. $http({
  761. url: `/project/${$scope.project_id}/output`,
  762. method: 'DELETE',
  763. params: {
  764. clsiserverid: ide.clsiServerId
  765. },
  766. headers: {
  767. 'X-Csrf-Token': window.csrfToken
  768. }
  769. })
  770. .then(function(response) {
  771. $scope.pdf.clearingCache = false
  772. return deferred.resolve()
  773. })
  774. .catch(function(response) {
  775. console.error(response)
  776. const error = response.data
  777. $scope.pdf.clearingCache = false
  778. $scope.pdf.renderingError = false
  779. $scope.pdf.error = true
  780. $scope.pdf.view = 'errors'
  781. return deferred.reject(error)
  782. })
  783. return deferred.promise
  784. }
  785. $scope.recompileFromScratch = function() {
  786. $scope.pdf.compiling = true
  787. return $scope
  788. .clearCache()
  789. .then(() => {
  790. $scope.pdf.compiling = false
  791. $scope.recompile()
  792. })
  793. .catch(error => {
  794. console.error(error)
  795. })
  796. }
  797. $scope.toggleLogs = function() {
  798. $scope.$applyAsync(() => {
  799. $scope.shouldShowLogs = !$scope.shouldShowLogs
  800. if ($scope.shouldShowLogs) {
  801. eventTracking.sendMBOnce('ide-open-logs-once')
  802. }
  803. })
  804. }
  805. $scope.showPdf = function() {
  806. $scope.pdf.view = 'pdf'
  807. $scope.shouldShowLogs = false
  808. }
  809. $scope.toggleRawLog = function() {
  810. $scope.pdf.showRawLog = !$scope.pdf.showRawLog
  811. if ($scope.pdf.showRawLog) {
  812. eventTracking.sendMB('logs-view-raw')
  813. }
  814. }
  815. $scope.openClearCacheModal = function() {
  816. $modal.open({
  817. templateUrl: 'clearCacheModalTemplate',
  818. controller: 'ClearCacheModalController',
  819. scope: $scope
  820. })
  821. }
  822. $scope.syncToCode = function(position) {
  823. synctex.syncToCode(position).then(function(data) {
  824. const { doc, line } = data
  825. ide.editorManager.openDoc(doc, { gotoLine: line })
  826. })
  827. }
  828. $scope.setAutoCompile = function(isOn) {
  829. $scope.$applyAsync(function() {
  830. $scope.autocompile_enabled = isOn
  831. })
  832. }
  833. $scope.setDraftMode = function(isOn) {
  834. $scope.$applyAsync(function() {
  835. $scope.draft = isOn
  836. })
  837. }
  838. $scope.setSyntaxCheck = function(isOn) {
  839. $scope.$applyAsync(function() {
  840. $scope.stop_on_validation_error = isOn
  841. })
  842. }
  843. $scope.runSyntaxCheckNow = function() {
  844. $scope.$applyAsync(function() {
  845. $scope.recompile({ check: true })
  846. })
  847. }
  848. $scope.openInEditor = function(entry) {
  849. let column, line
  850. eventTracking.sendMBOnce('logs-jump-to-location-once')
  851. const entity = ide.fileTreeManager.findEntityByPath(entry.file)
  852. if (entity == null || entity.type !== 'doc') {
  853. return
  854. }
  855. if (entry.line != null) {
  856. line = entry.line
  857. }
  858. if (entry.column != null) {
  859. column = entry.column
  860. }
  861. ide.editorManager.openDoc(entity, {
  862. gotoLine: line,
  863. gotoColumn: column
  864. })
  865. }
  866. })
  867. App.factory('synctex', function(ide, $http, $q) {
  868. const synctex = {
  869. syncToPdf(cursorPosition) {
  870. const deferred = $q.defer()
  871. const docId = ide.editorManager.getCurrentDocId()
  872. if (docId == null) {
  873. deferred.reject()
  874. return deferred.promise
  875. }
  876. const doc = ide.fileTreeManager.findEntityById(docId)
  877. if (doc == null) {
  878. deferred.reject()
  879. return deferred.promise
  880. }
  881. let path = ide.fileTreeManager.getEntityPath(doc)
  882. if (path == null) {
  883. deferred.reject()
  884. return deferred.promise
  885. }
  886. // If the root file is folder/main.tex, then synctex sees the
  887. // path as folder/./main.tex
  888. const rootDocDirname = ide.fileTreeManager.getRootDocDirname()
  889. if (rootDocDirname != null && rootDocDirname !== '') {
  890. path = path.replace(RegExp(`^${rootDocDirname}`), `${rootDocDirname}/.`)
  891. }
  892. const { row, column } = cursorPosition
  893. $http({
  894. url: `/project/${ide.project_id}/sync/code`,
  895. method: 'GET',
  896. params: {
  897. file: path,
  898. line: row + 1,
  899. column,
  900. clsiserverid: ide.clsiServerId
  901. }
  902. })
  903. .then(function(response) {
  904. const { data } = response
  905. return deferred.resolve(data.pdf || [])
  906. })
  907. .catch(function(response) {
  908. const error = response.data
  909. return deferred.reject(error)
  910. })
  911. return deferred.promise
  912. },
  913. syncToCode(position, options) {
  914. if (options == null) {
  915. options = {}
  916. }
  917. const deferred = $q.defer()
  918. if (position == null) {
  919. deferred.reject()
  920. return deferred.promise
  921. }
  922. // FIXME: this actually works better if it's halfway across the
  923. // page (or the visible part of the page). Synctex doesn't
  924. // always find the right place in the file when the point is at
  925. // the edge of the page, it sometimes returns the start of the
  926. // next paragraph instead.
  927. const h = position.offset.left
  928. // Compute the vertical position to pass to synctex, which
  929. // works with coordinates increasing from the top of the page
  930. // down. This matches the browser's DOM coordinate of the
  931. // click point, but the pdf position is measured from the
  932. // bottom of the page so we need to invert it.
  933. let v
  934. if (
  935. options.fromPdfPosition &&
  936. (position.pageSize != null ? position.pageSize.height : undefined) !=
  937. null
  938. ) {
  939. v = position.pageSize.height - position.offset.top || 0 // measure from pdf point (inverted)
  940. } else {
  941. v = position.offset.top || 0 // measure from html click position
  942. }
  943. // It's not clear exactly where we should sync to if it wasn't directly
  944. // clicked on, but a little bit down from the very top seems best.
  945. if (options.includeVisualOffset) {
  946. v += 72 // use the same value as in pdfViewer highlighting visual offset
  947. }
  948. $http({
  949. url: `/project/${ide.project_id}/sync/pdf`,
  950. method: 'GET',
  951. params: {
  952. page: position.page + 1,
  953. h: h.toFixed(2),
  954. v: v.toFixed(2),
  955. clsiserverid: ide.clsiServerId
  956. }
  957. })
  958. .then(function(response) {
  959. const { data } = response
  960. if (
  961. data.code != null &&
  962. data.code.length > 0 &&
  963. data.code[0].file !== ''
  964. ) {
  965. const doc = ide.fileTreeManager.findEntityByPath(data.code[0].file)
  966. if (doc == null) {
  967. deferred.reject()
  968. }
  969. return deferred.resolve({ doc, line: data.code[0].line })
  970. } else if (data.code[0].file === '') {
  971. ide.$scope.sync_tex_error = true
  972. setTimeout(() => (ide.$scope.sync_tex_error = false), 4000)
  973. }
  974. })
  975. .catch(function(response) {
  976. const error = response.data
  977. return deferred.reject(error)
  978. })
  979. return deferred.promise
  980. }
  981. }
  982. return synctex
  983. })
  984. App.controller('PdfSynctexController', function($scope, synctex, ide) {
  985. this.cursorPosition = null
  986. $scope.syncToPdfInFlight = false
  987. $scope.syncToCodeInFlight = false
  988. ide.$scope.$on('cursor:editor:update', (event, cursorPosition) => {
  989. this.cursorPosition = cursorPosition
  990. })
  991. $scope.syncToPdf = () => {
  992. if (this.cursorPosition == null) {
  993. return
  994. }
  995. $scope.syncToPdfInFlight = true
  996. synctex
  997. .syncToPdf(this.cursorPosition)
  998. .then(highlights => {
  999. $scope.pdf.highlights = highlights
  1000. })
  1001. .finally(() => ($scope.syncToPdfInFlight = false))
  1002. }
  1003. ide.$scope.$on('cursor:editor:syncToPdf', $scope.syncToPdf)
  1004. $scope.syncToCode = function() {
  1005. $scope.syncToCodeInFlight = true
  1006. synctex
  1007. .syncToCode($scope.pdf.position, {
  1008. includeVisualOffset: true,
  1009. fromPdfPosition: true
  1010. })
  1011. .then(function(data) {
  1012. const { doc, line } = data
  1013. ide.editorManager.openDoc(doc, { gotoLine: line })
  1014. })
  1015. .finally(() => ($scope.syncToCodeInFlight = false))
  1016. }
  1017. })
  1018. App.controller('ClearCacheModalController', function($scope, $modalInstance) {
  1019. $scope.state = { error: false, inflight: false }
  1020. $scope.clear = function() {
  1021. $scope.state.inflight = true
  1022. $scope
  1023. .clearCache()
  1024. .then(function() {
  1025. $scope.state.inflight = false
  1026. $modalInstance.close()
  1027. })
  1028. .catch(function() {
  1029. $scope.state.error = true
  1030. $scope.state.inflight = false
  1031. })
  1032. }
  1033. $scope.cancel = () => $modalInstance.dismiss('cancel')
  1034. })
  1035. // Wrap React component as Angular component. Only needed for "top-level" component
  1036. App.component(
  1037. 'previewPane',
  1038. react2angular(
  1039. rootContext.use(PreviewPane),
  1040. Object.keys(PreviewPane.propTypes)
  1041. )
  1042. )