-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnetpaint.py
executable file
·1699 lines (1353 loc) · 74 KB
/
netpaint.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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python3
# This file is a part of NetPaint (http://github.com/SyntheticDreams/NetPaint)
#
# Copyright (C) 2019 Synthetic Dreams (Anthony Westbrook)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
import argparse
import math
import os
import struct
import sys
import time
import urwid
from functools import partial
from PIL import Image
class WidgetManager():
""" Manage all widgets and associated functionality """
def __init__(self, palette, encoding):
self.palette = palette
self.encoding = encoding
self.widgets = dict()
self.groups = dict()
self.base = None
self.update_palette()
def register(self, name, widget, attr=None):
""" Register new widget """
self.widgets[name] = urwid.AttrMap(widget, attr)
def get(self, name, orig=False):
""" Get a widget attr or base object """
if orig:
return self.widgets[name]._original_widget
else:
return self.widgets[name]
def __setitem__(self, key, value):
""" Overload for register shortcut """
self.register(key, value)
def __getitem__(self, key):
""" Overload for get shortcut """
return self.get(key)
def update_attr(self, name, attr):
""" Update attribute associated with widget """
self.widgets[name].set_attr_map({None: attr})
def group_add(self, group, objects, multi=False):
""" Add object (widget/tuples/other) to a group """
self.groups.setdefault(group, [])
if multi:
self.groups[group].extend(objects)
else:
self.groups[group].append(objects)
def group_get(self, group):
""" Get object list for a group """
self.groups.setdefault(group, [])
return self.groups[group]
def register_base(self, base, default):
""" Register overlay base and default child """
self.base = (base, default)
def activate_overlay(self, name):
""" Activate overlay over canvas portion of body """
if isinstance(self.get(self.base[0], True).contents[0][0]._original_widget, urwid.Overlay):
return
# Reset overlay if applicable
if getattr(self.get(name, True), "reset", False):
self.get(name, True).reset()
self.get(self.base[0], True).contents[0] = (self.widgets[name], self.get(self.base[0], True).contents[0][1])
def deactivate_overlay(self):
""" Deactivate overlay covering canvas """
if isinstance(self.get(self.base[0], True).contents[0][0]._original_widget, urwid.Overlay):
self.get(self.base[0], True).contents[0] = (self.widgets[self.base[1]], self.get(self.base[0], True).contents[0][1])
def get_overlay(self):
""" Get current overlay """
if not isinstance(self.get(self.base[0], True).contents[0][0]._original_widget, urwid.Overlay):
return None
return self.get(self.base[0], True).contents[0][0]._original_widget
def get_color_name(self, color, clean=True):
""" Generate the text color name for the index """
name = urwid.display_common._BASIC_COLORS[color]
if clean:
name = name.replace(" ", "_")
return name
def update_palette(self):
""" Add color name combinations to palette """
for fore_idx in range(16):
for back_idx in range(16):
colors_id = "{}-{}".format(self.get_color_name(fore_idx), self.get_color_name(back_idx))
colors = (colors_id, self.get_color_name(fore_idx, False), self.get_color_name(back_idx, False))
self.palette.append(colors)
class TextGrid(urwid.Widget):
""" Provide coordinate addressable text grid """
CONFIG_DEFAULTS = {"back_char": b" ", "back_attrs": (0, 0, 0), "ext_char": bytes("\u2591", "utf8"), "ext_attrs": (8, 0, 0),
"scroll_attrs": (0, 7, 0), "dims": None, "scroll_h": True, "scroll_v": True}
_sizing = frozenset([urwid.BOX])
def __init__(self, wm, config={}):
self.wm = wm
self.config = dict(self.CONFIG_DEFAULTS)
self.config.update(config)
self.scroll_x = 0
self.scroll_y = 0
self.layer = 0
# Initialize canvas
self.reset()
def convert_attrs(self, attrs):
""" Convert TextGrid attributes to Urwid palette attribute """
return "{}-{}".format(self.wm.get_color_name(attrs[0]), self.wm.get_color_name(attrs[1]))
def plot(self, col, row, char, attrs, layer=None):
""" Assign a character to a location on the grid """
# Select desired layer
if layer is None:
layer = self.layer
# Adjust dimensions for dynamic sized grids if necessary
while row >= len(self.content[layer]):
if self.config["dims"]:
return
self.content[layer].append([None] * len(self.content[layer][0]))
self.attrs[layer].append([None] * len(self.content[layer][0]))
while col >= len(self.content[layer][0]):
if self.config["dims"]:
return
for cur_row in range(len(self.content[layer])):
self.content[layer][cur_row].append(None)
self.attrs[layer][cur_row].append(None)
# Assign character
self.content[layer][row][col] = char
self.attrs[layer][row][col] = attrs
self._invalidate()
def reset(self):
""" Reset grid back to default """
cols, rows = self.config["dims"] if self.config["dims"] else (1, 1)
# Remove all layers and create bottom layer
self.content = [[[None for col_idx in range(cols)] for row_idx in range(rows)]]
self.attrs = [[[None for col_idx in range(cols)] for row_idx in range(rows)]]
# Create cursor layer
self.content.append([[None for col_idx in range(cols)] for row_idx in range(rows)])
self.attrs.append([[None for col_idx in range(cols)] for row_idx in range(rows)])
# Set bottom and cursor layer to visible
self.visibility = [True, True]
self._invalidate()
def clear(self, layer=None):
""" Clear the specified layer """
# Select desired layer
if layer is None:
layer = self.layer
for row_idx in range(len(self.content[layer])):
for col_idx in range(len(self.content[layer][row_idx])):
self.content[layer][row_idx][col_idx] = None
self.attrs[layer][row_idx][col_idx] = None
self._invalidate()
def render(self, size, focus=False):
""" Widget render implementation """
encoding = self.wm.encoding
# Calculate render dimensions (exclusive range)
last_row = size[1] if len(size) == 2 else len(self.content[0])
last_col = size[0] if len(size) > 0 else len(self.content[0][0])
# Flatten layers into buffer
flat_text, flat_attrs = self.get_flattened()
# Copy rendered portion of flattened buffer
text = [b"".join(row[self.scroll_x:last_col + self.scroll_x]) for row in flat_text[self.scroll_y:last_row + self.scroll_y]]
attrs = []
for row_idx in range(self.scroll_y, min(len(flat_attrs), last_row + self.scroll_y)):
attrs.append([])
for col_idx in range(self.scroll_x, min(len(flat_attrs[row_idx]), last_col + self.scroll_x)):
cur_attr = (self.convert_attrs(flat_attrs[row_idx][col_idx]), len(flat_text[row_idx][col_idx]))
attrs[row_idx - self.scroll_y].append(cur_attr)
# Fill in remaining with background (dynamic) or invalid (fixed) characters
fill_char = self.config["ext_char"] if self.config["dims"] else self.config["back_char"]
fill_attrs = self.config["ext_attrs"] if self.config["dims"] else self.config["back_attrs"]
while last_row > len(text):
text.append(fill_char * len(text[0].decode(self.wm.encoding)))
attrs.append([(self.convert_attrs(fill_attrs), len(fill_char))] * len(text[0].decode(encoding)))
while last_col > len(text[0].decode(encoding)):
for cur_row in range(last_row):
if last_col > len(text[cur_row].decode(encoding)):
add_len = last_col - len(text[cur_row].decode(encoding))
text[cur_row] += (fill_char * add_len)
attrs[cur_row].extend([(self.convert_attrs(fill_attrs), len(fill_char))] * add_len)
# If scrollbars are active, overwrite right/bottom edge
if self.config["scroll_h"]:
last_h = last_col - 3 if self.config["scroll_v"] else last_col - 2
text[last_row - 1] = bytes("\u2190", "utf8") + bytes("\u2591", "utf8") * last_h + bytes("\u2192", "utf8")
attrs[last_row - 1] = [(self.convert_attrs(self.config["scroll_attrs"]), len(char.encode(encoding))) for char in text[last_row - 1].decode(encoding)]
if self.config["scroll_v"]:
last_v = -2 if self.config["scroll_h"] else -1
text[0] = text[0].decode(encoding)[:-1].encode(encoding) + bytes("\u2191", "utf8")
attrs[0][-1] = (self.convert_attrs(self.config["scroll_attrs"]), 3)
text[last_v] = text[last_v].decode(encoding)[:-1].encode(encoding) + bytes("\u2193", "utf8")
attrs[last_v][-1] = (self.convert_attrs(self.config["scroll_attrs"]), 3)
for (idx, row) in enumerate(text[1:last_v]):
text[idx + 1] = row.decode(encoding)[:-1].encode(encoding) + bytes("\u2591", "utf8")
attrs[idx + 1][-1] = (self.convert_attrs(self.config["scroll_attrs"]), 3)
canvas = urwid.TextCanvas(text, attr=attrs, maxcol=last_col)
return canvas
def mouse_event(self, size, event, button, col, row, focus):
""" Handle mouse actions (scrolling) """
x = 0
y = 0
v_pos = size[1] - 2 if self.config["scroll_h"] else size[1] - 1
h_pos = size[0] - 2 if self.config["scroll_v"] else size[0] - 1
# Calculate scroll distance
distance = 0
if int(button) == 1 or int(button) == 4 or int(button) == 5:
distance = 1
if int(button) == 3:
distance = 10
# Detect if scroll buttons/bar clicked (bar currently does nothing)
scroll = False
if self.config["scroll_v"]:
if col == size[0] - 1:
scroll = True
if row == 0:
# Scroll up
y = -distance
if row == v_pos:
# Scroll down
y = distance
# Scroll wheel
if int(button) == 4:
# Scroll up
scroll = True
y = -distance
if int(button) == 5:
# Scroll down
scroll = True
y = distance
if self.config["scroll_h"]:
if row == size[1] - 1:
scroll = True
if col == 0:
# Scroll left
x = -distance
if col == h_pos:
# Scroll right
x = distance
if scroll:
self.scroll(x, y)
else:
# If unhandled, pass to grid event
grid_col = col + self.scroll_x
grid_row = row + self.scroll_y
self.grid_event(size, event, button, grid_col, grid_row, focus)
def grid_event(self, size, event, button, col, row, focus):
""" Handle grid mouse action """
pass
def select_layer(self, idx):
""" Change active layer """
if (idx < 0) or (idx >= len(self.content) - 1):
return False
self.layer = idx
return True
def show_layer(self, idx, visible):
""" Set layer visibility """
if (idx < 1) or (idx >= len(self.content) - 1):
return False
self.visibility[idx] = visible
return True
def add_layer(self, idx):
""" Add new empty layer """
if (idx < 1) or (idx > len(self.content) - 1):
return False
rows = len(self.content[0])
cols = len(self.content[0][0])
self.content.insert(idx, [[None for col_idx in range(cols)] for row_idx in range(rows)])
self.attrs.insert(idx, [[None for col_idx in range(cols)] for row_idx in range(rows)])
self.visibility.insert(idx, True)
return True
def del_layer(self, idx):
""" Delete an existing layer """
if (idx < 1) or (idx >= len(self.content) - 1):
return False
del self.content[idx]
del self.attrs[idx]
del self.visibility[idx]
self._invalidate()
return True
def scroll(self, x=0, y=0, rel=True):
""" Scroll canvas in requested direction """
if rel:
self.scroll_x += x
self.scroll_y += y
else:
self.scroll_x = 0
self.scroll_y = 0
# Check for boundaries
if self.scroll_x < 0:
self.scroll_x = 0
if self.scroll_x >= len(self.content[0][0]):
self.scroll_x = len(self.content[0][0]) - 1
if self.scroll_y < 0:
self.scroll_y = 0
if self.scroll_y >= len(self.content[0]):
self.scroll_y = len(self.content[0]) - 1
# Update canvas
self._invalidate()
def get_flattened(self):
""" Get flattened buffer """
# Start with base of background character and color
cols = len(self.content[0][0])
rows = len(self.content[0])
flat_text = [[self.config["back_char"] for col_idx in range(cols)] for row_idx in range(rows)]
flat_attrs = [[self.config["back_attrs"] for col_idx in range(cols)] for row_idx in range(rows)]
for layer_idx in range(len(self.content)):
# Skip hidden layers
if not self.visibility[layer_idx]:
continue
for row_idx in range(len(self.content[layer_idx])):
for col_idx in range(len(self.content[layer_idx][row_idx])):
char = self.content[layer_idx][row_idx][col_idx]
attr = self.attrs[layer_idx][row_idx][col_idx]
if char is not None:
flat_text[row_idx][col_idx] = char
if attr is not None:
flat_attrs[row_idx][col_idx] = attr
return flat_text, flat_attrs
def get_dims(self):
""" Get (layers, cols, rows) dimensions of image """
layers = len(self.content)
rows = len(self.content[0])
cols = len(self.content[0][0])
return layers, cols, rows
def set_dims(self, cols, rows):
""" Set dimensions of all layers """
if cols < 1 or rows < 1:
return False
# Reset scroll to prevent offscreen draw
self.scroll(0, 0, rel=False)
cur_layers, cur_cols, cur_rows = self.get_dims()
for layer_idx in range(cur_layers):
if rows < cur_rows:
# Truncate rows
self.content[layer_idx] = self.content[layer_idx][:rows]
self.attrs[layer_idx] = self.attrs[layer_idx][:rows]
else:
# Add rows
self.content[layer_idx].extend([[None for ins_idx2 in range(cur_cols)] for ins_idx1 in range(rows - cur_rows)])
self.attrs[layer_idx].extend([[None for ins_idx2 in range(cur_cols)] for ins_idx1 in range(rows - cur_rows)])
for row_idx in range(rows):
if cols < cur_cols:
# Truncate columns
self.content[layer_idx][row_idx] = self.content[layer_idx][row_idx][:cols]
self.attrs[layer_idx][row_idx] = self.attrs[layer_idx][row_idx][:cols]
else:
# Add columns
self.content[layer_idx][row_idx].extend([None for ins_idx in range(cols - cur_cols)])
self.attrs[layer_idx][row_idx].extend([None for ins_idx in range(cols - cur_cols)])
self._invalidate()
# Update config
self.config["dims"] = (cols, rows)
return True
class DrawCanvas(TextGrid):
""" Provide text grid with tool functionality """
TOOLS = [["Paint", "Erase", "Draw", "Text", "Select", "Stamp"], ["Image", "Layer"]]
TOOL_DEFAULTS = {"Paint": {"size": 1}, "Erase": {"size": 1}, "Draw": {"size": 1}, "Text": {"active": False}, "Select": {"active": False}, "Stamp": {"original": True}}
TOOL_RESET = {"Text": {"active": False}, "Select": {"active": False}}
@classmethod
def attr_ansi(cls, attr):
""" Convert attributes to ANSI escape codes """
# Foreground
mod = 30 if attr[0] < 8 else 82
fore = "{}".format(attr[0] + mod)
# Background
mod = 40 if attr[1] < 8 else 92
back = "{}".format(attr[1] + mod)
return bytes("\x1B[{}m\x1B[{}m".format(fore, back).encode("utf-8"))
def __init__(self, wm, config={}):
super().__init__(wm, config=config)
self.active_attrs = [0, 0, 0]
self.pointer_tool = self.TOOLS[0][0]
self.options_tool = self.TOOLS[0][0]
self.active_symbol = b""
self.option_vals = {tool: dict(DrawCanvas.TOOL_DEFAULTS[tool]) for tool in DrawCanvas.TOOL_DEFAULTS}
def selectable(self):
return True
def keypress(self, size, key):
""" Handle canvas key events """
if self.option_vals["Text"]["active"]:
# Intercept keys for text mode
self.text_plot(key.encode("utf-8"))
else:
return key
def grid_event(self, size, event, button, col, row, focus):
""" Handle drawing mouse events """
options = self.option_vals.setdefault(self.pointer_tool, {})
# Mouse release
if int(button) == 0:
if self.pointer_tool in ["Paint", "Erase", "Draw", "Stamp"]:
# Turn off hint cursor after releasing button
self.clear(layer=-1)
if self.pointer_tool == "Select":
options["active"] = False
# Left button
if int(button) == 1:
if self.pointer_tool == "Paint":
self.plot(col, row, b' ', (self.active_attrs[0], self.active_attrs[0], 0), size=options["size"])
if self.pointer_tool == "Erase":
self.plot(col, row, None, None, size=options["size"])
if self.pointer_tool == "Draw":
self.plot(col, row, self.active_symbol, (self.active_attrs[0], self.active_attrs[1], 0), size=options["size"])
if self.pointer_tool == "Text":
options["active"] = True
options["col"] = col
options["row"] = row
options["col_start"] = col
options["row_start"] = row
self.clear(layer=-1)
self.plot(col, row, None, None, layer=-1, size=1, inverse=True)
if self.pointer_tool == "Select":
self.select_area(col, row, reselect=options["active"])
self.plot_select()
options["active"] = True
if self.pointer_tool == "Stamp":
self.plot_stamp(col, row, self.layer)
# Right button
if int(button) == 3:
if self.pointer_tool in ["Paint", "Erase", "Draw"]:
# Display hint cursor
self.clear(layer=-1)
self.plot(col, row, None, None, layer=-1, size=self.option_vals[self.pointer_tool]["size"], inverse=True)
if self.pointer_tool == "Select":
# Reselect end bounds
self.select_area(col, row)
self.plot_select()
if self.pointer_tool == "Stamp":
# Stamp hint
self.clear(layer=-1)
self.plot_stamp(col, row)
def plot(self, col, row, char, attrs, layer=None, size=1, inverse=False):
""" Extended plotting (size control, inverse) """
start_col = max(0, col - math.ceil(size / 2) + 1)
start_row = max(0, row - math.ceil(size / 2) + 1)
dims = self.get_dims()
for col_idx in range(start_col, start_col + size):
for row_idx in range(start_row, start_row + size):
# Check bounds
if row_idx >= dims[2] or col_idx >= dims[1]:
break
cur_attr = attrs
if inverse:
old_attr = self.attrs[self.layer][row_idx][col_idx]
inv_attr = list(old_attr if old_attr is not None else (0, 0, 0))
inv_attr[0] = (inv_attr[0] + 7) % 16
inv_attr[1] = (inv_attr[1] + 7) % 16
cur_attr = tuple(inv_attr)
super().plot(col_idx, row_idx, char, cur_attr, layer)
def text_plot(self, char):
""" Plot character from text tool """
options = self.option_vals["Text"]
if len(char) > 1:
if char == b"backspace":
# Calculate if a non-background/transparent char underneath cursor
existing_char = False
if self.content[self.layer][options["row"]][options["col"]] is not None:
existing_char = True
if options["row"] == options["row_start"] and options["col"] == options["col_start"]:
# Starting cursor location, do nothing
return
if options["col"] >= len(self.content[0][0]) - 1 and existing_char:
# Cursor at end of line with something underneath, delete current character and do not move cursor
pass
elif options["col"] > options["col_start"]:
# Cursor at non-start of line, delete previous character and move cursor back
options["col"] -= 1
else:
# Cursor at start of line, move up a line
options["col"] = options["col_end"]
options["row"] -= 1
# Set to transparent
self.plot(options["col"], options["row"], None, None, size=1)
elif char == b"enter":
options["col_end"] = options["col"]
options["col"] = options["col_start"]
options["row"] += 1
elif char == b"esc":
options["active"] = False
else:
# Unrecognized character
return
else:
self.plot(options["col"], options["row"], char, list(self.active_attrs))
options["col"] += 1
# Check bounds
if options["col"] >= len(self.content[0][0]):
options["col"] = len(self.content[0][0]) - 1
if options["row"] >= len(self.content[0]):
options["row"] = len(self.content[0]) - 1
# Keep cursor on if active
self.clear(layer=-1)
if options["active"]:
self.plot(options["col"], options["row"], None, None, layer=-1, inverse=True)
def plot_select(self):
""" Plot selection rectangle """
options = self.option_vals["Select"]
self.clear(layer=-1)
row_step = 1 if options["row_start"] < options["row_end"] else -1
for row_idx in range(options["row_start"], options["row_end"] + row_step, row_step):
self.plot(options["col_start"], row_idx, None, None, layer=-1, size=1, inverse=True)
self.plot(options["col_end"], row_idx, None, None, layer=-1, size=1, inverse=True)
col_step = 1 if options["col_start"] < options["col_end"] else -1
for col_idx in range(options["col_start"], options["col_end"] + col_step, col_step):
self.plot(col_idx, options["row_start"], None, None, layer=-1, size=1, inverse=True)
self.plot(col_idx, options["row_end"], None, None, layer=-1, size=1, inverse=True)
def plot_stamp(self, col, row, layer=-1):
""" Plot clip buffer """
options_select = self.option_vals["Select"]
options_stamp = self.option_vals["Stamp"]
if "clip_content" not in options_select:
return
for row_idx in range(len(options_select["clip_content"])):
for col_idx in range(len(options_select["clip_content"][0])):
char = options_select["clip_content"][row_idx][col_idx]
attr = options_select["clip_attrs"][row_idx][col_idx]
if not options_stamp["original"]:
if char == b" " and attr[0] == attr[1]:
attr = (self.active_attrs[0], self.active_attrs[0], 0)
else:
attr = (self.active_attrs[0], self.active_attrs[1], 0)
if char is not None:
# Only stamp non-transparent characters
self.plot(col + col_idx, row + row_idx, char, attr, layer=layer)
def select_area(self, col, row, reselect=True):
""" Select area of canvas """
options = self.option_vals["Select"]
if ("col_start" not in options) or not reselect:
options["col_start"] = col
options["row_start"] = row
options["col_end"] = col
options["row_end"] = row
# Check bounds
options["col_start"] = min(options["col_start"], len(self.content[self.layer][0]) - 1)
options["col_end"] = min(options["col_end"], len(self.content[self.layer][0]) - 1)
options["row_start"] = min(options["row_start"], len(self.content[self.layer]) - 1)
options["row_end"] = min(options["row_end"], len(self.content[self.layer]) - 1)
def copy_area(self, copy, clear):
""" Cut/Copy/Clear selected area to clipboard """
options = self.option_vals["Select"]
# Check if no area selected
if "row_start" not in options:
return
clip_content = []
clip_attrs = []
row_bounds = sorted([options["row_start"], options["row_end"]])
col_bounds = sorted([options["col_start"], options["col_end"]])
for row_idx in range(row_bounds[0], row_bounds[1] + 1):
clip_content.append([])
clip_attrs.append([])
for col_idx in range(col_bounds[0], col_bounds[1] + 1):
clip_content[-1].append(self.content[self.layer][row_idx][col_idx])
clip_attrs[-1].append(self.attrs[self.layer][row_idx][col_idx])
# Remove if clear mode
if clear:
self.content[self.layer][row_idx][col_idx] = None
self.attrs[self.layer][row_idx][col_idx] = None
if copy:
options["clip_content"] = clip_content
options["clip_attrs"] = clip_attrs
if clear:
self._invalidate()
def save(self, path):
""" Save all non-cursor layers to file """
dims = self.get_dims()
full_path = os.path.expanduser(path)
with open(full_path, "wb") as handle:
# Write layer count
handle.write(struct.pack("I", dims[0] - 1))
for layer_idx in range(dims[0] - 1):
# Write row count
handle.write(struct.pack("I", dims[2]))
for row_idx in range(dims[2]):
# Write column count
handle.write(struct.pack("I", dims[1]))
for col_idx in range(dims[1]):
char = self.content[layer_idx][row_idx][col_idx]
char = b"\0\0\0\0" if char is None else char.ljust(4, b"\0")
attr = self.attrs[layer_idx][row_idx][col_idx]
attr = (255, 255) if attr is None else attr
# Write unicode character as fixed 4-byte value
handle.write(char)
# Write attribute as fixed 2-byte value (FG,BG)
handle.write(attr[0].to_bytes(1, "little"))
handle.write(attr[1].to_bytes(1, "little"))
def load(self, path):
""" Load non-cursor layers from a file """
full_path = os.path.expanduser(path)
self.reset()
with open(full_path, "rb") as handle:
# Read layer count
layers = handle.read(4)
layers = struct.unpack("I", layers)[0]
for layer_idx in range(layers):
# Read row count
rows = handle.read(4)
rows = struct.unpack("I", rows)[0]
# Add layers above 0
if layer_idx > 0:
self.add_layer(layer_idx)
self.content[layer_idx].clear()
self.attrs[layer_idx].clear()
for row_idx in range(rows):
self.content[layer_idx].append([])
self.attrs[layer_idx].append([])
# Read column count
cols = handle.read(4)
cols = struct.unpack("I", cols)[0]
for col_idx in range(cols):
# Read unicode character as fixed 4-byte value
char = handle.read(4).rstrip(b"\0")
char = None if char == b"" else char
self.content[layer_idx][row_idx].append(char)
# Read attribute as fixed 2-byte value (FG,BG)
fore = int.from_bytes(handle.read(1), "little")
back = int.from_bytes(handle.read(1), "little")
attr = None if (fore == 255 and back == 255) else (fore, back, 0)
self.attrs[layer_idx][row_idx].append(attr)
def export_text(self, path, color):
""" Export text version of flattened image """
full_path = os.path.expanduser(path)
flat_text, flat_attrs = self.get_flattened()
with open(full_path, "wb") as handle:
for row_idx in range(len(flat_text)):
for col_idx in range(len(flat_text[row_idx])):
if color:
code = DrawCanvas.attr_ansi(flat_attrs[row_idx][col_idx])
handle.write(code)
char = flat_text[row_idx][col_idx]
handle.write(char)
handle.write(b"\n")
# End file with attribute reset
handle.write(b"\x1B[0m")
def import_image(self, path):
""" Import and convert supported image """
full_path = os.path.expanduser(path)
dims = self.get_dims()
self.reset()
with Image.open(full_path, "r") as handle:
pixels = handle.getdata()
# Calculate pixels per character
ppc_width = handle.width / dims[1]
ppc_height = handle.height / dims[2]
# Generate chunk coordinates
chunks_width = [int(idx * ppc_width) for idx in range(int(handle.width / ppc_width))]
chunks_height = [int(idx * ppc_height) for idx in range(int(handle.height / ppc_height))]
chunks_width.append(handle.width)
chunks_height.append(handle.height)
for chunk_y in range(len(chunks_height) - 1):
for chunk_x in range(len(chunks_width) - 1):
chunk_pixels = []
# Calculate mean chunk color
for idx_y in range(chunks_height[chunk_y], chunks_height[chunk_y + 1]):
for idx_x in range(chunks_width[chunk_x], chunks_width[chunk_x + 1]):
chunk_pixels.append(pixels[idx_y * handle.width + idx_x])
chunk_pixels = zip(*chunk_pixels)
chunk_color = [int(sum(channel) / len(channel)) for channel in chunk_pixels]
NetPaint.inst.log(chunk_color)
# Calculate color distances
distances = []
for idx, color in enumerate(NetPaint.inst.RGB_LOOKUP):
distance = math.sqrt((chunk_color[0] - color[0])**2 + (chunk_color[1] - color[1])**2 + (chunk_color[2] - color[2])**2)
distances.append((distance, idx))
# Get primary and secondary, calculate ratio, choose character
distances = sorted(distances)
ratio = distances[0][0] / distances[1][0]
if ratio > 0.66:
char = bytes(chr(9618), "utf8")
elif ratio > 0.33:
char = bytes(chr(9617), "utf8")
else:
char = b" "
# Draw character
self.content[0][chunk_y][chunk_x] = char
self.attrs[0][chunk_y][chunk_x] = (distances[1][1], distances[0][1], 0)
def select_tool(self, tool):
""" Setup selected tool"""
self.options_tool = tool
if tool in DrawCanvas.TOOLS[0]:
self.pointer_tool = tool
# Reset all tools
for tool in DrawCanvas.TOOL_RESET:
for option, val in DrawCanvas.TOOL_RESET[tool].items():
self.option_vals[tool][option] = val
class SymbolSelect(TextGrid):
""" Provide text grid with symbol selection functionality """
def __init__(self, wm, symbols):
super().__init__(wm, config={"scroll_h": False})
self.active_row = 0
self.active_col = 0
pos = 0
for sym_set in symbols:
for sym_idx in range(*sym_set):
self.plot(pos % 20, pos // 20, bytes(chr(sym_idx), "utf8"), [15, 0, 0])
pos += 1
self.select_symbol(0, 0)
def grid_event(self, size, event, button, col, row, focus):
""" Process mouse events """
if int(button) == 1:
# Check symbol was clicked
if row < len(self.content[0]) and col < len(self.content[0][0]):
self.select_symbol(col, row)
def select_symbol(self, col, row):
""" Select symbol from grid """
self.attrs[0][self.active_row][self.active_col] = [15, 0, 0]
self.attrs[0][row][col] = [0, 6, 0]
self.active_row, self.active_col = row, col
self._invalidate()
self.wm.get("canvas", True).active_symbol = self.content[0][row][col]
class TextArea(TextGrid):
""" Provide text grid with printed text functionality """
def __init__(self, wm, text, attr, width):
super().__init__(wm, config={"scroll_h": False})
self.width = width
self.set_text(text, attr)
def set_text(self, text, attr):
""" Plot text on grid """
# Set background color
self.config["back_attrs"] = attr
row = 0
col = 0
for char_idx in range(len(text)):
if text[char_idx] == "\n" or col >= self.width or self.wrap_word(col, text[char_idx:]):
col = 0
row += 1
if text[char_idx] != "\n":
self.plot(col, row, bytes(text[char_idx], "utf8"), attr)
col += 1
def wrap_word(self, col, remaining):
""" Detect if word needs to be wrapped """
next_space = remaining.find(" ")
if next_space == -1:
return False
else:
return col + next_space >= self.width
class ColorSelect(urwid.SolidFill):
""" Provide foreground/background color selection functionality """
class ColorButton(urwid.SolidFill):
""" Provide color selection button functionality """
def __init__(self, parent, color):
super().__init__()
self.parent = parent
self.color = color
def mouse_event(self, size, event, button, col, row, focus):
""" Process mouse events """
self.parent.set_color(self.color)
self.parent.wm.deactivate_overlay()
def __init__(self, wm, canvas, color, select):
super().__init__(b" ")
self.wm = wm
self.canvas = canvas
self.color = color
self.select = select
self.palette_id = "palette_{}".format(self.select)
self.wm.get(self.canvas, True).active_attrs[self.select] = self.color
self.setup_widgets()
def setup_widgets(self):
""" Setup color button widgets """
for color in range(16):
color_id = "{0}-{0}".format(self.wm.get_color_name(color))
button_name = "{}_button_{}".format(self.palette_id, color)
self.wm.register(button_name, urwid.BoxAdapter(self.ColorButton(self, color), 2), color_id)
self.wm.group_add("{}_buttons".format(self.palette_id), self.wm[button_name])
self.wm["{}_grid".format(self.palette_id)] = urwid.GridFlow(self.wm.group_get("{}_buttons".format(self.palette_id)), 4, 1, 1, "center")
self.wm["{}_filler".format(self.palette_id)] = urwid.Filler(self.wm["{}_grid".format(self.palette_id)], height="pack")
self.wm["{}_box".format(self.palette_id)] = urwid.LineBox(self.wm["{}_filler".format(self.palette_id)], "Select Color", title_align="left")
self.wm["{}_overlay".format(self.palette_id)] = urwid.Overlay(self.wm["{}_box".format(self.palette_id)], self.wm[self.canvas], align="center", width=44, valign="middle", height=9)
def set_color(self, color):
""" Set active color """
self.color = color
self.wm.get(self.canvas, True).active_attrs[self.select] = self.color
self._invalidate()
def mouse_event(self, size, event, button, col, row, focus):
""" Process mouse events """
if button == 1:
self.wm.activate_overlay("{}_overlay".format(self.palette_id))
def render(self, size, focus=False):
""" Render color buttons """
canvas = urwid.CompositeCanvas(super().render(size, focus))
canvas.fill_attr("{0}-{0}".format(self.wm.get_color_name(self.color)))
return canvas
class DialogBox(urwid.Overlay):
""" Provide customizable dialog box functionality """
FIELD_DEFAULTS = {"width": 60, "height": 14, "msg": "", "buttons": None, "edit": None, "scroll": None, "align": "left", "space": 4}
def __init__(self, name, wm, canvas, handler, config):