-
Notifications
You must be signed in to change notification settings - Fork 14
/
abacus_window.py
1722 lines (1517 loc) · 63.5 KB
/
abacus_window.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
# -*- coding: utf-8 -*-
# Copyright 2010-13, Walter Bender
# Copyright 2010, Tuukka Hastrup
# This file is part of the Abacus Activity.
# The Abacus Activity is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# The Abacus Activity 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 General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with the Abacus Activity. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gdk, GdkPixbuf
from math import floor, ceil
import locale
import traceback
import logging
_logger = logging.getLogger('abacus-activity')
try:
from sugar3.graphics import style
GRID_CELL_SIZE = style.GRID_CELL_SIZE
except ImportError:
GRID_CELL_SIZE = 0
from sprites import Sprites, Sprite
INSTANCE = 0
CLASS = 1
MAX_RODS = 18
MAX_TOP = 4
MAX_BOT = 14
MAX_BEADS = MAX_RODS * (MAX_TOP + MAX_BOT)
BEAD_WIDTH = 40
BEAD_HEIGHT = 30
BEAD_OFFSET = 10
FRAME_STROKE_WIDTH = 45
FRAME_LAYER = 100
ROD_LAYER = 101
BEAD_LAYER = 102
BAR_LAYER = 103
DOT_LAYER = 104
MARK_LAYER = 105
MAX_FADE_LEVEL = 3
CURSOR = '█'
ROD_COLORS = ['#282828', '#A0A0A0', '#282828', '#A0A0A0', '#282828',
'#A0A0A0', '#282828', '#A0A0A0', '#282828', '#A0A0A0',
'#282828', '#A0A0A0', '#282828', '#A0A0A0', '#282828']
COLORS = ('#FFFFFF', '#FF0000', '#88FF00', '#FF00FF', '#FFFF00',
'#00CC00', '#000000', '#AA6600', '#00CCFF', '#FF8800')
LABELS = ('#000000', '#FFFFFF', '#000000', '#FFFFFF', '#000000',
'#000000', '#FFFFFF', '#FFFFFF', '#000000', '#000000')
WHITE_BEADS = []
COLOR_BEADS = []
BLACK_BEAD = None
ROD_BEADS = []
KEYS_1 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'period',
'minus', 'Return', 'BackSpace', 'comma']
KEYS_2 = {'KP_7': '7', 'KP_8': '8',
'KP_9': '9', 'KP_4': '4',
'KP_5': '5', 'KP_6': '6',
'KP_1': '1', 'KP_2': '2',
'KP_3': '3', 'KP_0': '0'}
def make_bead_pixbufs(scale, bead_scale=1.0):
global WHITE_BEADS
global COLOR_BEADS
global BLACK_BEAD
global ROD_BEADS
for i in range(MAX_FADE_LEVEL + 1):
fade = _calc_fade('#FFFFFF', '#FFFF00', i, MAX_FADE_LEVEL)
WHITE_BEADS.append(_svg_str_to_pixbuf(
_svg_header(BEAD_WIDTH, BEAD_HEIGHT, scale,
stretch=bead_scale) +
_svg_bead(fade, '#000000', stretch=bead_scale) +
_svg_footer()))
fade = _calc_fade('#FFFFFF', '#FFFFFF', i, MAX_FADE_LEVEL)
WHITE_BEADS.append(_svg_str_to_pixbuf(
_svg_header(BEAD_WIDTH, BEAD_HEIGHT, scale,
stretch=bead_scale) +
_svg_bead(fade, '#000000', stretch=bead_scale) +
_svg_footer()))
BLACK_BEAD = _svg_str_to_pixbuf(
_svg_header(BEAD_WIDTH, BEAD_HEIGHT, scale,
stretch=bead_scale) +
_svg_bead('#000000', '#000000', stretch=bead_scale) +
_svg_footer())
for i in range(len(COLORS)):
COLOR_BEADS.append(_svg_str_to_pixbuf(
_svg_header(BEAD_WIDTH, BEAD_HEIGHT, scale,
stretch=bead_scale) +
_svg_bead(COLORS[i], '#000000', stretch=bead_scale) +
_svg_footer()))
rod_scale = 10.0 / (i + 1)
ROD_BEADS.append(_svg_str_to_pixbuf(
_svg_header(BEAD_WIDTH, BEAD_HEIGHT, scale,
stretch=rod_scale) +
_svg_bead(COLORS[i], '#000000', stretch=rod_scale) +
_svg_footer()))
def dec2frac(d):
''' Convert float to its approximate fractional representation. '''
'''
This code was translated to Python from the answers at
http://stackoverflow.com/questions/95727/how-to-convert-floats-to-human-\
readable-fractions/681534#681534
For example:
>>> 3./5
0.59999999999999998
>>> dec2frac(3./5)
"3/5"
'''
if d > 1:
return '%s' % d
df = 1.0
top = 1
bot = 1
while abs(df - d) > 0.00000001:
if df < d:
top += 1
else:
bot += 1
top = int(d * bot)
df = float(top) / bot
if bot == 1:
return '%s' % top
elif top == 0:
return ''
return '%s/%s' % (top, bot)
#
# Utilities for generating artwork as SVG
#
def _svg_str_to_pixbuf(svg_string):
''' Load pixbuf from SVG string '''
if type(svg_string) is str:
svg_string = svg_string.encode()
pl = GdkPixbuf.PixbufLoader.new_with_type('svg')
pl.write(svg_string)
pl.close()
pixbuf = pl.get_pixbuf()
return pixbuf
def _svg_circle(r, cx, cy, fill, stroke):
''' Returns an SVG circle '''
svg_string = ' <circle\n'
svg_string += ' r="%f"\n' % (r)
svg_string += ' cx="%f"\n' % (cx)
svg_string += ' cy="%f"\n' % (cy)
svg_string += _svg_style('fill:%s;stroke:%s;' % (fill, stroke))
return svg_string
def _svg_rect(w, h, rx, ry, x, y, fill, stroke):
''' Returns an SVG rectangle '''
svg_string = ' <rect\n'
svg_string += ' width="%f"\n' % (w)
svg_string += ' height="%f"\n' % (h)
svg_string += ' rx="%f"\n' % (rx)
svg_string += ' ry="%f"\n' % (ry)
svg_string += ' x="%f"\n' % (x)
svg_string += ' y="%f"\n' % (y)
svg_string += _svg_style('fill:%s;stroke:%s;' % (fill, stroke))
return svg_string
def _svg_indicator():
''' Returns a wedge-shaped indicator as SVG '''
svg_string = '%s %s' % ('<path d="m1.5 1.5 L 18.5 1.5 L 10 13.5 L 1.5',
'1.5 z"\n')
svg_string += _svg_style('fill:#ff0000;stroke:#ff0000;stroke-width:3.0;')
return svg_string
def _svg_bead(fill, stroke, stretch=1.0):
''' Returns a bead-shaped SVG object; scale is used to elongate '''
h = 15 + 30 * (stretch - 1.0)
h2 = 30 * stretch - 1.5
svg_string = '<path d="m 1.5 15 A 15 13.5 90 0 1 15 1.5 L 25 1.5 A 15 \
13.5 90 0 1 38.5 15 L 38.5 %f A 15 13.5 90 0 1 25 %f L 15 %f A 15 13.5 90 0 \
1 1.5 %f L 1.5 15 z"\n' % (h, h2, h2, h)
svg_string += _svg_style('fill:%s;stroke:%s;stroke-width:1.5' %
(fill, stroke))
return svg_string
def _svg_header(w, h, scale, stretch=1.0):
''' Returns SVG header; some beads are elongated (stretch) '''
svg_string = '<?xml version="1.0" encoding="UTF-8"'
svg_string += ' standalone="no"?>\n'
svg_string += '<!-- Created with Python -->\n'
svg_string += '<svg\n'
svg_string += ' xmlns:svg="http://www.w3.org/2000/svg"\n'
svg_string += ' xmlns="http://www.w3.org/2000/svg"\n'
svg_string += ' version="1.0"\n'
svg_string += '%s%f%s' % (' width="', w * scale, '"\n')
svg_string += '%s%f%s' % (' height="', h * scale * stretch, '">\n')
svg_string += '%s%f%s%f%s' % ('<g\n transform="matrix(',
scale, ', 0, 0,', scale, ',0,0)">\n')
return svg_string
def _svg_footer():
''' Returns SVG footer '''
svg_string = '</g>\n'
svg_string += '</svg>\n'
return svg_string
def _svg_style(extras=''):
''' Returns SVG style for shape rendering '''
return '%s%s%s' % ('style="', extras, '"/>\n')
def _calc_fade(bead_color, fade_color, i, n):
''' Fade from bead color to fade color '''
r = i * float.fromhex('0x' + fade_color[1:3]) / n + \
(n - i) * float.fromhex('0x' + bead_color[1:3]) / n
g = i * float.fromhex('0x' + fade_color[3:5]) / n + \
(n - i) * float.fromhex('0x' + bead_color[3:5]) / n
b = i * float.fromhex('0x' + fade_color[5:]) / n + \
(n - i) * float.fromhex('0x' + bead_color[5:]) / n
return '#%02x%02x%02x' % (int(r), int(g), int(b))
class Bead():
''' The Bead class is used to define the individual beads. '''
def __init__(self):
self.spr = None
self.state = 0
self.fade_level = 0
self.value = 0
self.offset = 0
def update(self, sprites, pixbuf, offset, value, max_fade=MAX_FADE_LEVEL,
tristate=False):
''' We store a sprite, an offset, and a value for each bead. '''
if self.spr is None:
self.spr = Sprite(sprites, 0, 0, pixbuf)
else:
self.spr.set_image(pixbuf)
self.spr.set_label('')
self.spr.set_label_color('black')
self.offset = offset
# Decimals will be converted to fractions;
# and we want to avoid decimal points in our whole numbers.
if value < 1:
self.value = value
else:
self.value = int(value)
self.state = 0
self.spr.type = 'bead'
self.fade_level = 0 # Used for changing color.
self.max_fade_level = max_fade
self.tristate = tristate # Beads can be +/- or off.
def hide(self):
''' Hide the sprite associated with the bead. '''
if self.spr is not None:
self.spr.hide()
def show(self):
''' Show the sprite associated with the bead. '''
if self.spr is not None:
self.spr.set_layer(BEAD_LAYER)
def move(self, offset, move_the_bead=True):
''' Generic move method: sets state and level. '''
if self.spr is None:
return
if move_the_bead:
self.spr.move_relative((0, offset))
if not self.tristate:
self.state = 1 - self.state
elif self.state == 1: # moving bead back to center
self.state = 0
elif self.state == -1: # moving bead back to center
self.state = 0
else: # bead is in the center
if offset > 0: # moving bead down to bottom
self.state = -1
else: # moving bead up to top
self.state = 1
self.set_fade_level(self.max_fade_level)
self.update_label()
def move_up(self):
''' Move a bead up as far as it will go. '''
self.move(-self.offset)
def move_down(self):
''' Move a bead down as far as it will go. '''
self.move(self.offset)
def get_value(self):
''' Return a value based upon bead state. '''
return self.state * self.value
def get_state(self):
''' Is the bead active? '''
return self.state
def set_color(self, color):
''' Set the color of the bead. '''
if self.spr is None:
return
self.spr.set_image(color)
self.spr.inval()
self.show()
def set_label_color(self, color):
''' Set the label color for a bead (default is black). '''
if self.spr is None:
return
self.spr.set_label_color(color)
def get_fade_level(self):
''' Return color fade level of bead. '''
return self.fade_level
def set_fade_level(self, fade_level):
''' Set color fade level of bead. '''
self.fade_level = fade_level
def update_label(self):
''' Label active beads. '''
if self.spr is None:
return
value = self.get_value()
if self.state == 1 and value < 10000 and value > 0.05:
value = self.get_value()
if value < 1:
self.spr.set_label(dec2frac(value))
else:
self.spr.set_label(int(value))
elif self.state == -1 and value > -10000 and value < -0.05:
value = self.get_value()
if value > -1:
self.spr.set_label('–' + dec2frac(-value))
else:
self.spr.set_label(int(value))
else:
self.spr.set_label('')
class Rod():
''' The Rod class is used to define a rod to hold beads. '''
def __init__(self, beads):
''' We store a sprite for each rod and allocate its beads. '''
self.spr = None
self.label = None
self.beads = beads
def update(self, sprites, color, frame_height, i, x, y, scale,
bead_count, bead_color, cuisenaire=False):
self._bead_count = bead_count
self.sprites = sprites
rod = _svg_header(10, frame_height - (FRAME_STROKE_WIDTH * 2),
scale) + \
_svg_rect(10, frame_height - (FRAME_STROKE_WIDTH * 2),
0, 0, 0, 0, color, '#404040') + \
_svg_footer()
self.index = i
self.scale = scale
if self.spr is None:
self.spr = Sprite(sprites, x, y, _svg_str_to_pixbuf(rod))
else:
self.spr.set_image(_svg_str_to_pixbuf(rod))
self.spr.move((x, y))
self.spr.type = 'frame'
self.lozenge = False
if cuisenaire:
self.lozenge = True
bo = (BEAD_WIDTH - BEAD_OFFSET) * self.scale / 2
if self.label is None:
self.label = Sprite(
self.sprites, x - bo, y + self.spr.rect[3],
_svg_str_to_pixbuf(
_svg_header(BEAD_WIDTH, BEAD_HEIGHT, self.scale,
stretch=1.0) +
_svg_rect(BEAD_WIDTH, BEAD_HEIGHT, 0, 0, 0, 0,
'none', 'none') +
_svg_footer()))
else:
self.label.move((x - bo, y + self.spr.rect[3]))
self.label.type = 'frame'
self.label.set_label_color('white')
self.label.set_layer(MARK_LAYER)
def allocate_beads(self, top_beads, bot_beads, top_factor,
bead_value, bot_size, color=False, middle_black=False,
all_black=False, tristate=False):
''' Beads get allocated per rod '''
global WHITE_BEADS
global COLOR_BEADS
global BLACK_BEAD
global ROD_BEADS
self.top_beads = top_beads # number of beads above the bar
self.bot_beads = bot_beads # number of beads below the bar
# number of beads that could fit might not match number of beads
# (e.g., Schety)
self.bot_size = bot_size
# top bead value == bead value * top factor
self.top_factor = top_factor
self.fade = False
x = self.spr.rect[0]
y = self.spr.rect[1]
bo = (BEAD_WIDTH - BEAD_OFFSET) * self.scale / 4
ro = (BEAD_WIDTH + 5) * self.scale / 2
# how far this bead moves
bead_displacement = 2 * BEAD_HEIGHT * self.scale
if self.lozenge:
bead_color = ROD_BEADS[self.index]
elif color:
bead_color = COLOR_BEADS[self.index]
elif all_black:
bead_color = BLACK_BEAD
elif middle_black: # special patterning for Schety
if bot_beads == self.bot_size:
middle = [4, 5]
else:
middle = [1, 2]
else:
bead_color = WHITE_BEADS[0]
self.fade = True
if self.fade:
max_fade_level = MAX_FADE_LEVEL
else:
max_fade_level = 0
for i in range(top_beads):
self.beads[i + self._bead_count].update(
self.sprites, bead_color, bead_displacement,
top_factor * bead_value, max_fade=max_fade_level)
self.beads[i + self._bead_count].spr.move(
(x - ro + bo, y + i * BEAD_HEIGHT * self.scale))
for i in range(bot_beads):
displacement = bead_displacement
if top_beads > 0:
yy = y + (top_beads + 5 + i) * BEAD_HEIGHT * self.scale
else:
yy = y + (2 + i) * BEAD_HEIGHT * self.scale
if all_black:
bead_color = BLACK_BEAD
elif middle_black:
if i in middle:
bead_color = BLACK_BEAD
else:
bead_color = WHITE_BEADS[0]
elif not color:
bead_color = WHITE_BEADS[0]
# short row
if not self.lozenge and (self.bot_beads < self.bot_size):
offset = (self.bot_size - self.bot_beads) * BEAD_HEIGHT * \
self.scale
yy += offset
displacement += offset
# center tristate beads vertically on the rod
if tristate:
if self.lozenge:
offset = BEAD_HEIGHT * self.scale
else:
offset = (self.bot_size - self.bot_beads + 2) * \
BEAD_HEIGHT * self.scale / 2
yy -= offset
displacement -= offset
self.beads[i + self._bead_count + top_beads].update(
self.sprites, bead_color, displacement,
bead_value, tristate=tristate, max_fade=max_fade_level)
self.beads[i + self._bead_count + top_beads].spr.move(
(x - ro + bo, yy))
if bead_color == BLACK_BEAD:
self.beads[i + self._bead_count + top_beads].set_label_color(
'#ffffff')
# Lozenged-shaped beads need to be spaced out more
j = i + self._bead_count + top_beads
if self.beads[j].spr.rect[3] > BEAD_HEIGHT * self.scale:
self.beads[j].spr.move_relative(
(0, i * (self.beads[j].spr.rect[3] -
(BEAD_HEIGHT * self.scale))))
# self._bead_count -= (self.top_beads + self.bot_beads)
if color:
for i in range(self.top_beads + self.bot_beads):
self.beads[i + self._bead_count].set_label_color(
LABELS[self.index])
def hide(self):
if self.spr is None:
return
for i in range(self.top_beads + self.bot_beads):
self.beads[i + self._bead_count].hide()
self.spr.hide()
self.label.hide()
def show(self):
if self.spr is None:
return
for i in range(self.top_beads + self.bot_beads):
self.beads[i + self._bead_count].show()
self.spr.set_layer(ROD_LAYER)
self.label.set_layer(MARK_LAYER)
def get_max_value(self):
''' Returns maximum numeric value for this rod '''
if self.spr is None:
return 0
max = 0
for i in range(self.top_beads + self.bot_beads):
max += self.beads[i + self._bead_count].value
return max
def get_value(self):
if self.spr is None:
return 0
sum = 0
for i in range(self.top_beads + self.bot_beads):
sum += self.beads[i + self._bead_count].get_value()
return sum
def get_bead_count(self):
''' Returns number of active bottom-bead equivalents on this rod'''
if self.spr is None:
return 0
count = 0
for i in range(self.top_beads + self.bot_beads):
if self.beads[i + self._bead_count].get_state() == 1:
if i < self.top_beads:
count += self.top_factor
else:
count += 1
if self.beads[i + self._bead_count].get_state() == -1:
count -= 1
return count
def set_number(self, number):
''' Try to set a value equal to number; return any remainder '''
if self.spr is None:
return 0
count = 0
for i in range(self.top_beads + self.bot_beads):
if number >= self.beads[i + self._bead_count].value:
number -= self.beads[i + self._bead_count].value
if i < self.top_beads:
count += self.top_factor
else:
count += 1
self.set_value(count)
return number
def set_value(self, value):
''' Move beads to represent a numeric value '''
if self.spr is None:
return
if self.top_beads > 0:
bot = value % self.top_factor
top = (value - bot) // self.top_factor
else:
bot = value
top = 0
self.reset()
# Set the top.
for i in range(top):
self.beads[self._bead_count + self.top_beads - i - 1].move_down()
# Set the bottom
for i in range(bot):
self.beads[self._bead_count + self.top_beads + i].move_up()
if value > 0:
self.set_label(self.get_bead_count())
else:
self.label.set_label('')
def reset(self):
if self.spr is None:
return
# Clear the top.
for i in range(self.top_beads):
if self.beads[i + self._bead_count].get_state() == 1:
self.beads[i + self._bead_count].move_up()
# Clear the bottom.
for i in range(self.bot_beads):
if self.beads[self.top_beads + i + self._bead_count].get_state() \
== 1:
self.beads[self.top_beads + i + self._bead_count].move_down()
# Fade beads
for i in range(self.top_beads + self.bot_beads):
if self.beads[self._bead_count + i].fade_level > 0:
self.beads[self._bead_count + i].fade_level = 0
self.beads[self._bead_count + i].set_color(WHITE_BEADS[0])
self.label.set_label('')
def fade_colors(self):
''' Reduce the saturation level of every bead. '''
if self.spr is None:
return
if self.fade:
for i in range(self.top_beads + self.bot_beads):
j = self._bead_count + i
if self.beads[j].get_fade_level() > 0:
self.beads[j].set_color(
WHITE_BEADS[self.beads[j].get_fade_level() - 1])
self.beads[j].set_fade_level(
self.beads[j].get_fade_level() - 1)
def move_bead(self, sprite, dy):
''' Move a bead (or beads) up or down a rod. '''
if self.spr is None:
return False
# Find the bead associated with the sprite.
i = -1
for j in range(self.top_beads + self.bot_beads):
if sprite == self.beads[self._bead_count + j].spr:
i = j
break
if i == -1:
return False
if self.fade and self.beads[self._bead_count + i].max_fade_level > 0:
self.beads[self._bead_count + i].set_color(WHITE_BEADS[3])
if i < self.top_beads:
if dy > 0 and self.beads[self._bead_count + i].get_state() == 0:
self.beads[self._bead_count + i].move_down()
# Make sure beads below this bead are also moved.
for ii in range(self.top_beads - i):
if self.beads[self._bead_count + i + ii].state == 0:
if self.fade and \
self.beads[self._bead_count + i].max_fade_level > 0:
self.beads[self._bead_count + i + ii].set_color(
WHITE_BEADS[3])
self.beads[self._bead_count + i + ii].move_down()
elif dy < 0 and self.beads[self._bead_count + i].state == 1:
self.beads[self._bead_count + i].move_up()
# Make sure beads above this bead are also moved.
for ii in range(i + 1):
if self.beads[self._bead_count + i - ii].state == 1:
if self.fade and \
self.beads[self._bead_count + i].max_fade_level > 0:
self.beads[self._bead_count + i - ii].set_color(
WHITE_BEADS[3])
self.beads[self._bead_count + i - ii].move_up()
else:
if dy < 0 and self.beads[self._bead_count + i].state == 0:
self.beads[self._bead_count + i].move_up()
# Make sure beads above this bead are also moved.
for ii in range(i - self.top_beads + 1):
if self.beads[self._bead_count + i - ii].state == 0:
if self.fade and \
self.beads[self._bead_count + i].max_fade_level > 0:
self.beads[self._bead_count + i - ii].set_color(
WHITE_BEADS[3])
self.beads[self._bead_count + i - ii].move_up()
elif dy < 0 and self.beads[self._bead_count + i].state == -1:
self.beads[self._bead_count + i].move_up()
for ii in range(i - self.top_beads + 1):
if self.beads[self._bead_count + i - ii].state == -1:
if self.fade and \
self.beads[self._bead_count + i].max_fade_level > 0:
self.beads[self._bead_count + i - ii].set_color(
WHITE_BEADS[3])
self.beads[self._bead_count + i - ii].move_up()
elif dy > 0 and self.beads[self._bead_count + i].state == 1:
self.beads[self._bead_count + i].move_down()
# Make sure beads below this bead are also moved.
for ii in range(self.top_beads + self.bot_beads - i):
if self.beads[self._bead_count + i + ii].state == 1:
if self.fade and \
self.beads[self._bead_count + i].max_fade_level > 0:
self.beads[self._bead_count + i + ii].set_color(
WHITE_BEADS[3])
self.beads[self._bead_count + i + ii].move_down()
elif dy > 0 and self.beads[self._bead_count + i].state == 0 and \
self.beads[self._bead_count + i].tristate:
self.beads[self._bead_count + i].move_down()
# Make sure beads below this bead are also moved.
for ii in range(self.top_beads + self.bot_beads - i):
if self.beads[self._bead_count + i + ii].state == 0:
if self.fade and \
self.beads[self._bead_count + i].max_fade_level > 0:
self.beads[self._bead_count + i + ii].set_color(
WHITE_BEADS[3])
self.beads[self._bead_count + i + ii].move_down()
self.set_label(self.get_bead_count())
def set_label(self, n):
''' Different abaci use different labeling schemes. '''
if self.spr is None:
return
# Use hex notation on hex abacus
if self.top_beads == 1 and self.bot_beads == 7 and \
self.top_factor == 8:
self.label.set_label('%x' % int(n))
# Only show 0 on binary abacus
elif n == 0 and not (self.top_beads == 0 and self.bot_beads == 1):
self.label.set_label('')
else:
self.label.set_label(n)
return
class Abacus():
''' The Abacus class is used to define the user interaction. '''
def __init__(self, canvas, parent=None):
''' Initialize the canvas and set up the callbacks. '''
self.activity = parent
if parent is None: # Starting from command line
self.sugar = False
self.canvas = canvas
self.bead_colors = ['#FFFFFF', '#FFFFFF']
else: # Starting from Sugar
self.sugar = True
self.canvas = canvas
self.bead_colors = parent.bead_colors
parent.show_all()
self.canvas.set_can_focus(True)
self.canvas.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
self.canvas.add_events(Gdk.EventMask.BUTTON_RELEASE_MASK)
self.canvas.add_events(Gdk.EventMask.POINTER_MOTION_MASK)
self.canvas.connect('draw', self.__draw_cb)
self.canvas.connect('button-press-event', self._button_press_cb)
self.canvas.connect('button-release-event', self._button_release_cb)
self.canvas.connect('motion-notify-event', self._mouse_move_cb)
self.canvas.connect('key_press_event', self._keypress_cb)
Gdk.Screen.get_default().connect('size-changed', self._configure_cb)
self.width = Gdk.Screen.width()
self.height = Gdk.Screen.height() - GRID_CELL_SIZE
self.sprites = Sprites(self.canvas)
self.sprites.set_delay(True)
self.scale = 1.33 * Gdk.Screen.height() / 900.0
self.dragpos = 0
self.press = None
self.last = None
try:
locale.setlocale(locale.LC_NUMERIC, '')
except locale.Error: # doesn't matter if $LANG invalid
pass
self.decimal_point = locale.localeconv()['decimal_point']
if self.decimal_point == '' or self.decimal_point is None:
self.decimal_point = '.'
size = max(self.width, self.height)
background_svg = _svg_header(size, size, 1.0) + \
_svg_rect(size, size, 0, 0, 0, 0, '#FFFFFF', '#FFFFFF') + \
_svg_footer()
background = Sprite(self.sprites, 0, 0,
_svg_str_to_pixbuf(background_svg))
background.set_layer(1)
# Only generate bead pixbufs once
make_bead_pixbufs(self.scale)
self.decimal = None
self.soroban = None
self.suanpan = None
self.nepohualtzintzin = None
self.hexadecimal = None
self.binary = None
self.russian = None
self.fraction = None
self.caacupe = None
self.cuisenaire = None
self.custom = None
# name: [INSTANCE, CLASS]
self.mode_dict = {'decimal': [self.decimal, Decimal],
'soroban': [self.soroban, Soroban],
'suanpan': [self.suanpan, Suanpan],
'nepohualtzintzin': [self.nepohualtzintzin,
Nepohualtzintzin],
'hexadecimal': [self.hexadecimal, Hexadecimal],
'binary': [self.binary, Binary],
'schety': [self.russian, Schety],
'fraction': [self.fraction, Fractions],
'caacupe': [self.caacupe, Caacupe],
'cuisenaire': [self.cuisenaire, Cuisenaire],
'custom': [self.custom, Custom]
}
self.bead_cache = []
for i in range(MAX_BEADS):
self.bead_cache.append(Bead())
self.rod_cache = []
for i in range(MAX_BEADS):
self.rod_cache.append(Rod(self.bead_cache))
self.suanpan = Suanpan(self, self.bead_colors)
self.mode = self.suanpan
self.mode.show()
self._configure_cb(None)
def _configure_cb(self, event):
self.width = Gdk.Screen.width()
self.height = Gdk.Screen.height() - GRID_CELL_SIZE
if self.width > self.height:
self.scale = 1.33 * Gdk.Screen.height() / 900.0
else:
self.scale = 1.33 * Gdk.Screen.width() / 1200.0
if self.sugar:
if Gdk.Screen.width() / 14 < style.GRID_CELL_SIZE:
for sep in self.activity.sep:
sep.hide()
sep.props.draw = False
else:
for sep in self.activity.sep:
sep.show()
sep.props.draw = True
self.canvas.set_size_request(self.width, self.height)
def select_abacus(self, abacus):
if self.mode == self.mode_dict[abacus][INSTANCE]:
_logger.debug('abacus_window: %s already select' % abacus)
return
self.mode.hide()
_logger.debug('abacus_window: selecting %s' % abacus)
if self.mode_dict[abacus][INSTANCE] is None:
_logger.debug('creating new instance')
self.mode_dict[abacus][INSTANCE] = \
self.mode_dict[abacus][CLASS](self, self.bead_colors)
else:
_logger.debug('restoring old instance')
self.mode_dict[abacus][INSTANCE].draw_rods_and_beads()
self.mode = self.mode_dict[abacus][INSTANCE]
self.mode.show()
self.mode.label(self.generate_label())
def _button_press_cb(self, win, event):
''' Callback to handle the button presses '''
win.grab_focus()
x, y = list(map(int, event.get_coords()))
self.press = self.sprites.find_sprite((x, y))
self.last = self.press
if self.press is not None:
if self.press.type == 'bead':
self.dragpos = y
elif self.press.type == 'mark':
self.dragpos = x
elif self.press == self.mode.label_bar:
self.mode.label(self.generate_label(sum_only=True) + CURSOR)
number = self.press.labels[0].replace(CURSOR, '')
if '/' in number: # need to convert to decimal form
try:
userdefined = {}
exec('def f(): return ' + number.replace(' ', '+') +
'.', globals(), userdefined)
value = list(userdefined.values())[0]()
number = str(value)
self.press.set_label(
number.replace('.', self.decimal_point) + CURSOR)
except BaseException:
traceback.print_exc()
number = ''
self.press = None
else:
self.press = None
return True
def _mouse_move_cb(self, win, event):
''' Callback to handle the mouse moves '''
if self.press is None:
self.dragpos = 0
return True
win.grab_focus()
x, y = list(map(int, event.get_coords()))
if self.press.type == 'mark':
mx, my = self.mode.mark.get_xy()
self.mode.move_mark(x - mx)
return True
def _button_release_cb(self, win, event):
''' Callback to handle the button releases '''
if self.press is None:
self.dragpos = 0
return True
win.grab_focus()
x, y = list(map(int, event.get_coords()))
if self.press.type == 'bead':
self.mode.move_bead(self.press, y - self.dragpos)
self.press = None
self.mode.label(self.generate_label())
return True
def _keypress_cb(self, area, event):
''' Keypress: moving the slides with the arrow keys '''
k = Gdk.keyval_name(event.keyval)
if k in KEYS_1 or k in KEYS_2.keys():
if self.last == self.mode.label_bar:
self._process_numeric_input(self.last, k)
elif k == 'r':
self.mode.reset_abacus()
return True
def _process_numeric_input(self, sprite, keyname):
''' Make sure numeric input is valid. '''
oldnum = sprite.labels[0].replace(CURSOR, '')
newnum = oldnum
if len(oldnum) == 0:
oldnum = '0'
if keyname == 'minus':
if oldnum == '0':
newnum = '-'
elif oldnum[0] != '-':
newnum = '-' + oldnum
else:
newnum = oldnum
elif keyname == 'comma' and self.decimal_point == ',' and \
',' not in oldnum:
newnum = oldnum + ','
elif keyname == 'period' and self.decimal_point == '.' and \
'.' not in oldnum:
newnum = oldnum + '.'
elif keyname == 'BackSpace':
if len(oldnum) > 0:
newnum = oldnum[:len(oldnum) - 1]
else:
newnum = ''
elif keyname in [str(x) for x in range(10)]:
if oldnum == '0':
newnum = keyname
else:
newnum = oldnum + keyname
elif keyname in KEYS_2.keys():
if oldnum == '0':
newnum = KEYS_2[keyname]
else:
newnum = oldnum + KEYS_2[keyname]
elif keyname == 'Return':
self.mode.reset_abacus()
self.mode.set_value_from_number(
float(newnum.replace(self.decimal_point, '.')))
self.mode.label(self.generate_label())
return
else:
newnum = oldnum
if newnum == '.':
newnum = '0.'
if len(newnum) > 0 and newnum != '-':
try:
float(newnum.replace(self.decimal_point, '.'))
except ValueError as e:
_logger.debug('Error converting numeric input %s: %s' %
(str(newnum), e))
newnum = oldnum
sprite.set_label(newnum + CURSOR)
# Handle the expose-event by drawing
def __draw_cb(self, canvas, cr):
self.sprites.redraw_sprites(cr=cr)