Skip to content

Commit

Permalink
Better type hinting, fstrings in threads and mainapp
Browse files Browse the repository at this point in the history
  • Loading branch information
Liquid369 committed Jul 23, 2024
1 parent 2adbf04 commit 13fe7fb
Show file tree
Hide file tree
Showing 8 changed files with 96 additions and 91 deletions.
8 changes: 4 additions & 4 deletions src/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import os
from queue import Queue

wqueue = Queue() # type: Queue[str]
wqueue: Queue[str] = Queue()

APPDATA_DIRNAME = ".PET4L-DATA"

Expand All @@ -21,7 +21,7 @@
TESTNET_MAGIC_BYTE = 139
TESTNET_STAKE_MAGIC_BYTE = 73
DEFAULT_PROTOCOL_VERSION = 70915
MINIMUM_FEE = 0.0001 # minimum PIV/kB
MINIMUM_FEE = 0.0001 # minimum PIV/kB
SECONDS_IN_2_MONTHS = 60 * 24 * 60 * 60
MAX_INPUTS_NO_WARNING = 75
starting_width = 1033
Expand Down Expand Up @@ -50,8 +50,8 @@
trusted_RPC_Servers = [
["https", "lithuania.fuzzbawls.pw:8080", "spmtUser", "WUss6sr8956S5Paex254"],
["https", "latvia.fuzzbawls.pw:8080", "spmtUser", "8X88u7TuefPm7mQaJY52"],
["https", "charlotte.fuzzbawls.pw:8080", "spmtUser", "ZyD936tm9dvqmMP8A777"]]

["https", "charlotte.fuzzbawls.pw:8080", "spmtUser", "ZyD936tm9dvqmMP8A777"]
]

HW_devices = [
# (model name, api index)
Expand Down
16 changes: 8 additions & 8 deletions src/mainApp.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@
from misc import printDbg, initLogs, saveCacheSettings, readCacheSettings, getVersion
from mainWindow import MainWindow
from constants import user_dir, SECONDS_IN_2_MONTHS
from qt.dlg_configureRPCservers import ConfigureRPCservers_dlg
from qt.dlg_signmessage import SignMessage_dlg
from qt.dlg_configureRPCservers import ConfigureRPCserversDlg
from qt.dlg_signmessage import SignMessageDlg


class ServiceExit(Exception):
Expand All @@ -30,7 +30,7 @@ class ServiceExit(Exception):


def service_shutdown(signum, frame):
print('Caught signal %d' % signum)
print(f'Caught signal {signum}')
raise ServiceExit


Expand All @@ -54,7 +54,7 @@ def __init__(self, imgDir, app, start_args):

# Get version and title
self.version = getVersion()
self.title = 'PET4L - PIVX Emergency Tool For Ledger - v.%s-%s' % (self.version['number'], self.version['tag'])
self.title = f'PET4L - PIVX Emergency Tool For Ledger - v.{self.version["number"]}-{self.version["tag"]}'

# Open database
self.db = Database(self)
Expand Down Expand Up @@ -107,7 +107,7 @@ def initUI(self, imgDir):
self.show()
self.activateWindow()

def closeEvent(self, *args, **kwargs):
def closeEvent(self, event):
# Terminate the running threads.
# Set the shutdown flag on each thread to trigger a clean shutdown of each thread.
self.mainWindow.myRpcWd.shutdown_flag.set()
Expand All @@ -133,16 +133,16 @@ def closeEvent(self, *args, **kwargs):

# Adios
print("Bye Bye.")
return QMainWindow.closeEvent(self, *args, **kwargs)
return super().closeEvent(event)

def onEditRPCServer(self):
# Create Dialog
ui = ConfigureRPCservers_dlg(self)
ui = ConfigureRPCserversDlg(self)
if ui.exec():
printDbg("Configuring RPC Servers...")

def onSignVerifyMessage(self):
# Create Dialog
ui = SignMessage_dlg(self.mainWindow)
ui = SignMessageDlg(self.mainWindow)
if ui.exec():
printDbg("Sign/Verify message...")
40 changes: 19 additions & 21 deletions src/mainWindow.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from PyQt5.QtCore import pyqtSignal, Qt, QThread
from PyQt5.QtGui import QPixmap, QColor, QPalette, QTextCursor, QFont, QIcon
from PyQt5.QtWidgets import QWidget, QPushButton, QHBoxLayout, QGroupBox, QVBoxLayout, \
QFileDialog, QTextEdit, QTabWidget, QLabel, QSplitter
QFileDialog, QTextEdit, QTabWidget, QLabel, QSplitter, QAction, QMenuBar

from apiClient import ApiClient
from constants import starting_height, DefaultCache, wqueue
Expand Down Expand Up @@ -41,9 +41,8 @@ class MainWindow(QWidget):
# signal: UTXO list loading percent (emitted by load_utxos_thread in tabRewards)
sig_UTXOsLoading = pyqtSignal(int)


def __init__(self, parent, imgDir):
super(QWidget, self).__init__(parent)
super().__init__(parent)
self.parent = parent
self.imgDir = imgDir
self.runInThread = ThreadFuns.runInThread
Expand Down Expand Up @@ -79,7 +78,7 @@ def __init__(self, parent, imgDir):
self.hwdevice = HWdevice(self)

# -- init Api Client
self.apiClient = ApiClient(self.isTestnetRPC)
self.apiClient = ApiClient(self) # Pass 'self' as main_wnd reference

# -- Create Queue to redirect stdout
self.queue = wqueue
Expand Down Expand Up @@ -257,15 +256,15 @@ def checkVersion(self, ctrl):
(remote_version[0] == local_version[0] and remote_version[1] > local_version[1]) or \
(remote_version[0] == local_version[0] and remote_version[1] == local_version[1] and remote_version[2] >
local_version[2]):
self.versionMess = '<b style="color:red">New Version Available:</b> %s ' % (self.gitVersion)
self.versionMess = f'<b style="color:red">New Version Available:</b> {self.gitVersion} '
self.versionMess += '(<a href="https://github.com/PIVX-Project/PET4L/releases/">download</a>)'
else:
self.versionMess = "You have the latest version of PET4L"

def updateVersion(self):
if self.versionMess is not None:
self.versionLabel.setText(self.versionMess)
printOK("Remote version: %s" % str(self.gitVersion))
printOK(f"Remote version: {self.gitVersion}")

def onChangeSelectedHW(self, i):
# Clear status
Expand All @@ -288,14 +287,13 @@ def onSaveConsole(self):
timestamp = strftime('%Y-%m-%d_%H-%M-%S', gmtime(now()))
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
fileName, _ = QFileDialog.getSaveFileName(self, "Save Logs to file", "PET4L_Logs_%s.txt" % timestamp, "All Files (*);; Text Files (*.txt)", options=options)
fileName, _ = QFileDialog.getSaveFileName(self, f"Save Logs to file PET4L_Logs_{timestamp}.txt", "All Files (*);; Text Files (*.txt)", options=options)
try:
if fileName:
printOK("Saving logs to %s" % fileName)
log_file = open(fileName, 'w+', encoding="utf-8")
log_text = self.consoleArea.toPlainText()
log_file.write(log_text)
log_file.close()
printOK(f"Saving logs to {fileName}")
with open(fileName, 'w+', encoding="utf-8") as log_file:
log_text = self.consoleArea.toPlainText()
log_file.write(log_text)

except Exception as e:
err_msg = "error writing Log file"
Expand All @@ -315,14 +313,14 @@ def onToggleConsole(self):

def showHWstatus(self):
self.updateHWleds()
myPopUp_sb(self, "info", 'PET4L - hw check', "%s" % self.hwStatusMess)
myPopUp_sb(self, "info", 'PET4L - hw check', f"{self.hwStatusMess}")

def showRPCstatus(self, server_index, fDebug):
# Update displayed status only if selected server is not changed
if server_index == self.header.rpcClientsBox.currentIndex():
self.updateRPCled(fDebug)
if fDebug:
myPopUp_sb(self, "info", 'PET4L - rpc check', "%s" % self.rpcStatusMess)
myPopUp_sb(self, "info", 'PET4L - rpc check', f"{self.rpcStatusMess}")

def updateHWleds(self):
if self.hwStatus == 1:
Expand All @@ -342,7 +340,7 @@ def updateHWstatus(self, ctrl):
printDbg(str(e))
pass

printDbg("status:%s - mess: %s" % (self.hwStatus, self.hwStatusMess))
printDbg(f"status:{self.hwStatus} - mess: {self.hwStatusMess}")

def updateLastBlockLabel(self):
text = '--'
Expand Down Expand Up @@ -370,9 +368,9 @@ def updateLastBlockPing(self):
color = "green"
self.header.lastPingIcon.setPixmap(self.connGreen_icon)
if self.rpcResponseTime is not None:
self.header.responseTimeLabel.setText("%.3f" % self.rpcResponseTime)
self.header.responseTimeLabel.setStyleSheet("color: %s" % color)
self.header.lastPingIcon.setStyleSheet("color: %s" % color)
self.header.responseTimeLabel.setText(f"{self.rpcResponseTime:.3f}")
self.header.responseTimeLabel.setStyleSheet(f"color: {color}")
self.header.lastPingIcon.setStyleSheet(f"color: {color}")

def updateRPCled(self, fDebug=False):
if self.rpcConnected:
Expand Down Expand Up @@ -403,7 +401,7 @@ def updateRPClist(self):
# Add public servers (italics)
italicsFont = QFont("Times", italic=True)
for s in public_servers:
url = s["protocol"] + "://" + s["host"].split(':')[0]
url = f"{s['protocol']}://{s['host'].split(':')[0]}"
self.header.rpcClientsBox.addItem(url, s)
self.header.rpcClientsBox.setItemData(self.getServerListIndex(s), italicsFont, Qt.FontRole)
# Add Local Wallet (bold)
Expand All @@ -413,7 +411,7 @@ def updateRPClist(self):
self.header.rpcClientsBox.setItemData(self.getServerListIndex(custom_servers[0]), boldFont, Qt.FontRole)
# Add custom servers
for s in custom_servers[1:]:
url = s["protocol"] + "://" + s["host"].split(':')[0]
url = f"{s['protocol']}://{s['host'].split(':')[0]}"
self.header.rpcClientsBox.addItem(url, s)
# reset index
if self.parent.cache['selectedRPC_index'] >= self.header.rpcClientsBox.count():
Expand All @@ -428,7 +426,7 @@ def updateRPClist(self):
def updateRPCstatus(self, ctrl, fDebug=False):
rpc_index, rpc_protocol, rpc_host, rpc_user, rpc_password = self.getRPCserver()
if fDebug:
printDbg("Trying to connect to RPC %s://%s..." % (rpc_protocol, rpc_host))
printDbg(f"Trying to connect to RPC {rpc_protocol}://{rpc_host}...")

try:
rpcClient = RpcClient(rpc_protocol, rpc_host, rpc_user, rpc_password)
Expand Down
6 changes: 3 additions & 3 deletions src/qt/guiHeader.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

class GuiHeader(QWidget):
def __init__(self, caller, *args, **kwargs):
QWidget.__init__(self)
super().__init__(*args, **kwargs)
layout = QHBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
# --- 1) Check Box
Expand All @@ -28,7 +28,7 @@ def __init__(self, caller, *args, **kwargs):
self.button_checkRpc.setToolTip("try to connect to RPC server")
self.centralBox.addWidget(self.button_checkRpc, 0, 2)
self.rpcLed = QLabel()
self.rpcLed.setToolTip("%s" % caller.rpcStatusMess)
self.rpcLed.setToolTip(f"{caller.rpcStatusMess}")
self.rpcLed.setPixmap(caller.ledGrayH_icon)
self.centralBox.addWidget(self.rpcLed, 0, 3)
self.lastPingBox = QWidget()
Expand Down Expand Up @@ -65,7 +65,7 @@ def __init__(self, caller, *args, **kwargs):
self.button_checkHw.setToolTip("try to connect to Hardware Wallet")
self.centralBox.addWidget(self.button_checkHw, 1, 2)
self.hwLed = QLabel()
self.hwLed.setToolTip("status: %s" % caller.hwStatusMess)
self.hwLed.setToolTip(f"status: {caller.hwStatusMess}")
self.hwLed.setPixmap(caller.ledGrayH_icon)
self.centralBox.addWidget(self.hwLed, 1, 3)
layout.addLayout(self.centralBox)
Expand Down
Loading

0 comments on commit 13fe7fb

Please sign in to comment.