Skip to content

Commit 2fd76fe

Browse files
authored
Merge pull request #4 from HellAholic/2.0.4
2.0.4
2 parents cd3c92d + 789a042 commit 2fd76fe

File tree

6 files changed

+17
-64
lines changed

6 files changed

+17
-64
lines changed

GCodeManager.py

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -30,15 +30,12 @@ def _find_current_settings_container(self, global_stack):
3030
found_container = global_stack.findContainer(criteria={"id": printer_settings_container_id})
3131
if found_container and isinstance(found_container, InstanceContainer):
3232
settings_container = found_container
33-
Logger.log("i", f"PrintSkewCompensation: Found settings container by ID: {printer_settings_container_id}")
3433

3534
if not settings_container: # Fallback to top if no settings container found (less ideal but safe in terms of functionality)
36-
self._logger.log("w", f"{self._plugin_id}: No specific settings container found, falling back to global stack top.")
3735
top_container = global_stack.getTop()
3836
if isinstance(top_container, InstanceContainer):
3937
settings_container = top_container
4038
else:
41-
self._logger.log("w", f"{self._plugin_id}: Top container in stack is not an InstanceContainer.")
4239
return None
4340

4441
return settings_container
@@ -57,19 +54,16 @@ def sync_start_gcode(self, skew_calculator: "SkewCalculator", method: str, marli
5754

5855
global_stack = self._application.getGlobalContainerStack()
5956
if not global_stack:
60-
self._logger.log("w", f"{self._plugin_id}: Could not get global container stack for G-code sync.")
6157
return
6258

6359
settings_container = self._find_current_settings_container(global_stack)
6460
if not settings_container:
65-
self._logger.log("w", f"{self._plugin_id}: Could not find a suitable settings container for G-code sync.")
6661
return
6762

6863
try:
6964
# Get property from the global stack to ensure we get inherited values
7065
current_start_gcode = global_stack.getProperty(self._starg_gcode_key, "value")
7166
if current_start_gcode is None:
72-
self._logger.log("w", f"{self._plugin_id}: '{self._starg_gcode_key}' is None in the global stack. Using empty string.")
7367
current_start_gcode = ""
7468
except Exception as e:
7569
self._logger.logException("e", f"{self._plugin_id}: Error getting current start G-code from global stack: {e}")
@@ -137,11 +131,9 @@ def sync_start_gcode(self, skew_calculator: "SkewCalculator", method: str, marli
137131
new_start_gcode = "\n".join(new_gcode_lines)
138132
# Final check against original content, just in case logic above resulted in no net change
139133
if new_start_gcode != current_start_gcode:
140-
self._logger.log("i", f"{self._plugin_id}: Synchronizing start G-code skew command. Added={command_added}, Removed={command_removed}")
141134
try:
142135
# Set the property in the found settings_container
143136
settings_container.setProperty(self._starg_gcode_key, "value", new_start_gcode)
144-
self._logger.log("i", f"{self._plugin_id}: Successfully set start G-code in container '{settings_container.getId()}'.")
145137
except Exception as e:
146138
self._logger.logException("e", f"{self._plugin_id}: Error setting start G-code in container '{settings_container.getId()}': {e}")
147139
else:

MeasurementDialogUI.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -320,5 +320,4 @@ def reject(self):
320320
lifetime=5,
321321
title=catalog.i18n("[Print Skew Compensation]"),
322322
message_type=Message.MessageType.NEUTRAL).show()
323-
Logger.log("i", f"{PluginConstants.PLUGIN_ID}: MeasurementDialog rejected (Cancel clicked or closed).")
324323
super().reject()

PluginController.py

Lines changed: 14 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -38,24 +38,22 @@ def __init__(self) -> None:
3838
self.pp_script_checkbox_state = False
3939

4040
self._global_container_stack = None
41+
self._last_printer_was_none = False # Track printer state to reduce logging spam
4142
self._connect_to_global_stack_metadata()
4243
Application.getInstance().globalContainerStackChanged.connect(self._handle_global_container_stack_changed)
4344

4445
self.setMenuName(catalog.i18n("Print Skew Compensation"))
4546

4647
self._update_internal_state_from_printer_config()
4748

48-
action_open_menu = self.addMenuItem(catalog.i18n("Calibrate Skew..."), self._show_plugin_menu_dialog)
49-
if not action_open_menu:
50-
Logger.log("e", f"{PluginConstants.PLUGIN_ID}: Failed to create 'Open Plugin Menu' menu item action.")
49+
self.addMenuItem(catalog.i18n("Calibrate Skew..."), self._show_plugin_menu_dialog)
5150

5251
if self._preferences:
5352
self._preferences.preferenceChanged.connect(self._on_preference_changed)
5453
else:
55-
Logger.log("w", f"{PluginConstants.PLUGIN_ID}: Could not get preferences instance to connect signal.")
54+
Logger.log("e", f"{PluginConstants.PLUGIN_ID}: Could not get preferences instance to connect signal.")
5655

5756
PluginConstants.get_operating_system()
58-
Logger.log("i", f"{PluginConstants.PLUGIN_ID}: PluginController Initialized for {PluginConstants.CURRENT_OS} OS.")
5957

6058
# Handlers for reading/writing printer settings
6159

@@ -81,14 +79,12 @@ def _read_printer_settings_from_file(self, printer_name) -> dict:
8179
"""Reads printer settings from the plugin's configuration file for the given printer name."""
8280
cfg_path = self._get_printer_cfg_path(printer_name)
8381
if not os.path.exists(cfg_path):
84-
Logger.log("w", f"{PluginConstants.PLUGIN_ID}: Printer settings file does not exist: {cfg_path}. Using default settings.")
8582
return self._get_default_settings()
8683

8784
config = configparser.ConfigParser()
8885
config.read(cfg_path)
8986

9087
if 'settings' not in config:
91-
Logger.log("w", f"{PluginConstants.PLUGIN_ID}: No 'settings' section found in {cfg_path}. Using default settings.")
9288
return self._get_default_settings()
9389

9490
settings = {k: v for k, v in config['settings'].items()}
@@ -139,9 +135,12 @@ def _update_internal_state_from_printer_config(self):
139135
default_settings = self._get_default_settings()
140136

141137
if not printer_name:
142-
Logger.log("w", f"{PluginConstants.PLUGIN_ID}: No printer selected, using default settings.")
138+
# Only log once, when the state actually changes
139+
if not hasattr(self, '_last_printer_was_none') or not self._last_printer_was_none:
140+
self._last_printer_was_none = True
143141
current_settings_source = default_settings # Use defaults directly, types are correct
144142
else:
143+
self._last_printer_was_none = False
145144
current_settings_source = self._read_printer_settings_from_file(printer_name)
146145

147146
# Helper to get a value and convert if it's a string, falling back to default typed value
@@ -160,16 +159,13 @@ def get_typed_value(key_name, default_typed_value_from_schema):
160159
else: # Fallback for unexpected types, try direct conversion
161160
return target_type(value_from_source)
162161
except ValueError:
163-
Logger.log("w", f"{PluginConstants.PLUGIN_ID}: Invalid value '{value_from_source}' for '{key_name}'. Using default: {default_typed_value_from_schema}")
164162
return default_typed_value_from_schema
165163
elif isinstance(value_from_source, target_type):
166164
return value_from_source
167165
else:
168166
try:
169-
Logger.log("d", f"{PluginConstants.PLUGIN_ID}: Value for '{key_name}' is of type {type(value_from_source)}, attempting cast to {target_type}.")
170167
return target_type(value_from_source)
171168
except Exception as e:
172-
Logger.log("w", f"{PluginConstants.PLUGIN_ID}: Could not convert value '{value_from_source}' for '{key_name}' to {target_type}. Error: {e}. Using default: {default_typed_value_from_schema}")
173169
return default_typed_value_from_schema
174170

175171
self.enabled = get_typed_value("compensation_enabled", default_settings["compensation_enabled"])
@@ -205,7 +201,6 @@ def _save_current_settings(self):
205201
self._update_plugin_menu_dialog_state()
206202
printer_name = self._get_current_printer_name()
207203
if not printer_name:
208-
Logger.log("w", f"{PluginConstants.PLUGIN_ID}: No printer selected, cannot save settings.")
209204
return
210205
settings = {
211206
"compensation_enabled": self.enabled,
@@ -235,7 +230,7 @@ def _connect_to_global_stack_metadata(self):
235230
try:
236231
self._global_container_stack.metaDataChanged.disconnect(self._on_global_metadata_changed)
237232
except TypeError:
238-
Logger.log("w", f"{PluginConstants.PLUGIN_ID}: Error disconnecting from old global_container_stack.metaDataChanged; was it connected?")
233+
pass # Connection didn't exist
239234
except Exception as e:
240235
Logger.logException("e", f"{PluginConstants.PLUGIN_ID}: Unexpected error disconnecting from old global_container_stack: {e}")
241236

@@ -245,32 +240,31 @@ def _connect_to_global_stack_metadata(self):
245240
if self._global_container_stack:
246241
try:
247242
self._global_container_stack.metaDataChanged.connect(self._on_global_metadata_changed)
248-
Logger.log("i", f"{PluginConstants.PLUGIN_ID}: Connected listener to global_container_stack.metaDataChanged.")
249243
# Trigger a check to sync state immediately after connecting/reconnecting
250244
self._on_global_metadata_changed()
251245
except Exception as e:
252246
Logger.logException("e", f"{PluginConstants.PLUGIN_ID}: Failed to connect to global_container_stack.metaDataChanged: {e}")
253247
else:
254-
Logger.log("w", f"{PluginConstants.PLUGIN_ID}: No global_container_stack available to connect metaDataChanged listener.")
248+
pass # No stack available during startup is normal
255249

256250
def _handle_global_container_stack_changed(self):
257251
"""Handles the global container stack changing."""
258-
Logger.log("i", f"{PluginConstants.PLUGIN_ID}: Global container stack has changed. Re-evaluating metadata listener connection.")
259252
self._connect_to_global_stack_metadata()
260253

261254
def _on_global_metadata_changed(self): # Signature changed: no key argument
262255
"""Handles changes to the global container stack's metadata."""
263256
self._update_plugin_menu_dialog_state()
264257

265258
def _on_preference_changed(self, *args): # Add *args to accept any additional arguments
266-
self._update_internal_state_from_printer_config()
259+
# Avoid unnecessary updates during startup when no printer is selected
260+
if self._get_current_printer_name():
261+
self._update_internal_state_from_printer_config()
267262

268263
def _show_plugin_menu_dialog(self):
269264
"""Displays the main plugin menu dialog."""
270265
# --- Check actual script state and update internal state/preference ---
271266
actual_script_state = self._is_post_processing_script_active()
272267
if self.pp_script_checkbox_state != actual_script_state:
273-
Logger.log("i", f"{PluginConstants.PLUGIN_ID}: Actual PP script state ({actual_script_state}) differs from saved state ({self.pp_script_checkbox_state}). Updating.")
274268
self.pp_script_checkbox_state = actual_script_state
275269
# --- End check ---
276270

@@ -333,7 +327,7 @@ def _is_post_processing_script_active(self) -> bool:
333327
self.pp_script_checkbox_state = is_active # Update internal state
334328
return is_active
335329
else:
336-
Logger.log("w", f"{PluginConstants.PLUGIN_ID}: Could not get PostProcessingPlugin instance to check active scripts.")
330+
pass # PostProcessingPlugin not available
337331
except Exception as e:
338332
Logger.logException("e", f"{PluginConstants.PLUGIN_ID}: Error checking active post-processing scripts: {e}")
339333
self.pp_script_checkbox_state = False # Reset state if we can't determine it
@@ -342,7 +336,6 @@ def _is_post_processing_script_active(self) -> bool:
342336
def _ensure_pp_script_state(self, target_state: bool) -> bool:
343337
"""Adds or removes the PP script to match the target state."""
344338
script_key = PluginConstants.POST_PROCESSING_SCRIPT_NAME
345-
Logger.log("i", f"{PluginConstants.PLUGIN_ID}: Ensuring PP script '{script_key}' state is {target_state}.")
346339
try:
347340
post_processing_plugin = Application.getInstance().getPluginRegistry().getPluginObject("PostProcessingPlugin")
348341
if not post_processing_plugin:
@@ -367,7 +360,6 @@ def _ensure_pp_script_state(self, target_state: bool) -> bool:
367360
# Move the newly added script to index 0, one step at a time
368361
for current_index in range(len(active_script_keys) - 1, 0, -1):
369362
post_processing_plugin.moveScript(current_index, current_index - 1)
370-
Logger.log("i", f"{PluginConstants.PLUGIN_ID}: Added script '{script_key}' to active post-processing list.")
371363
return True
372364
else:
373365
Logger.log("e", f"{PluginConstants.PLUGIN_ID}: Script '{script_key}' not found in loaded scripts. Cannot add.")
@@ -377,7 +369,6 @@ def _ensure_pp_script_state(self, target_state: bool) -> bool:
377369
elif not target_state and is_currently_active:
378370
post_processing_plugin.removeScriptByIndex(current_index)
379371
post_processing_plugin.writeScriptsToStack()
380-
Logger.log("i", f"{PluginConstants.PLUGIN_ID}: Removed script '{script_key}' from active post-processing list.")
381372
return True
382373
else:
383374
return True # State already correct
@@ -411,7 +402,6 @@ def _sync_gcode_based_on_state(self):
411402
)
412403

413404
def _handle_add_marlin_gcode_request(self, enable: bool):
414-
Logger.log("i", f"{PluginConstants.PLUGIN_ID}: Manual request to add Marlin G-code to start script.")
415405
if not self.enabled:
416406
Message(text=catalog.i18n("Skew compensation is currently disabled. Marlin G-code will not be active until enabled."),
417407
lifetime=10,
@@ -443,7 +433,6 @@ def _handle_add_marlin_gcode_request(self, enable: bool):
443433

444434

445435
def _handle_add_klipper_gcode_request(self, enable: bool):
446-
Logger.log("i", f"{PluginConstants.PLUGIN_ID}: Manual request to add Klipper G-code to start script.")
447436
if not self.enabled:
448437
Message(text=catalog.i18n("Skew compensation is currently disabled. Klipper G-code will not be active until enabled."),
449438
lifetime=10,
@@ -474,7 +463,6 @@ def _handle_add_klipper_gcode_request(self, enable: bool):
474463

475464
def _handle_toggle_post_processing_script(self, enable: bool):
476465
script_key = PluginConstants.POST_PROCESSING_SCRIPT_NAME
477-
Logger.log("i", f"{PluginConstants.PLUGIN_ID}: Request to {'enable' if enable else 'disable'} post-processing script '{script_key}'. Current checkbox state: {self.pp_script_checkbox_state}")
478466
if not self.enabled:
479467
Message(text=catalog.i18n("Skew compensation is currently disabled. Post Processing G-code will not be active until enabled."),
480468
title=catalog.i18n("[Print Skew Compensation]"),
@@ -504,7 +492,6 @@ def _handle_enable_compensation_toggle(self, enable: bool):
504492
self._save_current_settings()
505493

506494
def _on_plugin_menu_dialog_finished(self, result):
507-
Logger.log("i", f"Plugin menu dialog finished with result: {result}")
508495
self._plugin_menu_dialog_instance = None
509496

510497
def _show_measurement_dialog(self):
@@ -521,7 +508,6 @@ def _show_measurement_dialog(self):
521508
self._measurement_dialog_instance.activateWindow()
522509

523510
def _on_dialog_settings_saved(self):
524-
Logger.log("i", f"{PluginConstants.PLUGIN_ID}: Measurement dialog settings saved.")
525511
self._save_current_settings()
526512
if self.enabled:
527513
self._gcode_manager.sync_start_gcode(
@@ -535,7 +521,6 @@ def _on_dialog_settings_saved(self):
535521
self._update_plugin_menu_dialog_state()
536522

537523
def _on_dialog_finished(self, result):
538-
Logger.log("i", f"Measurement dialog finished with result: {result}")
539524
self._measurement_dialog_instance = None
540525

541526
def _load_single_model(self, model_path: str) -> bool:
@@ -544,11 +529,7 @@ def _load_single_model(self, model_path: str) -> bool:
544529
return False
545530
try:
546531
file_url = QUrl.fromLocalFile(model_path)
547-
success = self._application.readLocalFile(file_url)
548-
if success:
549-
Logger.log("i", f"readLocalFile returned True for: {model_path}")
550-
else:
551-
Logger.log("w", f"readLocalFile returned False for: {model_path}. Model might still load asynchronously.")
532+
self._application.readLocalFile(file_url)
552533
return True
553534
except Exception as e:
554535
Logger.logException("e", f"Error calling readLocalFile for model {model_path}: {e}")
@@ -591,10 +572,8 @@ def _add_calibration_model(self, model_type: str):
591572
title=catalog.i18n("[Print Skew Compensation]"),
592573
message_type=Message.MessageType.NEUTRAL).show()
593574
elif success_count > 0:
594-
Logger.log("w", f"Initiated loading for {success_count}/{total_expected} model(s) of type '{model_type}', but failed for: {', '.join(failed_models)}")
595575
Message(text=("Some calibration models failed to load: {failed_list}").format(failed_list=', '.join(failed_models)), title=catalog.i18n("[Print Skew Compensation] Warning"), parent=parent_widget).show()
596576
else:
597-
Logger.log("e", f"Failed to initiate loading for any calibration models of type '{model_type}'. Failed: {', '.join(failed_models)}")
598577
Message(
599578
text="Could not find or load the requested calibration model(s). Please check they exist in the plugin's 'calibration_model' folder.",
600579
lifetime=10,

SkewCalculator.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,6 @@ def calculate_skew_factors(self):
7373
if AD <= 0: raise ValueError("AD distance must be positive")
7474
self.marlin_I = (AC**2 - BD**2) / (4 * AD**2)
7575
except (ValueError, TypeError, ZeroDivisionError) as e:
76-
Logger.log("w", f"Could not calculate Marlin I factor (XY): {e}. Using 0.0")
7776
self.marlin_I = 0.0
7877

7978
try:
@@ -83,7 +82,6 @@ def calculate_skew_factors(self):
8382
if AD <= 0: raise ValueError("AD distance must be positive")
8483
self.marlin_J = (AC**2 - BD**2) / (4 * AD**2) if AD != 0 else 0.0
8584
except (ValueError, TypeError, ZeroDivisionError) as e:
86-
Logger.log("w", f"Could not calculate Marlin J factor (XZ): {e}. Using 0.0")
8785
self.marlin_J = 0.0
8886

8987
try:
@@ -93,11 +91,8 @@ def calculate_skew_factors(self):
9391
if AD <= 0: raise ValueError("AD distance must be positive")
9492
self.marlin_K = (AC**2 - BD**2) / (4 * AD**2) if AD != 0 else 0.0
9593
except (ValueError, TypeError, ZeroDivisionError) as e:
96-
Logger.log("w", f"Could not calculate Marlin K factor (YZ): {e}. Using 0.0")
9794
self.marlin_K = 0.0
9895

99-
Logger.log("i", f"Calculated Marlin Factors: I={self.marlin_I:.8f}, J={self.marlin_J:.8f}, K={self.marlin_K:.8f}")
100-
10196
def _calculate_skew_factor(self, ac: float, bd: float, ad: float) -> float:
10297
"""
10398
Calculates the skew factor for a single plane given its measurements.

plugin.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "Print Skew Compensation",
33
"author": "HellAholic, GregValiant",
4-
"version": "2.0.3",
4+
"version": "2.0.4",
55
"description": "Compensates for XY, XZ, and YZ skew by modifying the model pre-slice or the G-code post-slice, or by providing Marlin/Klipper commands.",
66
"api": 8,
77
"supported_sdk_versions": ["8.7.0", "8.8.0", "8.9.0"],

0 commit comments

Comments
 (0)