Skip to content
Open
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
3 changes: 1 addition & 2 deletions BlocksScreen/BlocksScreen.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import logging
import sys
import typing

from logger import CrashHandler, LogManager, install_crash_handler, setup_logging

Expand Down Expand Up @@ -39,7 +38,7 @@ def notify(self, a0: QtCore.QObject, a1: QtCore.QEvent) -> bool: # type: ignore
RESET = "\033[0m"


def show_splash(window: typing.Optional[QtWidgets.QWidget] = None):
def show_splash(window: QtWidgets.QWidget | None = None):
"""Show splash screen on app initialization"""
logo = QtGui.QPixmap("BlocksScreen/BlocksScreen/lib/ui/resources/logoblocks.png")
splash = QtWidgets.QSplashScreen(pixmap=logo)
Expand Down
31 changes: 15 additions & 16 deletions BlocksScreen/lib/filament.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Class that represents a filament spool

from typing import Optional
from __future__ import annotations

import enum


Expand Down Expand Up @@ -29,17 +30,18 @@ def __init__(
self,
name: str,
temperature: int,
brand: Optional[str] = None,
spool_type: Optional[SpoolMaterial] = None,
spool_weight: Optional[float] = None,
brand: str | None = None,
spool_type: SpoolMaterial | None = None,
spool_weight: float | None = None,
):
if not isinstance(name, str) or not isinstance(temperature, int):
raise TypeError("__init__() invalid argument type")

self._name: str = name
self._temperature: int = temperature
self._weight: Optional[float] = None
self._brand: Optional[str] = brand
self._weight: float | None = None
self._brand: str | None = brand
self._spool_type: Filament.SpoolMaterial | None = None

if spool_type is not None and spool_type in self.SpoolMaterial:
self._spool_type = spool_type
Expand All @@ -55,7 +57,7 @@ def temperature(self) -> int:
return self._temperature

@property
def weight(self) -> Optional[float]:
def weight(self) -> float | None:
if self._weight is None:
return
return self._weight
Expand All @@ -65,22 +67,19 @@ def weight(self, new_value: float):
self._weight = new_value

@property
def brand(self) -> Optional[str]:
def brand(self) -> str | None:
return self._brand

@brand.setter
def brand(self, new_value: str) -> Optional[str]:
def brand(self, new_value: str) -> None:
self._brand = new_value

@property
def spool_type(self) -> Optional[SpoolMaterial]:
def spool_type(self) -> SpoolMaterial | None:
return self._spool_type

@spool_type.setter
def spool_type(self, new):
if new not in self.SpoolMaterial:
if isinstance(new, self.SpoolMaterial):
raise ValueError(
"Spool Material type is invalid"
) # Correct type but invalid option
def spool_type(self, new) -> None:
if new is not None and not isinstance(new, self.SpoolMaterial):
raise ValueError(f"Spool Material type is invalid: {new!r}")
self._spool_type = new
21 changes: 10 additions & 11 deletions BlocksScreen/lib/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
from pathlib import Path

import events
from events import ReceivedFileData
from lib.moonrakerComm import MoonWebSocket
from PyQt6 import QtCore, QtGui, QtWidgets

Expand Down Expand Up @@ -54,7 +53,7 @@ class FileMetadata:

filename: str = ""
thumbnail_images: list[QtGui.QImage] = field(default_factory=list)
filament_total: typing.Union[dict, str, float] = field(default_factory=dict)
filament_total: dict | str | float = field(default_factory=dict)
estimated_time: int = 0
layer_count: int = -1
total_layer: int = -1
Expand All @@ -74,8 +73,8 @@ class FileMetadata:
slicer_version: str = "Unknown"
gcode_start_byte: int = 0
gcode_end_byte: int = 0
print_start_time: typing.Optional[float] = None
job_id: typing.Optional[str] = None
print_start_time: float | None = None
job_id: str | None = None

def to_dict(self) -> dict:
"""Convert to dictionary for signal emission."""
Expand Down Expand Up @@ -255,7 +254,7 @@ def is_loaded(self) -> bool:
"""Check if initial load is complete."""
return self._initial_load_complete

def get_file_metadata(self, filename: str) -> typing.Optional[FileMetadata]:
def get_file_metadata(self, filename: str) -> FileMetadata | None:
"""Get cached metadata for a file."""
return self._files_metadata.get(filename.removeprefix("/"))

Expand All @@ -279,7 +278,7 @@ def initial_load(self) -> None:
self._initial_load_complete = False
self.request_dir_info[str, bool].emit("", True)

def handle_filelist_changed(self, data: typing.Union[dict, list]) -> None:
def handle_filelist_changed(self, data: dict | list) -> None:
"""Handle notify_filelist_changed from Moonraker."""
if isinstance(data, dict) and "params" in data:
data = data.get("params", [])
Expand Down Expand Up @@ -492,7 +491,7 @@ def _process_metadata(self, data: dict) -> None:
self.fileinfo.emit(metadata.to_dict())
logger.debug(f"Metadata loaded for: {filename}")

def handle_metadata_error(self, error_data: typing.Union[str, dict]) -> None:
def handle_metadata_error(self, error_data: str | dict) -> None:
"""
Handle metadata request error from Moonraker.

Expand Down Expand Up @@ -538,7 +537,7 @@ def _preload_usb_contents(self, usb_path: str) -> None:
self._usb_preload_queue.append(usb_path)
self.ws.api.get_dir_information(usb_path, True)

def get_cached_usb_files(self, usb_path: str) -> typing.Optional[list[dict]]:
def get_cached_usb_files(self, usb_path: str) -> list[dict] | None:
"""
Get cached files for a USB path if available.

Expand Down Expand Up @@ -646,7 +645,7 @@ def on_request_fileinfo(self, filename: str) -> None:
@QtCore.pyqtSlot(str, bool, name="get_dir_info")
def get_dir_information(
self, directory: str = "", extended: bool = True
) -> typing.Optional[list]:
) -> list | None:
"""Get directory information."""
self._current_directory = directory

Expand All @@ -669,8 +668,8 @@ def eventFilter(self, obj: QtCore.QObject, event: QtCore.QEvent) -> bool:

def event(self, event: QtCore.QEvent) -> bool:
"""Handle object-level events."""
if event.type() == ReceivedFileData.type():
if isinstance(event, ReceivedFileData):
if event.type() == events.ReceivedFileData.type():
if isinstance(event, events.ReceivedFileData):
self.handle_message_received(event.method, event.data, event.params)
return True
return super().event(event)
Expand Down
9 changes: 4 additions & 5 deletions BlocksScreen/lib/moonrest.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
import logging

import requests
from requests import Request, Response

logger = logging.getLogger(__name__)

Expand All @@ -38,7 +37,7 @@ class UncallableError(Exception):
"""Raised when a method is not callable"""

def __init__(self, message="Unable to call method", errors=None):
super(UncallableError, self).__init__(message, errors)
super().__init__(message, errors)
self.errors = errors
self.message = message

Expand Down Expand Up @@ -128,7 +127,7 @@ def _request(
_headers = {"x-api-key": self._api_key} if self._api_key else {}
try:
if hasattr(requests, request_type):
_request_method: Request = getattr(requests, request_type)
_request_method = getattr(requests, request_type)
if not callable(_request_method):
raise UncallableError(
"Invalid request method",
Expand All @@ -142,9 +141,9 @@ def _request(
headers=_headers,
timeout=timeout,
)
if isinstance(response, Response):
if isinstance(response, requests.Response):
response.raise_for_status()
return response.json() if json_response else response.content

except Exception as e:
logger.info(f"Unexpected error while sending HTTP request: {e}")
logger.info("Unexpected error while sending HTTP request: %s", e)
2 changes: 2 additions & 0 deletions BlocksScreen/lib/panels/widgets/bannerPopup.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ def _calculate_target_geometry(self) -> QtCore.QRect:
if isinstance(widget, QtWidgets.QMainWindow):
main_window = widget
break
if main_window is None:
return QtCore.QRect()
parent_rect = main_window.geometry()
width = int(parent_rect.width() * 0.35)
height = 80
Expand Down
9 changes: 4 additions & 5 deletions BlocksScreen/lib/panels/widgets/fansPage.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
from PyQt6 import QtCore, QtWidgets
import typing


class FansPage(QtWidgets.QWidget):
def __init__(
self,
parent: typing.Optional["QtWidgets.QWidget"],
flags: typing.Optional["QtCore.Qt.WindowType"],
parent: QtWidgets.QWidget | None,
flags: QtCore.Qt.WindowType | None,
) -> None:
if parent is not None and flags is not None:
super(FansPage, self).__init__(parent, flags)
super().__init__(parent, flags)

else:
super(FansPage, self).__init__()
super().__init__()
9 changes: 4 additions & 5 deletions BlocksScreen/lib/panels/widgets/filesPage.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import json
import logging
import typing

import helper_methods
from lib.utils.blocks_Scrollbar import CustomScrollBar
Expand Down Expand Up @@ -34,13 +33,13 @@ class FilesPage(QtWidgets.QWidget):
ICON_PATHS = {
"back_folder": ":/ui/media/btn_icons/back_folder.svg",
"folder": ":/ui/media/btn_icons/folderIcon.svg",
"right_arrow": ":/arrow_icons/media/btn_icons/right_arrow.svg",
"right_arrow": ":/arrow_icons/media/btn_icons/arrow_right.svg",
"usb": ":/ui/media/btn_icons/usb_icon.svg",
"back": ":/ui/media/btn_icons/back.svg",
"refresh": ":/ui/media/btn_icons/refresh.svg",
}

def __init__(self, parent: typing.Optional[QtWidgets.QWidget] = None) -> None:
def __init__(self, parent: QtWidgets.QWidget | None = None) -> None:
super().__init__(parent)

self._file_list: list[dict] = []
Expand Down Expand Up @@ -263,7 +262,7 @@ def _find_file_insert_position(self, modified_time: float) -> int:

return insert_pos

def _find_file_key_by_display_name(self, display_name: str) -> typing.Optional[str]:
def _find_file_key_by_display_name(self, display_name: str) -> str | None:
"""Find the file key in _files_data by its display name."""
for key in self._files_data:
if self._get_display_name(key) == display_name:
Expand Down Expand Up @@ -691,7 +690,7 @@ def _add_file_to_list(self, file_item: dict) -> None:
if item:
self._model.add_item(item)

def _create_file_list_item(self, filedata: dict) -> typing.Optional[ListItem]:
def _create_file_list_item(self, filedata: dict) -> ListItem | None:
"""Create a ListItem from file metadata."""
filename = filedata.get("filename", "")
if not filename:
Expand Down
3 changes: 1 addition & 2 deletions BlocksScreen/lib/panels/widgets/numpadPage.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from lib.utils.icon_button import IconButton
from lib.utils.blocks_label import BlocksLabel
from lib.utils.icon_button import IconButton
from lib.utils.numpad_button import NumpadButton

from PyQt6 import QtCore, QtGui, QtWidgets


Expand Down
2 changes: 1 addition & 1 deletion BlocksScreen/lib/panels/widgets/optionCardWidget.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import typing

from PyQt6 import QtCore, QtGui, QtWidgets
from lib.utils.icon_button import IconButton
from PyQt6 import QtCore, QtGui, QtWidgets


class OptionCard(QtWidgets.QAbstractButton):
Expand Down
8 changes: 4 additions & 4 deletions BlocksScreen/lib/panels/widgets/popupDialogWidget.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import enum
from collections import deque
from typing import Deque

from lib.utils.icon_button import IconButton
from PyQt6 import QtCore, QtGui, QtWidgets
Expand All @@ -26,9 +25,9 @@ def __init__(self, parent) -> None:
super().__init__(parent)
self.timeout_timer = QtCore.QTimer(self)
self.timeout_timer.setSingleShot(True)
self.messages: Deque = deque()
self.messages: deque = deque()
self.isShown = False
self.persistent_notifications: Deque = deque()
self.persistent_notifications: deque = deque()
self.message_type: Popup.MessageType = Popup.MessageType.INFO
self.default_background_color = QtGui.QColor(164, 164, 164)
self.info_icon = QtGui.QPixmap(":ui/media/btn_icons/info.svg")
Expand Down Expand Up @@ -81,7 +80,8 @@ def _calculate_target_geometry(self) -> QtCore.QRect:
if isinstance(widget, QtWidgets.QMainWindow):
main_window = widget
break

if main_window is None:
return QtCore.QRect()
parent_rect = main_window.geometry()

width = int(parent_rect.width() * 0.85)
Expand Down
2 changes: 2 additions & 0 deletions BlocksScreen/lib/panels/widgets/printcorePage.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ def _geometry_calc(self) -> None:
for widget in app_instance.allWidgets():
if isinstance(widget, QtWidgets.QMainWindow):
main_window = widget
if main_window is None:
return
x = main_window.geometry().x()
y = main_window.geometry().y()
width = main_window.width()
Expand Down
15 changes: 8 additions & 7 deletions BlocksScreen/lib/panels/widgets/sensorWidget.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,11 @@ class SensorState(enum.IntEnum):

def __init__(self, parent, sensor_name: str):
super().__init__(parent)
self.name = str(sensor_name).split(" ")[1]
_parts = str(sensor_name).split(" ", 1)
self.name = _parts[1] if len(_parts) > 1 else _parts[0]
self.sensor_type: SensorWidget.SensorType = (
self.SensorType.SWITCH
if "switch" in str(sensor_name).split(" ")[0].lower()
if "switch" in _parts[0].lower()
else self.SensorType.MOTION
)

Expand Down Expand Up @@ -96,13 +97,13 @@ def text(self, new_text) -> None:
self._text_label.setText(f"{new_text}")
self._text = new_text

@QtCore.pyqtSlot(FilamentState, name="change_fil_sensor_state")
def change_fil_sensor_state(self, state: FilamentState):
"""Invert the filament state in response to a Klipper update"""
def set_filament_state(self, state: FilamentState) -> None:
"""Set the filament state directly from a Klipper update."""
if not isinstance(state, SensorWidget.FilamentState):
return
self.filament_state = SensorWidget.FilamentState(not state.value)
self.update()
if self.filament_state != state:
self.filament_state = state
self.update()

def toggle_button_state(self, state: ToggleAnimatedButton.State) -> None:
"""Called when the Klipper firmware reports an update to the filament sensor state"""
Expand Down
Loading
Loading