-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathColorAlterator.FCMacro
389 lines (307 loc) · 15.1 KB
/
ColorAlterator.FCMacro
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
__Name__ = 'Color Alterator'
__Comment__ = 'Parses the user config for colors and presents them in a grid'
__Author__ = 'Axeia'
__Version__ = '3'
__Date__ = '2023-09-25'
__License__ = 'CC0-1.0'
__Web__ = ''
__Wiki__ = ''
__Icon__ = 'https://svgshare.com/i/wZ8.svg'
__Help__ = ''
__Status__ = 'Beta'
__Requires__ = 'FreeCAD >= v0.19'
__Communication__ = 'https://forum.freecad.org/memberlist.php?mode=viewprofile&u=54199'
__Files__ = ''
import os
from PySide2.QtWidgets import QColorDialog, QTreeWidget, QTreeWidgetItem, QDialog, QHeaderView, QStyledItemDelegate, QApplication, QGridLayout, QPushButton, QMenu, QAction, QWidgetAction, QLabel, QWidget, QHBoxLayout
from PySide2.QtGui import QCursor, QCloseEvent, QFont, QBrush, QColor, QPixmap, QIcon
from PySide2.QtCore import QDir, QFile, QTimer, QIODevice, QSize, QSettings
from PySide2.QtCore import Qt
from FreeCAD import Console, ParamGet
from PySide2.QtXml import QDomDocument, QDomNodeList, QDomElement
from PySide2.QtXml import QDomDocument, QDomNode
from typing import Dict
import FreeCADGui
import FreeCAD
settings = QSettings('FreeCAD', 'ColorAlterator')
class TreeItemWithColorDomElement(QTreeWidgetItem):
def __init__(self, parent: QTreeWidget, sequence: [], domElement: QDomElement):
super().__init__(parent, sequence)
self.domElement = domElement
monospaceFont = QFont("Courier New")
self.setFont(1, monospaceFont)
self.setFont(3, monospaceFont)
class ColorConfigTree(QTreeWidget):
COLORCOLINDEX = 2
def __init__(self) -> None:
super().__init__()
self.setItemDelegateForColumn(2, CustomDelegate(self))
self.setHeaderLabels(["Path", "Value", "Color", "Hex Color"])
self.hideColumn(4)
self.header().setSectionResizeMode(0, QHeaderView.Stretch)
self.header().setSectionResizeMode(1, QHeaderView.Fixed)
self.header().setSectionResizeMode(2, QHeaderView.Fixed)
self.header().setSectionResizeMode(3, QHeaderView.Fixed)
self.header().setStretchLastSection(False)
self.resizeColumnToContents(0)
self.resizeColumnToContents(1)
self.setColumnWidth(1, 100)
self.setColumnWidth(2, 50)
self.setColumnWidth(3, 80)
self.setMouseTracking(True)
def actuallyRestoreCursor(self):
while QApplication.overrideCursor() is not None:
QApplication.restoreOverrideCursor()
def mouseMoveEvent(self, event):
index = self.indexAt(event.pos())
if index.column() == self.COLORCOLINDEX:
QApplication.setOverrideCursor(Qt.PointingHandCursor)
elif event.pos().y() < self.header().height() \
or event.pos().y() > self.visualItemRect(self.topLevelItem(self.topLevelItemCount() - 1)).bottom():
self.actuallyRestoreCursor()
elif index.isValid():
self.actuallyRestoreCursor()
super().mouseMoveEvent(event)
def leaveEvent(self, event):
self.actuallyRestoreCursor()
super().leaveEvent(event)
class CustomDelegate(QStyledItemDelegate):
def __init__(self, parent=None):
super().__init__(parent)
def paint(self, painter, option, index):
# Check if the current column is column 2
if index.column() == 2:
# Get the background color for column 2
background_brush = index.data(Qt.BackgroundRole)
if background_brush is not None:
# Use the background color for column 2
painter.fillRect(option.rect, background_brush)
else:
# If no background color is set, use the default styling
super().paint(painter, option, index)
else:
# For other columns, use the default styling
super().paint(painter, option, index)
def initStyleOption(self, option, index):
# Call the base class implementation
super().initStyleOption(option, index)
# Check if the current column is column 2
if index.column() == 2:
# Set the cursor shape to the pointing hand
option.cursor = QCursor(Qt.PointingHandCursor)
# opens the preferences dialog and then closes it by accepting it.
# This forces FreeCAD to save the settings to user.cfg so that next time the
# macro opens up it actually loads the saved values
def openAndAcceptPreferencesDialog():
if not openAndAcceptPreferencesDialog.triggered:
openAndAcceptPreferencesDialog.triggered = True
def acceptPreferences():
for widget in QApplication.allWidgets():
if isinstance(widget, QDialog):
dialog: QDialog = widget
dialog.accept()
timer = QTimer(singleShot=True)
timer.timeout.connect(acceptPreferences)
timer.setInterval(200)
timer.start()
FreeCADGui.runCommand('Std_DlgPreferences', 0)
openAndAcceptPreferencesDialog.triggered = False
class ColorFetcherDialog(QDialog):
def __init__(self):
super().__init__()
self.tree = None
self.setWindowFlags(Qt.WindowCloseButtonHint)
self.setWindowTitle(__Name__)
self.resize(800, 800)
self.setUpUi()
self.aColorHasChanged = False
self.markTheRightTreeBgAction()
def closeEvent(self, event: QCloseEvent):
if self.aColorHasChanged:
openAndAcceptPreferencesDialog()
def setUpUi(self):
self.gridLayoutMain = QGridLayout(self)
self.addTreeBackgroundColorButton()
strFolder = FreeCAD.getUserAppDataDir()
if hasattr(FreeCAD, 'getUserConfigDir'):
strFolder = FreeCAD.getUserConfigDir()
folder = QDir(strFolder)
userCfgPath = folder.filePath('user.cfg')
domDoc = QDomDocument('user-config')
self.userConfigFile = QFile(userCfgPath)
if self.userConfigFile.open(QIODevice.ReadOnly | QIODevice.Text):
content = self.userConfigFile.readAll().data().decode()
if domDoc.setContent(content):
Console.PrintMessage(
f"Loaded QDomDocument with content from: {userCfgPath}")
else:
Console.PrintMessage("Failed to set QDomDocument content")
else:
Console.PrintMessage("Failed to open user config file for reading")
self.tree = self.createTree(domDoc)
self.gridLayoutMain.setColumnStretch(0, 1)
self.gridLayoutMain.setColumnStretch(1, 0)
def addTreeBackgroundColorButton(self):
self.treeBgColorButton = QPushButton('Set tree background color', self)
self.gridLayoutMain.addWidget(self.treeBgColorButton, 0, 1, 1, 1)
self.treeBackgroundColorMenu = QMenu('Tree background options', self.treeBgColorButton)
self.actionDefault = QAction('Default (from theme)', self.treeBackgroundColorMenu)
self.actionDefault.setCheckable(True)
self.actionDefault.triggered.connect(self.defaultTreeBgClicked)
self.treeBackgroundColorMenu.addAction(self.actionDefault)
self.actionCustom = QAction('Custom', self.treeBackgroundColorMenu)
self.actionCustom.setCheckable(True)
self.actionCustom.triggered.connect(self.customTreeBgClicked)
self.treeBackgroundColorMenu.addAction(self.actionCustom)
self.treeBackgroundColorMenu.setCursor(Qt.PointingHandCursor)
self.markTheRightTreeBgAction()
self.menuWidth = self.treeBackgroundColorMenu.sizeHint().width()
# Create a custom widget to hold the pixmap
pixmapWidget = QWidget(self.treeBackgroundColorMenu)
pixmapWidget.setFixedHeight(32)
pixmapWidget.setFixedWidth(self.menuWidth)
# Create a layout for the custom widget
pixmapLayout = QHBoxLayout(pixmapWidget)
pixmapLayout.setContentsMargins(0, 0, 0, 0)
pixmapLayout.setAlignment(Qt.AlignCenter)
# Create the pixmap and add it to the custom widget
self.pm = QPixmap(self.menuWidth, 32) # Set the width of the pixmap to the width of the menu
self.pm.fill(QColor(settings.value('tree_background_color', '#FF00FF')))
self.pixmapLabel = QLabel(pixmapWidget)
self.pixmapLabel.setPixmap(self.pm)
pixmapLayout.addWidget(self.pixmapLabel)
# Create a QWidgetAction with the custom widget
pixmapAction = QWidgetAction(self.treeBackgroundColorMenu)
pixmapAction.setDefaultWidget(pixmapWidget)
pixmapAction.triggered.connect(self.setTreeBackgroundColor)
# Add the pixmap action to the menu
self.treeBackgroundColorMenu.addAction(pixmapAction)
self.treeBgColorButton.setMenu(self.treeBackgroundColorMenu)
def setTreeBackgroundColor(self):
color = settings.value('tree_background_color', '#FF00FF', str)
colorDialog = QColorDialog(color)
result = colorDialog.exec()
if result == QDialog.Accepted and colorDialog.currentColor() != color:
newColor = colorDialog.currentColor()
newColorHexStr = newColor.name()
settings.setValue('tree_background_color', newColorHexStr)
# Repaint the pixmap with the new color
self.pm.fill(newColor)
self.pixmapLabel.setPixmap(self.pm)
self.setTreeBackgroundStylesheet(newColorHexStr)
def setTreeBackgroundStylesheet(self, color: str):
if self.actionCustom.isChecked():
# Create a QColor object from the background color
bgColor = QColor(color)
# Calculate the brightness of the background color
brightness = bgColor.lightness()
# Choose black or white based on the brightness
textColor = '#000000' if brightness > 127 else '#FFFFFF'
self.tree.setStyleSheet(
f'QTreeWidget{{ background-color: {color}; color: {textColor}; }}')
else:
self.tree.setStyleSheet(f'')
def defaultTreeBgClicked(self):
settings.setValue('tree_use_default_background', self.actionDefault.isChecked())
self.markTheRightTreeBgAction()
def customTreeBgClicked(self):
settings.setValue('tree_use_default_background', not self.actionCustom.isChecked())
self.markTheRightTreeBgAction()
def markTheRightTreeBgAction(self):
useDefault = settings.value('tree_use_default_background', True, bool)
self.actionDefault.setChecked(useDefault)
self.actionCustom.setChecked(not useDefault)
if self.tree:
self.setTreeBackgroundStylesheet(settings.value('tree_background_color', '#FF00FF'))
def ColorIsTranslucent(self, color: QColor):
return color.alpha() < 255
def createTree(self, domDoc: QDomDocument) -> QTreeWidget:
tree = ColorConfigTree()
self.gridLayoutMain.addWidget(tree, 1, 0, 1, 2)
root = domDoc.documentElement()
mapped = self.findValuesWithColors(root, '')
for path, varNameAndElement in mapped.items():
topItem = QTreeWidgetItem(tree, [path])
topItem.setFirstColumnSpanned(True)
for varName, element in varNameAndElement.items():
qColor = self.decimalToQColor(int(element.attribute('Value')))
hexColor = qColor.name()
if self.ColorIsTranslucent(qColor):
hexColor = qColor.name(QColor.HexArgb)
childItem = TreeItemWithColorDomElement(
topItem,
[varName, element.attribute('Value'), "", hexColor],
element
)
childItem.setBackground(2, QBrush(qColor))
childItem.setSizeHint(2, QSize(20, 50))
childItem.setFlags(
childItem.flags() |
Qt.ItemIsSelectable |
Qt.ItemIsEditable
)
tree.itemPressed.connect(self.onPressedTreeColor)
tree.expandAll() # Expand all tree items
return tree
def decimalToQColor(self, argb: str) -> QColor:
rgbaHex = format(int(argb), '08x')
r, g, b, a = rgbaHex[:2], rgbaHex[2:4], rgbaHex[4:6], rgbaHex[6:8]
return QColor(int(r, 16), int(g, 16), int(b, 16), int(a, 16))
def qColorToDecimal(self, color: QColor) -> int:
red = color.red()
green = color.green()
blue = color.blue()
alpha = color.alpha()
# Convert each color component to a 2-digit hexadecimal string
red_hex = format(red, '02x')
green_hex = format(green, '02x')
blue_hex = format(blue, '02x')
alpha_hex = format(alpha, '02x')
# Concatenate the hexadecimal strings and convert to an integer
decimal_value = int(red_hex + green_hex + blue_hex + alpha_hex, 16)
return decimal_value
def findValuesWithColors(self, node: QDomNode, currentPath: str, mapping=None) -> Dict[str, Dict[str, QDomElement]]:
if mapping is None:
mapping = {}
if node.isElement():
element = node.toElement()
if element.tagName() == "FCUInt"\
and element.hasAttribute("Value")\
and element.attribute("Value").isnumeric()\
and "Color" in element.attribute("Name"):
colorValue = element.attribute("Value")
if len(colorValue) > 0 and colorValue.isdigit():
if currentPath not in mapping:
mapping[currentPath] = {}
mapping[currentPath][element.attribute('Name')] = element
currentPath += "/" + element.attribute("Name")
childNodes: QDomNodeList = node.childNodes()
for i in range(childNodes.size()):
childNode: QDomNode = childNodes.at(i)
self.findValuesWithColors(childNode, currentPath, mapping)
return mapping
def onPressedTreeColor(self, it: TreeItemWithColorDomElement, col: int):
isColorColumn = col == 2
if isColorColumn:
modifiers = QApplication.keyboardModifiers()
ctrlAndShiftPressed = modifiers & Qt.ControlModifier and modifiers & Qt.ShiftModifier
color = it.backgroundColor(2)
colorDialog = QColorDialog(color)
showAlpha = self.ColorIsTranslucent(color) or ctrlAndShiftPressed
colorDialog.setOption(QColorDialog.ShowAlphaChannel, showAlpha)
result = colorDialog.exec()
if result == QDialog.Accepted \
and colorDialog.currentColor() != color:
newColor = colorDialog.currentColor()
newColorDecimal = self.qColorToDecimal(newColor)
parent: QTreeWidgetItem = it.parent()
paramPathMinusRoot = parent.text(0)[7:] # strips off '//root/'
parameterGrp = ParamGet(f'User parameter:{paramPathMinusRoot}')
parameterGrp.SetUnsigned(it.text(0), newColorDecimal)
it.setText(3, newColor.name())
it.setBackgroundColor(2, newColor)
it.setText(1, str(newColorDecimal))
self.aColorHasChanged = True
# Create and show the dialog
dialog = ColorFetcherDialog()
dialog.show()