-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEditor.py
526 lines (419 loc) · 17.3 KB
/
Editor.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
import re
import numpy as np
from PIL import Image
import sys
import os
from PyQt5.QtGui import QColor, QImage, QPainter, QPen, QCursor, QPixmap, QBrush, QIcon
from PyQt5.QtWidgets import QAction, QApplication, QFileDialog, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, \
QColorDialog, QGridLayout, QLabel, QMessageBox
from PyQt5.QtCore import QTimer, Qt, QSize, QPoint
image_file_types = ('.png', '.jpg', '.bmp', '.webp', '.gif', '.jpeg', '.ico')
MAX_SIZE = 64
ICON_SIZE = 32 # when loading ico files use 32x32 image
# Removes file extension from a file path/name
def strip_extension(file_name, part=0):
base_name = os.path.splitext(file_name)[part]
return base_name
# Create a QImage from a generated bitmap array (used for dynamic window icon)
def bitmap_array_to_qimage(bitmap_array, width, height):
# Create an array for RGB888 data
rgb888_array = np.zeros((height, width, 3), dtype=np.uint8)
for y in range(height):
for x in range(width):
rgb565 = bitmap_array[y * width + x]
r = (rgb565 >> 11) & 0x1F
g = (rgb565 >> 5) & 0x3F
b = rgb565 & 0x1F
# Convert 5-bit color components to 8-bit
rgb888_array[y, x] = [r << 3, g << 2, b << 3]
# Create QImage from the RGB888 array
qimage = QImage(rgb888_array.data, width, height, width * 3, QImage.Format_RGB888)
return qimage
# Convert RGB565 color to QColor
def rgb565_to_qcolor(color):
r = ((color >> 11) & 0x1F) * 255 // 31
g = ((color >> 5) & 0x3F) * 255 // 63
b = (color & 0x1F) * 255 // 31
return QColor(r, g, b)
# Scales an 8bit value to n bits
def scale_8bit_to_nbit(value, numBits):
if not (0 <= value <= 255):
raise ValueError("Input value must be an 8-bit integer (0-255)")
if not (1 <= numBits <= 32):
raise ValueError("numBits must be between 1 and 32")
max_8bit = 255 # Maximum value for 8-bit
max_nbit = (1 << numBits) - 1 # Maximum value for numBits
# Scale the value
scaled_value = round((value / max_8bit) * max_nbit)
return scaled_value
# Convert rgb color to rgb565
def rgb_to_rgb565(r, g, b):
r_5bit = scale_8bit_to_nbit(r, 5)
g_6bit = scale_8bit_to_nbit(g, 6)
b_5bit = scale_8bit_to_nbit(b, 5)
rgb565 = (r_5bit << 11) | (g_6bit << 5) | b_5bit
return rgb565
# Convert QColor to RGB565
def qcolor_to_rgb565(color):
r = color.red()
g = color.green()
b = color.blue()
return rgb_to_rgb565(r, g, b)
# Function to format and generate PROGMEM array output
def format_bitmap_array(bitmap_array, file_name, w, h):
if not (0 <= w <= 255):
raise ValueError("Width must be an 8-bit integer (0-255)")
if not (0 <= h <= 255):
raise ValueError("Height must be an 8-bit integer (0-255)")
imgName = strip_extension(file_name)
output = f"""// Generated by : QcentICON Editor v0.1
// Generated from : {file_name}
// Image Size : {w}x{h} pixels
#if defined(__AVR__)
#include <avr/pgmspace.h>
#elif defined(__PIC32MX__)
#define PROGMEM
#elif defined(__arm__)
#define PROGMEM
#endif
const unsigned short
{imgName}_DATA[{(w * h) + 1}] PROGMEM =
{{
({w} << 8) | {h}, // First two bytes: width and height
"""
line_length = w
pixel_count = 0
for i in range(0, len(bitmap_array), line_length):
line = bitmap_array[i:i + line_length]
# Convert RGB565 integers to formatted hexadecimal strings
hex_line = [f'0x{num:04X}' for num in line]
output += ' ' + ', '.join(hex_line) + ', // 0x{:04X} ({} pixels)\n'.format(pixel_count,
pixel_count + len(line))
pixel_count += len(line)
output += "};\n"
output += f"const unsigned short *{imgName} = {imgName}_DATA + 1;"
return output
# Turns C/C++ PROGMEM data into bitmap array
def parse_progmem_data(file_path):
try:
with open(file_path, 'r') as file:
content = file.read()
except Exception as e:
print(f"{e}")
# Extract the PROGMEM array
pattern = re.compile(r'const unsigned short.*?\{(.*?)\};', re.DOTALL)
match = pattern.search(content)
if not match:
raise ValueError("PROGMEM array not found in file")
data_str = match.group(1)
# Extract width and height from the first line
size_pattern = re.compile(r'\((\d+) << 8\) \| (\d+)')
size_match = size_pattern.search(data_str)
if not size_match:
raise ValueError("Width and height information not found")
width = int(size_match.group(1))
height = int(size_match.group(2))
# Extract numbers from the PROGMEM array, ignoring comments
pixel_data = []
lines = data_str.splitlines()
for line in lines:
line = line.split('//')[0].strip() # Ignore comments after '//'
if line:
pixel_data.extend(int(num, 16) for num in re.findall(r'0x[0-9A-Fa-f]+', line))
if len(pixel_data) != width * height:
raise ValueError("Pixel data does not match the specified width and height")
return width, height, pixel_data
# Convert PIL image to bitmap array
def img_to_bitmap_array(img):
# Convert image to numpy array
img_array = np.array(img)
# Convert RGBA values to 565 format, setting transparent pixels to 0x0000
bitmap_array = []
for row in img_array:
for r, g, b, a in row:
if a < 20: # Check if the pixel is transparent
rgb565 = 0x0000
else:
rgb565 = rgb_to_rgb565(r, g, b)
bitmap_array.append(rgb565)
return bitmap_array
# Given a file path will reckon images, icons, PROGMEM and produce pixels or error
def get_pixels_from_file(file_path):
width = None
height = None
pixel_data = None
if file_path.lower().endswith(image_file_types):
# Load Data from img file
try:
img = Image.open(file_path).convert('RGBA')
if file_path.lower().endswith('.ico'):
print("Available sizes:", img.info['sizes'])
desired_size = (ICON_SIZE, ICON_SIZE) # Example size, choose the one you need
img = img.resize(desired_size)
except Exception as e:
print(e)
sys.exit(app.exec_())
width = img.width
height = img.height
pixel_data = img_to_bitmap_array(img)
if width > MAX_SIZE or height > MAX_SIZE:
print("Image is too large to open in editor")
sys.exit(app.exec_())
else:
# Load Data from c style header file
width, height, pixel_data = parse_progmem_data(file_path)
if pixel_data is not None:
print(F"Loaded : {file_path}")
return width, height, pixel_data
# Popup user notification widget
class NotificationWidget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.initUI()
def initUI(self):
self.setAutoFillBackground(True)
self.setStyleSheet("background-color: #2c3e50; color: white; border-radius: 5px;")
self.layout = QVBoxLayout()
self.setLayout(self.layout)
self.label = QLabel(self)
self.label.setAlignment(Qt.AlignCenter)
self.layout.addWidget(self.label)
def show_notification(self, message, duration=3000):
self.label.setText(message)
self.setGeometry(0, 0, 180, 40)
self.show()
self.timer = QTimer.singleShot(duration, self.hide)
# A box for selecting drawing color
class ColorBox(QWidget):
def __init__(self, color, id, active=False, parent=None):
super().__init__(parent)
self.active = active
self.color = QColor(color)
self.id = id # Identifier for the color box
self.setFixedSize(25, 35)
self.setAutoFillBackground(True)
def paintEvent(self, event):
painter = QPainter(self)
if self.active:
painter.setPen(QPen(Qt.white, 3)) # White border with 3px width
else:
painter.setPen(QPen(Qt.black, 2))
painter.setBrush(self.color)
painter.drawRect(0, 0, self.width(), self.height())
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.parent().set_active_color(self.id)
self.parent().change_cursor_color(self.color)
if not self.active:
self.parent().toggleActiveCols()
def toggleActive(self):
self.active = not self.active
self.update()
# Custom widget for each pixel cell
class PixelDataCell(QWidget):
def __init__(self, idx, color, parent=None):
super().__init__(parent)
self.setMinimumSize(20, 20) # Set the size of each cell
self.setAutoFillBackground(True)
self.index = idx
p = self.palette()
p.setColor(self.backgroundRole(), Qt.black)
self.setPalette(p)
self.color = color # Store the color
self.hovered = False # Flag to track hover state
# Modify paintEvent in CellWidget class
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing) # Optional: for smoother edges
painter.setBrush(QColor(self.color)) # Use the specified color
# Calculate radius with additional spacing
spacing = 4
if self.hovered:
painter.setPen(QColor(153, 155, 103, 155)) # Pale yellow color
radius = (min(self.width(), self.height()) - spacing // 2) // 2
else:
painter.setPen(Qt.NoPen) # No outline
radius = (min(self.width(), self.height()) - spacing) // 2
center = self.rect().center()
painter.drawEllipse(center, radius, radius)
def enterEvent(self, event):
self.hovered = True
self.update()
def leaveEvent(self, event):
self.hovered = False
self.update()
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
active_color = self.parent().get_active_color()
self.set_color(active_color)
def set_color(self, color):
self.color = color
self.update()
def get_rgb565_color(self):
return qcolor_to_rgb565(self.color)
# Main window to display the grid of circles
class MainWindow(QWidget):
def __init__(self, width, height, pixel_data, file_path):
super().__init__()
self.file_path = file_path
self.original_width = width
self.original_height = height
self.file_name = file_path.split('/')[-1]
self.title = strip_extension(self.file_name)
self.img_width = width
self.img_height = height
self.tool = 1
self.activeCol = 1
self.color1 = QColor(255, 255, 255)
self.color2 = QColor(0, 255, 0)
main_layout = QHBoxLayout()
self.grid_layout = QGridLayout()
self.grid_layout.setSpacing(1)
idx = 0
for row in range(height):
for col in range(width):
color = pixel_data[idx]
cell = PixelDataCell(idx, rgb565_to_qcolor(color), self)
self.grid_layout.addWidget(cell, row, col)
idx += 1
# Right-side layout for buttons and other widgets
right_layout = QVBoxLayout()
# Add color picker button and dialog
self.color_button = QPushButton('Pick Color')
self.color_button.clicked.connect(self.show_color_dialog)
self.color_button.setStyleSheet(f"background-color: gray;")
right_layout.addWidget(self.color_button)
# Add ColorBox widgets to right_layout
self.box1 = ColorBox(self.color1, 1, True)
self.box2 = ColorBox(self.color2, 2)
right_layout.addWidget(self.box1)
right_layout.addWidget(self.box2)
# Add save button
self.save_button = QPushButton('Save')
self.save_button.clicked.connect(self.save_work)
self.save_button.setStyleSheet(f"background-color: gray;")
right_layout.addWidget(self.save_button)
# Add reload button
self.reload_button = QPushButton('Reload')
self.reload_button.clicked.connect(self.reload_pixel_data)
self.reload_button.setStyleSheet(f"background-color: gray;")
right_layout.addWidget(self.reload_button)
main_layout.addLayout(self.grid_layout)
main_layout.addLayout(right_layout)
self.setLayout(main_layout)
self.setWindowTitle(f"{self.title}")
self.initUI_notifications()
# Set main window background color
self.setStyleSheet("background-color: #111111;")
self.change_cursor_color(self.color1)
def reload_pixel_data(self):
self.load_pixel_data(self.file_path)
self.show_notification("Pixels Reloaded!")
def load_pixel_data(self, file_path):
width, height, pixel_data = get_pixels_from_file(file_path)
# Update the cell widgets with the loaded pixel data
for row in range(self.grid_layout.rowCount()):
for col in range(self.grid_layout.columnCount()):
item = self.grid_layout.itemAtPosition(row, col)
if item is not None:
cell = item.widget()
if isinstance(cell, PixelDataCell):
cell.set_color(rgb565_to_qcolor(pixel_data[cell.index]))
def get_pixel_data(self):
pixel_data = []
for row in range(self.grid_layout.rowCount()):
for col in range(self.grid_layout.columnCount()):
item = self.grid_layout.itemAtPosition(row, col)
if item is not None:
cell = item.widget()
if isinstance(cell, PixelDataCell):
color = cell.get_rgb565_color()
pixel_data.append(color)
return pixel_data
def show_color_dialog(self):
color_dialog = QColorDialog(self)
# Position the color dialog relative to the main window using mapToParent
main_window_geometry = self.geometry()
dialog_position = self.mapToParent(main_window_geometry.topRight())
color_dialog.move(dialog_position)
color = color_dialog.getColor()
if color.isValid():
if self.activeCol == 1:
self.color1 = color
self.box1.color = self.color1
self.box1.update()
elif self.activeCol == 2:
self.color2 = color
self.box2.color = self.color2
self.box2.update()
self.change_cursor_color(color)
def set_active_color(self, color_id):
self.activeCol = color_id
def get_active_color(self):
if self.activeCol == 1:
return self.color1
elif self.activeCol == 2:
return self.color2
def change_cursor_color(self, color):
pixmap = QPixmap(16, 16)
pixmap.fill(Qt.transparent)
painter = QPainter(pixmap)
painter.setBrush(QBrush(color))
painter.drawEllipse(0, 0, 16, 16)
painter.end()
cursor = QCursor(pixmap)
self.setCursor(cursor)
def toggleActiveCols(self):
self.box1.toggleActive()
self.box2.toggleActive()
def save_work(self):
try:
source_name = self.file_name
# Collect RGB565 values from cell widgets
rgb565_data = self.get_pixel_data()
if file_path.lower().endswith(image_file_types): # if editing an image file
self.file_path = os.path.splitext(self.file_path)[0] + '.h' # save as a .h header file
self.file_name = self.file_path.split('/')[-1]
# Format the PROGMEM array and write to file
formatted_data = format_bitmap_array(rgb565_data, source_name, self.img_width, self.img_height)
with open(self.file_path, 'w') as file:
file.write(formatted_data)
#QMessageBox.information(self, "File Saved", "File saved successfully.")
self.show_notification("File saved successfully!")
print(f"Saved {self.file_path}")
except Exception as e:
#QMessageBox.critical(self, "Error Saving File", str(e))
self.show_notification("Failed to Save File!" + str(e))
print(f"Save Failed: {e}")
def initUI_notifications(self):
self.notification_widget = NotificationWidget(self)
self.notification_widget.hide()
def show_notification(self, msg):
self.notification_widget.show_notification(msg, duration=3000)
if __name__ == "__main__":
app = QApplication(sys.argv)
file_path = None
pixel_data = None
width = None
height = None
if len(sys.argv) == 2:
file_path = sys.argv[1]
else:
# Open a file picker dialog if no file is provided
file_dialog = QFileDialog()
file_dialog.setWindowTitle("Choose a C/C++ PROGMEM or Image File")
file_dialog.setFileMode(QFileDialog.ExistingFile)
file_dialog.setNameFilter("All Files (*)")
if file_dialog.exec_():
file_path = file_dialog.selectedFiles()[0]
else:
sys.exit(app.exec_())
# determine image data
width, height, pixel_data = get_pixels_from_file(file_path)
window = MainWindow(width, height, pixel_data, file_path)
# set icon dynamically
qimage = bitmap_array_to_qimage(pixel_data, width, height)
icon = QIcon(QPixmap.fromImage(qimage))
window.setWindowIcon(icon)
window.show()
sys.exit(app.exec_())