Skip to content

Commit

Permalink
Acceptable Ruff formatter changes
Browse files Browse the repository at this point in the history
  • Loading branch information
Avasam committed Oct 20, 2023
1 parent 1394bf0 commit 20ae6c7
Show file tree
Hide file tree
Showing 17 changed files with 552 additions and 2,349 deletions.
34 changes: 21 additions & 13 deletions src/AutoSplit.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ def __init__(self): # noqa: PLR0915
# Setup global error handling
def _show_error_signal_slot(error_message_box: Callable[..., object]):
return error_message_box()

self.show_error_signal.connect(_show_error_signal_slot)
sys.excepthook = error_messages.make_excepthook(self)

Expand Down Expand Up @@ -194,6 +195,7 @@ def _show_error_signal_slot(error_message_box: Callable[..., object]):

def _update_checker_widget_signal_slot(latest_version: str, check_on_open: bool):
return open_update_checker(self, latest_version, check_on_open)

self.update_checker_widget_signal.connect(_update_checker_widget_signal_slot)

self.load_start_image_signal.connect(self.__load_start_image)
Expand All @@ -214,6 +216,7 @@ def _update_checker_widget_signal_slot(latest_version: str, check_on_open: bool)

try:
import pyi_splash # pyright: ignore[reportMissingModuleSource]

pyi_splash.close()
except ModuleNotFoundError:
pass
Expand Down Expand Up @@ -251,9 +254,11 @@ def __update_live_image_details(self, capture: MatLike | None, called_from_timer
capture, _ = self.capture_method.get_frame(self)

# Update title from target window or Capture Device name
capture_region_window_label = self.settings_dict["capture_device_name"] \
if self.settings_dict["capture_method"] == CaptureMethodEnum.VIDEO_CAPTURE_DEVICE \
capture_region_window_label = (
self.settings_dict["capture_device_name"]
if self.settings_dict["capture_method"] == CaptureMethodEnum.VIDEO_CAPTURE_DEVICE
else self.settings_dict["captured_window_title"]
)
self.capture_region_window_label.setText(capture_region_window_label)

# Simply clear if "live capture region" setting is off
Expand Down Expand Up @@ -330,7 +335,6 @@ def __start_image_function(self):
(below_flag and self.split_below_threshold and similarity_diff < 0 and is_valid_image(capture)) # noqa: PLR0916 # See above TODO
or (not below_flag and similarity_diff >= 0)
):

self.timer_start_image.stop()
self.split_below_threshold = False

Expand Down Expand Up @@ -456,10 +460,12 @@ def skip_split(self, navigate_image_only: bool = False):
"""Skip Split" and "Next Img." buttons connect to here."""
# Can't skip or split until timer is started
# or Splitting/skipping when there are no images left
if not self.is_running \
or "Delayed Split" in self.current_split_image.text() \
or not (self.skip_split_button.isEnabled() or self.is_auto_controlled or navigate_image_only) \
or self.__is_current_split_out_of_range():
if (
not self.is_running
or "Delayed Split" in self.current_split_image.text()
or not (self.skip_split_button.isEnabled() or self.is_auto_controlled or navigate_image_only)
or self.__is_current_split_out_of_range()
):
return

if not navigate_image_only:
Expand Down Expand Up @@ -558,7 +564,6 @@ def __auto_splitter(self): # noqa: PLR0912,PLR0915

# First loop: stays in this loop until all of the split images have been split
while self.split_image_number < number_of_split_images:

# Check if we are not waiting for the split delay to send the key press
if self.waiting_for_split_delay:
time_millis = int(round(time() * 1000))
Expand Down Expand Up @@ -882,9 +887,11 @@ def exit_program() -> NoReturn:
if user_profile.have_settings_changed(self):
# Give a different warning if there was never a settings file that was loaded successfully,
# and "save as" instead of "save".
settings_file_name = "Untitled" \
if not self.last_successfully_loaded_settings_file_path \
settings_file_name = (
"Untitled"
if not self.last_successfully_loaded_settings_file_path
else os.path.basename(self.last_successfully_loaded_settings_file_path)
)

warning = QMessageBox.warning(
self,
Expand Down Expand Up @@ -923,9 +930,10 @@ def set_preview_image(qlabel: QLabel, image: MatLike | None):

qimage = QtGui.QImage(
capture.data, # pyright: ignore[reportGeneralTypeIssues] # https://bugreports.qt.io/browse/PYSIDE-2476
width, height,
width *
channels, image_format,
width,
height,
width * channels,
image_format,
)
qlabel.setPixmap(
QtGui.QPixmap(qimage).scaled(
Expand Down
11 changes: 7 additions & 4 deletions src/AutoSplitImage.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
from utils import BGR_CHANNEL_COUNT, MAXBYTE, ColorChannel, ImageShape, is_valid_image

if TYPE_CHECKING:

from AutoSplit import AutoSplit


Expand Down Expand Up @@ -150,13 +149,17 @@ def compare_with_capture(
comparison_method = self.__get_comparison_method(default)

return COMPARE_METHODS_BY_INDEX.get(
comparison_method, compare_dummy,
comparison_method,
compare_dummy,
)(
self.byte_array, resized_capture, self.mask,
self.byte_array,
resized_capture,
self.mask,
)


def compare_dummy(*_: object): return 0.0
def compare_dummy(*_: object):
return 0.0


if True:
Expand Down
1 change: 0 additions & 1 deletion src/capture_method/BitBltCaptureMethod.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
from utils import BGRA_CHANNEL_COUNT, get_window_bounds, is_valid_hwnd, try_delete_dc

if TYPE_CHECKING:

from AutoSplit import AutoSplit

# This is an undocumented nFlag value for PrintWindow
Expand Down
1 change: 0 additions & 1 deletion src/capture_method/CaptureMethodBase.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from utils import is_valid_hwnd

if TYPE_CHECKING:

from AutoSplit import AutoSplit


Expand Down
12 changes: 6 additions & 6 deletions src/capture_method/VideoCaptureDeviceCaptureMethod.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
from utils import ImageShape, is_valid_image

if TYPE_CHECKING:

from AutoSplit import AutoSplit

OBS_VIRTUALCAM_PLUGIN_BLANK_PIXEL = [127, 129, 128]
Expand All @@ -27,9 +26,10 @@ def is_blank(image: MatLike):
# Instead we check for a few key pixels, in this case, corners
return np.all(
image[
::image.shape[ImageShape.Y] - 1,
::image.shape[ImageShape.X] - 1,
] == OBS_VIRTUALCAM_PLUGIN_BLANK_PIXEL,
:: image.shape[ImageShape.Y] - 1,
:: image.shape[ImageShape.X] - 1,
]
== OBS_VIRTUALCAM_PLUGIN_BLANK_PIXEL,
)


Expand Down Expand Up @@ -136,8 +136,8 @@ def get_frame(self, autosplit: AutoSplit):
y = min(selection["y"], image.shape[ImageShape.Y] - 1)
x = min(selection["x"], image.shape[ImageShape.X] - 1)
image = image[
y:y + selection["height"],
x:x + selection["width"],
y: y + selection["height"],
x: x + selection["width"],
]
return cv2.cvtColor(image, cv2.COLOR_BGR2BGRA), is_old_image

Expand Down
5 changes: 3 additions & 2 deletions src/capture_method/WindowsGraphicsCaptureMethod.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ async def coroutine():
if not frame:
return None
return await (SoftwareBitmap.create_copy_from_surface_async(frame.surface) or asyncio.sleep(0, None))

try:
software_bitmap = asyncio.run(coroutine())
except SystemError as exception:
Expand All @@ -125,8 +126,8 @@ async def coroutine():
image = np.frombuffer(cast(bytes, reference), dtype=np.uint8)
image.shape = (self.size.height, self.size.width, BGRA_CHANNEL_COUNT)
image = image[
selection["y"]:selection["y"] + selection["height"],
selection["x"]:selection["x"] + selection["width"],
selection["y"]: selection["y"] + selection["height"],
selection["x"]: selection["x"] + selection["width"],
]
self.last_captured_frame = image
return image, False
Expand Down
7 changes: 5 additions & 2 deletions src/capture_method/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ def __hash__(self):
# https://github.com/python/typeshed/issues/10428
@override
def _generate_next_value_( # type:ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
name: str | CaptureMethodEnum, *_, # noqa: N805
name: str | CaptureMethodEnum, # noqa: N805
*_,
):
return name

Expand Down Expand Up @@ -127,6 +128,7 @@ def get(self, key: CaptureMethodEnum, __default: object = None):
CAPTURE_METHODS[CaptureMethodEnum.BITBLT] = BitBltCaptureMethod
try: # Test for laptop cross-GPU Desktop Duplication issue
import d3dshot

d3dshot.create(capture_output="numpy")
except (ModuleNotFoundError, COMError):
pass
Expand Down Expand Up @@ -198,7 +200,8 @@ async def get_camera_info(index: int, device_name: str):
else None

return [
camera_info for camera_info
camera_info
for camera_info
# Note: Return type required https://github.com/python/typeshed/issues/2652
in await asyncio.gather(*starmap(get_camera_info, enumerate(named_video_inputs)))
if camera_info is not None
Expand Down
7 changes: 5 additions & 2 deletions src/error_messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,8 +152,10 @@ def already_open():

def exception_traceback(exception: BaseException, message: str = ""):
if not message:
message = "AutoSplit encountered an unhandled exception and will try to recover, " + \
f"however, there is no guarantee it will keep working properly. {CREATE_NEW_ISSUE_MESSAGE}"
message = (
"AutoSplit encountered an unhandled exception and will try to recover, "
+ f"however, there is no guarantee it will keep working properly. {CREATE_NEW_ISSUE_MESSAGE}"
)
set_text_message(
message,
"\n".join(traceback.format_exception(None, exception, exception.__traceback__)),
Expand Down Expand Up @@ -181,6 +183,7 @@ def excepthook(exception_type: type[BaseException], exception: BaseException, _t
return
# Whithin LiveSplit excepthook needs to use MainWindow's signals to show errors
autosplit.show_error_signal.emit(lambda: exception_traceback(exception))

return excepthook


Expand Down
3 changes: 3 additions & 0 deletions src/hotkeys.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ def __get_hotkey_name(names: list[str]):

def sorting_key(key: str):
return not keyboard.is_modifier(keyboard.key_to_scan_codes(key)[0])

clean_names = sorted(keyboard.get_hotkey_name(names).split("+"), key=sorting_key)
# Replace the last key in hotkey_name with what we actually got as a last key_name
# This ensures we keep proper keypad names
Expand Down Expand Up @@ -224,11 +225,13 @@ def __get_hotkey_action(autosplit: AutoSplit, hotkey: Hotkey):
if hotkey == "undo_split":
return lambda: autosplit.undo_split(True)
if hotkey == "toggle_auto_reset_image":

def toggle_auto_reset_image():
new_value = not autosplit.settings_dict["enable_auto_reset"]
autosplit.settings_dict["enable_auto_reset"] = new_value
if autosplit.SettingsWidget:
autosplit.SettingsWidget.enable_auto_reset_image_checkbox.setChecked(new_value)

return toggle_auto_reset_image
return getattr(autosplit, f"{hotkey}_signal").emit

Expand Down
5 changes: 3 additions & 2 deletions src/menu_bar.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,6 @@ def __init__(self, autosplit: AutoSplit):
# Don't autofocus any particular field
self.setFocus()


# region Build the Capture method combobox
capture_method_values = CAPTURE_METHODS.values()
self.__set_all_capture_devices()
Expand Down Expand Up @@ -279,6 +278,7 @@ def __setup_bindings(self):
# Hotkey initial values and bindings
def hotkey_connect(hotkey: Hotkey):
return lambda: set_hotkey(self.autosplit, hotkey)

for hotkey in HOTKEYS:
hotkey_input: QtWidgets.QLineEdit = getattr(self, f"{hotkey}_input")
set_hotkey_hotkey_button: QtWidgets.QPushButton = getattr(self, f"set_{hotkey}_hotkey_button")
Expand Down Expand Up @@ -331,7 +331,8 @@ def hotkey_connect(hotkey: Hotkey):
# Image Settings
self.default_comparison_method_combobox.currentIndexChanged.connect(
lambda: self.__set_value(
"default_comparison_method", self.default_comparison_method_combobox.currentIndex(),
"default_comparison_method",
self.default_comparison_method_combobox.currentIndex(),
),
)
self.default_similarity_threshold_spinbox.valueChanged.connect(
Expand Down
12 changes: 7 additions & 5 deletions src/region_selection.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@


if TYPE_CHECKING:

from AutoSplit import AutoSplit

ALIGN_REGION_THRESHOLD = 0.9
Expand All @@ -54,15 +53,18 @@
("Radiance HDR", "*.hdr *.pic"),
]
"""https://docs.opencv.org/4.8.0/d4/da8/group__imgcodecs.html#imread"""
IMREAD_EXT_FILTER = "All Files (" \
+ " ".join([f"{extensions}" for _, extensions in SUPPORTED_IMREAD_FORMATS]) \
+ ");;"\
IMREAD_EXT_FILTER = (
"All Files ("
+ " ".join([f"{extensions}" for _, extensions in SUPPORTED_IMREAD_FORMATS])
+ ");;"
+ ";;".join([f"{imread_format} ({extensions})" for imread_format, extensions in SUPPORTED_IMREAD_FORMATS])
)


# TODO: For later as a different picker option
def __select_graphics_item(autosplit: AutoSplit): # pyright: ignore [reportUnusedFunction]
# TODO: For later as a different picker option
"""Uses the built-in GraphicsCapturePicker to select the Window."""

def callback(async_operation: IAsyncOperation[GraphicsCaptureItem], async_status: AsyncStatus):
try:
if async_status != AsyncStatus.COMPLETED:
Expand Down
2 changes: 2 additions & 0 deletions src/split_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,8 +211,10 @@ def parse_and_validate_images(autosplit: AutoSplit):
for image in split_images:
# Test for image without transparency
if not is_valid_image(image.byte_array):

def image_validity(filename: str):
return lambda: error_messages.image_validity(filename)

error_message = image_validity(image.filename)
break

Expand Down
25 changes: 15 additions & 10 deletions src/user_profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,17 +72,19 @@ class UserProfileDict(TypedDict):


def have_settings_changed(autosplit: AutoSplit):
return (
return (
autosplit.settings_dict != autosplit.last_saved_settings
or autosplit.settings_dict != autosplit.last_loaded_settings
or autosplit.settings_dict != autosplit.last_loaded_settings
)


def save_settings(autosplit: AutoSplit):
"""@return: The save settings filepath. Or None if "Save Settings As" is cancelled."""
return __save_settings_to_file(autosplit, autosplit.last_successfully_loaded_settings_file_path) \
if autosplit.last_successfully_loaded_settings_file_path \
return (
__save_settings_to_file(autosplit, autosplit.last_successfully_loaded_settings_file_path)
if autosplit.last_successfully_loaded_settings_file_path
else save_settings_as(autosplit)
)


def save_settings_as(autosplit: AutoSplit):
Expand Down Expand Up @@ -160,12 +162,15 @@ def __load_settings_from_file(autosplit: AutoSplit, load_settings_file_path: str


def load_settings(autosplit: AutoSplit, from_path: str = ""):
load_settings_file_path = from_path or QtWidgets.QFileDialog.getOpenFileName(
autosplit,
"Load Profile",
os.path.join(auto_split_directory, "settings.toml"),
"TOML (*.toml)",
)[0]
load_settings_file_path = (
from_path
or QtWidgets.QFileDialog.getOpenFileName(
autosplit,
"Load Profile",
os.path.join(auto_split_directory, "settings.toml"),
"TOML (*.toml)",
)[0]
)
if not (load_settings_file_path and __load_settings_from_file(autosplit, load_settings_file_path)):
return

Expand Down
Loading

0 comments on commit 20ae6c7

Please sign in to comment.