Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/TurtleArtActivity.py
blob: dbe357c969720e0a8665cabf83d10e73138c27c1 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
#Copyright (c) 2007, Playful Invention Company
#Copyright (c) 2008-9, Walter Bender
#Copyright (c) 2009, Raul Gutierrez Segales

#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 tawindow
import talogo

import pygtk
pygtk.require('2.0')
import gtk
import gobject

import logging
_logger = logging.getLogger('turtleart-activity')

import sugar
from sugar.activity import activity
try: # 0.86 toolbar widgets
    from sugar.bundle.activitybundle import ActivityBundle
    from sugar.activity.widgets import ActivityToolbarButton
    from sugar.activity.widgets import StopButton
    from sugar.graphics.toolbarbox import ToolbarBox
    from sugar.graphics.toolbarbox import ToolbarButton
except ImportError:
    pass
from sugar.graphics.toolbutton import ToolButton
from sugar.graphics.menuitem import MenuItem
from sugar.graphics.icon import Icon
from sugar.datastore import datastore

import telepathy
from dbus.service import method, signal
from dbus.gobject_service import ExportedGObject
from sugar.presence import presenceservice
from sugar.presence.tubeconn import TubeConnection

from sugar import profile
from gettext import gettext as _
import locale
import os.path
import subprocess
import tarfile
import sys
from taexporthtml import *
from taexportlogo import *
import re

SERVICE = 'org.laptop.TurtleArtActivity'
IFACE = SERVICE
PATH = '/org/laptop/TurtleArtActivity'

class TurtleArtActivity(activity.Activity):

    def __init__(self, handle):
        super(TurtleArtActivity,self).__init__(handle)

        try:
            datapath = os.path.join(activity.get_activity_root(), "data")
        except:
            # Early versions of Sugar (e.g., 656) didn't support
            # get_activity_root()
            datapath = os.path.join( \
                os.environ['HOME'], \
                ".sugar/default/org.laptop.TurtleArtActivity/data")

        # Notify when the visibility state changes
        self.add_events(gtk.gdk.VISIBILITY_NOTIFY_MASK)
        self.connect("visibility-notify-event", self.__visibility_notify_cb)

        try: 
            # Use 0.86 toolbar design
            toolbar_box = ToolbarBox()

            # Buttons added to the Activity toolbar
            activity_button = ActivityToolbarButton(self)

            # Save snapshot is like Keep, but it creates a new activity id
            self.keep_button = ToolButton('filesave')
            self.keep_button.set_tooltip(_("Save snapshot"))
            self.keep_button.connect('clicked', self._do_savesnapshot_cb)
            self.keep_button.show()
            activity_button.props.page.insert(self.keep_button, -1)
            separator = gtk.SeparatorToolItem()
            separator.props.draw = True
            activity_button.props.page.insert(separator, -1)
            separator.show()

            # Save as HTML
            self.save_as_html = ToolButton('htmloff')
            self.save_as_html.set_tooltip(_("Save as HTML"))
            self.save_as_html.connect('clicked', self._do_savehtml_cb)
            self.save_as_html.show()
            activity_button.props.page.insert(self.save_as_html, -1)

            # Save as Logo
            self.save_as_logo = ToolButton('logo-saveoff')
            self.save_as_logo.set_tooltip(_("Save as Logo"))
            self.save_as_logo.connect('clicked', self._do_savelogo_cb)
            self.save_as_logo.show()
            activity_button.props.page.insert(self.save_as_logo, -1)

            # Save as image
            self.save_as_image = ToolButton('image-saveoff')
            self.save_as_image.set_tooltip(_("Save as image"))
            self.save_as_image.connect('clicked', self._do_saveimage_cb)
            self.save_as_image.show()
            activity_button.props.page.insert(self.save_as_image, -1)

            # Load Python code into programmable brick
            self.load_python = ToolButton('pippy-openoff')
            self.load_python.set_tooltip(_("Load my block"))
            self.load_python.connect('clicked', self._do_loadpython_cb)
            self.load_python.show()
            activity_button.props.page.insert(self.load_python, -1)

            # Open project from the Journal 
            self.load_ta_project = ToolButton('load-from-journal')
            self.load_ta_project.set_tooltip(\
                                           _("Import project from the Journal"))
            self.load_ta_project.connect('clicked', self._do_load_ta_project_cb)
            self.load_ta_project.show()
            activity_button.props.page.insert(self.load_ta_project, -1)

            toolbar_box.toolbar.insert(activity_button, 0)
            activity_button.show()

            # The edit toolbar -- copy and paste
            edit_toolbar = EditToolbar(self)
            edit_toolbar_button = ToolbarButton(
                    page=edit_toolbar,
                    icon_name='toolbar-edit')
            edit_toolbar.show()
            toolbar_box.toolbar.insert(edit_toolbar_button, -1)
            edit_toolbar_button.show()

            # The view toolbar -- just full screen
            view_toolbar = gtk.Toolbar()
            fullscreen_button = ToolButton('view-fullscreen')
            fullscreen_button.set_tooltip(_("Fullscreen"))
            fullscreen_button.props.accelerator = '<Alt>Enter'
            fullscreen_button.connect('clicked', self.__fullscreen_cb)
            view_toolbar.insert(fullscreen_button,-1)
            fullscreen_button.show()

            view_toolbar_button = ToolbarButton(
                    page=view_toolbar,
                    icon_name='toolbar-view')
            view_toolbar.show()
            toolbar_box.toolbar.insert(view_toolbar_button, -1)
            view_toolbar_button.show()

            # palette button (blocks)
            self.palette = ToolButton( "blocksoff" )
            self.palette.set_tooltip(_('Hide palette'))
            self.palette.props.sensitive = True
            self.palette.connect('clicked', self._do_palette_cb)
            self.palette.props.accelerator = _('<Ctrl>p')
            toolbar_box.toolbar.insert(self.palette, -1)
            self.palette.show()

            # blocks button (hideshow)
            self.blocks = ToolButton( "hideshowoff" )
            self.blocks.set_tooltip(_('Hide blocks'))
            self.blocks.props.sensitive = True
            self.blocks.connect('clicked', self.do_hideshow)
            self.blocks.props.accelerator = _('<Ctrl>b')
            toolbar_box.toolbar.insert(self.blocks, -1)
            self.blocks.show()

            # eraser button
            self.eraser_button = ToolButton( "eraseron" )
            self.eraser_button.set_tooltip(_('Clean'))
            self.eraser_button.props.sensitive = True
            self.eraser_button.connect('clicked', self._do_eraser_cb)
            self.eraser_button.props.accelerator = _('<Ctrl>e')
            toolbar_box.toolbar.insert(self.eraser_button, -1)
            self.eraser_button.show()

            # run button
            self.runproject = ToolButton( "run-fastoff" )
            self.runproject.set_tooltip(_('Run'))
            self.runproject.props.sensitive = True
            self.runproject.connect('clicked', self._do_run_cb)
            self.runproject.props.accelerator = _('<Ctrl>r')
            toolbar_box.toolbar.insert(self.runproject, -1)
            self.runproject.show()

            # step button
            self.stepproject = ToolButton( "run-slowoff" )
            self.stepproject.set_tooltip(_('Step'))
            self.stepproject.props.sensitive = True
            self.stepproject.connect('clicked', self._do_step_cb)
            self.stepproject.props.accelerator = _('<Ctrl>w')
            toolbar_box.toolbar.insert(self.stepproject, -1)
            self.stepproject.show()

            # debug button
            self.debugproject = ToolButton( "debugoff" )
            self.debugproject.set_tooltip(_('Debug'))
            self.debugproject.props.sensitive = True
            self.debugproject.connect('clicked', self._do_debug_cb)
            self.debugproject.props.accelerator = _('<Alt>d')
            toolbar_box.toolbar.insert(self.debugproject, -1)
            self.debugproject.show()

            # stop button
            self.stop = ToolButton( "stopitoff" )
            self.stop.set_tooltip(_('Stop turtle'))
            self.stop.props.sensitive = True
            self.stop.connect('clicked', self._do_stop_cb)
            self.stop.props.accelerator = _('<Ctrl>s')
            toolbar_box.toolbar.insert(self.stop, -1)
            self.stop.show()

            separator = gtk.SeparatorToolItem()
            separator.set_draw(True)
            toolbar_box.toolbar.insert(separator, -1)
            separator.show()

            # The Help toolbar -- sample code and hover help
            help_toolbar = gtk.Toolbar()
            samples_button = ToolButton( "stock-open" )
            samples_button.set_tooltip(_('Samples'))
            samples_button.connect('clicked', self._do_samples_cb)
            samples_button.show()
            help_toolbar.insert(samples_button, -1)
    
            separator = gtk.SeparatorToolItem()
            separator.props.draw = True
            help_toolbar.insert(separator, -1)
            separator.show()

            self.hover_help_label = \
              gtk.Label(_("Move the cursor over the orange palette for help."))
            self.hover_help_label.set_line_wrap(True)
            self.hover_help_label.show()
            self.hover_toolitem = gtk.ToolItem()
            self.hover_toolitem.add(self.hover_help_label)
            help_toolbar.insert(self.hover_toolitem,-1)
            self.hover_toolitem.show()

            help_toolbar_button = ToolbarButton(
                    label=_("Help"),
                    page=help_toolbar,
                    icon_name='help-toolbar')
            help_toolbar.show()
            toolbar_box.toolbar.insert(help_toolbar_button, -1)
            help_toolbar_button.show()

            separator = gtk.SeparatorToolItem()
            separator.props.draw = False
            separator.set_expand(True)
            toolbar_box.toolbar.insert(separator, -1)
            separator.show()

            # The ever-present Stop Button
            stop_button = StopButton(self)
            stop_button.props.accelerator = '<Ctrl>Q'
            toolbar_box.toolbar.insert(stop_button, -1)
            stop_button.show()

            self.set_toolbar_box(toolbar_box)
            toolbar_box.show()

        except NameError:
            # Use pre-0.86 toolbar design
            self.toolbox = activity.ActivityToolbox(self)
            self.set_toolbox(self.toolbox)

            # Add additional panels
            self.projectToolbar = ProjectToolbar(self)
            self.toolbox.add_toolbar( _('Project'), self.projectToolbar )
            self.editToolbar = EditToolbar(self)
            self.toolbox.add_toolbar(_('Edit'), self.editToolbar)
            self.saveasToolbar = SaveAsToolbar(self)
            self.toolbox.add_toolbar( _('Import/Export'), self.saveasToolbar )
            self.helpToolbar = HelpToolbar(self)
            self.toolbox.add_toolbar(_('Help'),self.helpToolbar)
            self.toolbox.show()

            # Set the project toolbar as the initial one selected
            self.toolbox.set_current_toolbar(1)
            pass

        # Create a scrolled window to contain the turtle canvas
        self.sw = gtk.ScrolledWindow()
        self.set_canvas(self.sw)
        self.sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        self.sw.show()
        canvas = gtk.DrawingArea()
        canvas.set_size_request(gtk.gdk.screen_width()*2, \
                                gtk.gdk.screen_height()*2)
        self.sw.add_with_viewport(canvas)
        canvas.show()

        """
        To be replaced with date checking in tasetup.py; 
        each language group should be stored in it's own sub-directory
        """
        # Check to see if the version or language has changed
        try:
            version = os.environ['SUGAR_BUNDLE_VERSION']
        except:
            version = " unknown"

        lang = locale.getdefaultlocale()[0]
        if not lang:
            lang = 'en'
        lang = lang[0:2]
        if not os.path.isdir(os.path.join(activity.get_bundle_path(), \
                             'images', lang)):
            lang = 'en'

        # If either has changed, remove the old png files
        filename = "version.dat"
        versiondata = []
        newversion = True
        try:
            FILE = open(os.path.join(datapath, filename), "r")
            if FILE.readline() == lang + version:
                newversion = False
            else:
                _logger.debug("out with the old, in with the new")
                cmd = "rm " + os.path.join(datapath, '*.png')
                subprocess.check_call(cmd, shell=True)
        except:
            _logger.debug("writing new version data")
            _logger.debug("and creating a tamyblock.py Journal entry")

        """
        Make sure there is a copy of tamyblock.py in the Journal
        """
        if newversion is True:
            dsobject = datastore.create()
            dsobject.metadata['title'] = 'tamyblock.py'
            dsobject.metadata['icon-color'] = \
                profile.get_color().to_string()
            dsobject.metadata['mime_type'] = 'text/x-python'
            dsobject.metadata['activity'] = 'org.laptop.Pippy'
            dsobject.set_file_path(os.path.join( \
                activity.get_bundle_path(), 'tamyblock.py'))
            datastore.write(dsobject)
            dsobject.destroy()

        versiondata.append(lang + version)
        FILE = open(os.path.join(datapath, filename), "w")
        FILE.writelines(versiondata)
        FILE.close()

        # Initialize the turtle art canvas
        self.tw = tawindow.twNew(canvas,activity.get_bundle_path(), \
                                 lang, self)
        self.tw.activity = self
        self.tw.window.grab_focus()
        self.tw.save_folder=os.path.join( \
            os.environ['SUGAR_ACTIVITY_ROOT'], 'data')

        if self._jobject and self._jobject.file_path:
            self.read_file(self._jobject.file_path)

        """
        A simplistic sharing model: the sharer is the master;
        TODO: hand off role of master is sharer leaves
        """
        # Get the Presence Service
        self.pservice = presenceservice.get_instance()
        self.initiating = None # sharing (True) or joining (False)

        # Add my buddy object to the list
        owner = self.pservice.get_owner()
        self.owner = owner
        self.tw.buddies.append(self.owner)
        self._share = ""

        self.connect('shared', self._shared_cb)
        self.connect('joined', self._joined_cb)

    """ Activity toolbar callbacks """

    def _do_savehtml_cb(self, button):
        # write html out to datastore
        self.save_as_html.set_icon("htmlon")
        _logger.debug("saving html code")
        # til we add the option
        embed_flag = True

        # grab code from stacks
        html = save_html(self,self.tw,embed_flag)
        if len(html) == 0:
            return

        # save the html code to the instance directory
        datapath = os.path.join(activity.get_activity_root(), "instance")

        html_file = os.path.join(datapath, "portfolio.html")
        f = file(html_file, "w")
        f.write(html)
        f.close()

        if embed_flag == False:
        # need to make a tarball that includes the images
            tar_path = os.path.join(datapath, 'portfolio.tar')
            tar_fd = tarfile.open(tar_path, 'w')
            try:
                tar_fd.add(html_file, "portfolio.html")
                import glob
                image_list = glob.glob(os.path.join(datapath, 'image*'))
                for i in image_list:
                    tar_fd.add(i, os.path.basename(i))
            finally:
                tar_fd.close()

        # Create a datastore object
        dsobject = datastore.create()

        # Write any metadata (here we specifically set the title of the file
        # and specify that this is a plain text file). 
        dsobject.metadata['title'] = self.metadata['title'] + " " + \
                                     _("presentation")
        dsobject.metadata['icon-color'] = profile.get_color().to_string()
        if embed_flag == True:
            dsobject.metadata['mime_type'] = 'text/html'
            dsobject.set_file_path(html_file)
        else:
            dsobject.metadata['mime_type'] = 'application/x-tar'
            dsobject.set_file_path(tar_path)

        dsobject.metadata['activity'] = 'org.laptop.WebActivity'
        datastore.write(dsobject)
        dsobject.destroy()
        gobject.timeout_add(250,self.save_as_html.set_icon, "htmloff")
        return

    def _do_savelogo_cb(self, button):
        # write logo code out to datastore
        self.save_as_logo.set_icon("logo-saveon")
        # grab code from stacks
        logocode = save_logo(self,self.tw)
        if len(logocode) == 0:
            return
        filename = "logosession.lg"

        # Create a datastore object
        dsobject = datastore.create()

        # Write any metadata (here we specifically set the title of the file
        # and specify that this is a plain text file). 
        dsobject.metadata['title'] = self.metadata['title'] + ".lg"
        dsobject.metadata['mime_type'] = 'text/plain'
        dsobject.metadata['icon-color'] = profile.get_color().to_string()

        # save the html code to the instance directory
        datapath = os.path.join(activity.get_activity_root(), "instance")

        # Write the file to the data directory of this activity's root. 
        file_path = os.path.join(datapath, filename)
        f = open(file_path, 'w')
        try:
            f.write(logocode)
        finally:
            f.close()

        # Set the file_path in the datastore.
        dsobject.set_file_path(file_path)

        datastore.write(dsobject)
        gobject.timeout_add(250,self.save_as_logo.set_icon, "logo-saveoff")
        return

    def _do_loadpython_cb(self, button):
        self.load_python.set_icon("pippy-openon")
        self._import_py()
        gobject.timeout_add(250,self.load_python.set_icon, "pippy-openoff")
        return

    def _do_load_ta_project_cb(self, button):
        from sugar.graphics.objectchooser import ObjectChooser
        chooser = ObjectChooser(_("Project"), None, gtk.DIALOG_MODAL | \
            gtk.DIALOG_DESTROY_WITH_PARENT)
        try:
            result = chooser.run()
            if result == gtk.RESPONSE_ACCEPT:
                dsobject = chooser.get_selected_object()
                try:
                    _logger.debug("opening %s " % dsobject.file_path)
                    self.read_file(dsobject.file_path, False)
                except:
                    _logger.debug("couldn't open %s" % dsobject.file_path)
                dsobject.destroy()
        finally:
            chooser.destroy()
            del chooser
        return 

    # Import Python code from the Journal to load into "myblock"
    def _import_py(self):
        from sugar.graphics.objectchooser import ObjectChooser
        chooser = ObjectChooser('Python code', None, gtk.DIALOG_MODAL | \
            gtk.DIALOG_DESTROY_WITH_PARENT)
        try:
            result = chooser.run()
            if result == gtk.RESPONSE_ACCEPT:
                dsobject = chooser.get_selected_object()
                try:
                    _logger.debug("opening %s " % dsobject.file_path)
                    FILE = open(dsobject.file_path, "r")
                    self.tw.myblock = FILE.read()
                    FILE.close()
	            tawindow.set_userdefined(self.tw)
                except:
                    _logger.debug("couldn't open %s" % dsobject.file_path)
                dsobject.destroy()
        finally:
            chooser.destroy()
            del chooser

    def _do_saveimage_cb(self, button):
        self.save_as_image.set_icon("image-saveon")
        _logger.debug("saving image to journal")

        filename = "ta.png"
        # save the image to the instance directory
        datapath = os.path.join(activity.get_activity_root(), "instance")

        # Write the file to the instance directory of this activity's root. 
        file_path = os.path.join(datapath, filename)

        tawindow.save_pict(self.tw,file_path)

        # Create a datastore object
        dsobject = datastore.create()

        # Write metadata
        dsobject.metadata['title'] = self.metadata['title'] + " " + _("image")
        dsobject.metadata['icon-color'] = profile.get_color().to_string()
        dsobject.metadata['mime_type'] = 'image/png'
        dsobject.set_file_path(file_path)

        datastore.write(dsobject)
        dsobject.destroy()
        gobject.timeout_add(250,self.save_as_image.set_icon, "image-saveoff")
        return

    """ Save snapshot """
    def _do_savesnapshot_cb(self, button):
        # Create a datastore object
        # save the current state of the project to the instance directory

        import tempfile
        tafd, tafile = tempfile.mkstemp(".ta")
        print tafile
        try:
            tawindow.save_data(self.tw,tafile)
        except:
            _logger.debug("couldn't save snapshot to journal")

        # Create a datastore object
        dsobject = datastore.create()

        # Write any metadata
        dsobject.metadata['title'] = self.metadata['title'] + " " + \
                                     _("snapshot")
        dsobject.metadata['icon-color'] = profile.get_color().to_string()
        dsobject.metadata['mime_type'] = 'application/x-turtle-art'
        dsobject.metadata['activity'] = 'org.laptop.TurtleArtActivity'
        dsobject.set_file_path(tafile)
        datastore.write(dsobject)

        # Clean up
        dsobject.destroy()
        os.remove(tafile)
        del tafd
        return

    """ Main toolbar button callbacks """
    """ Show/hide palette """
    def _do_palette_cb(self, button):
        if self.tw.palette == True:
            tawindow.hideshow_palette(self.tw,False)
            self.palette.set_icon("blockson")
            self.palette.set_tooltip(_('Show palette'))
        else:
            tawindow.hideshow_palette(self.tw,True)
            self.palette.set_icon("blocksoff")
            self.palette.set_tooltip(_('Hide palette'))

    """ These methods are called both from buttons and blocks """
    def do_hidepalette(self):
        # print "in do_hidepalette"
        self.palette.set_icon("blockson")
        self.palette.set_tooltip(_('Show palette'))

    def do_showpalette(self):
        # print "in do_showpalette"
        self.palette.set_icon("blocksoff")
        self.palette.set_tooltip(_('Hide palette'))

    def do_hideshow(self, button):
        tawindow.hideshow_button(self.tw)
        if self.tw.hide == True: # we just hid the blocks
            self.blocks.set_icon("hideshowon")
            self.blocks.set_tooltip(_('Show blocks'))
        else:
            self.blocks.set_icon("hideshowoff")
            self.blocks.set_tooltip(_('Hide blocks'))
        # update palette buttons too
        if self.tw.palette == False: 
            self.palette.set_icon("blockson")
            self.palette.set_tooltip(_('Show palette'))
        else:
            self.palette.set_icon("blocksoff")
            self.palette.set_tooltip(_('Hide palette'))

    def do_hide(self):
        self.blocks.set_icon("hideshowon")
        self.blocks.set_tooltip(_('Show blocks'))
        self.palette.set_icon("blockson")
        self.palette.set_tooltip(_('Show palette'))

    def do_show(self):
        self.blocks.set_icon("hideshowoff")
        self.blocks.set_tooltip(_('Hide blocks'))
        self.palette.set_icon("blocksoff")
        self.palette.set_tooltip(_('Hide palette'))

    def _do_eraser_cb(self, button):
        self.eraser_button.set_icon("eraseroff")
        self.recenter()
        tawindow.eraser_button(self.tw)
        gobject.timeout_add(250,self.eraser_button.set_icon,"eraseron")

    def _do_run_cb(self, button):
        self.runproject.set_icon("run-faston")
        self.stop.set_icon("stopiton")
        self.tw.lc.trace = 0
        tawindow.runbutton(self.tw, 0)
        gobject.timeout_add(1000,self.runproject.set_icon,"run-fastoff")

    def _do_step_cb(self, button):
        self.stepproject.set_icon("run-slowon")
        self.stop.set_icon("stopiton")
        self.tw.lc.trace = 0
        tawindow.runbutton(self.tw, 3)
        gobject.timeout_add(1000,self.stepproject.set_icon,"run-slowoff")

    def _do_debug_cb(self, button):
        self.debugproject.set_icon("debugon")
        self.stop.set_icon("stopiton")
        self.tw.lc.trace = 1
        tawindow.runbutton(self.tw, 6)
        gobject.timeout_add(1000,self.debugproject.set_icon,"debugoff")

    def _do_stop_cb(self, button):
        self.stop.set_icon("stopitoff")
        tawindow.stop_button(self.tw)
        self.stepproject.set_icon("run-slowoff")
        self.runproject.set_icon("run-fastoff")

    """ Sample projects open dialog """
    def _do_samples_cb(self, button):
        tawindow.load_file(self.tw, True)
        # run the activity
        self.stop.set_icon("stopiton")
        tawindow.runbutton(self.tw, 0)

    """
    Recenter scrolled window around canvas
    """
    def recenter(self):
        hadj = self.sw.get_hadjustment()
        # print hadj
        hadj.set_value(0)
        self.sw.set_hadjustment(hadj)
        vadj = self.sw.get_vadjustment()
        # print vadj
        vadj.set_value(0)
        self.sw.set_vadjustment(vadj)

    def __fullscreen_cb(self, button):    
        self.fullscreen()
        self.recenter()

    """
    Either set up initial share...
    """
    def _shared_cb(self, activity):
        if self._shared_activity is None:
            _logger.error("Failed to share or join activity ... \
                _shared_activity is null in _shared_cb()")
            return

        self.initiating = True
        self.waiting_for_blocks = False
        _logger.debug('I am sharing...')

        self.conn = self._shared_activity.telepathy_conn
        self.tubes_chan = self._shared_activity.telepathy_tubes_chan
        self.text_chan = self._shared_activity.telepathy_text_chan
        
        # call back for "NewTube" signal
        self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].connect_to_signal \
            ('NewTube', self._new_tube_cb)

        _logger.debug('This is my activity: making a tube...')
        id = self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].OfferDBusTube(
            SERVICE, {})

    """
    ...or join an exisiting share.
    """
    def _joined_cb(self, activity):
        if self._shared_activity is None:
            _logger.error("Failed to share or join activity ... \
                _shared_activity is null in _shared_cb()")
            return

        self.initiating = False
        _logger.debug('I joined a shared activity.')

        self.conn = self._shared_activity.telepathy_conn
        self.tubes_chan = self._shared_activity.telepathy_tubes_chan
        self.text_chan = self._shared_activity.telepathy_text_chan
        
        # call back for "NewTube" signal
        self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].connect_to_signal( \
            'NewTube', self._new_tube_cb)

        _logger.debug('I am joining an activity: waiting for a tube...')
        self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].ListTubes(
            reply_handler=self._list_tubes_reply_cb, 
            error_handler=self._list_tubes_error_cb)

        # joiner should request current state from sharer
        self.waiting_for_blocks = True

    def _list_tubes_reply_cb(self, tubes):
        for tube_info in tubes:
            self._new_tube_cb(*tube_info)

    def _list_tubes_error_cb(self, e):
        _logger.error('ListTubes() failed: %s', e)

    """
    Create a new tube
    """
    def _new_tube_cb(self, id, initiator, type, service, params, state):
        _logger.debug('New tube: ID=%d initator=%d type=%d service=%s '
                     'params=%r state=%d', id, initiator, type, service, 
                     params, state)

        if (type == telepathy.TUBE_TYPE_DBUS and service == SERVICE):
            if state == telepathy.TUBE_STATE_LOCAL_PENDING:
                self.tubes_chan[ \
                              telepathy.CHANNEL_TYPE_TUBES].AcceptDBusTube(id)

            tube_conn = TubeConnection(self.conn, 
                self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES], id, \
                group_iface=self.text_chan[telepathy.CHANNEL_INTERFACE_GROUP])

            # we'll use a chat tube to send serialized stacks back and forth
            self.chattube = ChatTube(tube_conn, self.initiating, \
                self.event_received_cb)

            # now that we have the tube, we can ask for an initialization
            if self.waiting_for_blocks is True:
                self._send_event("i")

    """
    Handle the receiving of events in share
    Events are sent as a tuple
        cmd:data
    where cmd is a mouse or keyboard event and data are x,y coordinates
    or a keysroke
    """
    def event_received_cb(self, text):
        # maybe we can use a stack to share events to new-comers?
        # self._share += "text + "\n"
        if text[0] == 'p': # button press
            e,x,y,mask = re.split(":",text)
            # _logger.debug("receiving button press: "+x+" "+y+" "+mask)
            if mask == 'T':
                tawindow.button_press(self.tw,True,int(x),int(y),False)
            else:
                tawindow.button_press(self.tw,False,int(x),int(y),False)
        elif text[0] == 'r': # block release
            e,x,y = re.split(":",text)
            # _logger.debug("receiving button release: " + x + " " + y)
            tawindow.button_release(self.tw,int(x),int(y),False)
        elif text[0] == 'm': # mouse move
            e,x,y = re.split(":",text)
            _logger.debug("receiving move: " + x + " " + y)
            tawindow.mouse_move(self.tw,0,0,False,int(x),int(y))
        elif text[0] == 'k': # typing
            e,mask,keyname = re.split(":",text,3)
            # _logger.debug("recieving key press: " + mask + " " + keyname)
            if mask == 'T':
                tawindow.key_press(self.tw,True,keyname,False)
            else:
                tawindow.key_press(self.tw,False,keyname,False)
        elif text[0] == 'i': # request for current state
            # sharer should send current state to joiner
            if self.initiating is True:
                _logger.debug("serialize the project and send to joiner")
                text = tawindow.save_string(self.tw)
                self._send_event("I:" + text)
                tawindow.show_palette(self.tw)
        elif text[0] == 'I': # receiving current state
            if self.waiting_for_blocks:
                _logger.debug("receiving project from sharer")
                e,text = re.split(":",text,2)
                # unpack data
                tawindow.load_string(self.tw,text)
                # all caught up
                self.waiting_for_blocks = False

    """
    Send event through the tube
    """
    def _send_event(self, entry):
        # nick = profile.get_nick_name()
        # nick = nick.upper()
        if hasattr(self, 'chattube') and self.chattube is not None:
            self.chattube.SendText(entry)

    """
    Callback method for when the activity's visibility changes
    """
    def __visibility_notify_cb(self, window, event):
        if event.state == gtk.gdk.VISIBILITY_FULLY_OBSCURED:
            # _logger.debug("I am not visible so I should free the audio")
            self.tw.lc.ag = None
        elif event.state in \
            [gtk.gdk.VISIBILITY_UNOBSCURED, gtk.gdk.VISIBILITY_PARTIAL]:
            pass

    def update_title_cb(self, widget, event, toolbox):
        toolbox._activity_toolbar._update_title_cb()
        toolbox._activity_toolbar._update_title_sid = True

    def _keep_clicked_cb(self, button):
        self.jobject_new_patch()

    """
    Write the project to the Journal
    """
    def write_file(self, file_path):
        _logger.debug("Write file: %s" % file_path)
        self.metadata['mime_type'] = 'application/x-turtle-art'
        tawindow.save_data(self.tw,file_path)

    """
    Read a project in and then run it
    """
    def read_file(self, file_path, run_it = True):
        import tarfile,os,tempfile,shutil

        if hasattr(self, 'tw'):
            _logger.debug("Read file: %s" %  file_path)
            # Could be a gtar (newer builds) or tar (767) file
            if file_path[-5:] == ".gtar" or file_path[-4:] == ".tar":
                tar_fd = tarfile.open(file_path, 'r')
                tmpdir = tempfile.mkdtemp()
                try:
                    # We'll get 'ta_code.ta' and possibly a 'ta_image.png'
                    # but we will ignore the .png file
                    # If run_it is True, we want to create a new project
                    tar_fd.extractall(tmpdir)
                    tawindow.load_files(self.tw, \
                                        os.path.join(tmpdir,'ta_code.ta'), \
                                        run_it) # create a new project flag
                finally:
                    shutil.rmtree(tmpdir)
                    tar_fd.close()
            # Otherwise, assume it is a .ta file
            else:
                print "trying to open a .ta file:" + file_path
                tawindow.load_files(self.tw, file_path, run_it)
  
            # run the activity
            if run_it:
                try:
                    # Use 0.86 toolbar design
                    self.stop.set_icon("stopiton")
                except:
                    # Use pre-0.86 toolbar design
                    self.projectToolbar.stop.set_icon("stopiton")

                tawindow.runbutton(self.tw, 0)
        else:
            _logger.debug("Deferring reading file %s" %  file_path)

    """
    Save instance to Journal
    """
    def jobject_new_patch(self):
        oldj = self._jobject
        self._jobject = datastore.create()
        self._jobject.metadata['title'] = oldj.metadata['title']
        self._jobject.metadata['title_set_by_user'] = \
            oldj.metadata['title_set_by_user']
        # self._jobject.metadata['activity'] = self.get_service_name()
        self._jobject.metadata['activity_id'] = self.get_id()
        self._jobject.metadata['keep'] = '0'
        # Is this the correct syntax for saving the buddies list?
        # self._jobject.metadata['buddies'] = self.tw.buddies
        self._jobject.metadata['preview'] = ''
        self._jobject.metadata['icon-color'] = profile.get_color().to_string()
        self._jobject.file_path = ''
        datastore.write(self._jobject,
                reply_handler=self._internal_jobject_create_cb,
                error_handler=self._internal_jobject_error_cb)
        self._jobject.destroy()

"""
Class for setting up tube for sharing
"""
class ChatTube(ExportedGObject):
 
    def __init__(self, tube, is_initiator, stack_received_cb):
        super(ChatTube, self).__init__(tube, PATH)
        self.tube = tube
        self.is_initiator = is_initiator # Are we sharing or joining activity?
        self.stack_received_cb = stack_received_cb
        self.stack = ''

        self.tube.add_signal_receiver(self.send_stack_cb, 'SendText', IFACE, \
            path=PATH, sender_keyword='sender')

    def send_stack_cb(self, text, sender=None):
        if sender == self.tube.get_unique_name():
            return
        self.stack = text
        self.stack_received_cb(text)

    @signal(dbus_interface=IFACE, signature='s')
    def SendText(self, text):
        self.stack = text

"""
Edit toolbar: copy and paste text and stacks
"""
class EditToolbar(gtk.Toolbar):
    def __init__(self, pc):
        gtk.Toolbar.__init__(self)
        self.activity = pc

        # Copy button
        self.copy = ToolButton( "edit-copy" )
        self.copy.set_tooltip(_('Copy'))
        self.copy.props.sensitive = True
        self.copy.connect('clicked', self._copy_cb)
        try:
            self.copy.props.accelerator = '<Ctrl>C'
        except:
            pass
        self.insert(self.copy, -1)
        self.copy.show()

        # Paste button
        self.paste = ToolButton( "edit-paste" )
        self.paste.set_tooltip(_('Paste'))
        self.paste.props.sensitive = True
        self.paste.connect('clicked', self._paste_cb)
        try:
            self.paste.props.accelerator = '<Ctrl>V'
        except:
            pass
        self.insert(self.paste, -1)
        self.paste.show()

    def _copy_cb(self, button):
        clipBoard = gtk.Clipboard()
        _logger.debug("serialize the project and copy to clipboard")
        text = tawindow.serialize_stack(self.activity.tw)
        clipBoard.set_text(text)

    def _paste_cb(self, button):
        clipBoard = gtk.Clipboard()
        _logger.debug("paste to the project")
        text = clipBoard.wait_for_text()
        if text is not None:
            tawindow.clone_stack(self.activity.tw,text)

"""
Help toolbar: Just an icon and a label for displaying hover help
"""
class HelpToolbar(gtk.Toolbar):
    def __init__(self, pc):
        gtk.Toolbar.__init__(self)
        self.activity = pc

        # Help icon
        self.help = ToolButton( "help-toolbar" )
        self.help.props.sensitive = False
        self.insert(self.help, -1)
        self.help.show()

        # Help label
        self.hover_help_label = \
          gtk.Label(_("Move the cursor over the orange palette for help."))
        self.hover_help_label.set_line_wrap(True)
        self.hover_help_label.show()
        self.hover_toolitem = gtk.ToolItem()
        self.hover_toolitem.add(self.hover_help_label)
        self.insert(self.hover_toolitem,-1)
        self.hover_toolitem.show()

"""
SaveAs toolbar: (1) load samples; (2) save as HTML; (3) save as LOGO;
(4) save as PNG; and (5) import Python code.
"""
class SaveAsToolbar(gtk.Toolbar):
    def __init__(self, pc):
        gtk.Toolbar.__init__(self)
        self.activity = pc

        # HTML save source button
        self.savehtml = ToolButton( "htmloff" )
        self.savehtml.set_tooltip(_('Save as HTML'))
        self.savehtml.props.sensitive = True
        self.savehtml.connect('clicked', self.do_savehtml)
        self.insert(self.savehtml, -1)
        self.savehtml.show()

        # Berkeley Logo save source button
        self.savelogo = ToolButton( "logo-saveoff" )
        self.savelogo.set_tooltip(_('Save Logo'))
        self.savelogo.props.sensitive = True
        self.savelogo.connect('clicked', self.do_savelogo)
        self.insert(self.savelogo, -1)
        self.savelogo.show()

        # Save as image button
        self.saveimage = ToolButton( "image-saveoff" )
        self.saveimage.set_tooltip(_('Save as image'))
        self.saveimage.props.sensitive = True
        self.saveimage.connect('clicked', self.do_saveimage)
        self.insert(self.saveimage, -1)
        self.saveimage.show()

        separator = gtk.SeparatorToolItem()
        separator.set_draw(True)
        self.insert(separator, -1)
        separator.show()

        # Pippy load myblock source button
        self.loadmyblock = ToolButton( "pippy-openoff" )
        self.loadmyblock.set_tooltip(_('Load my block'))
        self.loadmyblock.props.sensitive = True
        self.loadmyblock.connect('clicked', self.do_loadmyblock)
        self.insert(self.loadmyblock, -1)
        self.loadmyblock.show()

        # Open TA project from the Journal 
        self.load_ta_project = ToolButton('load-from-journal')
        self.load_ta_project.set_tooltip(_("Import project from the Journal"))
        self.load_ta_project.props.sensitive = True
        self.load_ta_project.connect('clicked', self.do_load_ta_project_cb)
        self.insert(self.load_ta_project, -1)
        self.load_ta_project.show()

    def do_savehtml(self, button):
        # write html out to datastore
        self.savehtml.set_icon("htmlon")
        _logger.debug("saving html code")
        # til we add the option
        embed_flag = True

        # grab code from stacks
        html = save_html(self,self.activity.tw,embed_flag)
        if len(html) == 0:
            return

        # save the html code to the instance directory
        try:
            datapath = os.path.join(activity.get_activity_root(), "instance")
        except:
            # early versions of Sugar (656) didn't support get_activity_root()
            datapath = os.path.join( \
                os.environ['HOME'], \
                ".sugar/default/org.laptop.TurtleArtActivity/instance")

        html_file = os.path.join(datapath, "portfolio.html")
        f = file(html_file, "w")
        f.write(html)
        f.close()

        if embed_flag == False:
        # need to make a tarball that includes the images
            tar_path = os.path.join(datapath, 'portfolio.tar')
            tar_fd = tarfile.open(tar_path, 'w')
            try:
                tar_fd.add(html_file, "portfolio.html")
                import glob
                image_list = glob.glob(os.path.join(datapath, 'image*'))
                for i in image_list:
                    tar_fd.add(i, os.path.basename(i))
            finally:
                tar_fd.close()

        # Create a datastore object
        dsobject = datastore.create()

        # Write any metadata (here we specifically set the title of the file
        # and specify that this is a plain text file). 
        dsobject.metadata['title'] = self.activity.get_title() + " " + \
            _("presentation")
        dsobject.metadata['icon-color'] = profile.get_color().to_string()
        if embed_flag == True:
            dsobject.metadata['mime_type'] = 'text/html'
            dsobject.set_file_path(html_file)
        else:
            dsobject.metadata['mime_type'] = 'application/x-tar'
            dsobject.set_file_path(tar_path)

        dsobject.metadata['activity'] = 'org.laptop.WebActivity'
        datastore.write(dsobject)
        dsobject.destroy()
        gobject.timeout_add(250,self.savehtml.set_icon, "htmloff")
        return

    def do_savelogo(self, button):
        # write logo code out to datastore
        self.savelogo.set_icon("logo-saveon")
        # grab code from stacks
        logocode = save_logo(self,self.activity.tw)
        if len(logocode) == 0:
            return
        filename = "logosession.lg"

        # Create a datastore object
        dsobject = datastore.create()

        # Write any metadata (here we specifically set the title of the file
        # and specify that this is a plain text file). 
        dsobject.metadata['title'] = self.activity.get_title() + ".lg"
        dsobject.metadata['mime_type'] = 'text/plain'
        dsobject.metadata['icon-color'] = profile.get_color().to_string()

        # save the html code to the instance directory
        try:
            datapath = os.path.join(activity.get_activity_root(), "instance")
        except:
            # Early versions of Sugar (656) didn't support get_activity_root()
            datapath = os.path.join( \
                os.environ['HOME'], \
                ".sugar/default/org.laptop.TurtleArtActivity/instance")

        # Write the file to the data directory of this activity's root. 
        file_path = os.path.join(datapath, filename)
        f = open(file_path, 'w')
        try:
            f.write(logocode)
        finally:
            f.close()

        # Set the file_path in the datastore.
        dsobject.set_file_path(file_path)

        datastore.write(dsobject)
        gobject.timeout_add(250,self.savelogo.set_icon, "logo-saveoff")
        return

    def do_loadmyblock(self, button):
        self.loadmyblock.set_icon("pippy-openon")
        self.import_py()
        gobject.timeout_add(250,self.loadmyblock.set_icon, "pippy-openoff")
        return

    def do_load_ta_project_cb(self, button):
        from sugar.graphics.objectchooser import ObjectChooser
        chooser = ObjectChooser(_("Project"), None, gtk.DIALOG_MODAL | \
            gtk.DIALOG_DESTROY_WITH_PARENT)
        try:
            result = chooser.run()
            if result == gtk.RESPONSE_ACCEPT:
                dsobject = chooser.get_selected_object()
                try:
                    _logger.debug("opening %s " % dsobject.file_path)
                    self.activity.read_file(dsobject.file_path, False)
                except:
                    _logger.debug("couldn't open %s" % dsobject.file_path)
                dsobject.destroy()
        finally:
            chooser.destroy()
            del chooser
        return 

    # Import Python code from the Journal to load into "myblock"
    def import_py(self):
        from sugar.graphics.objectchooser import ObjectChooser
        chooser = ObjectChooser('Python code', None, gtk.DIALOG_MODAL | \
            gtk.DIALOG_DESTROY_WITH_PARENT)
        try:
            result = chooser.run()
            if result == gtk.RESPONSE_ACCEPT:
                dsobject = chooser.get_selected_object()
                try:
                    _logger.debug("opening %s " % dsobject.file_path)
                    FILE = open(dsobject.file_path, "r")
                    self.activity.tw.myblock = FILE.read()
                    FILE.close()
	            tawindow.set_userdefined(self.activity.tw)
                except:
                    _logger.debug("couldn't open %s" % dsobject.file_path)
                dsobject.destroy()
        finally:
            chooser.destroy()
            del chooser

    def do_saveimage(self, button):
        self.saveimage.set_icon("image-saveon")
        _logger.debug("saving image to journal")

        filename = "ta.png"
        # save the image to the instance directory
        datapath = os.path.join(activity.get_activity_root(), "instance")

        # Write the file to the instance directory of this activity's root. 
        file_path = os.path.join(datapath, filename)

        tawindow.save_pict(self.activity.tw,file_path)

        # Create a datastore object
        dsobject = datastore.create()

        # Write metadata
        dsobject.metadata['title'] = self.activity.get_title() + " " + \
                                     _("image")
        dsobject.metadata['icon-color'] = profile.get_color().to_string()
        dsobject.metadata['mime_type'] = 'image/png'
        dsobject.set_file_path(file_path)

        datastore.write(dsobject)
        dsobject.destroy()
        gobject.timeout_add(250,self.saveimage.set_icon, "image-saveoff")
        return

"""
Project toolbar: show/hide palettes; show/hide blocks; run; walk; stop; erase;
                 load sample project; fullscreen
"""
class ProjectToolbar(gtk.Toolbar):

    def __init__(self, pc):
        gtk.Toolbar.__init__(self)
        self.activity = pc

        # palette button (blocks)
        self.palette = ToolButton( "blocksoff" )
        self.palette.set_tooltip(_('Hide palette'))
        self.palette.props.sensitive = True
        self.palette.connect('clicked', self.do_palette)
        try:
            self.palette.props.accelerator = _('<Ctrl>p')
        except:
            pass
        self.insert(self.palette, -1)
        self.palette.show()

        # blocks button (hideshow)
        self.blocks = ToolButton( "hideshowoff" )
        self.blocks.set_tooltip(_('Hide blocks'))
        self.blocks.props.sensitive = True
        self.blocks.connect('clicked', self.do_hideshow)
        try:
            self.blocks.props.accelerator = _('<Ctrl>b')
        except:
            pass
        self.insert(self.blocks, -1)
        self.blocks.show()

        separator = gtk.SeparatorToolItem()
        separator.set_draw(True)
        self.insert(separator, -1)
        separator.show()

        # run button
        self.runproject = ToolButton( "run-fastoff" )
        self.runproject.set_tooltip(_('Run'))
        self.runproject.props.sensitive = True
        self.runproject.connect('clicked', self.do_run)
        try:
            self.runproject.props.accelerator = _('<Ctrl>r')
        except:
            pass
        self.insert(self.runproject, -1)
        self.runproject.show()

        # step button
        self.stepproject = ToolButton( "run-slowoff" )
        self.stepproject.set_tooltip(_('Step'))
        self.stepproject.props.sensitive = True
        self.stepproject.connect('clicked', self.do_step)
        try:
            self.stepproject.props.accelerator = _('<Ctrl>w')
        except:
            pass
        self.insert(self.stepproject, -1)
        self.stepproject.show()

        # debug button
        self.debugproject = ToolButton( "debugoff" )
        self.debugproject.set_tooltip(_('Debug'))
        self.debugproject.props.sensitive = True
        self.debugproject.connect('clicked', self.do_debug)
        try:
            self.debugproject.props.accelerator = _('<Ctrl>d')
        except:
            pass
        self.insert(self.debugproject, -1)
        self.debugproject.show()

        # stop button
        self.stop = ToolButton( "stopitoff" )
        self.stop.set_tooltip(_('Stop turtle'))
        self.stop.props.sensitive = True
        self.stop.connect('clicked', self.do_stop)
        try:
            self.stop.props.accelerator = _('<Ctrl>s')
        except:
            pass
        self.insert(self.stop, -1)
        self.stop.show()

        separator = gtk.SeparatorToolItem()
        separator.set_draw(True)
        self.insert(separator, -1)
        separator.show()

        # eraser button
        self.eraser = ToolButton( "eraseron" )
        self.eraser.set_tooltip(_('Clean'))
        self.eraser.props.sensitive = True
        self.eraser.connect('clicked', self.do_eraser)
        try:
            self.eraser.props.accelerator = _('<Ctrl>e')
        except:
            pass
        self.insert(self.eraser, -1)
        self.eraser.show()

        separator = gtk.SeparatorToolItem()
        separator.set_draw(True)
        self.insert(separator, -1)
        separator.show()

        # full screen
        self.fullscreenb = ToolButton( "view-fullscreen" )
        self.fullscreenb.set_tooltip(_('Fullscreen'))
        self.fullscreenb.props.sensitive = True
        try:
            self.fullscreenb.props.accelerator = '<Alt>Enter'
        except:
            pass
        self.fullscreenb.connect('clicked', self.do_fullscreen)
        self.insert(self.fullscreenb, -1)
        self.fullscreenb.show()

        separator = gtk.SeparatorToolItem()
        separator.set_draw(True)
        self.insert(separator, -1)
        separator.show()

        # Save snapshot ("keep")
        self.keepb = ToolButton( "filesave" )
        self.keepb.set_tooltip(_('Save snapshot'))
        self.keepb.props.sensitive = True
        try:
            self.fullscreenb.props.accelerator = '<Ctrl>S'
        except:
            pass
        self.keepb.connect('clicked', self.do_savesnapshot)
        self.insert(self.keepb, -1)
        self.keepb.show()

        separator = gtk.SeparatorToolItem()
        separator.set_draw(True)
        self.insert(separator, -1)
        separator.show()

        # project open
        self.sampb = ToolButton( "stock-open" )
        self.sampb.set_tooltip(_('Samples'))
        self.sampb.props.sensitive = True
        self.sampb.connect('clicked', self.do_samples)
        try:
             self.sampb.props.accelerator = _('<Ctrl>o')
        except:
            pass
        self.insert(self.sampb, -1)
        self.sampb.show()

    def do_palette(self, button):
        if self.activity.tw.palette == True:
            tawindow.hideshow_palette(self.activity.tw,False)
            self.palette.set_icon("blockson")
            self.palette.set_tooltip(_('Show palette'))
        else:
            tawindow.hideshow_palette(self.activity.tw,True)
            self.palette.set_icon("blocksoff")
            self.palette.set_tooltip(_('Hide palette'))

    def do_hidepalette(self):
        # print "in do_hidepalette"
        self.palette.set_icon("blockson")
        self.palette.set_tooltip(_('Show palette'))

    def do_showpalette(self):
        # print "in do_showpalette"
        self.palette.set_icon("blocksoff")
        self.palette.set_tooltip(_('Hide palette'))
 
    def do_run(self, button):
        self.runproject.set_icon("run-faston")
        self.stop.set_icon("stopiton")
        self.activity.tw.lc.trace = 0
        tawindow.runbutton(self.activity.tw, 0)
        gobject.timeout_add(1000,self.runproject.set_icon,"run-fastoff")

    def do_step(self, button):
        self.stepproject.set_icon("run-slowon")
        self.stop.set_icon("stopiton")
        self.activity.tw.lc.trace = 0
        tawindow.runbutton(self.activity.tw, 3)
        gobject.timeout_add(1000,self.stepproject.set_icon,"run-slowoff")

    def do_debug(self, button):
        self.debugproject.set_icon("debugon")
        self.stop.set_icon("stopiton")
        self.activity.tw.lc.trace = 1
        tawindow.runbutton(self.activity.tw, 6)
        gobject.timeout_add(1000,self.debugproject.set_icon,"debugoff")

    def do_stop(self, button):
        self.stop.set_icon("stopitoff")
        tawindow.stop_button(self.activity.tw)
        self.stepproject.set_icon("run-slowoff")
        self.runproject.set_icon("run-fastoff")

    def do_hideshow(self, button):
        tawindow.hideshow_button(self.activity.tw)
        if self.activity.tw.hide == True: # we just hid the blocks
            self.blocks.set_icon("hideshowon")
            self.blocks.set_tooltip(_('Show blocks'))
        else:
            self.blocks.set_icon("hideshowoff")
            self.blocks.set_tooltip(_('Hide blocks'))
        # update palette buttons too
        if self.activity.tw.palette == False: 
            self.palette.set_icon("blockson")
            self.palette.set_tooltip(_('Show palette'))
        else:
            self.palette.set_icon("blocksoff")
            self.palette.set_tooltip(_('Hide palette'))

    def do_hide(self):
        self.blocks.set_icon("hideshowon")
        self.blocks.set_tooltip(_('Show blocks'))
        self.palette.set_icon("blockson")
        self.palette.set_tooltip(_('Show palette'))

    def do_show(self):
        self.blocks.set_icon("hideshowoff")
        self.blocks.set_tooltip(_('Hide blocks'))
        self.palette.set_icon("blocksoff")
        self.palette.set_tooltip(_('Hide palette'))

    def do_eraser(self, button):
        self.eraser.set_icon("eraseroff")
        self.activity.recenter()
        tawindow.eraser_button(self.activity.tw)
        gobject.timeout_add(250,self.eraser.set_icon,"eraseron")

    def do_fullscreen(self, button):
        self.activity.fullscreen()
        self.activity.recenter()

    def do_samples(self, button):
        tawindow.load_file(self.activity.tw, True)
        # run the activity
        self.stop.set_icon("stopiton")
        tawindow.runbutton(self.activity.tw, 0)

    def do_savesnapshot(self, button):
        # Create a datastore object
        # save the current state of the project to the instance directory
        print "### in savesnapshot ###"

        import tempfile
        tafd, tafile = tempfile.mkstemp(".ta")
        print tafile
        try:
            tawindow.save_data(self.activity.tw,tafile)
        except:
            _logger.debug("couldn't save snapshot to journal")

        # Create a datastore object
        dsobject = datastore.create()

        # Write any metadata
        dsobject.metadata['title'] = self.activity.get_title() + " " + \
                                     _("snapshot")
        dsobject.metadata['icon-color'] = profile.get_color().to_string()
        dsobject.metadata['mime_type'] = 'application/x-turtle-art'
        dsobject.metadata['activity'] = 'org.laptop.TurtleArtActivity'
        dsobject.set_file_path(tafile)
        datastore.write(dsobject)

        # Clean up
        dsobject.destroy()
        os.remove(tafile)
        del tafd
        return