Skip to content

Commit

Permalink
no idea why this doesn't work in the wizard
Browse files Browse the repository at this point in the history
  • Loading branch information
retorquere committed Oct 27, 2023
1 parent 3aaedb2 commit 6612698
Show file tree
Hide file tree
Showing 4 changed files with 118 additions and 85 deletions.
2 changes: 1 addition & 1 deletion content/ErrorReport.pug
Original file line number Diff line number Diff line change
Expand Up @@ -60,5 +60,5 @@ wizard#better-bibtex-error-report(
script(src='chrome://zotero/content/include.js')
script.
window.addEventListener('load', function() {
(new Zotero.BetterBibTeX.ErrorReport).load(window).catch(err => Zotero.debug(`BBT.ErrorReport: ${err}`))
(new Zotero.BetterBibTeX.ErrorReport).load(window).catch(err => Zotero.debug(`BBT.ErrorReport: error: ${err}`))
})
60 changes: 22 additions & 38 deletions content/ErrorReport.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
let $window: Window & {
arguments?: any[]
ErrorReport?: ErrorReport
}

Components.utils.import('resource://gre/modules/Services.jsm')

import { Preference } from './prefs'
import { defaults } from '../gen/preferences/meta'
import { Translators } from './translators'
import { byId } from '../gen/translators'
import { log } from './logger'
import { AutoExport } from './auto-export'
import { KeyManager } from './key-manager'
Expand Down Expand Up @@ -42,13 +37,13 @@ type Wizard = HTMLElement & {

export class ErrorReport {
private previewSize = 3 * kB // eslint-disable-line yoda
private document: Document

private key: string
private timestamp: string
private tarball: string

private bucket: string
private params: any
private cacheState: string

private errorlog: {
Expand All @@ -59,8 +54,8 @@ export class ErrorReport {
}

public async send(): Promise<void> {
const doc = $window.document
const wizard: Wizard = doc.getElementById('better-bibtex-error-report') as Wizard
const wizard: Wizard = this.document.getElementById('better-bibtex-error-report') as Wizard

wizard.getButton('next').disabled = true
wizard.getButton('cancel').disabled = true
wizard.canRewind = false
Expand All @@ -84,8 +79,8 @@ export class ErrorReport {
wizard.advance();

// eslint-disable-next-line no-magic-numbers
(<HTMLInputElement>doc.getElementById('better-bibtex-report-id')).value = `${this.key}/${version}-${is7 ? 7 : 6}${Zotero.BetterBibTeX.outOfMemory ? '/oom' : ''}`
doc.getElementById('better-bibtex-report-result').hidden = false
(<HTMLInputElement>this.document.getElementById('better-bibtex-report-id')).value = `${this.key}/${version}-${is7 ? 7 : 6}${Zotero.BetterBibTeX.outOfMemory ? '/oom' : ''}`
this.document.getElementById('better-bibtex-report-result').hidden = false
}
catch (err) {
log.error('failed to submit', this.key, err)
Expand All @@ -95,8 +90,7 @@ export class ErrorReport {
}

public show(): void {
const doc = $window.document
const wizard: Wizard = doc.getElementById('better-bibtex-error-report') as Wizard
const wizard: Wizard = this.document.getElementById('better-bibtex-error-report') as Wizard

if (wizard.onLastPage) wizard.canRewind = false
else if (wizard.pageIndex === 0) wizard.canRewind = false
Expand Down Expand Up @@ -148,7 +142,7 @@ export class ErrorReport {

if (this.errorlog.items) out = tape.append(`${this.key}/items.json`, this.errorlog.items)

if ((<HTMLInputElement>$window.document.getElementById('better-bibtex-error-report-include-db')).checked) {
if ((<HTMLInputElement>this.document.getElementById('better-bibtex-error-report-include-db')).checked) {
out = tape.append(`${this.key}/database.json`, JSON.stringify(KeyManager.all()))
out = tape.append(`${this.key}/cache.json`, Cache.serialize({ serializationMethod: 'pretty' }))
}
Expand All @@ -168,17 +162,16 @@ export class ErrorReport {
}

private setValue(id: string, value: string) {
(<HTMLInputElement>$window.document.getElementById(id)).value = value
(<HTMLInputElement>this.document.getElementById(id)).value = value
}

public async load(win: Window): Promise<void> {
$window = win as any
$window.ErrorReport = this
const doc = win.document
public async load(win: Window & { ErrorReport: ErrorReport, arguments: any[] }): Promise<void> {
this.document = win.document
win.ErrorReport = this

this.timestamp = (new Date()).toISOString().replace(/\..*/, '').replace(/:/g, '.')

const wizard: Wizard = doc.getElementById('better-bibtex-error-report') as Wizard
const wizard: Wizard = this.document.getElementById('better-bibtex-error-report') as Wizard
wizard.getPageById('page-enable-debug').addEventListener('pageshow', this.show.bind(this))
wizard.getPageById('page-review').addEventListener('pageshow', this.show.bind(this))
wizard.getPageById('page-send').addEventListener('pageshow', () => { this.send().catch(err => log.debug('could not send debug log:', err)) })
Expand All @@ -189,37 +182,27 @@ export class ErrorReport {
const continueButton = wizard.getButton('next')
continueButton.disabled = true

this.params = $window.arguments[0].wrappedJSObject

this.errorlog = {
info: await this.info(),
errors: `${Zotero.BetterBibTeX.outOfMemory}\n${Zotero.getErrors(true).join('\n')}`.trim(),
// # 1896
debug: Zotero.Debug.getConsoleViewerOutput().slice(-500000).join('\n'), // eslint-disable-line no-magic-numbers
}

if (this.params.scope) {
await Zotero.BetterBibTeX.ready
this.errorlog.items = await Translators.exportItems({
translatorID: Translators.bySlug.BetterBibTeXJSON.translatorID,
displayOptions: {exportNotes: true, dropAttachments: true, Normalize: true},
scope: this.params.scope,
})
debug: Zotero.Debug.getConsoleViewerOutput().slice(-500000).join('\n'),
items: win.arguments[0].wrappedJSObject.items,
}

this.setValue('better-bibtex-error-context', this.errorlog.info)
this.setValue('better-bibtex-error-errors', this.errorlog.errors)
this.setValue('better-bibtex-error-debug', this.preview(this.errorlog.debug))
if (this.errorlog.items) this.setValue('better-bibtex-error-items', this.preview(this.errorlog.items))
doc.getElementById('better-bibtex-error-tab-items').hidden = !this.errorlog.items
this.setValue('better-bibtex-error-items', this.preview(this.errorlog.items))
this.document.getElementById('better-bibtex-error-tab-items').hidden = !this.errorlog.items

const current = require('../gen/version.js')
this.setValue('better-bibtex-report-current', l10n.localize('better-bibtex_error-report_better-bibtex_current', { version: current }))

try {
const latest = await this.latest()

const show_latest = <HTMLInputElement>doc.getElementById('better-bibtex-report-latest')
const show_latest = <HTMLInputElement>this.document.getElementById('better-bibtex-report-latest')
if (current === latest) {
show_latest.hidden = true
}
Expand All @@ -228,20 +211,21 @@ export class ErrorReport {
show_latest.hidden = false
}

(<HTMLInputElement>doc.getElementById('better-bibtex-report-oom')).hidden = !Zotero.BetterBibTeX.outOfMemory
(<HTMLInputElement>this.document.getElementById('better-bibtex-report-oom')).hidden = !Zotero.BetterBibTeX.outOfMemory

this.setValue('better-bibtex-report-cache', this.cacheState = l10n.localize('better-bibtex_error-report_better-bibtex_cache', Cache.state()))

const region = await Zotero.Promise.any(Object.keys(s3.region).map(this.ping.bind(this)))
this.bucket = `https://${s3.bucket}-${region.short}.s3-${region.region}.amazonaws.com${region.tld || ''}`
this.key = `${Zotero.Utilities.generateObjectKey()}${this.params.scope ? '-refs' : ''}-${region.short}` // eslint-disable-line no-magic-numbers
this.key = `${Zotero.Utilities.generateObjectKey()}${this.errorlog.items ? '-refs' : ''}-${region.short}` // eslint-disable-line no-magic-numbers

this.tarball = OS.Path.join(Zotero.getTempDirectory().path, `${this.key}-${this.timestamp}.tgz`)

continueButton.disabled = false
continueButton.focus()
}
catch (err) {
log.error('errorreport:', err)
alert({ text: `No AWS region can be reached: ${err.message}` })
wizard.getButton('cancel').disabled = false
}
Expand Down Expand Up @@ -287,7 +271,7 @@ export class ErrorReport {
for (const [k, v] of Object.entries(ae)) {
if (k === 'path') continue
info += ` ${k}: ${JSON.stringify(v)}`
if (k === 'translatorID' && Translators.byId[v as string]) info += ` (${Translators.byId[v as string].label})`
if (k === 'translatorID' && byId[v as string]) info += ` (${byId[v as string].label})`
info += '\n'
}
}
Expand Down
86 changes: 55 additions & 31 deletions content/ZoteroPane.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { XUL } from '../typings/xul'

import { log } from './logger'
import { TeXstudio } from './tex-studio'
import { Translators } from './translators'
import { patch as $patch$, unpatch as $unpatch$, Trampoline } from './monkey-patch'
import { clean_pane_persist } from './clean_pane_persist'
import { Preference } from './prefs'
Expand All @@ -16,8 +17,13 @@ import { Elements } from './create-element'
import { is7 } from './client'
import { busyWait } from './busy-wait'

export async function newZoteroPane(win: Window): Promise<void> {
const zp = (win as any).ZoteroPane
type XULWindow = Window & {
openDialog?: (url: string, id: string, options?: string, io?: any) => void
ZoteroPane?: any
}

export async function newZoteroPane(win: XULWindow): Promise<void> {
const zp = win.ZoteroPane
await busyWait(() => typeof zp.itemsView.waitForLoad === 'function')
await zp.itemsView.waitForLoad()
await (new ZoteroPane).load(win)
Expand All @@ -27,14 +33,14 @@ class ZoteroPane {
private patched: Trampoline[] = []
private elements: Elements
private ZoteroPane: any
private window: Window
private window: XULWindow

public unload(): void {
$unpatch$(this.patched)
this.elements.remove()
}

public async load(win: Window) {
public async load(win: XULWindow) {
const doc = win.document
const elements = this.elements = new Elements(doc)
this.window = win
Expand All @@ -60,7 +66,7 @@ class ZoteroPane {
menupopup.appendChild(elements.create('menuitem', {
label: l10n.localize('better-bibtex_preferences_open.label'),
oncommand: () => {
(this.window as any).openDialog('chrome://zotero-better-bibtex/content/preferences.xul', 'better-bibtex-prefs-window')
this.window.openDialog('chrome://zotero-better-bibtex/content/preferences.xul', 'better-bibtex-prefs-window')
},
}))
}
Expand Down Expand Up @@ -141,7 +147,7 @@ class ZoteroPane {
menupopup.appendChild(elements.create('menuseparator'))
menupopup.appendChild(elements.create('menuitem', {
label: l10n.localize('better-bibtex_report-errors'),
oncommand: () => { bbt_zotero_pane_helper.errorReport('items') },
oncommand: () => { void bbt_zotero_pane_helper.errorReport('items') },
}))
})

Expand Down Expand Up @@ -196,7 +202,7 @@ class ZoteroPane {
menupopup.appendChild(elements.create('menuitem', {
id: 'bbt-collectionmenu-report-errors',
label: l10n.localize('better-bibtex_report-errors'),
oncommand: event => { event.stopPropagation(); bbt_zotero_pane_helper.errorReport('collection') },
oncommand: event => { event.stopPropagation(); void bbt_zotero_pane_helper.errorReport('collection') },
}))
}

Expand All @@ -221,16 +227,13 @@ class ZoteroPane {
const type = isCollection ? 'collection' : isLibrary ? 'library' : ''
if (Preference.autoExport !== 'immediate' && type) {
auto_exports = await AutoExport.find(type, [ treeRow.ref.id ])
log.debug('mae:', auto_exports)
}

const menulist: XUL.Menulist = doc.getElementById('zotero-collectionmenu-bbt-autoexport') as XUL.Menulist
if (!(menulist.hidden = auto_exports.length === 0)) {
const menupopup = doc.querySelector<HTMLElement>('#zotero-collectionmenu-bbt-autoexport menupopup')
while (menupopup.firstChild) menupopup.firstChild.remove()
log.debug('mae: reconstructing menu:', auto_exports.length, 'items')
for (const ae of auto_exports) {
log.debug('mae:', ae.path)
menupopup.appendChild(elements.create('menuitem', {
label: ae.path,
oncommand: () => AutoExport.run(ae.$loki),
Expand Down Expand Up @@ -289,7 +292,7 @@ class ZoteroPane {

if (!params.url.short) return

(this.window as any).openDialog(`chrome://zotero-better-bibtex/content/ServerURL.${is7 ? 'xhtml' : 'xul'}` , '', 'chrome,dialog,centerscreen,modal', params)
this.window.openDialog(`chrome://zotero-better-bibtex/content/ServerURL.${is7 ? 'xhtml' : 'xul'}` , '', 'chrome,dialog,centerscreen,modal', params)
}

public padNum(n: number, width: number): string {
Expand Down Expand Up @@ -361,35 +364,56 @@ class ZoteroPane {
await TeXstudio.push()
}

public errorReport(includeItems?: string): void {
let scope = null
public async errorReport(items?: string): Promise<void> {
// absolutely no idea why this does not run in the error report dialog anymore
const selection = async () => {
let scope = null
const zp = Zotero.getActiveZoteroPane()
switch (items) {
case 'collection':
case 'library':
scope = { type: 'collection', collection: zp.getSelectedCollection() }
if (!scope.collection) scope = { type: 'library', id: zp.getSelectedLibraryID() }
break

case 'items':
try {
scope = { type: 'items', items: zp.getSelectedItems() }
}
catch (err) { // ZoteroPane.getSelectedItems() doesn't test whether there's a selection and errors out if not
log.error('Could not get selected items:', err)
}
}

switch (this.ZoteroPane && includeItems) {
case 'collection':
case 'library':
scope = { type: 'collection', collection: this.ZoteroPane.getSelectedCollection() }
if (!scope.collection) scope = { type: 'library', id: this.ZoteroPane.getSelectedLibraryID() }
break
if (!scope) return ''

case 'items':
try {
scope = { type: 'items', items: this.ZoteroPane.getSelectedItems() }
try {
return await Translators.queueJob({
translatorID: Translators.bySlug.BetterBibTeXJSON.translatorID,
displayOptions: { exportNotes: true, dropAttachments: true, Normalize: true },
scope,
timeout: 40,
})
}
catch (err) {
if (err.timeout) {
log.debug('errorreport: items timed out after', err.timeout, 'seconds')
return 'Timeout retrieving items'
}
catch (err) { // zoteroPane.getSelectedItems() doesn't test whether there's a selection and errors out if not
log.error('Could not get selected items:', err)
scope = {}
else {
log.debug('errorreport: could not get items', err)
return `Error retrieving items: ${err}`
}

if (!scope.items || !scope.items.length) scope = null
break
}
}

(this.window as any).openDialog(
items = items ? await selection() : ''

this.window.openDialog(
`chrome://zotero-better-bibtex/content/ErrorReport.${ is7 ? 'xhtml' : 'xul'}`,
'better-bibtex-error-report',
'chrome,centerscreen,modal',
{ wrappedJSObject: { scope } }
)
{ wrappedJSObject: { items } })
}

public async sentenceCase(): Promise<void> {
Expand Down

0 comments on commit 6612698

Please sign in to comment.