PdfController.js 34 KB

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