-
Notifications
You must be signed in to change notification settings - Fork 11
/
AutoTowersGenerator.py
639 lines (416 loc) · 25.8 KB
/
AutoTowersGenerator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
from functools import cached_property
import glob
import os
import traceback
# Import the correct version of PyQt
try:
from PyQt6.QtCore import QObject, pyqtSlot, pyqtSignal, pyqtProperty
PYQT_VERSION = 6
except ImportError:
from PyQt5.QtCore import QObject, pyqtSlot, pyqtSignal, pyqtProperty
PYQT_VERSION = 5
from UM.Application import Application
from UM.Extension import Extension
from UM.Logger import Logger
from UM.Message import Message
from UM.PluginRegistry import PluginRegistry
from UM.i18n import i18nCatalog
from UM.Resources import Resources
from cura.CuraApplication import CuraApplication
from cura.Settings.ExtruderManager import ExtruderManager
from . import MeshImporter
from .PluginSettings import PluginSettings
from .OpenScadInterface import OpenScadInterface
from .OpenScadJob import OpenScadJob
from .Controllers.BedLevelPatternContoller import BedLevelPatternController
from .Controllers.FanTowerController import FanTowerController
from .Controllers.FlowTowerController import FlowTowerController
from .Controllers.RetractTowerController import RetractTowerController
from .Controllers.SpeedTowerController import SpeedTowerController
from .Controllers.TempTowerController import TempTowerController
# not sure it's necessar i18n could be store in a different place ?
Resources.addSearchPath(
os.path.join(os.path.abspath(os.path.dirname(__file__)),'Resources')
) # Plugin translation file import
catalog = i18nCatalog("autotowers")
if catalog.hasTranslationLoaded():
Logger.log("i", "Auto Towers Generator Plugin translation loaded!")
class AutoTowersGenerator(QObject, Extension):
# Add additional controller classes to this list
_controllerClasses = [BedLevelPatternController, FanTowerController, FlowTowerController, RetractTowerController, SpeedTowerController, TempTowerController]
def __init__(self):
QObject.__init__(self)
Extension.__init__(self)
self._pluginSettings = None
# Keep track of the post-processing callback and the node added by the OpenSCAD import
self._towerControllerPostProcessingCallback = None
self._importedNode = None
# Keep track of whether a model has been generated and is in the scene
self._autoTowerNode = None
self._autoTowerOperation = None
# Keep track of the currently active tower controller
self._currentTowerController = None
# Update the view when the main window is changed so the "remove" button is always visible when enabled
CuraApplication.getInstance().mainWindowChanged.connect(self._displayRemoveAutoTowerButton)
# Finish initializing the plugin after Cura is fully ready
CuraApplication.getInstance().pluginsLoaded.connect(self._onPluginsLoadedCallback)
# Make sure the tower is cleaned up before the application closes
CuraApplication.getInstance().getOnExitCallbackManager().addCallback(self._onExitCallback)
@cached_property
def _pluginDir(self)->str:
''' Returns the path to the plugin directory '''
return PluginRegistry.getInstance().getPluginPath(self.getPluginId())
@cached_property
def _openScadSourcePath(self)->str:
''' Returns the path to the OpenSCAD source models'''
return os.path.join(self._pluginDir, 'Resources', 'OpenScad')
@cached_property
def _qmlDir(self)->str:
''' Returns the location of the QML dialog files directory '''
return os.path.join(self._pluginDir, 'Resources', 'QML', f'QT{PYQT_VERSION}')
@cached_property
def _stlDir(self)->str:
''' Returns the directory where STL files are stored '''
return os.path.join(self._pluginDir, 'Resources', 'STL')
@cached_property
def _tempDir(self)->str:
''' Returns the directory to use for temporary files '''
return os.path.join(self._pluginDir, 'tmp')
@cached_property
def _pluginSettingsFilePath(self)->str:
''' Returns the path to the plugin settings file '''
return os.path.join(self._pluginDir, 'pluginSettings.json')
@cached_property
def _removeAutoTowerButton(self)->QObject:
''' Returns the button used to remove the Auto Tower from the scene '''
return self._createDialog('RemoveModelsButton.qml')
@cached_property
def _pluginSettingsDialog(self)->QObject:
''' Returns the settings dialog '''
return self._createDialog('PluginSettingsDialog.qml')
@cached_property
def _settingsVerificationDialog(self)->QObject:
''' Returns a dialog asking the user whether they want to continue with incompatible settings '''
return self._createDialog('SettingsVerificationDialog.qml')
@cached_property
def _waitDialog(self)->QObject:
''' Returns the dialog used to tell the user that generating a model may take a long time '''
return self._createDialog('WaitDialog.qml')
@cached_property
def _openScadInterface(self)->OpenScadInterface:
''' Provides lazy instantiation of the OpenScad interface '''
return OpenScadInterface(self._pluginName, self._tempDir)
@cached_property
def _gcodeProcessedMarker(self)->str:
return f';{self._pluginName}: Post-processed by {self._pluginName} version {self.pluginVersion}'
@cached_property
def _pluginName(self)->str:
''' Just a useless wrapper around getPluginId '''
return self.getPluginId()
autoTowerGeneratedChanged = pyqtSignal()
@pyqtProperty(bool, notify=autoTowerGeneratedChanged)
def autoTowerGenerated(self)->bool:
''' Used to show or hide the button for removing the generated Auto Tower '''
return not self._autoTowerOperation is None
@pyqtProperty(str)
def pluginVersion(self)->str:
''' Returns the plugin's version number '''
return self.getVersion()
_openScadPathSettingChanged = pyqtSignal()
def setOpenScadPathSetting(self, value)->None:
self._pluginSettings.SetValue('openscad path', value)
self._openScadInterface.SetOpenScadPath(value)
# Warn the user if the OpenScad path is not valid
if not self._openScadInterface.OpenScadPathValid:
message = f'{catalog.i18nc("@msg", "The OpenScad path")} "{self._openScadInterface.OpenScadPath}" {catalog.i18nc("@msg", "is not valid")}'
Message(message, title=self._pluginName, message_type=Message.MessageType.ERROR).show()
# Notify the user of the detected OpenScad version number and path
else:
message = f'{catalog.i18nc("@msg", "Found OpenScad version")} {self._openScadInterface.OpenScadVersion} {catalog.i18nc("@msg", "at")} {self._openScadInterface.OpenScadPath}'
Message(message, title=self._pluginName, message_type=Message.MessageType.POSITIVE, lifetime=8).show()
self._openScadPathSettingChanged.emit()
@pyqtProperty(str, notify=_openScadPathSettingChanged, fset=setOpenScadPathSetting)
def openScadPathSetting(self)->str:
# If the OpenSCAD path has not been set, use the default from the OpenSCAD interface
value = self._pluginSettings.GetValue('openscad path')
if value == '':
# Update the OpenScad path from the OpenScad interface
value = self._openScadInterface.OpenScadPath
return value
_correctPrintSettings = True
_correctPrintSettingsChanged = pyqtSignal()
def setCorrectPrintSettings(self, value:bool)->None:
self._pluginSettings.SetValue('correct print settings', value)
self._correctPrintSettingsChanged.emit()
@pyqtProperty(bool, notify=_correctPrintSettingsChanged, fset=setCorrectPrintSettings)
def correctPrintSettings(self)->bool:
return self._pluginSettings.GetValue('correct print settings', True)
_enableLcdMessagesSetting = True
_enableLcdMessagesSettingChanged = pyqtSignal()
def setEnableLcdMessagesSetting(self, value:bool)->None:
self._pluginSettings.SetValue('enable lcd messages', value)
self._enableLcdMessagesSettingChanged.emit()
@pyqtProperty(bool, notify=_enableLcdMessagesSettingChanged, fset=setEnableLcdMessagesSetting)
def enableLcdMessagesSetting(self)->bool:
return self._pluginSettings.GetValue('enable lcd messages', False)
_enableAdvancedGcodeCommentsSetting = True
_enableAdvancedGcodeCommentsSettingChanged = pyqtSignal()
def setAdvancedGcodeCommentsSetting(self, value:bool)->None:
self._pluginSettings.SetValue('advanced gcode comments', value)
self._enableAdvancedGcodeCommentsSettingChanged.emit()
@pyqtProperty(bool, notify=_enableAdvancedGcodeCommentsSettingChanged, fset=setAdvancedGcodeCommentsSetting)
def enableAdvancedGcodeCommentsSetting(self)->bool:
return self._pluginSettings.GetValue('advanced gcode comments', True)
_enableDescriptiveFileNamesSetting = True
_enableDescriptiveFileNamesSettingChanged = pyqtSignal()
def setEnableDescriptiveFileNamesSetting(self, value:bool)->None:
self._pluginSettings.SetValue('descriptive file names', value)
self._enableDescriptiveFileNamesSettingChanged.emit()
@pyqtProperty(bool, notify=_enableDescriptiveFileNamesSettingChanged, fset=setEnableDescriptiveFileNamesSetting)
def enableDescriptiveFileNamesSetting(self)->bool:
return self._pluginSettings.GetValue('descriptive file names', True)
@pyqtSlot()
def removeButtonClicked(self)->None:
''' Called when the remove button is clicked to remove the generated Auto Tower from the scene'''
# Remove the tower
self._removeAutoTower()
_cachedControllerTable = {}
def _retrieveTowerController(self, ControllerClass):
''' Provides lazy instantiation of the tower controllers '''
if not ControllerClass in self._cachedControllerTable:
self._cachedControllerTable[ControllerClass] = ControllerClass(guiDir=self._qmlDir, stlDir=self._stlDir, loadStlCallback=self._loadStlCallback, generateStlCallback=self._generateStlCallback, pluginName=self._pluginName)
return self._cachedControllerTable[ControllerClass]
def _initializeMenu(self)->None:
# Add a menu for this plugin
self.setMenuName(catalog.i18nc("@menu", "Auto Towers"))
# Add menu entries for each tower controller
for controllerClass in self._controllerClasses:
controller = self._retrieveTowerController(controllerClass)
self.addMenuItem(controller.name, lambda controllerClass=controllerClass: self._generateAutoTower(controllerClass))
# Add a menu item for modifying plugin settings
self.addMenuItem(' ', lambda: None)
self.addMenuItem(catalog.i18nc("@menu", "Settings"), lambda: self._displayPluginSettingsDialog())
def _generateAutoTower(self, controllerClass):
''' Tell the current tower controller to generate a tower '''
# Generate the auto tower
currentTowerController = self._retrieveTowerController(controllerClass)
currentTowerController.generate(customizable=self._openScadInterface.OpenScadPathValid)
def _removeAutoTower(self, message = None)->None:
''' Removes the generated Auto Tower and post-processing callbacks '''
# Stop listening for callbacks
self._towerControllerPostProcessingCallback = None
Application.getInstance().getOutputDeviceManager().writeStarted.disconnect(self._postProcessCallback)
# BAK: 25 Nov 2022 - Removing these callbacks for now, because they're catching changes they shouldn't and removing towers inappropriately
# CuraApplication.getInstance().getMachineManager().activeMachine.propertyChanged.disconnect(self._onPrintSettingChanged)
# ExtruderManager.getInstance().getActiveExtruderStack().propertiesChanged.disconnect(self._onExtruderPrintSettingChanged)
CuraApplication.getInstance().getController().getScene().getRoot().childrenChanged.disconnect(self._onSceneChanged)
try:
CuraApplication.getInstance().getMachineManager().globalContainerChanged.disconnect(self._onMachineChanged)
except TypeError as e:
# This exception is expected during Cura shutdown
pass
# Remove the Auto Tower itself
if not self._autoTowerOperation is None:
self._autoTowerOperation.undo()
self._autoTowerOperation = None
CuraApplication.getInstance().deleteAll()
# Clear the job name
CuraApplication.getInstance().getPrintInformation().setJobName('')
# Indicate that there is no longer an Auto Tower in the scene
self.autoTowerGeneratedChanged.emit()
# Clean up after the AutoTower
if not self._currentTowerController is None:
restoredSettings = self._currentTowerController.cleanup()
if len(restoredSettings) > 0:
message = message + '\n' if not message is None else ''
message += catalog.i18nc("@msg", "The following settings were restored :\n")
message += '\n'.join([f'{catalog.i18nc("@msg", "Restored")} {entry[0]} {catalog.i18nc("@msg", "to")} {entry[1]}' for entry in restoredSettings])
if message is not None:
Message(message, title=self._pluginName, lifetime=8).show()
self._currentTowerController = None
CuraApplication.getInstance().processEvents()
def _createDialog(self, qml_filename)->QObject:
''' Creates a dialog object from a QML file name
The QML file is assumed to be in the GUI directory
Returns a dialog object, with this object assigned as the "manager" '''
qml_file_path = os.path.join(self._qmlDir, qml_filename)
dialog = Application.getInstance().createQmlComponent(qml_file_path, {'manager': self})
return dialog
def _displayRemoveAutoTowerButton(self)->None:
''' Adds a button to Cura's window to remove the Auto Tower '''
CuraApplication.getInstance().addAdditionalComponent('saveButton', self._removeAutoTowerButton)
def _displayPluginSettingsDialog(self)->None:
''' Prepares and displays the plugin settings dialog '''
self._pluginSettingsDialog.show()
def _loadStlCallback(self, controller, towerName, stlFilePath, postProcessingCallback)->None:
''' This callback is called by the tower model controller if a preset tower is requested '''
# If the file does not exist, display an error message
if os.path.isfile(stlFilePath) == False:
errorMessage = f'{catalog.i18nc("@msg", "The STL file")} "{stlFilePath}" {catalog.i18nc("@msg", "does not exist")}'
Logger.log('e', errorMessage)
Message(errorMessage, title = self._pluginName, message_type=Message.MessageType.ERROR).show()
return
# Import the STL file into the scene
self._importStl(controller, towerName, stlFilePath, postProcessingCallback)
def _generateStlCallback(self, controller, towerName, openScadFilename, openScadParameters, postProcessingCallback)->None:
''' This callback is called by the tower model controller after a tower has been configured to generate an STL model from an OpenSCAD file '''
# This could take up to a couple of minutes...
self._waitDialog.show()
CuraApplication.getInstance().processEvents() # Allow Cura to update itself periodically through this method
# Compile the STL file name
openScadFilePath = os.path.join(self._openScadSourcePath, openScadFilename)
stlFilename = 'custom_autotower.stl'
stlFilePath = os.path.join(self._tempDir, stlFilename)
# Generate the STL file
# Since it can take a while to generate the STL file, this is done in a separate thread to allow the GUI to remain responsive
job = OpenScadJob(self._openScadInterface, openScadFilePath, openScadParameters, stlFilePath)
job.run()
# Wait for OpenSCAD to finish
# This should probably be done by having a function called when the job finishes...
while (job.isRunning()):
pass
# Make sure the STL file was generated
if os.path.isfile(stlFilePath) == False:
errorMessage = f'{catalog.i18nc("@msg", "Failed to generate")} "{stlFilePath}" {catalog.i18nc("@msg", "from")} "{openScadFilename}"\n{catalog.i18nc("@msg", "Command output was")}\n"{self._openScadInterface.commandResult}"'
Message(errorMessage, title = self._pluginName, message_type=Message.MessageType.ERROR).show()
Logger.log('e', errorMessage)
self._waitDialog.hide()
return
# Import the STL file into the scene
self._importStl(controller, towerName, stlFilePath, postProcessingCallback)
def _importStl(self, controller, towerName, stlFilePath, postProcessingCallback)->None:
''' Imports an STL file into the scene '''
# Make sure any previous auto towers are removed
self._removeAutoTower()
# Allow the tower controller to update Cura's settings to ensure it can be generated correctly
recommendedSettings = controller.checkPrintSettings(self.correctPrintSettings)
if len(recommendedSettings) > 0:
message = '\n'.join([f'{catalog.i18nc("@msg", "Changed")} {entry[0]} {catalog.i18nc("@msg", "from")} {entry[1]} {catalog.i18nc("@msg", "to")} {entry[2]}' for entry in recommendedSettings])
if self.correctPrintSettings:
message = catalog.i18nc("@msg", "The following settings were changed :\n") + message
Message(message, title=self._pluginName, lifetime=8).show()
else:
message = catalog.i18nc("@msg", "The following setting changes are recommended :\n") + message
Message(message, title=self._pluginName, message_type=Message.MessageType.WARNING, lifetime=8).show()
# Record the new tower controller
self._currentTowerController = controller
# Import the STL file into the scene
self._autoTowerOperation = MeshImporter.ImportMesh(stlFilePath, name=self._pluginName)
CuraApplication.getInstance().processEvents()
# The dialog is no longer needed
self._waitDialog.hide()
# Some printers cannot handle long, descriptive file names
# If descriptive file names have been disabled, truncate the tower name
# Google suggests 20 characters to be a safe limit
# Ideally, truncation should happen when the tower name is first
# generated by the tower controller, but that involves a lot of changes
# This is lazy but effective
if self.enableDescriptiveFileNamesSetting == False:
towerName = towerName.replace('Preset ', '')
towerName = towerName.replace('Custom', '')
towerName = towerName.replace('Tower', '')
towerName = towerName.replace('Bed Level Pattern', 'LVL')
towerName = towerName.replace('Distance', 'DST')
towerName = towerName.replace('Flow', 'FLW')
towerName = towerName.replace('Retraction', 'RT')
towerName = towerName.replace('Speed', 'SPD')
towerName = towerName.replace('Temp', 'TMP')
towerName = towerName.replace(' ', '')
towerName = towerName[:20]
# Rename the print job
CuraApplication.getInstance().getPrintInformation().setJobName(towerName)
# Register that the Auto Tower has been generated
self.autoTowerGeneratedChanged.emit()
# Register the post-processing callback for this particular tower
Application.getInstance().getOutputDeviceManager().writeStarted.connect(self._postProcessCallback)
self._towerControllerPostProcessingCallback = postProcessingCallback
# Remove the model if the machine is changed
CuraApplication.getInstance().getMachineManager().globalContainerChanged.connect(self._onMachineChanged)
# BAK: 25 Nov 2022 - Removing the following callbacks for now, because they're catching changes they shouldn't and removing towers inappropriately
# # Remove the tower and post-processing if critical print settings (settings that are important for the AutoTower) are changed
# CuraApplication.getInstance().getMachineManager().activeMachine.propertyChanged.connect(self._onPrintSettingChanged)
# # Remove the tower and post-processing if critical print settings (settings that are important for the AutoTower) are changed
# ExtruderManager.getInstance().getActiveExtruderStack().propertiesChanged.connect(self._onExtruderPrintSettingChanged)
# Remove the tower and post-processing if the model is deleted or another model is added to the scene
CuraApplication.getInstance().getController().getScene().getRoot().childrenChanged.connect(self._onSceneChanged)
def _onMachineChanged(self)->None:
''' Listen for machine changes made after an Auto Tower is generated
In this case, the Auto Tower needs to be removed and regenerated '''
self._removeAutoTower(catalog.i18nc("@msg", "The Auto Tower was removed because the active machine was changed"))
def _onPrintSettingChanged(self, settingKey, propertyName)->None:
''' Listen for setting changes made after an Auto Tower is generated '''
# Remove the tower in response to changes to critical print settings
if not self._currentTowerController is None:
if self._currentTowerController.settingIsCritical(settingKey):
settingLabel = CuraApplication.getInstance().getMachineManager().activeMachine.getProperty(settingKey, 'label')
self._removeAutoTower(f'{catalog.i18nc("@msg", "The Auto Tower was removed because the Cura setting")} "{settingLabel}" {catalog.i18nc("@msg", "has changed since the tower was generated")}')
def _onExtruderPrintSettingChanged(self, settingKey, propertyName)->None:
''' Listen for changes to the active extruder print settings '''
# Remove the tower in response to changes to critical print settings
if not self._currentTowerController is None:
if self._currentTowerController.settingIsCritical(settingKey):
settingLabel = ExtruderManager.getInstance().getActiveExtruderStack().getProperty(settingKey, 'label')
self._removeAutoTower(f'The Auto Tower was removed because the Cura setting "{settingLabel}" has changed since the tower was generated')
def _onPluginsLoadedCallback(self)->None:
''' Called after plugins have been loaded
Iniializing here means that Cura is fully ready '''
self._pluginSettings = PluginSettings(self._pluginSettingsFilePath)
# Init openscad path
self._openScadInterface.SetOpenScadPath(self._pluginSettings.GetValue('openscad path'))
# Make sure the temp directory exists
if not os.path.exists(self._tempDir):
os.makedirs(self._tempDir)
self._initializeMenu()
def _onSceneChanged(self, node)->None:
# Only process root node change
if node.getName() == 'Root':
# If the AutoTower node no longer exists, then clean up
AutoTowerNodes = [child for child in node.getChildren() if child.getName() == self._pluginName]
if len(AutoTowerNodes) <= 0:
self._removeAutoTower()
def _onExitCallback(self)->None:
''' Called as Cura is closing to ensure that any settings that were changed are restored before exiting '''
# Remove the tower
self._removeAutoTower(catalog.i18nc("@msg", "Removing the autotower because Cura is closing"))
# Save the plugin settings
try:
self._pluginSettings.SaveToFile(self._pluginSettingsFilePath)
except AttributeError:
pass
# Clear the temp directory
for file in glob.glob(os.path.join(self._tempDir, '*')):
os.remove(file)
CuraApplication.getInstance().triggerNextExitCheck()
def _postProcessCallback(self, output_device)->None:
''' This callback is called just before gcode is generated for the model
(this happens when the sliced model is sent to the printer or a file '''
# Retrieve the g-code
scene = Application.getInstance().getController().getScene()
try:
# Proceed if the g-code is valid
gcode_dict = getattr(scene, 'gcode_dict')
except AttributeError:
# If there is no g-code, there's nothing more to do
return
try:
# Retrieve the g-code for the current build plate
active_build_plate_id = CuraApplication.getInstance().getMultiBuildPlateModel().activeBuildPlate
gcode = gcode_dict[active_build_plate_id]
except (TypeError, KeyError):
# If there is no g-code for the current build plate, there's nothing more to do
return
try:
# Proceed if the g-code has not already been post-processed
if self._gcodeProcessedMarker not in gcode[0]:
# Mark the g-code as having been post-processed
gcode[0] += self._gcodeProcessedMarker + '\n'
# Call the tower controller post-processing callback to modify the g-code
try:
gcode = self._towerControllerPostProcessingCallback(gcode, self.enableLcdMessagesSetting, self.enableAdvancedGcodeCommentsSetting)
except Exception as e:
message = f'{catalog.i18nc("@msg", "An exception occured during post-processing")} : {e}'
Message(f'{message}', title=self._pluginName, message_type=Message.MessageType.ERROR).show()
Logger.log('e', f'{message}\n{traceback.format_exc()}')
except IndexError:
# This will be thrown if there is no gcode available
pass