Krita Source Code Documentation
Loading...
Searching...
No Matches
quick_settings_docker.py
Go to the documentation of this file.
1# By Wolthera(originally)
2
3# SPDX-License-Identifier: CC0-1.0
4
5'''A Python based docker for quickly choosing the brushsize like
6similar dockers in other drawing programs.
7
8@package quick_settings_docker
9
10'''
11
12# Importing the relevant dependencies:
13try:
14 from PyQt6.QtCore import pyqtSlot, Qt, QPointF
15 from PyQt6.QtGui import (QStandardItem, QStandardItemModel, QPainter, QPalette,
16 QPixmap, QImage, QBrush, QPen, QIcon)
17 from PyQt6.QtWidgets import (
18 QWidget, QTabWidget, QListView, QVBoxLayout,
19 QInputDialog, QMenu, QMessageBox
20 )
21except:
22 from PyQt5.QtCore import pyqtSlot, Qt, QPointF
23 from PyQt5.QtGui import (QStandardItem, QStandardItemModel, QPainter, QPalette,
24 QPixmap, QImage, QBrush, QPen, QIcon)
25 from PyQt5.QtWidgets import (
26 QWidget, QTabWidget, QListView, QVBoxLayout,
27 QInputDialog, QMenu, QMessageBox
28 )
29from krita import DockWidget
30from builtins import i18n, Application
31
32
33class QuickSettingsDocker(DockWidget):
34 # Init the docker
35
36 def __init__(self):
37 super(QuickSettingsDocker, self).__init__()
38 # make base-widget and layout
39 widget = QWidget()
40 layout = QVBoxLayout()
41 widget.setLayout(layout)
42 self.setWindowTitle(i18n("Quick Settings Docker"))
43 tabWidget = QTabWidget()
44
45 self.brushSizeTableView = QListView()
46 self.brushSizeTableView.setViewMode(QListView.ViewMode.IconMode)
47 self.brushSizeTableView.setMovement(QListView.Movement.Static)
48 self.brushSizeTableView.setResizeMode(QListView.ResizeMode.Adjust)
49 self.brushSizeTableView.setUniformItemSizes(True)
50 self.brushSizeTableView.setSelectionMode(QListView.SelectionMode.SingleSelection)
51
52 self.brushOpacityTableView = QListView()
53 self.brushOpacityTableView.setViewMode(QListView.ViewMode.IconMode)
54 self.brushOpacityTableView.setMovement(QListView.Movement.Static)
55 self.brushOpacityTableView.setResizeMode(QListView.ResizeMode.Adjust)
56 self.brushOpacityTableView.setUniformItemSizes(True)
57 self.brushOpacityTableView.setSelectionMode(QListView.SelectionMode.SingleSelection)
58
59 self.brushFlowTableView = QListView()
60 self.brushFlowTableView.setViewMode(QListView.ViewMode.IconMode)
61 self.brushFlowTableView.setMovement(QListView.Movement.Static)
62 self.brushFlowTableView.setResizeMode(QListView.ResizeMode.Adjust)
63 self.brushFlowTableView.setUniformItemSizes(True)
64 self.brushFlowTableView.setSelectionMode(QListView.SelectionMode.SingleSelection)
65
66 tabWidget.addTab(self.brushSizeTableView, i18n("Size"))
67 tabWidget.addTab(self.brushOpacityTableView, i18n("Opacity"))
68 tabWidget.addTab(self.brushFlowTableView, i18n("Flow"))
69
70 # Tab index variables
71 self.sizeTabIndex = 0
73 self.flowTabIndex = 2
74 # keep track of the selected tab
76 tabWidget.currentChanged.connect(self.onTabChangedonTabChanged)
77
78 layout.addWidget(tabWidget)
79 self.setWidget(widget) # Add the widget to the docker.
80
81 # amount of columns in each row for all the tables.
82
83 # We want a grid with possible options to select. To do this,
84 # we'll make a ListView widget and use a standarditemmodel for
85 # the entries. The entries are filled out based on the sizes
86 # and opacity lists.
87
88 # Sizes,opacity and flow lists. The former is half-way copied from
89 # ptsai, the latter is based on personal experience of useful
90 # opacities.
91 sizes = self.getPresetsFor("size")
92 opacity = self.getPresetsFor("opacity")
93 flow = self.getPresetsFor("flow")
94 # initialize the lists to the previously saved values else use the hardcoded lists
95 self.sizesList = sizes if sizes else [
96 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16,
97 20, 25, 30, 35, 40, 50, 60, 70, 80, 100, 120, 160, 200, 250, 300,
98 350, 400, 450, 500]
99 self.opacityList = opacity if opacity else [
100 1, 5, 10, 15, 20, 30, 40, 50, 60, 70, 80, 90, 100]
101 self.flowList = flow if flow else [
102 20, 25, 33, 50, 66, 75, 80, 90, 100]
103 self.brushSizeModel = QStandardItemModel()
104 self.brushOpacityModel = QStandardItemModel()
105 self.brushFlowModel = QStandardItemModel()
106 self.fillSizesModel()
107 self.fillOpacityModel()
108 self.fillFlowModel()
109
110 # Now we're done filling out our tables, we connect the views
111 # to the functions that'll change the settings.
115
116 # Enable right-click context menus
117 try:
118 contextMenuPolicy = Qt.ContextMenuPolicy.CustomContextMenu
119 except AttributeError:
120 contextMenuPolicy = Qt.CustomContextMenu
121
122 for tableView in (self.brushSizeTableView, self.brushOpacityTableView,
123 self.brushFlowTableView):
124
125 tableView.setContextMenuPolicy(contextMenuPolicy)
126 tableView.customContextMenuRequested.connect(
127 lambda pos, view=tableView:
128 self.handlePresetContextMenu(view, pos)
129 )
130
131 def handlePresetContextMenu(self, tableView, pos):
132 index = tableView.indexAt(pos)
133 # Determine which tab/list was right-clicked
134 if tableView == self.brushSizeTableView:
135 self.currentTabIndex = self.sizeTabIndex
136
137 elif tableView == self.brushOpacityTableView:
139
140 else:
141 self.currentTabIndex = self.flowTabIndex
142
143 # Create context menu
144 menu = QMenu(self)
145 addAction = menu.addAction(i18n("Add Preset"))
146 deleteAction = None
147 # Only allow deletion when clicking an existing preset
148 if index.isValid():
149 deleteAction = menu.addAction(i18n("Delete Preset"))
150
151 # Display menu at cursor position
152 globalPos = tableView.viewport().mapToGlobal(pos)
153 try:
154 action = menu.exec(globalPos)
155 except AttributeError:
156 action = menu.exec_(globalPos)
157
158 # Handle selection
159 if action == addAction:
160 self.addPreset()
161 elif deleteAction is not None and action == deleteAction:
162 self.removePreset(index.row())
163
164 def fillSizesModel(self):
165 # First we empty the old model. We might wanna use this
166 # function in the future to fill it with the brushmask of the
167 # selected brush, but there's currently no API for recognising
168 # changes in the current brush nor is there a way to get its
169 # brushmask.
170 self.brushSizeModel.clear()
171 for s in range(len(self.sizesList)):
172 # we're gonna iterate over our list, and make a new item
173 # for each entry. We need to disable a bunch of stuff to
174 # make sure people won't do funny things to our entries.
175 item = QStandardItem()
176 item.setCheckable(False)
177 item.setEditable(False)
178 item.setDragEnabled(False)
179 item.setText(str(self.sizesList[s])+" px")
180 # And from here on we'll make an icon.
181 brushImage = QPixmap(64, 64)
182 img = QImage(64, 64, QImage.Format.Format_RGBA8888)
183 circlePainter = QPainter()
184 img.fill(Qt.GlobalColor.transparent)
185 circlePainter.begin(img)
186 brush = QBrush(Qt.BrushStyle.SolidPattern)
187 brush.setColor(
188 self.brushSizeTableView.palette().color(QPalette.ColorRole.Text))
189 circlePainter.setBrush(brush)
190 circlePainter.setPen(QPen(QBrush(Qt.GlobalColor.transparent), 0))
191 brushSize = max(min(self.sizesList[s], 64), 1)
192 brushSize = brushSize * 0.5
193 circlePainter.drawEllipse(QPointF(32, 32), brushSize, brushSize)
194 circlePainter.end()
195 brushImage = QPixmap.fromImage(img)
196 # now we're done with drawing the icon, so we set it on the item.
197 item.setIcon(QIcon(brushImage))
198 self.brushSizeModel.appendRow(item)
199 self.brushSizeTableView.setModel(self.brushSizeModel)
200
202 self.brushOpacityModel.clear()
203 for s in range(len(self.opacityList)):
204 # we're gonna iterate over our list, and make a new item
205 # for each entry.
206 item = QStandardItem()
207 item.setCheckable(False)
208 item.setEditable(False)
209 item.setDragEnabled(False)
210 item.setText(str(self.opacityList[s])+" %")
211 brushImage = QPixmap(64, 64)
212 img = QImage(64, 64, QImage.Format.Format_RGBA8888)
213 circlePainter = QPainter()
214 img.fill(Qt.GlobalColor.transparent)
215 circlePainter.begin(img)
216 brush = QBrush(Qt.BrushStyle.SolidPattern)
217 brush.setColor(
218 self.brushSizeTableView.palette().color(QPalette.ColorRole.Text))
219 circlePainter.setBrush(brush)
220 circlePainter.setPen(QPen(QBrush(Qt.GlobalColor.transparent), 0))
221 circlePainter.setOpacity(float(self.opacityList[s]) / 100.0)
222 circlePainter.drawEllipse(QPointF(32, 32), 32, 32)
223 circlePainter.end()
224 brushImage = QPixmap.fromImage(img)
225 item.setIcon(QIcon(brushImage))
226 # now we are done with the icon for opacity, so we set it to the item.
227 self.brushOpacityModel.appendRow(item)
228 self.brushOpacityTableView.setModel(self.brushOpacityModel)
229
230 def fillFlowModel(self):
231 self.brushFlowModel.clear()
232 for s in range(len(self.flowList)):
233 # we're gonna iterate over our list, and make a new item
234 # for each entry.
235 item = QStandardItem()
236 item.setCheckable(False)
237 item.setEditable(False)
238 item.setDragEnabled(False)
239 item.setText(str(self.flowList[s]) + " %")
240 # Create icon canvas to create a different icon for flow using overlapping circles
241 brushImage = QPixmap(64, 64)
242 brushImage.fill(Qt.GlobalColor.transparent)
243 painter = QPainter(brushImage)
244 pen = QPen(self.brushFlowTableView.palette().color(QPalette.ColorRole.Text))
245 pen.setWidth(18)
246 pen.setCapStyle(Qt.PenCapStyle.RoundCap)
247 painter.setPen(pen)
248 # Non-linear mapping for visibility
249 flow_factor = self.flowList[s] / 100.0
250 # Strength of paint flow
251 strength = flow_factor ** 0.7
252 # Number of dabs
253 steps = 7
254 for i in range(steps):
255 # Adjust the opacity of each dab based on its number. This makes it so that the icon
256 # becomes a line which increases in opacity, which should give a good example of flow
257 painter.setOpacity(strength * ((i + 1) / steps))
258 # we draw the dabs close to each other to simulate a line
259 painter.drawPoint(12 + i * 6, 32)
260 # now we are done with the icon, so we set it to the item.
261 item.setIcon(QIcon(brushImage))
262 self.brushFlowModel.appendRow(item)
263 painter.end()
264 self.brushFlowTableView.setModel(self.brushFlowModel)
265
266 def canvasChanged(self, canvas):
267 pass
268
269 @pyqtSlot('QModelIndex')
270 def setBrushSize(self, index):
271 i = index.row()
272 brushSize = self.sizesList[i]
273 window = Application.activeWindow()
274 if window and window.views():
275 window.views()[0].setBrushSize(brushSize)
276
277 @pyqtSlot('QModelIndex')
278 def setBrushOpacity(self, index):
279 i = index.row()
280 brushOpacity = float(self.opacityList[i]) / 100.0
281 window = Application.activeWindow()
282 if window and window.views():
283 window.views()[0].setPaintingOpacity(brushOpacity)
284
285 @pyqtSlot('QModelIndex')
286 def setBrushFlow(self, index):
287 i = index.row()
288 brushFlow = float(self.flowList[i]) / 100.0
289 window = Application.activeWindow()
290 if window and window.views():
291 window.views()[0].setPaintingFlow(brushFlow)
292
293 # get preset from the saved preference setting
294 def getPresetsFor(self, tab=""):
295 # read the list that is saved as "val1;val2;val3;..."
296 rawList = Application.readSetting("quicksettings", str(tab), "")
297 if not rawList:
298 return None
299 try:
300 # if a list is found then it converts floats to ints and then splits the values
301 return sorted(set([int(float(x.strip())) for x in rawList.split(";") if x.strip()]))
302 except Exception as e:
303 print(f"Error parsing saved presets for '{tab}':", e)
304 return None
305
306 # Updates the current tab index to determine which list to modify based on active tab
307 def onTabChanged(self, index):
308 self.currentTabIndex = index
309
310 def addPreset(self):
311 if self.currentTabIndex == self.sizeTabIndex:
312 maxVal = 1000
313 label = i18n("Enter brush size (px):")
314 targetList = self.sizesList
315 saveFile = "size"
316
317 elif self.currentTabIndex == self.opacityTabIndex:
318 maxVal = 100
319 label = i18n("Enter opacity (%):")
320 targetList = self.opacityList
321 saveFile = "opacity"
322
323 elif self.currentTabIndex == self.flowTabIndex:
324 maxVal = 100
325 label = i18n("Enter flow (%):")
326 targetList = self.flowList
327 saveFile = "flow"
328
329 else:
330 return
331
332 # Ask for the new value
333 value, ok = QInputDialog.getInt(
334 self,
335 i18n("Add Preset"), label,
336 1,
337 1,
338 maxVal,
339 1
340 )
341
342 if not ok:
343 return
344
345 value = int(value)
346
347 # Add value if it doesn't already exist
348 if value not in targetList:
349 targetList.append(value)
350 targetList.sort()
351
352 # Save updated presets
353 content = ";".join(str(x) for x in sorted(set(targetList)))
354
355 # Refresh the correct list
356 if self.currentTabIndex == self.sizeTabIndex:
357 self.fillSizesModel()
358
359 elif self.currentTabIndex == self.opacityTabIndex:
360 self.fillOpacityModel()
361
362 elif self.currentTabIndex == self.flowTabIndex:
363 self.fillFlowModel()
364
365 Application.writeSetting("quicksettings", saveFile, content)
366
367 def removePreset(self, index):
368 if self.currentTabIndex == self.sizeTabIndex:
369 targetList = self.sizesList
370 saveFile = "size"
371
372 elif self.currentTabIndex == self.opacityTabIndex:
373 targetList = self.opacityList
374 saveFile = "opacity"
375
376 elif self.currentTabIndex == self.flowTabIndex:
377 targetList = self.flowList
378 saveFile = "flow"
379
380 else:
381 return
382
383 if index < 0 or index >= len(targetList):
384 return
385
386 value = targetList[index]
387
388 try:
389 yesButton = QMessageBox.StandardButton.Yes
390 noButton = QMessageBox.StandardButton.No
391 except AttributeError:
392 yesButton = QMessageBox.Yes
393 noButton = QMessageBox.No
394
395 reply = QMessageBox.question(
396 self,
397 i18n("Delete Preset"),
398 i18n("Are you sure you want to delete this preset?"),
399 yesButton | noButton,
400 noButton
401 )
402 if reply != yesButton:
403 return
404
405 targetList.remove(value)
406
407 # Save updated presets
408 content = ";".join(str(x) for x in sorted(set(targetList)))
409
410 # Refresh the correct list
411 if self.currentTabIndex == self.sizeTabIndex:
412 self.fillSizesModel()
413
414 elif self.currentTabIndex == self.opacityTabIndex:
415 self.fillOpacityModel()
416
417 elif self.currentTabIndex == self.flowTabIndex:
418 self.fillFlowModel()
419
420 Application.writeSetting("quicksettings", saveFile, content)
421