Skip to content

psbt_nostr: split generic and UI parts, implement for qml #9694

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 15, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions electrum/gui/qml/components/ExportTxDialog.qml
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ ElDialog {
}

ButtonContainer {
id: buttons
Layout.fillWidth: true

FlatButton {
Expand All @@ -97,6 +98,17 @@ ElDialog {
AppController.doShare(dialog.text, dialog.title)
}
}
function beforeLayout() {
var export_tx_buttons = app.pluginsComponentsByName('export_tx_button')
for (var i=0; i < export_tx_buttons.length; i++) {
var b = export_tx_buttons[i].createObject(buttons, {
dialog: dialog
})
b.Layout.fillWidth = true
b.Layout.preferredWidth = 1
buttons.addItem(b)
}
}
}
}

Expand Down
5 changes: 5 additions & 0 deletions electrum/gui/qml/components/TxDetails.qml
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,16 @@ Pane {
property alias label: txdetails.label

signal detailsChanged
signal closed

function close() {
app.stack.pop()
}

StackView.onRemoved: {
closed()
}

ColumnLayout {
anchors.fill: parent
spacing: 0
Expand Down
8 changes: 7 additions & 1 deletion electrum/gui/qml/components/controls/ButtonContainer.qml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,13 @@ Container {
contentItem = contentRoot
}

Component.onCompleted: fillContentItem()
// override this function to dynamically add buttons.
function beforeLayout() {}

Component.onCompleted: {
beforeLayout()
fillContentItem()
}

Component {
id: containerLayout
Expand Down
39 changes: 39 additions & 0 deletions electrum/gui/qml/components/main.qml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ ApplicationWindow

property var _exceptionDialog

property var pluginobjects: ({})

property QtObject appMenu: Menu {
id: menu

Expand Down Expand Up @@ -640,6 +642,43 @@ ApplicationWindow
})
app._exceptionDialog.open()
}
function onPluginLoaded(name) {
console.log('plugin ' + name + ' loaded')
var loader = AppController.plugin(name).loader
if (loader == undefined)
return
var url = Qt.resolvedUrl('../../../plugins/' + name + '/qml/' + loader)
var comp = Qt.createComponent(url)
if (comp.status == Component.Error) {
console.log('Could not find/parse PluginLoader for plugin ' + name)
console.log(comp.errorString())
return
}
var obj = comp.createObject(app)
if (obj != null)
app.pluginobjects[name] = obj
}
}

function pluginsComponentsByName(comp_name) {
// return named QML components from plugins
var plugins = AppController.plugins
var result = []
for (var i=0; i < plugins.length; i++) {
if (!plugins[i].enabled)
continue
var pluginobject = app.pluginobjects[plugins[i].name]
if (!pluginobject)
continue
if (!(comp_name in pluginobject))
continue
var comp = pluginobject[comp_name]
if (!comp)
continue

result.push(comp)
}
return result
}

Connections {
Expand Down
16 changes: 10 additions & 6 deletions electrum/gui/qml/qeapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ class QEAppController(BaseCrashReporter, QObject):
sendingBugreportFailure = pyqtSignal(str)
secureWindowChanged = pyqtSignal()
wantCloseChanged = pyqtSignal()
pluginLoaded = pyqtSignal(str)
startupFinished = pyqtSignal()

def __init__(self, qeapp: 'ElectrumQmlApplication', plugins: 'Plugins'):
BaseCrashReporter.__init__(self, None, None, None)
Expand Down Expand Up @@ -229,8 +231,11 @@ def on_new_intent(self, intent):
if scheme == BITCOIN_BIP21_URI_SCHEME or scheme == LIGHTNING_URI_SCHEME:
self.uriReceived.emit(data)

def startupFinished(self):
def startup_finished(self):
self._app_started = True
self.startupFinished.emit()
for plugin_name in self._plugins.plugins.keys():
self.pluginLoaded.emit(plugin_name)
if self._intent:
self.on_new_intent(self._intent)

Expand Down Expand Up @@ -304,18 +309,16 @@ def plugin(self, plugin_name):
self.logger.debug('None!')
return None

@pyqtProperty('QVariant', notify=_dummy)
@pyqtProperty('QVariantList', notify=_dummy)
def plugins(self):
s = []
for item in self._plugins.descriptions:
self.logger.info(item)
s.append({
'name': item,
'fullname': self._plugins.descriptions[item]['fullname'],
'enabled': bool(self._plugins.get(item))
})

self.logger.debug(f'{str(s)}')
return s

@pyqtSlot(str, bool)
Expand Down Expand Up @@ -511,10 +514,11 @@ def __init__(self, args, *, config: 'SimpleConfig', daemon: 'Daemon', plugins: '
# slot is called after loading root QML. If object is None, it has failed.
@pyqtSlot('QObject*', 'QUrl')
def objectCreated(self, object, url):
self.engine.objectCreated.disconnect(self.objectCreated)
if object is None:
self._valid = False
self.engine.objectCreated.disconnect(self.objectCreated)
self.appController.startupFinished()
else:
self.appController.startup_finished()

def message_handler(self, line, funct, file):
# filter out common harmless messages
Expand Down
9 changes: 8 additions & 1 deletion electrum/gui/qt/transaction_dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
import copy
import datetime
import time
from typing import TYPE_CHECKING, Optional, List, Union, Mapping
from typing import TYPE_CHECKING, Optional, List, Union, Mapping, Callable
from functools import partial
from decimal import Decimal

Expand Down Expand Up @@ -410,6 +410,7 @@ def show_transaction(
prompt_if_unsaved: bool = False,
external_keypairs: Mapping[bytes, bytes] = None,
payment_identifier: 'PaymentIdentifier' = None,
on_closed: Callable[[], None] = None,
):
try:
d = TxDialog(
Expand All @@ -418,6 +419,7 @@ def show_transaction(
prompt_if_unsaved=prompt_if_unsaved,
external_keypairs=external_keypairs,
payment_identifier=payment_identifier,
on_closed=on_closed,
)
except SerializationError as e:
_logger.exception('unable to deserialize the transaction')
Expand All @@ -438,6 +440,7 @@ def __init__(
prompt_if_unsaved: bool,
external_keypairs: Mapping[bytes, bytes] = None,
payment_identifier: 'PaymentIdentifier' = None,
on_closed: Callable[[], None] = None,
):
'''Transactions in the wallet will show their description.
Pass desc to give a description for txs not yet in the wallet.
Expand All @@ -451,6 +454,7 @@ def __init__(
self.wallet = parent.wallet
self.payment_identifier = payment_identifier
self.prompt_if_unsaved = prompt_if_unsaved
self.on_closed = on_closed
self.saved = False
self.desc = None
if txid := tx.txid():
Expand Down Expand Up @@ -608,6 +612,9 @@ def closeEvent(self, event):
self._fetch_txin_data_fut.cancel()
self._fetch_txin_data_fut = None

if self.on_closed:
self.on_closed()

def reject(self):
# Override escape-key to close normally (and invoke closeEvent)
self.close()
Expand Down
83 changes: 56 additions & 27 deletions electrum/gui/qt/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import os
import webbrowser
from functools import partial, lru_cache, wraps
from typing import (NamedTuple, Callable, Optional, TYPE_CHECKING, List, Any, Sequence, Tuple)
from typing import (NamedTuple, Callable, Optional, TYPE_CHECKING, List, Any, Sequence, Tuple, Union)

from PyQt6 import QtCore
from PyQt6.QtGui import (QFont, QColor, QCursor, QPixmap, QImage,
Expand All @@ -17,7 +17,7 @@
QStyle, QDialog, QGroupBox, QButtonGroup, QRadioButton,
QFileDialog, QWidget, QToolButton, QPlainTextEdit, QApplication, QToolTip,
QGraphicsEffect, QGraphicsScene, QGraphicsPixmapItem, QLayoutItem, QLayout, QMenu,
QFrame)
QFrame, QAbstractButton)

from electrum.i18n import _
from electrum.util import (FileImportFailed, FileExportFailed, resource_path, EventListener, event_listener,
Expand Down Expand Up @@ -262,13 +262,13 @@ def top_level_window(self, test_func=None):
return self.top_level_window_recurse(test_func)

def question(self, msg, parent=None, title=None, icon=None, **kwargs) -> bool:
Yes, No = QMessageBox.StandardButton.Yes, QMessageBox.StandardButton.No
return Yes == self.msg_box(icon=icon or QMessageBox.Icon.Question,
yes, no = QMessageBox.StandardButton.Yes, QMessageBox.StandardButton.No
return yes == self.msg_box(icon=icon or QMessageBox.Icon.Question,
parent=parent,
title=title or '',
text=msg,
buttons=Yes|No,
defaultButton=No,
buttons=yes | no,
defaultButton=no,
**kwargs)

def show_warning(self, msg, parent=None, title=None, **kwargs):
Expand All @@ -283,22 +283,27 @@ def show_critical(self, msg, parent=None, title=None, **kwargs):
return self.msg_box(QMessageBox.Icon.Critical, parent,
title or _('Critical Error'), msg, **kwargs)

def show_message(self, msg, parent=None, title=None, **kwargs):
return self.msg_box(QMessageBox.Icon.Information, parent,
title or _('Information'), msg, **kwargs)
def show_message(self, msg, parent=None, title=None, icon=QMessageBox.Icon.Information, **kwargs):
return self.msg_box(icon, parent, title or _('Information'), msg, **kwargs)

def msg_box(self, icon, parent, title, text, *, buttons=QMessageBox.StandardButton.Ok,
defaultButton=QMessageBox.StandardButton.NoButton, rich_text=False,
checkbox=None):
def msg_box(
self,
icon: Union[QMessageBox.Icon, QPixmap],
parent: QWidget,
title: str,
text: str,
*,
buttons: Union[QMessageBox.StandardButton,
List[Union[QMessageBox.StandardButton, Tuple[QAbstractButton, QMessageBox.ButtonRole, int]]]] = QMessageBox.StandardButton.Ok,
defaultButton: QMessageBox.StandardButton = QMessageBox.StandardButton.NoButton,
rich_text: bool = False,
checkbox: Optional[bool] = None
):
parent = parent or self.top_level_window()
return custom_message_box(icon=icon,
parent=parent,
title=title,
text=text,
buttons=buttons,
defaultButton=defaultButton,
rich_text=rich_text,
checkbox=checkbox)
return custom_message_box(
icon=icon, parent=parent, title=title, text=text, buttons=buttons, defaultButton=defaultButton,
rich_text=rich_text, checkbox=checkbox
)

def query_choice(self,
msg: Optional[str],
Expand Down Expand Up @@ -327,15 +332,35 @@ def password_dialog(self, msg=None, parent=None):
return d.run()



def custom_message_box(*, icon, parent, title, text, buttons=QMessageBox.StandardButton.Ok,
defaultButton=QMessageBox.StandardButton.NoButton, rich_text=False,
checkbox=None):
def custom_message_box(
*,
icon: Union[QMessageBox.Icon, QPixmap],
parent: QWidget,
title: str,
text: str,
buttons: Union[QMessageBox.StandardButton,
List[Union[QMessageBox.StandardButton, Tuple[QAbstractButton, QMessageBox.ButtonRole, int]]]] = QMessageBox.StandardButton.Ok,
defaultButton: QMessageBox.StandardButton = QMessageBox.StandardButton.NoButton,
rich_text: bool = False,
checkbox: Optional[bool] = None
) -> int:
custom_buttons = []
standard_buttons = QMessageBox.StandardButton.NoButton
if buttons:
if not isinstance(buttons, list):
buttons = [buttons]
for button in buttons:
if isinstance(button, QMessageBox.StandardButton):
standard_buttons |= button
else:
custom_buttons.append(button)
if type(icon) is QPixmap:
d = QMessageBox(QMessageBox.Icon.Information, title, str(text), buttons, parent)
d = QMessageBox(QMessageBox.Icon.Information, title, str(text), standard_buttons, parent)
d.setIconPixmap(icon)
else:
d = QMessageBox(icon, title, str(text), buttons, parent)
d = QMessageBox(icon, title, str(text), standard_buttons, parent)
for button, role, _ in custom_buttons:
d.addButton(button, role)
d.setWindowModality(Qt.WindowModality.WindowModal)
d.setDefaultButton(defaultButton)
if rich_text:
Expand All @@ -350,7 +375,11 @@ def custom_message_box(*, icon, parent, title, text, buttons=QMessageBox.Standar
d.setTextFormat(Qt.TextFormat.PlainText)
if checkbox is not None:
d.setCheckBox(checkbox)
return d.exec()
result = d.exec()
for button, _, value in custom_buttons:
if button == d.clickedButton():
return value
return result


class WindowModalDialog(QDialog, MessageBoxMixin):
Expand Down
2 changes: 1 addition & 1 deletion electrum/plugins/psbt_nostr/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"fullname": "Nostr Multisig",
"description": "This plugin facilitates the use of multi-signatures wallets. It sends and receives partially signed transactions from/to your cosigner wallet. PSBTs are sent and retrieved from Nostr relays.",
"author": "The Electrum Developers",
"available_for": ["qt"],
"icon":"nostr_multisig.png",
"available_for": ["qt", "qml"],
"version": "0.0.1"
}
Loading