Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/PortfolioActivity.py
blob: 029199269be729f01175a0cb2931b7fc6763b2e3 (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
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
# -*- coding: utf-8 -*-
#Copyright (c) 2011, 2012 Walter Bender

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# You should have received a copy of the GNU General Public License
# along with this library; if not, write to the Free Software
# Foundation, 51 Franklin Street, Suite 500 Boston, MA 02110-1335 USA


from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GObject
import subprocess
import os
import time
import string
from shutil import copyfile

from math import sqrt, ceil

from sugar3.activity import activity
from sugar3 import profile

from sugar3.graphics.toolbarbox import ToolbarBox
from sugar3.activity.widgets import ActivityToolbarButton
from sugar3.activity.widgets import StopButton
from sugar3.graphics.toolbarbox import ToolbarButton

from sugar3.datastore import datastore
from sugar3.graphics.alert import Alert

from sprites import Sprites, Sprite
from exportpdf import save_pdf
from utils import get_path, lighter_color, svg_str_to_pixbuf, svg_rectangle, \
    play_audio_from_file, get_pixbuf_from_journal, genblank, get_hardware, \
    pixbuf_to_base64, base64_to_pixbuf, get_pixbuf_from_file

from toolbar_utils import radio_factory, button_factory, separator_factory, \
    combo_factory, label_factory
from grecord import Grecord

from gettext import gettext as _

import logging
_logger = logging.getLogger("portfolio-activity")

try:
    from sugar3.graphics import style
    GRID_CELL_SIZE = style.GRID_CELL_SIZE
except ImportError:
    GRID_CELL_SIZE = 0

import json
from json import load as jload
from json import dump as jdump
from StringIO import StringIO

import telepathy
from dbus.service import signal
from dbus.gobject_service import ExportedGObject
from sugar3.presence import presenceservice
from sugar3.presence.tubeconn import TubeConnection


SERVICE = 'org.sugar3labs.PortfolioActivity'
IFACE = SERVICE
PATH = '/org/sugar3labs/PortfolioActivity'

# Size and position of title, preview image, and description
PREVIEWW = 600
PREVIEWH = 450
PREVIEWY = 80
TITLEH = 60
DESCRIPTIONY = 550

TWO = 0
TEN = 1
THIRTY = 2
SIXTY = 3
UNITS = [_('2 seconds'), _('10 seconds'), _('30 seconds'), _('1 minute')]
UNIT_DICTIONARY = {TWO: (UNITS[TWO], 2),
                   TEN: (UNITS[TEN], 10),
                   THIRTY: (UNITS[THIRTY], 30),
                   SIXTY: (UNITS[SIXTY], 60)}
XO1 = 'xo1'
XO15 = 'xo1.5'
XO175 = 'xo1.75'
UNKNOWN = 'unknown'

# sprite layers
DRAG = 6
STAR = 5
TOP = 4
UNDRAG = 3
MIDDLE = 2
BOTTOM = 1
HIDE = 0

DEAD_KEYS = ['grave', 'acute', 'circumflex', 'tilde', 'diaeresis', 'abovering']
DEAD_DICTS = [{'A': 192, 'E': 200, 'I': 204, 'O': 210, 'U': 217, 'a': 224,
               'e': 232, 'i': 236, 'o': 242, 'u': 249},
              {'A': 193, 'E': 201, 'I': 205, 'O': 211, 'U': 218, 'a': 225,
               'e': 233, 'i': 237, 'o': 243, 'u': 250},
              {'A': 194, 'E': 202, 'I': 206, 'O': 212, 'U': 219, 'a': 226,
               'e': 234, 'i': 238, 'o': 244, 'u': 251},
              {'A': 195, 'O': 211, 'N': 209, 'U': 360, 'a': 227, 'o': 245,
               'n': 241, 'u': 361},
              {'A': 196, 'E': 203, 'I': 207, 'O': 211, 'U': 218, 'a': 228,
               'e': 235, 'i': 239, 'o': 245, 'u': 252},
              {'A': 197, 'a': 229}]
NOISE_KEYS = ['Shift_L', 'Shift_R', 'Control_L', 'Caps_Lock', 'Pause',
              'Alt_L', 'Alt_R', 'KP_Enter', 'ISO_Level3_Shift', 'KP_Divide',
              'Escape', 'Return', 'KP_Page_Up', 'Up', 'Down', 'Menu',
              'Left', 'Right', 'KP_Home', 'KP_End', 'KP_Up', 'Super_L',
              'KP_Down', 'KP_Left', 'KP_Right', 'KP_Page_Down', 'Scroll_Lock',
              'Page_Down', 'Page_Up']
WHITE_SPACE = ['space', 'Tab']

CURSOR = '█'
NEWLINE = '\n'


class Slide():
    ''' A container for a slide '''

    def __init__(self, owner, uid, colors, title, preview, desc):
        self.active = True
        self.owner = owner
        self.uid = uid
        self.colors = colors
        self.title = title
        self.preview = preview
        self.preview2 = None  # larger version for fullscreen mode
        self.description = desc
        self.sound = None
        self.dirty = False
        self.fav = True
        self.thumb = None
        self.star = None

    def hide(self):
        if self.star is not None:
            self.star.hide()
        if self.thumb is not None:
            self.thumb.hide()


class PortfolioActivity(activity.Activity):
    ''' Make a slideshow from starred Journal entries. '''

    def __init__(self, handle):
        ''' Initialize the toolbars and the work surface '''
        super(PortfolioActivity, self).__init__(handle)

        self.datapath = get_path(activity, 'instance')
        self._buddies = [profile.get_nick_name()]
        self._colors = profile.get_color().to_string().split(',')
        self.initiating = None  # sharing (True) or joining (False)

        self._playing = False
        self._first_time = True

        self._width = Gdk.Screen.width()
        self._height = Gdk.Screen.height()
        self._scale = Gdk.Screen.height() / 900.

        self._titlewh = [self._width, TITLEH * self._scale]
        self._titlexy = [0, 0]
        self._previewwh = [PREVIEWW * self._scale, PREVIEWH * self._scale]
        self._previewxy = [(self._width - self._previewwh[0]) / 2,
                           PREVIEWY * self._scale]
        self._descriptionwh = [self._width,
                               self._height - DESCRIPTIONY * self._scale - 55]
        self._descriptionxy = [0, DESCRIPTIONY * self._scale]

        if hasattr(self, 'get_window') and \
           hasattr(self.get_window(), 'get_cursor'):
            self.old_cursor = self.get_window().get_cursor()
        else:
            self.old_cursor = None

        self._hw = get_hardware()

        self._setup_toolbars()
        self._setup_canvas()

        self._slides = []
        self._current_slide = 0

        self._thumbnail_mode = False
        self._find_starred()
        self._setup_workspace()

        self._recording = False
        self._grecord = None
        self._alert = None

        self._keypress = None
        self._selected_spr = None
        self._dead_key = ''
        self._saved_string = ''
        self._startpos = [0, 0]
        self._dragpos = [0, 0]

        self._setup_presence_service()

    def _setup_canvas(self):
        ''' Create a canvas '''
        self._canvas = Gtk.DrawingArea()
        self._canvas.set_size_request(int(Gdk.Screen.width()),
                                      int(Gdk.Screen.height()))
        self._canvas.show()
        self.set_canvas(self._canvas)
        self.show_all()

        self._canvas.set_flags(Gtk.CAN_FOCUS)
        self._canvas.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
        self._canvas.add_events(Gdk.EventMask.POINTER_MOTION_MASK)
        self._canvas.add_events(Gdk.EventMask.BUTTON_RELEASE_MASK)
        self._canvas.add_events(Gdk.EventMask.KEY_PRESS_MASK)
        self._canvas.add_events(Gdk.CONFIGURE)
        self._canvas.connect('expose-event', self._expose_cb)
        self._canvas.connect('button-press-event', self._button_press_cb)
        self._canvas.connect('button-release-event', self._button_release_cb)
        self._canvas.connect('motion-notify-event', self._mouse_move_cb)
        self._canvas.connect('key-press-event', self._keypress_cb)
        self._canvas.connect('configure-event', self._configure_cb)

        self._canvas.grab_focus()

    def _configure_cb(self, win, event):
        # landscape or portrait?
        self._width = Gdk.Screen.width()
        self._height = Gdk.Screen.height()
        if self._width > self._height:
            self._scale = Gdk.Screen.height() / 900.
        else:
            self._scale = Gdk.Screen.width() / 1200.

        self._my_canvas.hide()
        self._title.hide()
        self._description.hide()
        self._titlewh = [self._width, TITLEH * self._scale]
        self._titlexy = [0, 0]
        self._previewwh = [PREVIEWW * self._scale, PREVIEWH * self._scale]
        self._previewxy = [(self._width - self._previewwh[0]) / 2,
                           PREVIEWY * self._scale]
        self._descriptionwh = [self._width,
                               self._height - DESCRIPTIONY * self._scale - 55]
        self._descriptionxy = [0, DESCRIPTIONY * self._scale]

        self._configured_sprites()  # Some sprites are sized to screen
        self._clear_screen()
        if self._thumbnail_mode:
            self._thumbs_cb()
        else:
            self._show_slide()

    def _setup_workspace(self):
        ''' Prepare to render the datastore entries. '''

        # Use the lighter color for the text background
        if lighter_color(self._colors) == 0:
            tmp = self._colors[0]
            self._colors[0] = self._colors[1]
            self._colors[1] = tmp

        if self._hw[0:2] == 'xo':
            self._titlef = 18
            self._descriptionf = 12
        else:
            self._titlef = 36
            self._descriptionf = 24

        # Generate the sprites we'll need...
        self._sprites = Sprites(self._canvas)

        if self._nobjects == 0:
            star_size = 55
        else:
            star_size = int(150. / int(ceil(sqrt(self._nobjects))))
        self._fav_pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
            os.path.join(activity.get_bundle_path(), 'icons',
                         'favorite-on.svg'), star_size, star_size)
        self._unfav_pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
            os.path.join(activity.get_bundle_path(), 'icons',
                         'favorite-off.svg'), star_size, star_size)

        self.record_pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
            os.path.join(activity.get_bundle_path(), 'icons',
                         'media-audio.svg'), 55, 55)
        self.recording_pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
            os.path.join(activity.get_bundle_path(), 'icons',
                         'media-audio-recording.svg'), 55, 55)
        self.playback_pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
            os.path.join(activity.get_bundle_path(), 'icons',
                         'speaker-100.svg'), 55, 55)
        self.playing_pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
            os.path.join(activity.get_bundle_path(), 'icons',
                         'speaker-0.svg'), 55, 55)

        self._record_button = Sprite(self._sprites, 0, 0, self.record_pixbuf)
        self._record_button.set_layer(DRAG)
        self._record_button.type = 'record'

        self._playback_button = Sprite(self._sprites, 0, 0,
                                       self.playback_pixbuf)
        self._playback_button.type = 'noplay'
        self._playback_button.hide()

        self.prev_pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
            os.path.join(activity.get_bundle_path(), 'icons',
                         'go-previous.svg'), 55, 55)
        self.next_pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
            os.path.join(activity.get_bundle_path(), 'icons',
                         'go-next.svg'), 55, 55)
        self.prev_off_pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
            os.path.join(activity.get_bundle_path(), 'icons',
                         'go-previous-inactive.svg'), 55, 55)
        self.next_off_pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
            os.path.join(activity.get_bundle_path(), 'icons',
                         'go-next-inactive.svg'), 55, 55)

        self._prev = Sprite(self._sprites, 0, 0, self.prev_off_pixbuf)
        self._prev.set_layer(DRAG)
        self._prev.type = 'prev'

        self._next = Sprite(self._sprites, 0, 0, self.next_pixbuf)
        self._next.set_layer(DRAG)
        self._next.type = 'next'

        self._help = Sprite(self._sprites,
                            0, 0,
                            GdkPixbuf.Pixbuf.new_from_file_at_size(
                os.path.join(activity.get_bundle_path(), 'help.png'),
                int(self._previewwh[0]),
                int(self._previewwh[1])))
        self._help.hide()

        self._preview = Sprite(self._sprites,
                               0, 0,
                               svg_str_to_pixbuf(genblank(
                        int(self._previewwh[0]),
                        int(self._previewwh[1]),
                        self._colors)))

        self._configured_sprites()  # Some sprites are sized to screen

        self._clear_screen()

        self.i = 0
        self._show_slide()

        self._playing = False
        self._rate = 10

    def _configured_sprites(self):
        ''' Some sprites are sized or positioned based on screen
        configuration '''

        self._preview.move((int(self._previewxy[0]),
                            int(self._previewxy[1])))
        self._help.move((int(self._previewxy[0]),
                         int(self._previewxy[1])))
        self._record_button.move((self._width - 55, self._titlewh[1]))
        self._playback_button.move((self._width - 55, self._titlewh[1] + 55))
        self._prev.move((0, int((self._height - 55) / 2)))
        self._next.move((self._width - 55, int((self._height - 55) / 2)))
        self._title = Sprite(self._sprites,
                             int(self._titlexy[0]),
                             int(self._titlexy[1]),
                             svg_str_to_pixbuf(
                genblank(self._titlewh[0], self._titlewh[1], self._colors)))
        self._title.set_label_attributes(int(self._titlef * self._scale),
                                         rescale=False)
        self._title.type = 'title'

        self._description = Sprite(self._sprites,
                                   int(self._descriptionxy[0]),
                                   int(self._descriptionxy[1]),
                                   svg_str_to_pixbuf(
                genblank(int(self._descriptionwh[0]),
                         int(self._descriptionwh[1]),
                         self._colors)))
        self._description.set_label_attributes(
            int(self._descriptionf * self._scale))
        self._description.type = 'description'

        self._my_canvas = Sprite(
            self._sprites, 0, 0, svg_str_to_pixbuf(genblank(
                    self._width, self._height, (self._colors[0],
                                                self._colors[0]))))
        self._my_canvas.set_layer(BOTTOM)
        self._my_canvas.type = 'background'

    def _setup_toolbars(self):
        ''' Setup the toolbars. '''

        self.max_participants = 5  # sharing

        toolbox = ToolbarBox()

        # Activity toolbar
        activity_button_toolbar = ActivityToolbarButton(self)

        toolbox.toolbar.insert(activity_button_toolbar, 0)
        activity_button_toolbar.show()

        self.set_toolbar_box(toolbox)
        toolbox.show()
        self.toolbar = toolbox.toolbar

        adjust_toolbar = Gtk.Toolbar()
        adjust_toolbar_button = ToolbarButton(
            label=_('Adjust'),
            page=adjust_toolbar,
            icon_name='preferences-system')
        adjust_toolbar.show_all()
        adjust_toolbar_button.show()

        toolbox.toolbar.insert(adjust_toolbar_button, -1)

        button_factory('view-fullscreen', self.toolbar,
                       self.do_fullscreen_cb, tooltip=_('Fullscreen'),
                       accelerator='<Alt>Return')

        self._auto_button = button_factory(
            'media-playback-start', self.toolbar,
            self._autoplay_cb, tooltip=_('Autoplay'))

        label = label_factory(adjust_toolbar, _('Adjust playback speed'))
        label.show()

        separator_factory(adjust_toolbar, False, False)

        self._unit_combo = combo_factory(UNITS,
                                         adjust_toolbar,
                                         self._unit_combo_cb,
                                         default=UNITS[TEN],
                                         tooltip=_('Adjust playback speed'))
        self._unit_combo.show()

        separator_factory(adjust_toolbar)

        button_factory('system-restart',
                       adjust_toolbar,
                       self._rescan_cb,
                       tooltip=_('Refresh'))

        separator_factory(self.toolbar)

        self._slide_button = radio_factory('slide-view',
                                           self.toolbar,
                                           self._slides_cb,
                                           group=None,
                                           tooltip=_('Slide view'))

        self._thumb_button = radio_factory('thumbs-view',
                                           self.toolbar,
                                           self._thumbs_cb,
                                           tooltip=_('Thumbnail view'),
                                           group=self._slide_button)

        separator_factory(self.toolbar)
        self._save_pdf = button_factory('save-as-pdf',
                                        self.toolbar,
                                        self._save_as_pdf_cb,
                                        tooltip=_('Save as PDF'))

        separator_factory(toolbox.toolbar, True, False)

        stop_button = StopButton(self)
        stop_button.props.accelerator = '<Ctrl>q'
        toolbox.toolbar.insert(stop_button, -1)
        stop_button.show()

    def _destroy_cb(self, win, event):
        ''' Clean up on the way out. '''
        Gtk.main_quit()

    def _thumb_to_slide(self, spr):
        if spr is None:
            return None
        for slide in self._slides:
            if slide.thumb == spr:
                return slide
        return None

    def _star_to_slide(self, spr):
        if spr is None:
            return None
        for slide in self._slides:
            if slide.star == spr:
                return slide
        return None

    def _uid_to_slide(self, uid):
        for slide in self._slides:
            if slide.uid == uid:
                return slide
        return None

    def _make_star(self, slide):
        slide.star = Sprite(self._sprites, 0, 0, self._fav_pixbuf)
        slide.star.type = 'star'
        slide.star.set_layer(STAR)
        slide.fav = True

    def _find_starred(self):
        ''' Find all the _stars in the Journal. '''
        for slide in self._slides:
            slide.active = False
        self.dsobjects, self._nobjects = datastore.find({'keep': '1'})
        _logger.debug('found %d starred items', self._nobjects)
        for dsobj in self.dsobjects:
            slide = self._uid_to_slide(dsobj.object_id)
            owner = self._buddies[0]
            title = ''
            desc = ''
            preview = None
            if hasattr(dsobj, 'metadata'):
                if 'title' in dsobj.metadata:
                    title = dsobj.metadata['title']
                if 'description' in dsobj.metadata:
                    desc = dsobj.metadata['description']
                if 'mime_type' in dsobj.metadata and \
                   dsobj.metadata['mime_type'][0:5] == 'image':
                    preview = get_pixbuf_from_file(dsobj.file_path,
                                                   int(PREVIEWW * self._scale),
                                                   int(PREVIEWH * self._scale))
                elif 'preview' in dsobj.metadata:
                    preview = get_pixbuf_from_journal(dsobj, 300, 225)
            else:
                _logger.debug('dsobj has no metadata')

            if slide is None:
                self._slides.append(Slide(owner,
                                         dsobj.object_id,
                                         self._colors,
                                         title,
                                         preview,
                                         desc))
            else:
                slide.title = title
                slide.preview = preview
                slide.description = desc
                slide.active = True
                slide.fav = True
                if slide.star is not None:
                    slide.star.hide()
                if slide.thumb is not None:
                    slide.thumb.hide()

    def _rescan_cb(self, button=None):
        ''' Rescan the Journal for changes in starred items. '''
        if self.initiating is not None and not self.initiating:
            return
        if self.initiating:
            self._send_event('R:rescanning')
        self._help.hide()
        self._find_starred()
        self.i = 0
        if self.initiating:
            self._share_slides()
        if self._thumbnail_mode:
            self._thumbs_cb()
        else:
            self._show_slide()

    def _first_cb(self, button=None):
        self.i = 0
        self._show_slide(direction=-1)

    def _prev_cb(self, button=None):
        ''' The previous button has been clicked; goto previous slide. '''
        if self.i > 0:
            self.i -= 1
            self._show_slide(direction=-1)

    def _next_cb(self, button=None):
        ''' The next button has been clicked; goto next slide. '''
        if self.i < self._nobjects - 1:
            self.i += 1
            self._show_slide()

    def _last_cb(self, button=None):
        self.i = self._nobjects - 1
        self._show_slide()

    def _autoplay_cb(self, button=None):
        ''' The autoplay button has been clicked; step through slides. '''
        if self._playing:
            self._stop_autoplay()
        else:
            if self._thumbnail_mode:
                self._thumbnail_mode = False
                self.i = self._current_slide
            if self._first_time:
                self.i -= 1
                self._first_time = False
            self._playing = True
            self._auto_button.set_icon('media-playback-pause')
            self._loop()

    def _stop_autoplay(self):
        ''' Stop autoplaying. '''
        self._playing = False
        self._auto_button.set_icon('media-playback-start')
        if hasattr(self, '_timeout_id') and self._timeout_id is not None:
            GObject.source_remove(self._timeout_id)

    def _loop(self):
        ''' Show a slide and then call oneself with a timeout. '''
        self.i += 1
        if self.i == self._nobjects:
            self.i = 0
        self._show_slide()
        self._timeout_id = GObject.timeout_add(int(self._rate * 1000),
                                               self._loop)

    def _save_as_pdf_cb(self, button=None):
        ''' Export an PDF version of the slideshow to the Journal. '''
        if self.initiating is not None and not self.initiating:
            nick = self._buddies[-1]
        else:
            nick = profile.get_nick_name()
        _logger.debug('saving to PDF...')
        if 'description' in self.metadata:
            tmp_file = save_pdf(self, nick,
                                description=self.metadata['description'])
        else:
            tmp_file = save_pdf(self, profile.get_nick_name())

        dsobject = datastore.create()
        dsobject.metadata['title'] = '%s %s' % (nick, _('Portfolio'))
        dsobject.metadata['icon-color'] = profile.get_color().to_string()
        dsobject.metadata['mime_type'] = 'application/pdf'
        dsobject.set_file_path(tmp_file)
        dsobject.metadata['activity'] = 'org.laptop.sugar3.ReadActivity'
        datastore.write(dsobject)
        dsobject.destroy()
        return

    def _clear_screen(self):
        ''' Clear the screen to the darker of the two XO colors. '''
        for slide in self._slides:
            slide.hide()
        self._title.hide()
        self._preview.hide()
        self._description.hide()
        self.invalt(0, 0, self._width, self._height)

        # Reset drag settings
        self._press = None
        self._release = None
        self._dragpos = [0, 0]
        self._total_drag = [0, 0]
        self.last_spr_moved = None

    def _show_slide(self, direction=1):
        ''' Display a title, preview image, and decription for slide
        i. Play an audio note if there is one recorded for this
        object. '''
        self._clear_screen()

        if len(self._slides) == 0:
            self._prev.set_image(self.prev_off_pixbuf)
            self._next.set_image(self.next_off_pixbuf)
            self._description.set_label(
                _('Do you have any items in your Journal starred?'))
            self._help.set_layer(TOP)
            self._description.set_layer(MIDDLE)
            return

        slide = self._slides[self.i]
        # Skip slide if unstarred or inactive
        if not slide.active or not slide.fav:
            counter = 0
            while not slide.active or not slide.fav:
                self.i += direction
                if self.i < 0:
                    self.i = len(self._slides) - 1
                elif self.i > len(self._slides) - 1:
                    self.i = 0
                counter += 1
                if counter == len(self._slides):
                    _logger.debug('No _stars: nothing to show')
                    return
                slide = self._slides[self.i]

        if self.i == 0:
            self._prev.set_image(self.prev_off_pixbuf)
        else:
            self._prev.set_image(self.prev_pixbuf)
        if self.i == len(self._slides) - 1:
            self._next.set_image(self.next_off_pixbuf)
        else:
            self._next.set_image(self.next_pixbuf)

        pixbuf = slide.preview

        if pixbuf is not None:
            self._preview.set_shape(pixbuf.scale_simple(
                    int(PREVIEWW * self._scale),
                    int(PREVIEWH * self._scale),
                    GdkPixbuf.InterpType.NEAREST))
            self._preview.set_layer(MIDDLE)
        else:
            if self._preview is not None:
                self._preview.hide()

        self._title.set_label(slide.title)
        self._title.set_layer(MIDDLE)

        self._description.set_label(slide.description)
        self._description.set_layer(MIDDLE)

        if self.initiating is None or self.initiating:
            if slide.sound is None:
                slide.sound = self._search_for_audio_note(slide.uid)
            if slide.sound is not None:
                if self._playing:
                    _logger.debug('Playing audio note')
                    GObject.idle_add(play_audio_from_file,
                                     slide.sound.file_path)
                self._playback_button.set_image(self.playback_pixbuf)
                self._playback_button.type = 'play'
                self._playback_button.set_layer(DRAG)
            else:
                self._playback_button.hide()
                self._playback_button.type = 'noplay'
            self._record_button.set_image(self.record_pixbuf)
        else:
            self._record_button.hide()
            self._playback_button.hide()

    def _slides_cb(self, button=None):
        if self._thumbnail_mode:
            self._thumbnail_mode = False
        self.i = self._current_slide
        self._prev.set_layer(DRAG)
        self._next.set_layer(DRAG)
        self._record_button.set_layer(DRAG)
        self._playback_button.set_layer(DRAG)
        self._show_slide()

    def _thumbs_cb(self, button=None):
        ''' Toggle between thumbnail view and slideshow view. '''
        if not self._thumbnail_mode:
            self._thumbnail_mode = True
        self._first_time = True
        self._show_thumbs()
        return False

    def _count_active(self):
        count = 0
        for slide in self._slides:
            if slide.active:
                count += 1
        return count

    def _show_thumbs(self):
        self._stop_autoplay()
        self._current_slide = self.i
        self._clear_screen()

        self._record_button.hide()
        self._playback_button.hide()
        self._prev.hide()
        self._next.hide()

        n = int(ceil(sqrt(self._count_active())))
        if n > 0:
            w = int(self._width / n)
        else:
            w = self._width
        h = int(w * 0.75)  # maintain 4:3 aspect ratio
        x_off = int((self._width - n * w) / 2)
        x = x_off
        y = 0
        for slide in self._slides:
            if not slide.active:
                continue
            self._show_thumb(slide, x, y, w, h)
            x += w
            if x + w > self._width:
                x = x_off
                y += h
        self.i = 0  # Reset position in slideshow to the beginning

    def _show_thumb(self, slide, x, y, w, h):
        ''' Display a preview image and title as a thumbnail. '''

        # Is size has changed, regenerate the thumbnail
        if slide.thumb is not None:
            sw, sh = slide.thumb.get_dimensions()
            if sw == w and sh == h:
                slide.thumb.move((x, y))
            else:
                slide.thumb.hide()
                slide.thumb = None
        if slide.thumb is None:
            if slide.preview is not None:
                pixbuf_thumb = slide.preview.scale_simple(int(w), int(h),
                                                          GdkPixbuf.InterpType.TILES)
            else:
                pixbuf_thumb = svg_str_to_pixbuf(genblank(int(w), int(h),
                                                          self._colors))
            slide.thumb = Sprite(self._sprites, x, y, pixbuf_thumb)
            # Add a border
            slide.thumb.set_image(svg_str_to_pixbuf(
                    svg_rectangle(int(w), int(h), slide.colors)), i=1)
        slide.thumb.set_layer(TOP)
        if slide.star is None:
            self._make_star(slide)
        slide.star.set_layer(STAR)
        slide.star.move((x, y))

    def _expose_cb(self, win, event):
        ''' Callback to handle window expose events '''
        self.do_expose_event(event)
        return True

    # Handle the expose-event by drawing
    def do_expose_event(self, event):

        # Create the cairo context
        cr = self.canvas.window.cairo_create()

        # Restrict Cairo to the exposed area; avoid extra work
        cr.rectangle(event.area.x, event.area.y,
                event.area.width, event.area.height)
        cr.clip()

        # Refresh sprite list
        self._sprites.redraw_sprites(cr=cr)

    def write_file(self, file_path):
        ''' Clean up '''
        if self.initiating is not None and not self.initiating:
            _logger.debug('I am a joiner, so I am not saving.')
            return

        self._save_changes_cb()
        if os.path.exists(os.path.join(self.datapath, 'output.ogg')):
            os.remove(os.path.join(self.datapath, 'output.ogg'))

    def do_fullscreen_cb(self, button):
        ''' Hide the sugar3 toolbars. '''
        self.fullscreen()

    def invalt(self, x, y, w, h):
        ''' Mark a region for refresh '''
        self._canvas.window.invalidate_rect(
            (int(x), int(y), int(w), int(h)), False)

    def _button_press_cb(self, win, event):
        ''' The mouse button was pressed. Is it on a thumbnail sprite? '''
        x, y = map(int, event.get_coords())

        self._dragpos = [x, y]
        self._total_drag = [0, 0]

        spr = self._sprites.find_sprite((x, y))
        if spr is not None:
            self._startpos = spr.get_xy()
        self._press = None
        self._release = None

        # Are we clicking on a title or description?
        if spr.type == 'title' or spr.type == 'description':
            if spr == self._selected_spr:
                return True
            elif self._selected_spr is not None:
                self._unselect()
            self._selected_spr = spr
            self._saved_string = spr.labels[0]
            if spr.type == 'description':
                if self.initiating is not None and not self.initiating:
                    label = '%s\n[%s] %s' % (self._selected_spr.labels[0],
                                             profile.get_nick_name(), CURSOR)
                else:
                    label = '%s%s' % (self._selected_spr.labels[0], CURSOR)
                self._selected_spr.set_label(label)
            elif spr.type == 'title':
                if self.initiating is None or self.initiating:
                    label = '%s%s' % (self._selected_spr.labels[0], CURSOR)
                    self._selected_spr.set_label(label)
                else:
                    self._selected_spr = None
        else:
            self._unselect()

        # Are we clicking on a button?
        if spr.type == 'next':
            self._next_cb()
            return True
        elif spr.type == 'prev':
            self._prev_cb()
            return True
        elif spr.type == 'record':
            self._record_cb()
            return True
        elif spr.type == 'recording':
            self._record_cb()
            return True
        elif spr.type == 'play':
            self._playback_recording_cb()
            return True

        # Are we clicking on a star?
        if spr.type == 'star':
            spr.set_shape(self._unfav_pixbuf)
            spr.type = 'unstar'
            slide = self._star_to_slide(spr)
            slide.fav = False
            if self.initiating:
                self._send_star(slide.uid, False)
        elif spr.type == 'unstar':
            spr.set_shape(self._fav_pixbuf)
            spr.type = 'star'
            slide = self._star_to_slide(spr)
            slide.fav = True
            if self.initiating:
                self._send_star(slide.uid, True)

        # Are we clicking on a thumbnail?
        slide = self._thumb_to_slide(spr)
        if slide is None:
            return False

        self.last_spr_moved = spr
        self._press = spr
        self._press.set_layer(DRAG)
        slide.star.set_layer(DRAG+1)
        return False

    def _mouse_move_cb(self, win, event):
        ''' Drag a thumbnail with the mouse. '''
        spr = self._press
        if spr is None:
            self._dragpos = [0, 0]
            return False
        win.grab_focus()
        x, y = map(int, event.get_coords())
        dx = x - self._dragpos[0]
        dy = y - self._dragpos[1]
        spr.move_relative([dx, dy])
        # Also move the star
        slide = self._thumb_to_slide(spr)
        if slide is not None:
            slide.star.move_relative([dx, dy])
        self._dragpos = [x, y]
        self._total_drag[0] += dx
        self._total_drag[1] += dy
        return False

    def _button_release_cb(self, win, event):
        ''' Button event is used to swap slides or goto next slide. '''
        win.grab_focus()
        self._dragpos = [0, 0]
        x, y = map(int, event.get_coords())

        if self._press is None:
            return

        if self._thumbnail_mode:
            press_slide = self._thumb_to_slide(self._press)
            # Drop the dragged thumbnail below the other thumbnails so
            # that you can find the thumbnail beneath it...
            self._press.set_layer(UNDRAG)
            if press_slide is not None:
                press_slide.star.set_layer(STAR)
            spr = self._sprites.find_sprite((x, y))
            self._press.set_layer(TOP)  # and then restore press to top layer

            if press_slide is not None:
                self._release = spr
                # If we found a thumbnail
                # ...and it is the one we dragged, jump to that slide.
                if self._press == self._release:
                    if self._total_drag[0] * self._total_drag[0] + \
                       self._total_drag[1] * self._total_drag[1] < 200:
                        self.i = self._slides.index(press_slide)
                        self._current_slide = self.i
                        self._slide_button.set_active(True)
                    else:  # TODO: test for dragged to beginning
                        i = self._slides.index(press_slide)
                        n = len(self._slides) - 1
                        press_slide.thumb.move(self._startpos)
                        press_slide.star.move(self._startpos)
                        if self._total_drag[1] > 0:
                            while i < n:
                                self._swap_slides(i, i + 1)
                                i += 1
                        else:
                            while i > 0:
                                self._swap_slides(i, i - 1)
                                i -= 1
                # ...and it is not the one we dragged, swap their positions.
                else:
                    # Could have released on top of a star or a thumbnail
                    if self._release.type in ['star', 'unstar']:
                        release_slide = self._star_to_slide(self._release)
                    else:
                        release_slide = self._thumb_to_slide(self._release)
                    press_slide.thumb.move(self._startpos)
                    press_slide.star.move(self._startpos)
                    self._swap_slides(self._slides.index(press_slide),
                                      self._slides.index(release_slide))
        self._press = None
        self._release = None
        return False

    def _swap_slides(self, i, j):
        ''' Swap order and x, y position of two slides '''
        tmp = self._slides[i]
        self._slides[i] = self._slides[j]
        self._slides[j] = tmp
        xi, yi = self._slides[i].thumb.get_xy()
        xj, yj = self._slides[j].thumb.get_xy()
        self._slides[i].thumb.move((xj, yj))
        self._slides[i].star.move((xj, yj))
        self._slides[j].thumb.move((xi, yi))
        self._slides[j].star.move((xi, yi))

    def _unit_combo_cb(self, arg=None):
        ''' Read value of predefined conversion factors from combo box '''
        if hasattr(self, '_unit_combo'):
            active = self._unit_combo.get_active()
            if active in UNIT_DICTIONARY:
                self._rate = UNIT_DICTIONARY[active][1]

    def _record_cb(self, button=None):
        ''' Start/stop audio recording '''
        if self.initiating is not None and not self.initiating:
            return
        if self._grecord is None:
            _logger.debug('setting up grecord')
            self._grecord = Grecord(self)
        if self._recording:  # Was recording, so stop (and save?)
            _logger.debug('recording...True. Preparing to save.')
            self._grecord.stop_recording_audio()
            self._recording = False
            self._record_button.set_image(self.record_pixbuf)
            self._record_button.type = 'record'
            self._record_button.set_layer(DRAG)
            self._playback_button.set_image(self.playback_pixbuf)
            self._playback_button.type = 'play'
            self._playback_button.set_layer(DRAG)
            # Autosave if there was not already a recording
            slide = self._slides[self.i]
            _logger.debug('Autosaving recording')
            self._notify_successful_save(title=_('Save recording'))
            GObject.timeout_add(100, self._wait_for_transcoding_to_finish)
        else:  # Wasn't recording, so start
            _logger.debug('recording...False. Start recording.')
            self._record_button.set_image(self.recording_pixbuf)
            self._record_button.type = 'recording'
            self._record_button.set_layer(DRAG)
            self._grecord.record_audio()
            self._recording = True

    def _wait_for_transcoding_to_finish(self, button=None):
        while not self._grecord.transcoding_complete():
            time.sleep(1)
        if self._alert is not None:
            self.remove_alert(self._alert)
            self._alert = None
        self._save_recording()

    def _playback_recording_cb(self, button=None):
        ''' Play back current recording '''
        _logger.debug('Playback current recording from output.ogg...')
        self._playback_button.set_image(self.playing_pixbuf)
        self._playback_button.set_layer(DRAG)
        self._playback_button.type = 'playing'
        GObject.timeout_add(1000, self._playback_button_reset)
        GObject.idle_add(play_audio_from_file,
                         self._slides[self.i].sound.file_path)

    def _playback_button_reset(self):
        self._playback_button.set_image(self.playback_pixbuf)
        self._playback_button.set_layer(DRAG)
        self._playback_button.type = 'play'

    def _save_recording(self):
        if os.path.exists(os.path.join(self.datapath, 'output.ogg')):
            _logger.debug('Saving recording to Journal...')
            slide = self._slides[self.i]
            copyfile(os.path.join(self.datapath, 'output.ogg'),
                     os.path.join(self.datapath, '%s.ogg' % (slide.uid)))
            dsobject = self._search_for_audio_note(slide.uid)
            if dsobject is None:
                dsobject = datastore.create()
            if dsobject is not None:
                _logger.debug(slide.title)
                slide.sound = dsobject
                dsobject.metadata['title'] = _('audio note for %s') % \
                    (slide.title)
                dsobject.metadata['icon-color'] = \
                    profile.get_color().to_string()
                dsobject.metadata['tags'] = slide.uid
                dsobject.metadata['mime_type'] = 'audio/ogg'
                dsobject.set_file_path(
                    os.path.join(self.datapath, '%s.ogg' % (slide.uid)))
                datastore.write(dsobject)
                dsobject.destroy()
        else:
            _logger.debug('Nothing to save...')
        return

    def _search_for_audio_note(self, obj_id):
        ''' Look to see if there is already a sound recorded for this
        dsobject '''
        if self.initiating is not None and not self.initiating:
            return
        dsobjects, nobjects = datastore.find({'mime_type': ['audio/ogg']})
        # Look for tag that matches the target object id
        for dsobject in dsobjects:
            if 'tags' in dsobject.metadata and \
               obj_id in dsobject.metadata['tags']:
                _logger.debug('Found audio note')
                return dsobject
        return None

    def _save_changes_cb(self, button=None):
        ''' Find the object in the datastore and write out the changes
        to the decriptions and titles. '''
        if self.initiating is not None and not self.initiating:
            _logger.debug('skipping write (%s)' % (str(self.initiating)))
            return
        for slide in self._slides:
            if not slide.dirty:
                continue
            _logger.debug('%d is dirty... writing' % (
                    self._slides.index(slide)))
            jobject = datastore.get(slide.uid)
            jobject.metadata['description'] = slide.description
            jobject.metadata['title'] = slide.title
            datastore.write(jobject,
                            update_mtime=False,
                            reply_handler=self.datastore_write_cb,
                            error_handler=self.datastore_write_error_cb)

    def datastore_write_cb(self):
        pass

    def datastore_write_error_cb(self, error):
        _logger.error('datastore_write_error_cb: %r' % error)

    def _notify_successful_save(self, title='', msg=''):
        ''' Notify user when saves are completed '''
        self._alert = Alert()
        self._alert.props.title = title
        self._alert.props.msg = msg
        self.add_alert(self._alert)
        self._alert.show()

    def _keypress_cb(self, area, event):
        ''' Keyboard '''
        keyname = Gdk.keyval_name(event.keyval)
        keyunicode = Gdk.keyval_to_unicode(event.keyval)
        if event.get_state() & Gdk.ModifierType.MOD1_MASK:
            alt_mask = True
            alt_flag = 'T'
        else:
            alt_mask = False
            alt_flag = 'F'
        self._key_press(alt_mask, keyname, keyunicode)
        return keyname

    def _key_press(self, alt_mask, keyname, keyunicode):
        if keyname is None:
            return False
        self._keypress = keyname
        if alt_mask:
            if keyname == 'q':
                exit()
        elif self._selected_spr is not None:
            self.process_alphanumeric_input(keyname, keyunicode)
        elif not self._thumbnail_mode:
            if keyname == 'Home':
                self._first_cb()
            elif keyname == 'Left':
                self._prev_cb()
            elif keyname == 'Right' or keyname == 'space':
                self._next_cb()
            elif keyname == 'End':
                self._last_cb()
        return True

    def process_alphanumeric_input(self, keyname, keyunicode):
        ''' Make sure alphanumeric input is properly parsed. '''
        if len(self._selected_spr.labels[0]) > 0:
            c = self._selected_spr.labels[0].count(CURSOR)
            if c == 0:
                oldleft = self._selected_spr.labels[0]
                oldright = ''
            elif len(self._selected_spr.labels[0]) == 1:
                oldleft = ''
                oldright = ''
            elif CURSOR in self._selected_spr.labels[0]:
                oldleft, oldright = \
                    self._selected_spr.labels[0].split(CURSOR)
            else:  # Where did our cursor go?
                oldleft = self._selected_spr.labels[0]
                oldright = ''
        else:
            oldleft = ''
            oldright = ''
        newleft = oldleft
        if keyname in ['Shift_L', 'Shift_R', 'Control_L', 'Caps_Lock', \
                       'Alt_L', 'Alt_R', 'KP_Enter', 'ISO_Level3_Shift']:
            keyname = ''
            keyunicode = 0
        # Hack until I sort out input and unicode and dead keys,
        if keyname[0:5] == 'dead_':
            self._dead_key = keyname
            keyname = ''
            keyunicode = 0
        if keyname == 'space':
            keyunicode = 32
        elif keyname == 'Tab':
            keyunicode = 9
        if keyname == 'BackSpace':
            if len(oldleft) > 1:
                newleft = oldleft[:len(oldleft) - 1]
            else:
                newleft = ''
        if keyname == 'Delete':
            if len(oldright) > 0:
                oldright = oldright[1:]
        elif keyname == 'Home':
            oldright = oldleft + oldright
            newleft = ''
        elif keyname == 'Left':
            if len(oldleft) > 0:
                oldright = oldleft[len(oldleft) - 1:] + oldright
                newleft = oldleft[:len(oldleft) - 1]
        elif keyname == 'Right':
            if len(oldright) > 0:
                newleft = oldleft + oldright[0]
                oldright = oldright[1:]
        elif keyname == 'End':
            newleft = oldleft + oldright
            oldright = ''
        elif keyname == 'Return':
            newleft = oldleft + NEWLINE
        elif keyname == 'Down':
            if NEWLINE in oldright:
                parts = oldright.split(NEWLINE)
                newleft = oldleft + string.join(parts[0:2], NEWLINE)
                oldright = NEWLINE + string.join(parts[2:], NEWLINE)
        elif keyname == 'Up':
            if NEWLINE in oldleft:
                parts = oldleft.split(NEWLINE)
                newleft = string.join(parts[0:-1], NEWLINE)
                oldright = NEWLINE + parts[-1] + oldright
        elif keyname == 'Escape':  # Restore previous state
            self._selected_spr.set_label(self._saved_string)
            self._unselect()
            return
        else:
            if self._dead_key is not '':
                keyunicode = \
                    DEAD_DICTS[DEAD_KEYS.index(self._dead_key[5:])][keyname]
                self._dead_key = ''
            if keyunicode > 0:
                if unichr(keyunicode) != '\x00':
                    newleft = oldleft + unichr(keyunicode)
                else:
                    newleft = oldleft
            elif keyunicode == -1:  # clipboard text
                if keyname == NEWLINE:
                    newleft = oldleft + NEWLINE
                else:
                    newleft = oldleft + keyname
        self._selected_spr.set_label('%s%s%s' % (newleft, CURSOR, oldright))

    def _unselect(self):
        if self._selected_spr is not None:
            if CURSOR in self._selected_spr.labels[0]:
                parts = self._selected_spr.labels[0].split(CURSOR)
                self._selected_spr.set_label(string.join(parts))
                slide = self._slides[self.i]
                if self._selected_spr.type == 'title':
                    slide.title = self._selected_spr.labels[0]
                    if self.initiating is not None and self.initiating:
                        self._send_event('t:%s' % (self._data_dumper(
                                    [slide.uid, slide.title])))
                else:
                    slide.description = self._selected_spr.labels[0]
                    if self.initiating is not None:
                        self._send_event('d:%s' % (self._data_dumper(
                                    [slide.uid, slide.description])))
                _logger.debug('marking %d as dirty' % (self.i))
                slide.dirty = True
            self._selected_spr = None
            self._saved_string = ''

    def _restore_cursor(self):
        ''' No longer waiting, so restore standard cursor. '''
        if not hasattr(self, 'get_window'):
            return
        if hasattr(self.get_window(), 'get_cursor'):
            self.get_window().set_cursor(self.old_cursor)
        else:
            self.get_window().set_cursor(Gdk.Cursor.new(Gdk.CursorType.LEFT_PTR))

    def _waiting_cursor(self):
        ''' Waiting, so set watch cursor. '''
        if not hasattr(self, 'get_window'):
            return
        if hasattr(self.get_window(), 'get_cursor'):
            self.old_cursor = self.get_window().get_cursor()
        self.get_window().set_cursor(Gdk.Cursor.new(Gdk.CursorType.WATCH))

    # Serialize

    def _dump(self, slide):
        ''' Dump data for sharing.'''
        _logger.debug('dumping %s' % (slide.uid))
        if slide.preview is None:
            data = [slide.uid, slide.title, None, slide.description]
        else:
            data = [slide.uid, slide.title,
                    pixbuf_to_base64(activity, slide.preview,
                                     width=300, height=225),
                    slide.description]
        return self._data_dumper(data)

    def _data_dumper(self, data):
        return json.write(data)

    def _load(self, data):
        ''' Load slide data from a sharer. '''
        self._restore_cursor()
        uid, title, base64, description = self._data_loader(data)
        if self._uid_to_slide(uid) is None:
            _logger.debug('loading %s' % (uid))
            if base64 is None:
                preview = None
            else:
                preview = base64_to_pixbuf(activity, base64)
            self._slides.append(Slide(self._buddies[-1],
                                      uid,
                                      self._colors,
                                      title,
                                      preview,
                                      description))
        else:
            _logger.debug('updating description for %s' % (uid))
            slide = self._uid_to_slide(uid)
            slide.title = title
            if base64 is None:
                slide.preview = None
            else:
                slide.preview = base64_to_pixbuf(activity, base64)
            slide.description = description
            slide.active = True
            if not slide.fav:
                slide.fav = True
                if slide.star is not None:
                    slide.star.set_shape(self._fav_pixbuf)
                    slide.star.type = 'star'
        if not self._thumbnail_mode:
            self._thumb_button.set_active(True)
        else:
            self._show_thumbs()

    def _data_loader(self, data):
        return json.read(data)

    # When portfolio is shared, only sharer sends out slides, joiners
    # send back comments.

    def _setup_presence_service(self):
        ''' Setup the Presence Service. '''
        self.pservice = presenceservice.get_instance()

        owner = self.pservice.get_owner()
        self.owner = owner
        self.buddies = [owner]
        self._share = ''
        self.connect('shared', self._shared_cb)
        self.connect('joined', self._joined_cb)

    def _shared_cb(self, activity):
        ''' Either set up initial share...'''
        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 = 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

        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, {})

    def _joined_cb(self, activity):
        ''' ...or join an exisiting share. '''
        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

        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)

        self.waiting = True
        # Since we are joining, clear out the slide list
        for slide in self._slides:
            slide.active = False
        self._clear_screen()
        self._help.hide()
        self._description.set_layer(TOP)
        self._description.set_label(_('Please wait.'))
        self._waiting_cursor()

    def _list_tubes_reply_cb(self, tubes):
        ''' Reply to a list request. '''
        for tube_info in tubes:
            self._new_tube_cb(*tube_info)

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

    def _new_tube_cb(self, id, initiator, type, service, params, state):
        ''' Create a new tube. '''
        _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])

            self.chattube = ChatTube(tube_conn, self.initiating, \
                self.event_received_cb)

            if self.waiting:
                self._share_nick()

    def event_received_cb(self, text):
        ''' Data is passed as tuples: cmd:text '''
        dispatch_table = {'s': self._load,
                          'c': self._update_colors,
                          'd': self._update_description,
                          't': self._update_title,
                          'S': self._update_star,
                          'R': self._reset,
                          'j': self._new_join,
                          }
        _logger.debug('<<< %s' % (text[0]))
        dispatch_table[text[0]](text[2:])

    def _reset(self, data):
        for slide in self._slides:
            slide.active = False

    def _new_join(self, data):
        if data not in self._buddies:
            self._buddies.append(data)
        if self.initiating:
            self._share_nick()
            self._share_colors()
            self._share_slides()

    def _update_star(self, data):
        uid, status = self._data_loader(data)
        slide = self._uid_to_slide(uid)
        if slide is None:
            _logger.debug('slide %s not found' % (uid))
            return
        slide.fav = status
        if slide.star is not None:
            if status:
                slide.star.set_shape(self._fav_pixbuf)
                slide.star.type = 'star'
            else:
                slide.star.set_shape(self._unfav_pixbuf)
                slide.star.type = 'unstar'

    def _update_colors(self, data):
        colors = self._data_loader(data)
        if colors[0] != self._colors[0] or \
           colors[1] != self._colors[1]:
            self._colors = colors[:]
            self._my_canvas.set_image(svg_str_to_pixbuf(
                genblank(self._width, self._height, [self._colors[0],
                                                     self._colors[0]])))
            self._description.set_image(svg_str_to_pixbuf(
                    genblank(
                        int(self._descriptionwh[0]),
                        int(self._descriptionwh[1]),
                        self._colors)))
            self._title.set_image(svg_str_to_pixbuf(
                        genblank(int(self._titlewh[0]),
                                 int(self._titlewh[1]),
                                 self._colors)))

    def _update_description(self, data):
        uid, text = self._data_loader(data)
        slide = self._uid_to_slide(uid)
        if slide is None:
            _logger.debug('slide %s not found' % (uid))
            return
        _logger.debug('updating description %s' % (uid))
        slide.description = text
        if self.i == self._slides.index(slide):
            self._description.set_label(text)
        if self.initiating:
            slide.dirty = True

    def _update_title(self, data):
        uid, text = self._data_loader(data)
        slide = self._uid_to_slide(uid)
        if slide is None:
            _logger.debug('slide %s not found' % (uid))
            return
        _logger.debug('updating title %s' % (uid))
        slide.title = text
        if self.i == self._slides.index(slide):
            self._title.set_label(text)
        if self.initiating:
            slide.dirty = True

    def _share_nick(self):
        _logger.debug('sharing nick')
        self._send_event('j:%s' % (profile.get_nick_name()))

    def _share_colors(self):
        _logger.debug('sharing colors')
        self._send_event('c:%s' % (self._data_dumper(self._colors)))

    def _share_slides(self):
        for slide in self._slides:
            if slide.active and slide.fav:
                _logger.debug('sharing %s' % (slide.uid))
                GObject.idle_add(self._send_event, 's:%s' % (
                        str(self._dump(slide))))

    def _send_star(self, uid, status):
        _logger.debug('sharing star for %s (%s)' % (uid, str(status)))
        self._send_event('S:%s' % (self._data_dumper([uid, status])))

    def _send_event(self, text):
        ''' Send event through the tube. '''
        if hasattr(self, 'chattube') and self.chattube is not None:
            _logger.debug('>>> %s' % (text[0]))
            self.chattube.SendText(text)


class ChatTube(ExportedGObject):
    ''' Class for setting up tube for sharing '''
    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