forked from sugarlabs/turtleart-activity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TurtleArtActivity.py
1837 lines (1625 loc) · 75 KB
/
TurtleArtActivity.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 (c) 2007, Playful Invention Company
#Copyright (c) 2008-14, Walter Bender
#Copyright (c) 2009-13 Raul Gutierrez Segales
#Copyright (c) 2012 Alan Aguiar
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:
#The above copyright notice and this permission notice shall be included in
#all copies or substantial portions of the Software.
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#THE SOFTWARE.
import pygtk
pygtk.require('2.0')
import gtk
import cairo
import gobject
import dbus
import logging
_logger = logging.getLogger('turtleart-activity')
from sugar.activity import activity
try: # 0.86 toolbar widgets
from sugar.activity.widgets import (ActivityToolbarButton, StopButton)
from sugar.graphics.toolbarbox import (ToolbarBox, ToolbarButton)
HAS_TOOLBARBOX = True
except ImportError:
HAS_TOOLBARBOX = False
from sugar.graphics.toolbutton import ToolButton
from sugar.graphics.radiotoolbutton import RadioToolButton
from sugar.graphics.alert import (ConfirmationAlert, Alert)
from sugar.graphics import style
from sugar.graphics.icon import Icon
from sugar.graphics.xocolor import XoColor
from sugar.datastore import datastore
from sugar import profile
import os
import glob
import tarfile
import subprocess
import ConfigParser
import shutil
import tempfile
try:
import gconf
HAS_GCONF = True
except ImportError:
HAS_GCONF = False
from gettext import gettext as _
from TurtleArt.taplugin import (load_a_plugin, cancel_plugin_install,
complete_plugin_install)
from TurtleArt.tapalette import (palette_names, help_strings, help_palettes,
help_windows, default_values)
from TurtleArt.taconstants import (BLOCK_SCALE, XO1, XO15, XO175, XO4,
MIMETYPE, TMP_SVG_PATH, TMP_ODP_PATH,
PASTE_OFFSET)
from TurtleArt.taexportlogo import save_logo
from TurtleArt.taexportpython import save_python
from TurtleArt.tautils import (data_to_file, data_to_string, data_from_string,
get_path, chooser_dialog, get_hardware)
from TurtleArt.tawindow import TurtleArtWindow
from TurtleArt.tacollaboration import Collaboration
from TurtleArt.taprimitive import PyExportError
if HAS_TOOLBARBOX:
from util.helpbutton import (HelpButton, add_section, add_paragraph)
class TurtleArtActivity(activity.Activity):
''' Activity subclass for Turtle Art '''
_HOVER_HELP = '/desktop/sugar/activities/turtleart/hoverhelp'
_ORIENTATION = '/desktop/sugar/activities/turtleart/orientation'
_COORDINATE_SCALE = '/desktop/sugar/activities/turtleart/coordinatescale'
def __init__(self, handle):
''' Set up the toolbars, canvas, sharing, etc. '''
try:
super(TurtleArtActivity, self).__init__(handle)
except dbus.exceptions.DBusException, e:
_logger.error(str(e))
self.tw = None
self.init_complete = False
self.bundle_path = activity.get_bundle_path()
self.error_list = []
self.palette_buttons = []
self._palette_names = []
self._overflow_buttons = []
self._check_ver_change(get_path(activity, 'data'))
self.connect("notify::active", self._notify_active_cb)
self.has_toolbarbox = HAS_TOOLBARBOX
_logger.debug('_setup_toolbar')
self._setup_toolbar()
self.label_offset = style.GRID_CELL_SIZE
_logger.debug('_setup_canvas')
self._setup_canvas(self._setup_scrolled_window())
_logger.debug('_setup_palette_toolbar')
self._setup_palette_toolbar()
self._setup_extra_controls()
_logger.debug('_setup_sharing')
if self.shared_activity:
# We're joining
if not self.get_shared():
xocolors = XoColor(profile.get_color().to_string())
share_icon = Icon(icon_name='zoom-neighborhood',
xo_color=xocolors)
self._joined_alert = Alert()
self._joined_alert.props.icon = share_icon
self._joined_alert.props.title = _('Please wait')
self._joined_alert.props.msg = _('Starting connection...')
self.add_alert(self._joined_alert)
# Wait for joined signal
self.connect("joined", self._joined_cb)
self._setup_sharing()
# Activity count is the number of times this instance has been
# accessed
count = 1
if hasattr(self, 'metadata') and self.metadata is not None:
if 'activity count' in self.metadata:
count = int(self.metadata['activity count'])
count += 1
self.metadata['activity count'] = str(count)
self._defer_palette_move = False
# Now called from lazy_init
# self.check_buttons_for_fit()
if HAS_GCONF:
self.client = gconf.client_get_default()
if self.client.get_int(self._HOVER_HELP) == 1:
self._do_hover_help_toggle(None)
if not self.client.get_int(self._COORDINATE_SCALE) in [0, 1]:
self.tw.coord_scale = 1
self.do_rescale_cb(None)
else:
self.tw.coord_scale = 0
self.do_rescale_cb(None)
self._selected_sample = None
self._sample_window = None
self.init_complete = True
def update_palette_from_metadata(self):
if HAS_GCONF:
# We have to wait to set the orientation for the palettes
# to be loaded.
self.client = gconf.client_get_default()
if self.client.get_int(self._ORIENTATION) == 1:
self.tw.set_orientation(1)
if 'palette' in self.metadata:
n = int(self.metadata['palette'])
if n == -1:
self.tw.hideshow_palette(False)
else:
# Try to set radio button to active
if n < len(self.palette_buttons):
self.palette_buttons[n].set_active(True)
else:
self.tw.show_palette(n=0)
if 'orientation' in self.metadata:
self.tw.set_orientation(int(self.metadata['orientation']))
else:
# Else start on the Turtle palette
self.tw.show_palette(n=0)
def check_buttons_for_fit(self):
''' Check to see which set of buttons to display '''
if not self.has_toolbarbox:
return
# If there are too many palettes to fit, put them in a
# scrolling window
self._setup_palette_toolbar()
if self.samples_button in self.toolbox.toolbar:
self.toolbox.toolbar.remove(self.extras_separator)
self.toolbox.toolbar.remove(self.samples_button)
self.toolbox.toolbar.remove(self.stop_separator)
self.toolbox.toolbar.remove(self.stop_button)
self._view_toolbar.remove(self._coordinates_toolitem)
if gtk.gdk.screen_width() / 14 < style.GRID_CELL_SIZE:
self.samples_button2.show()
self.samples_label2.show()
self.toolbox.toolbar.insert(self.stop_button, -1)
else:
self.samples_button2.hide()
self.samples_label2.hide()
self.toolbox.toolbar.insert(self.extras_separator, -1)
self.extras_separator.props.draw = True
self.extras_separator.show()
self.toolbox.toolbar.insert(self.samples_button, -1)
self.samples_button.show()
self.toolbox.toolbar.insert(self.stop_separator, -1)
self.stop_separator.show()
self.toolbox.toolbar.insert(self.stop_button, -1)
self._view_toolbar.insert(self._coordinates_toolitem, -1)
self.toolbox.show_all()
# Activity toolbar callbacks
def do_save_as_logo_cb(self, button):
''' Write UCB logo code to datastore. '''
self.save_as_logo.set_icon('logo-saveon')
if hasattr(self, 'get_window'):
if hasattr(self.get_window(), 'get_cursor'):
self._old_cursor = self.get_window().get_cursor()
self.get_window().set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))
gobject.timeout_add(250, self.__save_as_logo)
def __save_as_logo(self):
logo_code_path = self._dump_logo_code()
if logo_code_path is not None:
dsobject = datastore.create()
dsobject.metadata['title'] = self.metadata['title'] + '.lg'
dsobject.metadata['mime_type'] = 'text/plain'
dsobject.metadata['icon-color'] = profile.get_color().to_string()
dsobject.set_file_path(logo_code_path)
datastore.write(dsobject)
dsobject.destroy()
os.remove(logo_code_path)
self.save_as_logo.set_icon('logo-saveoff')
if hasattr(self, 'get_window'):
self.get_window().set_cursor(self._old_cursor)
def do_save_as_python_cb(self, widget):
''' Callback for saving the project as Python code. '''
self.save_as_python.set_icon('python-saveon')
if hasattr(self, 'get_window'):
if hasattr(self.get_window(), 'get_cursor'):
self._old_cursor = self.get_window().get_cursor()
self.get_window().set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))
gobject.timeout_add(250, self.__save_as_python)
def __save_as_python(self):
# catch PyExportError and display a user-friendly message instead
try:
pythoncode = save_python(self.tw)
except PyExportError as pyee:
if pyee.block is not None:
pyee.block.highlight()
self.tw.showlabel('status', str(pyee))
_logger.debug(pyee)
if pythoncode:
datapath = get_path(activity, 'instance')
python_code_path = os.path.join(datapath, 'tmpfile.py')
f = file(python_code_path, 'w')
f.write(pythoncode)
f.close()
dsobject = datastore.create()
dsobject.metadata['title'] = self.metadata['title'] + '.py'
dsobject.metadata['mime_type'] = 'text/x-python'
dsobject.metadata['icon-color'] = profile.get_color().to_string()
dsobject.set_file_path(python_code_path)
datastore.write(dsobject)
dsobject.destroy()
os.remove(python_code_path)
self.save_as_python.set_icon('python-saveoff')
if hasattr(self, 'get_window'):
self.get_window().set_cursor(self._old_cursor)
def do_load_ta_project_cb(self, button, new=False):
''' Load a project from the Journal. '''
self._create_new = new
if hasattr(self, 'get_window'):
_logger.debug('setting watch cursor')
if hasattr(self.get_window(), 'get_cursor'):
self._old_cursor = self.get_window().get_cursor()
self.get_window().set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))
chooser_dialog(self, 'org.laptop.TurtleArtActivity',
self._load_ta_project)
def _load_ta_project(self, dsobject):
''' Load a TA project from the datastore. '''
if dsobject is None:
self.restore_cursor()
return
try:
_logger.debug('Opening %s ' % (dsobject.file_path))
self._tmp_dsobject = dsobject
self.read_file(dsobject.file_path, plugin=False)
except:
_logger.debug("Couldn't open %s" % (dsobject.file_path))
def do_load_ta_plugin_cb(self, button):
''' Load a plugin from the Journal. '''
if hasattr(self, 'get_window'):
if hasattr(self.get_window(), 'get_cursor'):
self._old_cursor = self.get_window().get_cursor()
self.get_window().set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))
# FIXME: we are looking for tar files
chooser_dialog(self, '', self._load_ta_plugin)
def _load_ta_plugin(self, dsobject):
''' Load a TA plugin from the datastore. '''
if dsobject is None:
self.restore_cursor()
return
_logger.debug('Opening %s ' % (dsobject.file_path))
self.read_file(dsobject.file_path, plugin=True)
dsobject.destroy()
def do_load_python_cb(self, button):
''' Load Python code from the Journal. '''
self.load_python.set_icon('pippy-openon')
self.tw.load_python_code_from_file(fname=None, add_new_block=True)
gobject.timeout_add(250, self.load_python.set_icon, 'pippy-openoff')
def do_save_as_odp_cb(self, button):
_logger.debug('saving odp to journal')
if hasattr(self, 'get_window'):
if hasattr(self.get_window(), 'get_cursor'):
self._old_cursor = self.get_window().get_cursor()
self.get_window().set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))
gobject.timeout_add(250, self.__save_as_odp)
def __save_as_odp(self):
self.tw.save_as_odp()
if hasattr(self, 'get_window'):
self.get_window().set_cursor(self._old_cursor)
def do_save_as_icon_cb(self, button):
_logger.debug('saving icon to journal')
if hasattr(self, 'get_window'):
if hasattr(self.get_window(), 'get_cursor'):
self._old_cursor = self.get_window().get_cursor()
self.get_window().set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))
gobject.timeout_add(250, self.__save_as_icon)
def __save_as_icon(self):
self.tw.write_svg_operation()
self.tw.save_as_icon()
if hasattr(self, 'get_window'):
self.get_window().set_cursor(self._old_cursor)
def do_save_as_image_cb(self, button):
''' Save the canvas to the Journal. '''
self.save_as_image.set_icon('image-saveon')
_logger.debug('saving image to journal')
if hasattr(self, 'get_window'):
if hasattr(self.get_window(), 'get_cursor'):
self._old_cursor = self.get_window().get_cursor()
self.get_window().set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))
gobject.timeout_add(250, self.__save_as_image)
def __save_as_image(self):
self.tw.save_as_image()
self.save_as_image.set_icon('image-saveoff')
if hasattr(self, 'get_window'):
self.get_window().set_cursor(self._old_cursor)
def do_keep_cb(self, button):
''' Save a snapshot of the project to the Journal. '''
if hasattr(self, 'get_window'):
if hasattr(self.get_window(), 'get_cursor'):
self._old_cursor = self.get_window().get_cursor()
self.get_window().set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))
gobject.timeout_add(250, self.__keep)
def __keep(self):
tmpfile = self._dump_ta_code()
if tmpfile is not None:
dsobject = datastore.create()
dsobject.metadata['title'] = self.metadata['title'] + ' ' + \
_('snapshot')
dsobject.metadata['icon-color'] = profile.get_color().to_string()
dsobject.metadata['mime_type'] = MIMETYPE[0]
dsobject.metadata['activity'] = 'org.laptop.TurtleArtActivity'
dsobject.set_file_path(tmpfile)
datastore.write(dsobject)
dsobject.destroy()
os.remove(tmpfile)
if hasattr(self, 'get_window'):
self.get_window().set_cursor(self._old_cursor)
# Main/palette toolbar button callbacks
def do_palette_cb(self, button):
''' Show/hide palette '''
if self.tw.palette:
self.tw.hideshow_palette(False)
self.do_hidepalette()
if not self.has_toolbarbox and \
self.tw.selected_palette is not None:
self.palette_buttons[self.tw.selected_palette].set_icon(
palette_names[self.tw.selected_palette] + 'off')
else:
self.tw.hideshow_palette(True)
self.do_showpalette()
if self.has_toolbarbox:
self.palette_buttons[0].set_icon(palette_names[0] + 'on')
def do_palette_buttons_cb(self, button, i):
''' Palette selector buttons '''
if hasattr(button, 'get_active') and not button.get_active():
return
if self._overflow_palette.is_up():
self._overflow_palette.popdown(immediate=True)
if self.tw.selected_palette is not None:
if not self.has_toolbarbox:
self.palette_buttons[self.tw.selected_palette].set_icon(
palette_names[self.tw.selected_palette] + 'off')
if self.tw.selected_palette == i:
# Hide the palette if it is already selected.
self.tw.hideshow_palette(False)
self.tw.selected_palette = None
return
if not self.has_toolbarbox:
self.palette_buttons[i].set_icon(palette_names[i] + 'on')
else:
self._help_button.set_current_palette(palette_names[i])
self.tw.show_palette(n=i)
self.do_showpalette()
def _do_hover_help_toggle(self, button):
''' Toggle hover help '''
if self.tw.no_help:
self.tw.no_help = False
self._hover_help_toggle.set_icon('help-off')
self._hover_help_toggle.set_tooltip(_('Turn off hover help'))
if HAS_GCONF:
self.client.set_int(self._HOVER_HELP, 0)
else:
self.tw.no_help = True
self.tw.last_label = None
if self.tw.status_spr is not None:
self.tw.status_spr.hide()
self._hover_help_toggle.set_icon('help-on')
self._hover_help_toggle.set_tooltip(_('Turn on hover help'))
if HAS_GCONF:
self.client.set_int(self._HOVER_HELP, 1)
# These methods are called both from toolbar buttons and blocks.
def do_hidepalette(self):
''' Hide the palette. '''
if hasattr(self, 'palette_button'):
self.palette_button.set_icon('paletteon')
self.palette_button.set_tooltip(_('Show palette'))
def do_showpalette(self):
''' Show the palette. '''
if hasattr(self, 'palette_button'):
self.palette_button.set_icon('paletteoff')
self.palette_button.set_tooltip(_('Hide palette'))
def do_hide_blocks(self):
''' Hide blocks. '''
self.do_hidepalette()
def do_show_blocks(self):
''' Show blocks. '''
self.do_showpalette()
def do_eraser_cb(self, button):
''' Clear the screen and recenter. '''
self.eraser_button.set_icon('eraseroff')
self.recenter()
self.tw.eraser_button()
gobject.timeout_add(250, self.eraser_button.set_icon, 'eraseron')
def do_run_cb(self, button):
''' Callback for run button (rabbit) '''
self.run_button.set_icon('run-faston')
self.step_button.set_icon('run-slowoff')
self.tw.lc.trace = 0
self.tw.step_time = 0
# Autohide blocks and palettes on run
self.tw.hideblocks()
self.tw.display_coordinates(clear=True)
self.tw.run_button(self.tw.step_time, running_from_button_push=True)
def do_step_cb(self, button):
''' Callback for step button (turtle) '''
self.step_button.set_icon('run-slowon')
self.run_button.set_icon('run-fastoff')
self.tw.lc.trace = 1
self.tw.step_time = 3
self.tw.run_button(self.tw.step_time, running_from_button_push=True)
def do_stop_cb(self, button):
''' Callback for stop button. '''
# Auto show blocks after stop
if not self.tw.hide and not self.tw.running_blocks:
self.tw.hideblocks()
self.stop_turtle_button.set_icon('hideshowon')
self.stop_turtle_button.set_tooltip(_('Show blocks'))
else:
self.tw.showblocks()
self.stop_turtle_button.set_icon('hideshowoff')
self.stop_turtle_button.set_tooltip(_('Hide blocks'))
# Note: We leave the old button state highlighted to indicate
# speed if blocks are clicked to run.
# self.run_button.set_icon('run-fastoff')
# self.step_button.set_icon('run-slowoff')
self.tw.stop_button()
self.tw.display_coordinates()
def do_samples_cb(self, button):
''' Sample-projects open dialog '''
if hasattr(self, 'get_window'):
_logger.debug('setting watch cursor')
if hasattr(self.get_window(), 'get_cursor'):
self._old_cursor = self.get_window().get_cursor()
self.get_window().set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))
self._create_store()
# self.tw.load_file_from_chooser(True)
# Now that the file is loaded, restore the cursor
_logger.debug('restoring cursor')
self.restore_cursor()
def adjust_sw(self, dx, dy):
''' Adjust the scrolled window position. '''
if not self.tw.hw in [XO1]:
self._defer_palette_move = True
hadj = self.sw.get_hadjustment()
hvalue = hadj.get_value() + dx
try:
if hvalue < hadj.get_lower():
hvalue = hadj.get_lower()
elif hvalue > hadj.get_upper():
hvalue = hadj.get_upper()
except AttributeError:
_logger.debug(
'get_lower, get_upper only available in PyGTK 2.14 and above.')
hadj.set_value(hvalue)
self.sw.set_hadjustment(hadj)
vadj = self.sw.get_vadjustment()
vvalue = vadj.get_value() + dy
try:
if vvalue < vadj.get_lower():
vvalue = vadj.get_lower()
elif vvalue > vadj.get_upper():
vvalue = vadj.get_upper()
except AttributeError:
_logger.debug(
'get_lower, get_upper only available in PyGTK 2.14 and above.')
vadj.set_value(vvalue)
self.sw.set_vadjustment(vadj)
def adjust_palette(self):
''' Align palette to scrolled window position. '''
if not self.tw.hw in [XO1]:
self.tw.move_palettes(self.sw.get_hadjustment().get_value(),
self.sw.get_vadjustment().get_value())
self._defer_palette_move = False
def recenter(self):
''' Recenter scrolled window around canvas. '''
self.hadj_value = 0
hadj = self.sw.get_hadjustment()
hadj.set_value(self.hadj_value)
self.sw.set_hadjustment(hadj)
self.vadj_value = 0
vadj = self.sw.get_vadjustment()
vadj.set_value(self.vadj_value)
self.sw.set_vadjustment(vadj)
self.adjust_palette()
def do_fullscreen_cb(self, button):
''' Hide the Sugar toolbars. '''
self.fullscreen()
self.recenter()
def do_grow_blocks_cb(self, button):
''' Grow the blocks. '''
self.do_resize_blocks(1)
def do_shrink_blocks_cb(self, button):
''' Shrink the blocks. '''
self.do_resize_blocks(-1)
def do_resize_blocks(self, inc):
''' Scale the blocks. '''
if self.tw.block_scale in BLOCK_SCALE:
i = BLOCK_SCALE.index(self.tw.block_scale) + inc
else:
i = 3
if i < 0:
self.tw.block_scale = BLOCK_SCALE[0]
elif i == len(BLOCK_SCALE):
self.tw.block_scale = BLOCK_SCALE[-1]
else:
self.tw.block_scale = BLOCK_SCALE[i]
self.tw.resize_blocks()
def do_cartesian_cb(self, button):
''' Display Cartesian-coordinate grid. '''
if self.tw.cartesian:
self.tw.set_cartesian(False)
else:
self.tw.set_cartesian(True)
def do_polar_cb(self, button):
''' Display polar-coordinate grid. '''
if self.tw.polar:
self.tw.set_polar(False)
else:
self.tw.set_polar(True)
def do_metric_cb(self, button):
''' Display metric-coordinate grid. '''
if self.tw.metric:
self.tw.set_metric(False)
else:
self.tw.set_metric(True)
def do_rescale_cb(self, button):
''' Rescale coordinate system (20==height/2 or 100 pixels). '''
if self.tw.coord_scale == 1:
self.tw.coord_scale = self.tw.height / 40
self.rescale_button.set_icon('contract-coordinates')
self.rescale_button.set_tooltip(_('Rescale coordinates down'))
default_values['forward'] = [10]
default_values['back'] = [10]
default_values['arc'] = [90, 10]
default_values['setpensize'] = [1]
self.tw.turtles.get_active_turtle().set_pen_size(1)
else:
self.tw.coord_scale = 1
self.rescale_button.set_icon('expand-coordinates')
self.rescale_button.set_tooltip(_('Rescale coordinates up'))
default_values['forward'] = [100]
default_values['back'] = [100]
default_values['arc'] = [90, 100]
default_values['setpensize'] = [5]
self.tw.turtles.get_active_turtle().set_pen_size(5)
if HAS_GCONF:
self.client.set_int(self._COORDINATE_SCALE, self.tw.coord_scale)
self.tw.recalculate_constants()
# Given the change in how overlays are handled (v123), there is no way
# to erase and then redraw the overlays.
def get_document_path(self, async_cb, async_err_cb):
''' View TA code as part of view source. '''
ta_code_path = self._dump_ta_code()
if ta_code_path is not None:
async_cb(ta_code_path)
def _dump_logo_code(self):
''' Save Logo code to temporary file. '''
datapath = get_path(activity, 'instance')
tmpfile = os.path.join(datapath, 'tmpfile.lg')
code = save_logo(self.tw)
if len(code) == 0:
_logger.debug('save_logo returned None')
return None
try:
f = file(tmpfile, 'w')
f.write(code)
f.close()
except Exception, e:
_logger.error("Couldn't save Logo code: " + str(e))
tmpfile = None
return tmpfile
def _dump_ta_code(self):
''' Save TA code to temporary file. '''
datapath = get_path(activity, 'instance')
tmpfile = os.path.join(datapath, 'tmpfile.ta')
try:
data_to_file(self.tw.assemble_data_to_save(), tmpfile)
except Exception, e:
_logger.error("Couldn't save project code: " + str(e))
tmpfile = None
return tmpfile
def _keep_clicked_cb(self, button):
''' Keep-button clicked. '''
self.jobject_new_patch()
def is_fullscreen(self):
''' Are we in fullscreen mode (toolbars hidden)? '''
# Fixme: this should be a exposed as a window property, not private
return self._is_fullscreen
def toolbars_expanded(self, palette=False):
''' Are any toolbars expanded? '''
if not self.has_toolbarbox:
if palette:
return None
else:
return False
if self.palette_toolbar_button.is_expanded():
if palette:
return self.palette_toolbar_button
else:
return True
elif self.edit_toolbar_button.is_expanded():
if palette:
return self.edit_toolbar_button
else:
return True
elif self.view_toolbar_button.is_expanded():
if palette:
return self.view_toolbar_button
else:
return True
elif self.activity_toolbar_button.is_expanded():
if palette:
return self.activity_toolbar_button
else:
return True
else:
if palette:
return None
else:
return False
def _setup_toolbar(self):
''' Setup toolbar according to Sugar version. '''
if self.has_toolbarbox:
self.max_participants = 4
self._setup_toolbar_help()
self.toolbox = ToolbarBox()
self.activity_toolbar_button = ActivityToolbarButton(self)
edit_toolbar = gtk.Toolbar()
self.edit_toolbar_button = ToolbarButton(label=_('Edit'),
page=edit_toolbar,
icon_name='toolbar-edit')
self._view_toolbar = gtk.Toolbar()
self.view_toolbar_button = ToolbarButton(label=_('View'),
page=self._view_toolbar,
icon_name='toolbar-view')
self._palette_toolbar = gtk.Toolbar()
self.palette_toolbar_button = ToolbarButton(
page=self._palette_toolbar, icon_name='palette')
self._help_button = HelpButton(self)
self._make_load_save_buttons(self.activity_toolbar_button)
self.activity_toolbar_button.show()
self.toolbox.toolbar.insert(self.activity_toolbar_button, -1)
self.edit_toolbar_button.show()
self.toolbox.toolbar.insert(self.edit_toolbar_button, -1)
self.view_toolbar_button.show()
self.toolbox.toolbar.insert(self.view_toolbar_button, -1)
self.palette_toolbar_button.show()
self.toolbox.toolbar.insert(self.palette_toolbar_button, -1)
self.set_toolbar_box(self.toolbox)
else:
self.toolbox = activity.ActivityToolbox(self)
self.set_toolbox(self.toolbox)
self._project_toolbar = gtk.Toolbar()
self.toolbox.add_toolbar(_('Project'), self._project_toolbar)
self._view_toolbar = gtk.Toolbar()
self.toolbox.add_toolbar(_('View'), self._view_toolbar)
edit_toolbar = gtk.Toolbar()
self.toolbox.add_toolbar(_('Edit'), edit_toolbar)
journal_toolbar = gtk.Toolbar()
self.toolbox.add_toolbar(_('Save/Load'), journal_toolbar)
self._make_palette_buttons(self._project_toolbar,
palette_button=True)
self._add_separator(self._project_toolbar)
self._make_load_save_buttons(journal_toolbar)
self._add_button('edit-copy', _('Copy'), self._copy_cb,
edit_toolbar, '<Ctrl>c')
self._add_button('edit-paste', _('Paste'), self._paste_cb,
edit_toolbar, '<Ctrl>v')
self._add_button('edit-undo', _('Restore blocks from trash'),
self._undo_cb, edit_toolbar)
self._add_separator(edit_toolbar)
self._add_button('save-blocks', _('Save stack'), self._save_macro_cb,
edit_toolbar)
self._add_button('delete-blocks', _('Delete stack'),
self._delete_macro_cb, edit_toolbar)
self._add_button('view-fullscreen', _('Fullscreen'),
self.do_fullscreen_cb, self._view_toolbar,
'<Alt>Return')
self._add_button('view-Cartesian', _('Cartesian coordinates'),
self.do_cartesian_cb, self._view_toolbar)
self._add_button('view-polar', _('Polar coordinates'),
self.do_polar_cb, self._view_toolbar)
if get_hardware() in [XO1, XO15, XO175, XO4]:
self._add_button('view-metric', _('Metric coordinates'),
self.do_metric_cb, self._view_toolbar)
self.rescale_button = self._add_button(
'expand-coordinates', _('Rescale coordinates up'),
self.do_rescale_cb, self._view_toolbar)
self.resize_up_button = self._add_button(
'resize+', _('Grow blocks'), self.do_grow_blocks_cb,
self._view_toolbar)
self.resize_down_button = self._add_button(
'resize-', _('Shrink blocks'), self.do_shrink_blocks_cb,
self._view_toolbar)
self._hover_help_toggle = self._add_button(
'help-off', _('Turn off hover help'), self._do_hover_help_toggle,
self._view_toolbar)
self._add_separator(self._view_toolbar, visible=False)
self.coordinates_label = gtk.Label('(0, 0) 0')
self.coordinates_label.show()
self._coordinates_toolitem = gtk.ToolItem()
self._coordinates_toolitem.add(self.coordinates_label)
self._coordinates_toolitem.show()
self._view_toolbar.insert(self._coordinates_toolitem, -1)
edit_toolbar.show()
self._view_toolbar.show()
self.toolbox.show()
if self.has_toolbarbox:
self.edit_toolbar_button.set_expanded(True)
self.edit_toolbar_button.set_expanded(False)
self.palette_toolbar_button.set_expanded(True)
else:
self.toolbox.set_current_toolbar(1)
def _setup_extra_controls(self):
''' Add the rest of the buttons to the main toolbar '''
if not self.has_toolbarbox:
self.samples_button = self._add_button(
'ta-open', _('Load example'), self.do_samples_cb,
self._project_toolbar)
self._add_separator(self._project_toolbar, expand=False,
visible=True)
self._make_project_buttons(self._project_toolbar)
return
self._make_project_buttons(self.toolbox.toolbar)
self.extras_separator = self._add_separator(
self.toolbox.toolbar, expand=False, visible=True)
self.samples_button = self._add_button(
'ta-open', _('Load example'), self.do_samples_cb,
self.toolbox.toolbar)
self.toolbox.toolbar.insert(self._help_button, -1)
self._help_button.show()
self.stop_separator = self._add_separator(
self.toolbox.toolbar, expand=True, visible=False)
self.stop_button = StopButton(self)
self.stop_button.props.accelerator = '<Ctrl>Q'
self.toolbox.toolbar.insert(self.stop_button, -1)
self.stop_button.show()
def _setup_toolbar_help(self):
''' Set up a help palette for the main toolbars '''
help_box = gtk.VBox()
help_box.set_homogeneous(False)
help_palettes['main-toolbar'] = help_box
help_windows['main-toolbar'] = gtk.ScrolledWindow()
help_windows['main-toolbar'].set_size_request(
int(gtk.gdk.screen_width() / 3),
gtk.gdk.screen_height() - style.GRID_CELL_SIZE * 3)
help_windows['main-toolbar'].set_policy(
gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
help_windows['main-toolbar'].add_with_viewport(
help_palettes['main-toolbar'])
help_palettes['main-toolbar'].show()
add_section(help_box, _('Save/Load'), icon='turtleoff')
add_section(help_box, _('Edit'), icon='toolbar-edit')
add_section(help_box, _('View'), icon='toolbar-view')
add_section(help_box, _('Project'), icon='palette')
add_paragraph(help_box, _('Clean'), icon='eraseron')
add_paragraph(help_box, _('Run'), icon='run-fastoff')
add_paragraph(help_box, _('Step'), icon='run-slowoff')
add_paragraph(help_box, _('Stop turtle'), icon='stopitoff')
add_paragraph(help_box, _('Show blocks'), icon='hideshowoff')
add_paragraph(help_box, _('Load example'), icon='ta-open')
add_paragraph(help_box, _('Help'), icon='help-toolbar')
add_paragraph(help_box, _('Stop'), icon='activity-stop')
help_box = gtk.VBox()
help_box.set_homogeneous(False)
help_palettes['activity-toolbar'] = help_box
help_windows['activity-toolbar'] = gtk.ScrolledWindow()
help_windows['activity-toolbar'].set_size_request(
int(gtk.gdk.screen_width() / 3),
gtk.gdk.screen_height() - style.GRID_CELL_SIZE * 3)
help_windows['activity-toolbar'].set_policy(
gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
help_windows['activity-toolbar'].add_with_viewport(
help_palettes['activity-toolbar'])
help_palettes['activity-toolbar'].show()
add_paragraph(help_box, _('Share selected blocks'), icon='shareon')
add_paragraph(help_box, _('Save/Load'), icon='save-load')
add_paragraph(help_box, _('Save as image'), icon='image-saveoff')
self.save_as_icon = add_paragraph(
help_box, _('Save as icon'), icon='image-saveoff')
self.save_as_icon.connect(
'expose-event', self._save_as_icon_expose_cb)
# TRANS: ODP is Open Office presentation
self.save_as_odp = add_paragraph(help_box, _('Save as ODP'),
icon='odp-saveoff')
self.save_as_odp.connect('expose-event',
self._save_as_odp_expose_cb)
add_paragraph(help_box, _('Save as Logo'), icon='logo-saveoff')
add_paragraph(help_box, _('Save as Python'), icon='python-saveoff')
add_paragraph(help_box, _('Save snapshot'), icon='filesaveoff')
add_paragraph(help_box, _('Add project'), icon='load-from-journal')
home = os.environ['HOME']
if activity.get_bundle_path()[0:len(home)] == home:
add_paragraph(help_box, _('Load plugin'), icon='pluginoff')
add_paragraph(help_box, _('Load Python block'),
icon='pippy-openoff')
help_box = gtk.VBox()
help_box.set_homogeneous(False)
help_palettes['edit-toolbar'] = help_box
help_windows['edit-toolbar'] = gtk.ScrolledWindow()
help_windows['edit-toolbar'].set_size_request(
int(gtk.gdk.screen_width() / 3),
gtk.gdk.screen_height() - style.GRID_CELL_SIZE * 3)
help_windows['edit-toolbar'].set_policy(
gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
help_windows['edit-toolbar'].add_with_viewport(
help_palettes['edit-toolbar'])
help_palettes['edit-toolbar'].show()
add_section(help_box, _('Edit'), icon='toolbar-edit')
add_paragraph(help_box, _('Copy'), icon='edit-copy')
add_paragraph(help_box, _('Paste'), icon='edit-paste')
add_paragraph(help_box, _('Save stack'), icon='save-macro')
help_box = gtk.VBox()
help_box.set_homogeneous(False)
help_palettes['view-toolbar'] = help_box
help_windows['view-toolbar'] = gtk.ScrolledWindow()
help_windows['view-toolbar'].set_size_request(
int(gtk.gdk.screen_width() / 3),
gtk.gdk.screen_height() - style.GRID_CELL_SIZE * 3)
help_windows['view-toolbar'].set_policy(
gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
help_windows['view-toolbar'].add_with_viewport(
help_palettes['view-toolbar'])
help_palettes['view-toolbar'].show()
add_section(help_box, _('View'), icon='toolbar-view')
add_paragraph(help_box, _('Fullscreen'), icon='view-fullscreen')
add_paragraph(help_box, _('Cartesian coordinates'),
icon='view-Cartesian')
add_paragraph(help_box, _('Polar coordinates'), icon='view-polar')
if get_hardware() in [XO1, XO15, XO175, XO4]:
add_paragraph(help_box, _('Metric coordinates'),
icon='view-metric')
add_paragraph(help_box, _('Rescale coordinates up'),
icon='expand-coordinates')
add_paragraph(help_box, _('Grow blocks'), icon='resize+')
add_paragraph(help_box, _('Shrink blocks'), icon='resize-')
add_paragraph(help_box, _('Turn off hover help'), icon='help-off')
def _save_as_icon_expose_cb(self, box, context):
for widget in box.get_children():
widget.set_sensitive(self.tw.canvas.cr_svg is not None)
def _save_as_odp_expose_cb(self, box, context):
for widget in box.get_children():