Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/app/static/doc/myosa/ch019_fun-with-the-journal.xhtml
blob: 981884d4dbb735a367e10586b3df0bb5dda1c213 (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
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><body><h1>Fun With The Journal
</h1>
<h2>Introduction
</h2>
<p>By default every Activity creates and reads one Journal entry.&#160; Most Activities don't need to do any more with the Journal than that, and if your Activity is like that you won't need the information&#160; in this chapter.&#160; Chances are that someday you will want to do more than that, so if you do keep reading.
</p>
<p> First let's review what the Journal is.&#160; The Journal is a collection of files that each have <strong>metadata</strong> (data about data) associated with them.&#160; Metadata is stored as text strings and includes such things as the <strong>Title</strong>, <strong>Description</strong>, <strong>Tags</strong>, <strong>MIME Type</strong>, and a screen shot of the Activity when it was last used.
</p>
<p>Your Activity cannot read and write these files directly.&#160; Instead Sugar provides an API (Application Programming Interface) that gives you an indirect way to add, delete and modify entries in the Journal, as well as a way to search Journal entries and make a list of entries that meet the search criteria.
</p>
<p>The API we'll use is in the <strong>datastore</strong> package.&#160; After version .82 of Sugar this API was rewritten, so we'll need to learn how to support both versions in the same Activity.
</p>
<p>If you've read this far you've seen several examples where Sugar started out doing one thing and then changed to do the same thing a better way but still provided a way to create Activities that would work with either the old or the new way.&#160; You may be wondering if it is normal for a project to do this.&#160; As a professional programmer I can tell you that doing tricks like this to maintain backward compatibility is extremely common, and Sugar does no more of this than any other project.&#160; There are decisions made by Herman Hollerith when he tabulated the 1890 census using punched cards that computer programmers must live with to this day.
</p>
<h2>Introducing Sugar Commander
</h2>
<p> I am a big fan of the concept of the Journal but not so much of the <strong>Journal Activity</strong> that Sugar uses to navigate through it and maintain it.&#160; My biggest gripe against it is that it represents the contents of thumb drives and SD cards as if the files on these were also Journal entries.&#160; My feeling is that files and directories are one thing and the Journal is another, and the user interface should recognize that.
</p>
<p>Strictly speaking the Journal Activity is and is not an Activity.&#160; It inherits code from the Activity class just like any other Activity, and it is written in Python and uses the same datastore API that other Activities use.&#160; However, it is run in a special way that gives it powers and abilities far beyond those of an ordinary Activity.&#160; In particular it can do two things:
</p>
<ul><li>It can write to files on external media like thumb drives and SD cards.</li>
  <li>It alone can be used to resume Journal entries using other Activities.</li>
</ul><p>While I would like to write a Journal Activity that does everything the original does but has a user interface more to my own taste the Sugar security model won't allow that.&#160; Recently I came to the conclusion that a more mild-mannered version of the Journal Activity might be useful.&#160; Just as Kal-El sometimes finds it more useful to be Clark Kent than Superman, my own Activity might be a worthy alternative to the built-in Journal Activity when super powers are not needed.
</p>
<p> My Activity, which I call <strong>Sugar Commander</strong>, has two tabs.&#160; One represents the Journal and looks like this:
</p>
<p><img alt="Sugar Commander Journal Tab" src="static/ActivitiesGuideSugar-SCommander2-en.jpg" height="450" width="600"/></p>
<p>This tab lets you browse through the Journal sorted by Title or MIME Type, select entries and view their details, update Title, Description or Tags, and delete entries you no longer want.&#160; The other tab shows files and folders and looks like this:
</p>
<p><img alt="Sugar Commander Files Tab" src="static/ActivitiesGuideSugar-SCommander1-en.jpg" height="450" width="600"/></p>
<p>This tab lets you browse through the files and folders or the regular file system, including thumb drives and SD cards.&#160; You can select a file and make a Journal entry out of it by pushing the button at the bottom of the screen.
</p>
<p>&#160;This Activity has very little code and still manages to do everything an ordinary Activity can do with the Journal.&#160; You can download the Git repository using this command:
  <br/></p>
<pre><code>git clone git://git.sugarlabs.org/sugar-commander/\
mainline.git</code></pre>
<p>There is only one source file, <strong>sugarcommander.py</strong>:
</p>
<pre>import logging
import os
import gtk
import pango
import zipfile
from sugar import mime
from sugar.activity import activity
from sugar.datastore import datastore
from sugar.graphics.alert import NotifyAlert
from sugar.graphics import style
from gettext import gettext as _
import gobject
import dbus

COLUMN_TITLE = 0
COLUMN_MIME = 1
COLUMN_JOBJECT = 2

DS_DBUS_SERVICE = 'org.laptop.sugar.DataStore'
DS_DBUS_INTERFACE = 'org.laptop.sugar.DataStore'
DS_DBUS_PATH = '/org/laptop/sugar/DataStore'

_logger = logging.getLogger('sugar-commander')

class SugarCommander(activity.Activity):
    def __init__(self, handle, create_jobject=True):
        "The entry point to the Activity"
        activity.Activity.__init__(self, handle,  False)
        self.selected_journal_entry = None
        self.selected_path = None

        canvas = gtk.Notebook()
        canvas.props.show_border = True
        canvas.props.show_tabs = True
        canvas.show()

        self.ls_journal = gtk.ListStore(
            gobject.TYPE_STRING,
            gobject.TYPE_STRING,
            gobject.TYPE_PYOBJECT)
        self.tv_journal = gtk.TreeView(self.ls_journal)
        self.tv_journal.set_rules_hint(True)
        self.tv_journal.set_search_column(COLUMN_TITLE)
        self.selection_journal = \
            self.tv_journal.get_selection()
        self.selection_journal.set_mode(
            gtk.SELECTION_SINGLE)
        self.selection_journal.connect("changed",
            self.selection_journal_cb)
        renderer = gtk.CellRendererText()
        renderer.set_property('wrap-mode', gtk.WRAP_WORD)
        renderer.set_property('wrap-width', 500)
        renderer.set_property('width', 500)
        self.col_journal = gtk.TreeViewColumn(_('Title'),
            renderer, text=COLUMN_TITLE)
        self.col_journal.set_sort_column_id(COLUMN_TITLE)
        self.tv_journal.append_column(self.col_journal)

        mime_renderer = gtk.CellRendererText()
        mime_renderer.set_property('width', 500)
        self.col_mime = gtk.TreeViewColumn(_('MIME'),
            mime_renderer, text=COLUMN_MIME)
        self.col_mime.set_sort_column_id(COLUMN_MIME)
        self.tv_journal.append_column(self.col_mime)

        self.list_scroller_journal = gtk.ScrolledWindow(
            hadjustment=None, vadjustment=None)
        self.list_scroller_journal.set_policy(
            gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        self.list_scroller_journal.add(self.tv_journal)

        label_attributes = pango.AttrList()
        label_attributes.insert(pango.AttrSize(
            14000, 0, -1))
        label_attributes.insert(pango.AttrForeground(
            65535, 65535, 65535, 0, -1))

        tab1_label = gtk.Label(_("Journal"))
        tab1_label.set_attributes(label_attributes)
        tab1_label.show()
        self.tv_journal.show()
        self.list_scroller_journal.show()

        column_table = gtk.Table(rows=1, columns=2,
            homogeneous = False)

        image_table = gtk.Table(rows=2, columns=2,
            homogeneous=False)
        self.image = gtk.Image()
        image_table.attach(self.image, 0, 2, 0, 1,
            xoptions=gtk.FILL|gtk.SHRINK,
            yoptions=gtk.FILL|gtk.SHRINK,
            xpadding=10,
            ypadding=10)

        self.btn_save = gtk.Button(_("Save"))
        self.btn_save.connect('button_press_event',
            self.save_button_press_event_cb)
        image_table.attach(self.btn_save, 0, 1, 1, 2,
            xoptions=gtk.SHRINK,
            yoptions=gtk.SHRINK, xpadding=10,
            ypadding=10)
        self.btn_save.props.sensitive = False
        self.btn_save.show()

        self.btn_delete = gtk.Button(_("Delete"))
        self.btn_delete.connect('button_press_event',
            self.delete_button_press_event_cb)
        image_table.attach(self.btn_delete, 1, 2, 1, 2,
            xoptions=gtk.SHRINK,
            yoptions=gtk.SHRINK, xpadding=10,
            ypadding=10)
        self.btn_delete.props.sensitive = False
        self.btn_delete.show()

        column_table.attach(image_table, 0, 1, 0, 1,
            xoptions=gtk.FILL|gtk.SHRINK,
            yoptions=gtk.SHRINK, xpadding=10,
            ypadding=10)

        entry_table = gtk.Table(rows=3, columns=2,
            homogeneous=False)

        title_label = gtk.Label(_("Title"))
        entry_table.attach(title_label, 0, 1, 0, 1,
            xoptions=gtk.SHRINK,
            yoptions=gtk.SHRINK,
            xpadding=10, ypadding=10)
        title_label.show()

        self.title_entry = gtk.Entry(max=0)
        entry_table.attach(self.title_entry, 1, 2, 0, 1,
            xoptions=gtk.FILL|gtk.SHRINK,
            yoptions=gtk.SHRINK, xpadding=10, ypadding=10)
        self.title_entry.connect('key_press_event',
                                 self.key_press_event_cb)
        self.title_entry.show()

        description_label = gtk.Label(_("Description"))
        entry_table.attach(description_label, 0, 1, 1, 2,
                           xoptions=gtk.SHRINK,
                           yoptions=gtk.SHRINK,
                           xpadding=10, ypadding=10)
        description_label.show()

        self.description_textview = gtk.TextView()
        self.description_textview.set_wrap_mode(
            gtk.WRAP_WORD)
        entry_table.attach(self.description_textview,
            1, 2, 1, 2,
            xoptions=gtk.EXPAND|gtk.FILL|gtk.SHRINK,
            yoptions=gtk.EXPAND|gtk.FILL|gtk.SHRINK,
            xpadding=10, ypadding=10)
        self.description_textview.props.accepts_tab = False
        self.description_textview.connect('key_press_event',
            self.key_press_event_cb)
        self.description_textview.show()

        tags_label = gtk.Label(_("Tags"))
        entry_table.attach(tags_label, 0, 1, 2, 3,
            xoptions=gtk.SHRINK,
            yoptions=gtk.SHRINK,
            xpadding=10, ypadding=10)
        tags_label.show()

        self.tags_textview = gtk.TextView()
        self.tags_textview.set_wrap_mode(gtk.WRAP_WORD)
        entry_table.attach(self.tags_textview, 1, 2, 2, 3,
            xoptions=gtk.FILL,
            yoptions=gtk.EXPAND|gtk.FILL,
            xpadding=10, ypadding=10)
        self.tags_textview.props.accepts_tab = False
        self.tags_textview.connect('key_press_event',
            self.key_press_event_cb)
        self.tags_textview.show()

        entry_table.show()

        self.scroller_entry = gtk.ScrolledWindow(
            hadjustment=None, vadjustment=None)
        self.scroller_entry.set_policy(gtk.POLICY_NEVER,
            gtk.POLICY_AUTOMATIC)
        self.scroller_entry.add_with_viewport(entry_table)
        self.scroller_entry.show()

        column_table.attach(self.scroller_entry,
            1, 2, 0, 1,
            xoptions=gtk.FILL|gtk.EXPAND|gtk.SHRINK,
            yoptions=gtk.FILL|gtk.EXPAND|gtk.SHRINK,
            xpadding=10, ypadding=10)
        image_table.show()
        column_table.show()

        vbox = gtk.VBox(homogeneous=True, spacing=5)
        vbox.pack_start(column_table)
        vbox.pack_end(self.list_scroller_journal)

        canvas.append_page(vbox,  tab1_label)

        self._filechooser = gtk.FileChooserWidget(
            action=gtk.FILE_CHOOSER_ACTION_OPEN,
            backend=None)
        self._filechooser.set_current_folder("/media")
        self.copy_button = gtk.Button(
            _("Copy File To The Journal"))
        self.copy_button.connect('clicked',
            self.create_journal_entry)
        self.copy_button.show()
        self._filechooser.set_extra_widget(self.copy_button)
        preview = gtk.Image()
        self._filechooser.set_preview_widget(preview)
        self._filechooser.connect("update-preview",
            self.update_preview_cb, preview)
        tab2_label = gtk.Label(_("Files"))
        tab2_label.set_attributes(label_attributes)
        tab2_label.show()
        canvas.append_page(self._filechooser, tab2_label)

        self.set_canvas(canvas)
        self.show_all()

        toolbox = activity.ActivityToolbox(self)
        activity_toolbar = toolbox.get_activity_toolbar()
        activity_toolbar.keep.props.visible = False
        activity_toolbar.share.props.visible = False
        self.set_toolbox(toolbox)
        toolbox.show()

        self.load_journal_table()

        bus = dbus.SessionBus()
        remote_object = bus.get_object(
            DS_DBUS_SERVICE, DS_DBUS_PATH)
        _datastore = dbus.Interface(remote_object,
            DS_DBUS_INTERFACE)
        _datastore.connect_to_signal('Created',
            self.datastore_created_cb)
        _datastore.connect_to_signal('Updated',
            self.datastore_updated_cb)
        _datastore.connect_to_signal('Deleted',
            self.datastore_deleted_cb)

        self.selected_journal_entry = None

    def update_preview_cb(self, file_chooser, preview):
        filename = file_chooser.get_preview_filename()
        try:
            file_mimetype = mime.get_for_file(filename)
            if file_mimetype.startswith('image/'):
                pixbuf = \
                    gtk.gdk.pixbuf_new_from_file_at_size(
                    filename,
                    style.zoom(320), style.zoom(240))
                preview.set_from_pixbuf(pixbuf)
                have_preview = True
            elif file_mimetype  == 'application/x-cbz':
                fname = self.extract_image(filename)
                pixbuf = \
                    gtk.gdk.pixbuf_new_from_file_at_size(
                    fname,
                    style.zoom(320), style.zoom(240))
                preview.set_from_pixbuf(pixbuf)
                have_preview = True
                os.remove(fname)
            else:
                have_preview = False
        except:
            have_preview = False
        file_chooser.set_preview_widget_active(
            have_preview)
        return

    def key_press_event_cb(self, entry, event):
        self.btn_save.props.sensitive = True

    def save_button_press_event_cb(self, entry, event):
        self.update_entry()

    def delete_button_press_event_cb(self, entry, event):
        datastore.delete(
            self.selected_journal_entry.object_id)

    def datastore_created_cb(self, uid):
        new_jobject = datastore.get(uid)
        iter = self.ls_journal.append()
        title = new_jobject.metadata['title']
        self.ls_journal.set(iter, COLUMN_TITLE, title)
        mime = new_jobject.metadata['mime_type']
        self.ls_journal.set(iter, COLUMN_MIME, mime)
        self.ls_journal.set(iter, COLUMN_JOBJECT,
            new_jobject)

    def datastore_updated_cb(self,  uid):
        new_jobject = datastore.get(uid)
        iter = self.ls_journal.get_iter_first()
        for row in self.ls_journal:
            jobject = row[COLUMN_JOBJECT]
            if jobject.object_id == uid:
                title = new_jobject.metadata['title']
                self.ls_journal.set_value(iter,
                    COLUMN_TITLE, title)
                break
            iter = self.ls_journal.iter_next(iter)
        object_id = self.selected_journal_entry.object_id
        if object_id == uid:
            self.set_form_fields(new_jobject)

    def datastore_deleted_cb(self,  uid):
        save_path = self.selected_path
        iter = self.ls_journal.get_iter_first()
        for row in self.ls_journal:
            jobject = row[COLUMN_JOBJECT]
            if jobject.object_id == uid:
                self.ls_journal.remove(iter)
                break
            iter = self.ls_journal.iter_next(iter)

        try:
            self.selection_journal.select_path(save_path)
            self.tv_journal.grab_focus()
        except:
            self.title_entry.set_text('')
            description_textbuffer = \
                self.description_textview.get_buffer()
            description_textbuffer.set_text('')
            tags_textbuffer = \
                self.tags_textview.get_buffer()
            tags_textbuffer.set_text('')
            self.btn_save.props.sensitive = False
            self.btn_delete.props.sensitive = False
            self.image.clear()
            self.image.show()

    def update_entry(self):
        needs_update = False

        if self.selected_journal_entry is None:
            return

        object_id = self.selected_journal_entry.object_id
        jobject = datastore.get(object_id)

        old_title = jobject.metadata.get('title', None)
        if old_title != self.title_entry.props.text:
            jobject.metadata['title'] = \
                self.title_entry.props.text
            jobject.metadata['title_set_by_user'] = '1'
            needs_update = True

        old_tags = jobject.metadata.get('tags', None)
        new_tags = \
            self.tags_textview.props.buffer.props.text
        if old_tags != new_tags:
            jobject.metadata['tags'] = new_tags
            needs_update = True

        old_description = jobject.metadata.get(
            'description', None)
        new_description = \
            self.description_textview.props.buffer.props.text
        if old_description != new_description:
            jobject.metadata['description'] = new_description
            needs_update = True

        if needs_update:
            datastore.write(jobject, update_mtime=False,
                reply_handler=self.datastore_write_cb,
                error_handler=self.datastore_write_error_cb)
        self.btn_save.props.sensitive = False

    def datastore_write_cb(self):
        pass

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

    def close(self,  skip_save=False):
        "Override the close method so we don't try to
        create a Journal entry."
        activity.Activity.close(self,  True)

    def selection_journal_cb(self, selection):
        self.btn_delete.props.sensitive = True
        tv = selection.get_tree_view()
        model = tv.get_model()
        sel = selection.get_selected()
        if sel:
            model, iter = sel
            jobject = model.get_value(iter,COLUMN_JOBJECT)
            jobject = datastore.get(jobject.object_id)
            self.selected_journal_entry = jobject
            self.set_form_fields(jobject)
            self.selected_path = model.get_path(iter)

    def set_form_fields(self, jobject):
        self.title_entry.set_text(jobject.metadata['title'])
        description_textbuffer = \
            self.description_textview.get_buffer()
        if jobject.metadata.has_key('description'):
            description_textbuffer.set_text(
                jobject.metadata['description'])
        else:
            description_textbuffer.set_text('')
        tags_textbuffer = self.tags_textview.get_buffer()
        if jobject.metadata.has_key('tags'):
            tags_textbuffer.set_text(jobject.metadata['tags'])
        else:
            tags_textbuffer.set_text('')
        self.create_preview(jobject.object_id)

    def create_preview(self,  object_id):
        jobject = datastore.get(object_id)

        if jobject.metadata.has_key('preview'):
            preview = jobject.metadata['preview']
            if preview is None or preview == '' \
                or preview == 'None':
                if jobject.metadata['mime_type'].startswith(
                    'image/'):
                    filename = jobject.get_file_path()
                    self.show_image(filename)
                    return
                if jobject.metadata['mime_type']  == \
                    'application/x-cbz':
                    filename = jobject.get_file_path()
                    fname = self.extract_image(filename)
                    self.show_image(fname)
                    os.remove(fname)
                    return

        if jobject.metadata.has_key('preview') and \
                len(jobject.metadata['preview']) &gt; 4:

            if jobject.metadata['preview'][1:4] == 'PNG':
                preview_data = jobject.metadata['preview']
            else:
                import base64
                preview_data = \
                    base64.b64decode(
                    jobject.metadata['preview'])

            loader = gtk.gdk.PixbufLoader()
            loader.write(preview_data)
            scaled_buf = loader.get_pixbuf()
            loader.close()
            self.image.set_from_pixbuf(scaled_buf)
            self.image.show()
        else:
            self.image.clear()
            self.image.show()

    def load_journal_table(self):
        self.btn_save.props.sensitive = False
        self.btn_delete.props.sensitive = False
        ds_mounts = datastore.mounts()
        mountpoint_id = None
        if len(ds_mounts) == 1 and \
            ds_mounts[0]['id'] == 1:
            pass
        else:
            for mountpoint in ds_mounts:
                id = mountpoint['id']
                uri = mountpoint['uri']
                if uri.startswith('/home'):
                    mountpoint_id = id

        query = {}
        if mountpoint_id is not None:
            query['mountpoints'] = [ mountpoint_id ]
        ds_objects, num_objects = \
            datastore.find(query, properties=['uid',
            'title',  'mime_type'])

        self.ls_journal.clear()
        for i in xrange (0, num_objects, 1):
            iter = self.ls_journal.append()
            title = ds_objects[i].metadata['title']
            self.ls_journal.set(iter, COLUMN_TITLE, title)
            mime = ds_objects[i].metadata['mime_type']
            self.ls_journal.set(iter, COLUMN_MIME, mime)
            self.ls_journal.set(iter, COLUMN_JOBJECT,
                ds_objects[i])
            if not self.selected_journal_entry is None and \
                self.selected_journal_entry.object_id == \
                ds_objects[i].object_id:
                self.selection_journal.select_iter(iter)

        self.ls_journal.set_sort_column_id(COLUMN_TITLE,
            gtk.SORT_ASCENDING)
        v_adjustment = \
            self.list_scroller_journal.get_vadjustment()
        v_adjustment.value = 0
        return ds_objects[0]

    def create_journal_entry(self,  widget,  data=None):
        filename = self._filechooser.get_filename()
        journal_entry = datastore.create()
        journal_entry.metadata['title'] = \
            self.make_new_filename(filename)
        journal_entry.metadata['title_set_by_user'] = '1'
        journal_entry.metadata['keep'] = '0'
        file_mimetype = mime.get_for_file(filename)
        if not file_mimetype is None:
            journal_entry.metadata['mime_type'] = \
                file_mimetype
        journal_entry.metadata['buddies'] = ''
        if file_mimetype.startswith('image/'):
            preview = \
                self.create_preview_metadata(filename)
        elif file_mimetype  == 'application/x-cbz':
            fname = self.extract_image(filename)
            preview = self.create_preview_metadata(fname)
            os.remove(fname)
        else:
            preview = ''
        if not preview  == '':
            journal_entry.metadata['preview'] = \
            dbus.ByteArray(preview)
        else:
            journal_entry.metadata['preview'] =  ''

        journal_entry.file_path = filename
        datastore.write(journal_entry)
        self.alert(_('Success'),  _('%s added to Journal.')
                    % self.make_new_filename(filename))

    def alert(self, title, text=None):
        alert = NotifyAlert(timeout=20)
        alert.props.title = title
        alert.props.msg = text
        self.add_alert(alert)
        alert.connect('response', self.alert_cancel_cb)
        alert.show()

    def alert_cancel_cb(self, alert, response_id):
        self.remove_alert(alert)

    def show_image(self, filename):
        "display a resized image in a preview"
        scaled_buf = gtk.gdk.pixbuf_new_from_file_at_size(
            filename,
            style.zoom(320), style.zoom(240))
        self.image.set_from_pixbuf(scaled_buf)
        self.image.show()

    def extract_image(self,  filename):
        zf = zipfile.ZipFile(filename, 'r')
        image_files = zf.namelist()
        image_files.sort()
        file_to_extract = image_files[0]
        extract_new_filename = self.make_new_filename(
            file_to_extract)
        if extract_new_filename is None or \
            extract_new_filename == '':
            # skip over directory name if the images
            # are in a subdirectory.
            file_to_extract = image_files[1]
            extract_new_filename = self.make_new_filename(
                file_to_extract)

        if len(image_files) &gt; 0:
            if self.save_extracted_file(zf, file_to_extract):
                fname = os.path.join(self.get_activity_root(),
                    'instance',
                    extract_new_filename)
                return fname

    def save_extracted_file(self, zipfile, filename):
        "Extract the file to a temp directory for viewing"
        try:
            filebytes = zipfile.read(filename)
        except zipfile.BadZipfile, err:
            print 'Error opening the zip file: %s' % (err)
            return False
        except KeyError,  err:
            self.alert('Key Error', 'Zipfile key not found: '
                        + str(filename))
            return
        outfn = self.make_new_filename(filename)
        if (outfn == ''):
            return False
        fname = os.path.join(self.get_activity_root(),
            'instance',  outfn)
        f = open(fname, 'w')
        try:
            f.write(filebytes)
        finally:
            f.close()
        return True

    def make_new_filename(self, filename):
        partition_tuple = filename.rpartition('/')
        return partition_tuple[2]

    def create_preview_metadata(self,  filename):

        file_mimetype = mime.get_for_file(filename)
        if not file_mimetype.startswith('image/'):
            return ''

        scaled_pixbuf = \
            gtk.gdk.pixbuf_new_from_file_at_size(
            filename,
            style.zoom(320), style.zoom(240))
        preview_data = []

        def save_func(buf, data):
            data.append(buf)

        scaled_pixbuf.save_to_callback(save_func,
            'png',
            user_data=preview_data)
        preview_data = ''.join(preview_data)

        return preview_data</pre>
<p>Let's look at this code one method at a time.
  <br/></p>
<h2> Adding A Journal Entry
  <br/></h2>
<p>We add a Journal entry when someone pushes a button on the gtk.FileChooser.&#160; This is the code that gets run:
</p>
<pre>    def create_journal_entry(self, widget, data=None):
        filename = self._filechooser.get_filename()
        journal_entry = datastore.create()
        journal_entry.metadata['title'] = \
            self.make_new_filename(
            filename)
        journal_entry.metadata['title_set_by_user'] = '1'
        journal_entry.metadata['keep'] = '0'
        file_mimetype = mime.get_for_file(filename)
        if not file_mimetype is None:
            journal_entry.metadata['mime_type'] = \
                file_mimetype
        journal_entry.metadata['buddies'] = ''
        if file_mimetype.startswith('image/'):
            preview = self.create_preview_metadata(filename)
        elif file_mimetype  == 'application/x-cbz':
            fname = self.extract_image(filename)
            preview = self.create_preview_metadata(fname)
            os.remove(fname)
        else:
            preview = ''
        if not preview  == '':
            journal_entry.metadata['preview'] = \
                dbus.ByteArray(preview)
        else:
            journal_entry.metadata['preview'] =  ''
        journal_entry.file_path = filename
        datastore.write(journal_entry)
</pre>
<p>The only thing worth commenting on here is the metadata.&#160; <strong>title</strong> is what appears as #3 in the picture below.&#160; <strong>title_set_by_user</strong> is set to 1 so that the Activity won't prompt the user to change the title when the Activity closes.&#160; <strong>keep</strong> refers to the little star that appears at the beginning of the Journal entry (see #1 in the picture below).&#160; Highlight it by setting this to 1, otherwise set to 0.&#160;&#160; <strong>buddies</strong> is a list of users that collaborated on the Journal entry, and in this case there aren't any (these show up as #4 in the picture below).&#160;
  <br/></p><img alt="Journal Legend" src="static/ActivitiesGuideSugar-journal_main_screen-en.png" height="415" width="600"/><h2>
</h2>
<p><strong>preview</strong> is an image file in the PNG format that is a screenshot of the Activity in action.&#160; This is created by the Activity itself when it is run so there is no need to make one when you add a Journal entry.&#160; You can simply use an empty string ('') for this property.
</p>
<p>Because previews are much more visible in Sugar Commander than they are in the regular Journal Activity I decided that Sugar Commander should make a preview image for image files and comic books as soon as they are added to the Journal.&#160; To do this I made a pixbuf of the image that would fit within the scaled dimensions of 320x240 pixels and made a <strong>dbus.ByteArray</strong> out of it, which is the format that the Journal uses to store preview images.
  <br/></p>
<p><strong>mime_type</strong> describes the format of the file and is generally assigned based on the filename suffix.&#160; For instance, files ending in .html have a MIME type of 'text/html'.&#160; Python has a package called <strong>mimetypes </strong>that takes a file name and figures out what its MIME type should be, but Sugar provides its own package to do the same thing.&#160; For most files either one would give the correct answer, but Sugar has its own MIME types for things like Activity bundles, etc. so for best results you really should use Sugar's mime package.&#160; You can import it like this:
</p>
<pre>from sugar import mime</pre>
<p>The rest of the metadata (icon, modified time) is created automatically.&#160;
  <br/></p>
<h2>NOT Adding A Journal Entry
</h2>
<p>Sugar Activities by default create a Journal entry using the <em>write_file()</em> method.&#160; There will be Activities that don't need to do this.&#160; For instance, <strong>Get Internet Archive Books</strong> downloads e-books to the Journal, but has no need for a Journal entry of its own.&#160; The same thing is true of <strong>Sugar Commander</strong>.&#160; You might make a game that keeps track of high scores.&#160; You could keep those scores in a Journal entry, but that would require players to resume the game from the Journal rather than just starting it up from the Activity Ring.&#160; For that reason you might prefer to store the high scores in a file in the <strong>data </strong>directory rather than the Journal, and not leave a Journal entry behind at all.
</p>
<p>Sugar gives you a way to do that.&#160; First you need to specify an extra argument in your Activity's <em>__init__()</em> method like this:
</p>
<pre>class SugarCommander(activity.Activity):
    def __init__(self, handle, create_jobject=True):
        "The entry point to the Activity"
        activity.Activity.__init__(self, handle, False)
</pre>
<p>Second, you need to override the <em>close()</em> method like this:
  <br/></p>
<pre>    def close(self,  skip_save=False):
        "Override the close method so we don't try to
        create a Journal entry."
        activity.Activity.close(self,  True)
</pre>
<p>That's all there is to it.
</p>
<h2>Listing Out Journal Entries
</h2>
<p>If you need to list out Journal entries you can use the <em>find()</em> method of <strong>datastore</strong>.&#160; The find method takes an argument containing search criteria.&#160; If you want to search for image files you can search by mime-type using a statement like this:
</p>
<pre>        ds_objects, num_objects = datastore.find(
            {'mime_type':['image/jpeg',
            'image/gif', 'image/tiff', 'image/png']},
            properties=['uid',
            'title', 'mime_type']))
</pre>
<p>You can use any metadata attribute to search on.&#160; If you want to list out everything in the Journal you can use an empty search criteria like this:
</p>
<pre>        ds_objects, num_objects = datastore.find({},
            properties=['uid',
            'title', 'mime_type']))
</pre>
<p>The properties argument specifies what metadata to return for each object in the list.&#160; You should limit these to what you plan to use, but always include <strong>uid</strong>.&#160; One thing you should <em>never</em> include in a list is <strong>preview</strong>.&#160; This is an image file showing what the Activity for the Journal object looked like when it was last used.&#160; If for some reason you need this there is a simple way to get it for an individual Journal object, but you never want to include it in a list because it will slow down your Activity enormously.
  <br/></p>
<p>Listing out what is in the Journal is complicated because of the datastore rewrite done for Sugar .84.&#160; Before .84 the <em>datastore.find()</em> method listed out both Journal entries and files on external media like thumb drives and SD cards and you need to figure out which is which.&#160; In .84 and later it only lists out Journal entries.&#160; Fortunately it is possible to write code that supports either behavior.&#160; Here is code in <strong>Sugar Commander</strong> that only lists Journal entries:
  <br/></p>
<pre>    def load_journal_table(self):
        self.btn_save.props.sensitive = False
        self.btn_delete.props.sensitive = False
        ds_mounts = datastore.mounts()
        mountpoint_id = None
        if len(ds_mounts) == 1 and ds_mounts[0]['id'] == 1:
               pass
        else:
            for mountpoint in ds_mounts:
                id = mountpoint['id']
                uri = mountpoint['uri']
                if uri.startswith('/home'):
                    mountpoint_id = id

        query = {}
        if mountpoint_id is not None:
            query['mountpoints'] = [ mountpoint_id ]
        ds_objects, num_objects = datastore.find(
            query, properties=['uid',
            'title',  'mime_type'])

        self.ls_journal.clear()
        for i in xrange (0, num_objects, 1):
            iter = self.ls_journal.append()
            title = ds_objects[i].metadata['title']
            self.ls_journal.set(iter,
                COLUMN_TITLE, title)
            mime = ds_objects[i].metadata['mime_type']
            self.ls_journal.set(iter, COLUMN_MIME, mime)
            self.ls_journal.set(iter, COLUMN_JOBJECT,
                ds_objects[i])
            if not self.selected_journal_entry is None and \
                self.selected_journal_entry.object_id == \
                    ds_objects[i].object_id:
                self.selection_journal.select_iter(iter)

        self.ls_journal.set_sort_column_id(COLUMN_TITLE,
            gtk.SORT_ASCENDING)
        v_adjustment = \
            self.list_scroller_journal.get_vadjustment()
        v_adjustment.value = 0
        return ds_objects[0]</pre>
<p>We need to use the <em>datastore.mounts()</em> method for two purposes:
</p>
<ul><li>In Sugar .82 and below it will list out all mount points, including the place the Journal is mounted on and the places external media is mounted on.&#160; The mountpoint is a Python dictionary that contains a <strong>uri</strong> property (which is the path to the mount point) and an <strong>id</strong> property (which is a name given to the mount point).&#160; Every Journal entry has a metadata attribute named <strong>mountpoint</strong>.&#160; The Journal <strong>uri</strong> will be the only one starting with <strong>/home</strong>, so if we limit the search to Journal objects where the <strong>id</strong> of that mountpoint equals the <strong>mountpoint</strong> metadata in the Journal objects we can easily list only objects from the Journal.</li>
  <li>In Sugar .84 and later the <em>datastore.mounts()</em> method still exists but doesn't tell you anything about mountpoints.&#160; However, you can use the code above to see if there is only one mountpoint and if its id is 1.&#160; If it is you know you're dealing with the rewritten datastore of .84 and later.&#160; The other difference is that the Journal objects no longer have metadata with a key of <strong>mountpoint</strong>.&#160; If you use the code above it will account for this difference and work with either version of Sugar.</li>
</ul><p>What if you want the Sugar .82 behavior, listing both Journal entries and USB files as Journal objects, in both .82 and .84 and up?&#160; I wanted to do that for <strong>View Slides</strong> and ended up using this code:
</p>
<pre>    def load_journal_table(self):
        ds_objects, num_objects = datastore.find(
            {'mime_type':['image/jpeg',
            'image/gif', 'image/tiff',  'image/png']},
            properties=['uid', 'title', 'mime_type'])
        self.ls_right.clear()
        for i in xrange (0, num_objects, 1):
            iter = self.ls_right.append()
            title = ds_objects[i].metadata['title']
            mime_type = ds_objects[i].metadata['mime_type']
            if mime_type == 'image/jpeg' \
                and not title.endswith('.jpg') \
                and not title.endswith('.jpeg') \
                and not title.endswith('.JPG') \
                and not title.endswith('.JPEG') :
                title = title + '.jpg'
            if mime_type == 'image/png' \
                and not title.endswith('.png') \
                and not title.endswith('.PNG'):
                title = title + '.png'
            if mime_type == 'image/gif' \
                and not title.endswith('.gif')\
                and not title.endswith('.GIF'):
                title = title + '.gif'
            if mime_type == 'image/tiff' \
                and not title.endswith('.tiff')\
                and not title.endswith('.TIFF'):
                title = title + '.tiff'
            self.ls_right.set(iter, COLUMN_IMAGE, title)
            jobject_wrapper = JobjectWrapper()
            jobject_wrapper.set_jobject(ds_objects[i])
            self.ls_right.set(iter, COLUMN_PATH,
                jobject_wrapper)

        valid_endings = ('.jpg',  '.jpeg', '.JPEG',
            '.JPG', '.gif', '.GIF', '.tiff',
            '.TIFF', '.png', '.PNG')
        ds_mounts = datastore.mounts()
        if len(ds_mounts) == 1 and ds_mounts[0]['id'] == 1:
            # datastore.mounts() is stubbed out,
            # we're running .84 or better
            for dirname, dirnames, filenames in os.walk(
                '/media'):
                if '.olpc.store' in dirnames:
                    dirnames.remove('.olpc.store')
                    # don't visit .olpc.store directories
                for filename in filenames:
                    if filename.endswith(valid_endings):
                        iter = self.ls_right.append()
                        jobject_wrapper = JobjectWrapper()
                        jobject_wrapper.set_file_path(
                            os.path.join(dirname, filename))
                        self.ls_right.set(iter, COLUMN_IMAGE,
                            filename)
                        self.ls_right.set(iter, COLUMN_PATH,
                            jobject_wrapper)

        self.ls_right.set_sort_column_id(COLUMN_IMAGE,
            gtk.SORT_ASCENDING)
</pre>
<p>In this case I use the <em>datastore.mounts()</em> method to figure out what version of the datastore I have and then if I'm running .84 and later I use <em>os.walk()</em> to create a flat list of all files in all directories found under the directory <strong>/media</strong> (which is where USB and SD cards are always mounted).&#160; I can't make these files into directories, but what I can do is make a wrapper class that can contain either a Journal object or a file and use those objects where I would normally use Journal objects.&#160; The wrapper class looks like this:
</p>
<pre>class JobjectWrapper():
    def __init__(self):
        self.__jobject = None
        self.__file_path = None

    def set_jobject(self,  jobject):
        self.__jobject = jobject

    def set_file_path(self,  file_path):
        self.__file_path = file_path

    def get_file_path(self):
        if  self.__jobject != None:
            return self.__jobject.get_file_path()
        else:
            return self.__file_path
</pre>
<h2> Using Journal Entries
</h2>
<p>When you're ready to read a file stored in a Journal object you can use the <em>get_file_path()</em> method of the Journal object to get a file path and open it for reading, like this:
  <br/></p>
<pre>        fname = jobject.get_file_path()
</pre>
<p>One word of caution: be aware that this path does not exist until you call <em>get_file_path()</em> and will not exist long after.&#160; With the Journal you work with copies of files in the Journal, not the originals.&#160; For that reason you don't want to store the return value of <em>get_file_path()</em> for later use because later it may not be valid.&#160; Instead, store the Journal object itself and call the method right before you need the path.
</p>
<p>Metadata entries for Journal objects generally contain strings and work the way you would expect, with one exception, which is the <strong>preview</strong>.
  <br/></p>
<pre>    def create_preview(self,  object_id):
        jobject = datastore.get(object_id)

        if jobject.metadata.has_key('preview'):
            preview = jobject.metadata['preview']
            if preview is None or preview == '' or
                preview == 'None':
                if jobject.metadata['mime_type'].startswith(
                    'image/'):
                    filename = jobject.get_file_path()
                    self.show_image(filename)
                    return
                if jobject.metadata['mime_type']  == \
                    'application/x-cbz':
                    filename = jobject.get_file_path()
                    fname = self.extract_image(filename)
                    self.show_image(fname)
                    os.remove(fname)
                    return

        if jobject.metadata.has_key('preview') and \
                len(jobject.metadata['preview']) &gt; 4:

            if jobject.metadata['preview'][1:4] == 'PNG':
                preview_data = jobject.metadata['preview']
            else:
                import base64
                preview_data = base64.b64decode(
                    jobject.metadata['preview'])

            loader = gtk.gdk.PixbufLoader()
            loader.write(preview_data)
            scaled_buf = loader.get_pixbuf()
            loader.close()
            self.image.set_from_pixbuf(scaled_buf)
            self.image.show()
        else:
            self.image.clear()
            self.image.show()
</pre>
<p> The <strong>preview </strong>metadata attribute is different in two ways:
</p>
<ul><li>We should never request <strong>preview</strong> as metadata to be returned in our list of Journal objects.&#160; We'll need to get a complete copy of the Journal object to get it.&#160; Since we already have a Journal object we can get the complete Journal object by getting its <strong>object id</strong> then requesting a new copy from the datastore using the id.</li>
  <li>The preview image is a <strong>binary</strong> object (<strong>dbus.ByteArray</strong>) but in versions of Sugar older than .82 it will be stored as a text string.&#160; To accomplish this it is <strong>base 64 encoded</strong>.</li>
</ul><p>The code you would use to get a complete copy of a Journal object looks like this:
</p>
<pre>        object_id = jobject.object_id
        jobject = datastore.get(object_id)
</pre>
<p>Now for an explanation of base 64 encoding.&#160; You've probably heard that computers use the base two numbering system, in which the only digits used are 1 and 0.&#160; A unit of data storage that can hold either a zero or a one is called a <strong>bit</strong>.&#160; Computers need to store information besides numbers, so to accomodate this we group bits into groups of 8 (usually) and these groups are called <strong>bytes</strong>.&#160; If you only use 7 of the 8 bits in a byte you can store a letter of the Roman alphabet, a punctuation mark, or a single digit, plus things like tabs and line feed characters.&#160; Any file that can be created using only 7 bits out of the 8 is called a <strong>text file</strong>.&#160; Everything that needs all 8 bits of each byte to make, including computer programs, movies, music, and pictures of Jessica Alba is a <strong>binary</strong>.&#160; In versions of Sugar before .82 Journal object metadata can only store text strings.&#160; Somehow we need to represent 8-bit bytes in 7 bits.&#160; We do this by grouping the bytes together into a larger collection of bits and then splitting them back out into groups of 7 bits.&#160; Python has the <strong>base64</strong> package to do this for us.
</p>
<p>Base 64 encoding is actually a pretty common technique.&#160; If you've ever sent an email with an attached file the file was base 64 encoded.
</p>
<p>The code above has a couple of ways of creating a preview image.&#160; If the preview metadata contains a PNG image it is loaded into a pixbuf and displayed.&#160; If there is no preview metadata but the MIME type is for an image file or a comic book zip file we create the preview from the Journal entry itself.
  <br/></p>
<p>The code checks the first three characters of the preview metadata to see if they are 'PNG'.&#160; If so, the file is a <strong>Portable Network Graphics</strong> image stored as a binary and does not need to be converted from base 64 encoding, otherwise it does.
</p>
<h2>Updating A Journal Object
</h2>
<p>The code to update a Journal object looks like this:
</p>
<pre>    def update_entry(self):
        needs_update = False

        if self.selected_journal_entry is None:
            return

        object_id = self.selected_journal_entry.object_id
        jobject = datastore.get(object_id)

        old_title = jobject.metadata.get('title', None)
        if old_title != self.title_entry.props.text:
            jobject.metadata['title'] = \
                self.title_entry.props.text
            jobject.metadata['title_set_by_user'] = '1'
            needs_update = True

        old_tags = jobject.metadata.get('tags', None)
        new_tags = \
            self.tags_textview.props.buffer.props.text
        if old_tags != new_tags:
            jobject.metadata['tags'] = new_tags
            needs_update = True

        old_description = \
            jobject.metadata.get('description', None)
        new_description = \
            self.description_textview.props.buffer.props.text
        if old_description != new_description:
            jobject.metadata['description'] = \
                new_description
            needs_update = True

        if needs_update:
            datastore.write(jobject, update_mtime=False,
                reply_handler=self.datastore_write_cb,
                error_handler=self.datastore_write_error_cb)
        self.btn_save.props.sensitive = False

    def datastore_write_cb(self):
        pass

    def datastore_write_error_cb(self, error):
        logging.error(
            'sugarcommander.datastore_write_error_cb:'
            ' %r' % error)
</pre>
<h2>Deleting A Journal Entry
</h2>
<p>The code to delete a Journal entry is this:
</p>
<pre>    def delete_button_press_event_cb(self, entry, event):
        datastore.delete(
            self.selected_journal_entry.object_id)
</pre>
<h2>Getting Callbacks From The Journal Using D-Bus
</h2>
<p>In the chapter on <strong>Making Shared Activities</strong> we saw how D-Bus calls sent over Telepathy Tubes could be used to send messages from an Activity running on one computer to the same Activity running on a different computer.&#160;&#160; D-Bus is not normally used that way; typically it is used to send messages between programs running on the same computer.&#160;
</p>
<p>For example, if you're working with the Journal you can get callbacks whenever the Journal is updated.&#160; You get the callbacks whether the update was done by your Activity or elsewhere.&#160; If it is important for your Activity to know when the Journal has been updated you'll want to get these callbacks.
</p>
<p>The first thing you need to do is define some constants and import the dbus package:
  <br/></p>
<pre>DS_DBUS_SERVICE = 'org.laptop.sugar.DataStore'
DS_DBUS_INTERFACE = 'org.laptop.sugar.DataStore'
DS_DBUS_PATH = '/org/laptop/sugar/DataStore'
import dbus
</pre>
<p>Next, in your __init__() method put code to connect to the signals and do the callbacks:
  <br/></p>
<pre>        bus = dbus.SessionBus()
        remote_object = bus.get_object(
            DS_DBUS_SERVICE, DS_DBUS_PATH)
        _datastore = dbus.Interface(remote_object,
            DS_DBUS_INTERFACE)
        _datastore.connect_to_signal('Created',
            self._datastore_created_cb)
        _datastore.connect_to_signal('Updated',
            self._datastore_updated_cb)
        _datastore.connect_to_signal('Deleted',
            self._datastore_deleted_cb)
</pre>
<p>The methods being run by the callbacks might look something like this:
</p>
<pre>    def datastore_created_cb(self, uid):
        new_jobject = datastore.get(uid)
        iter = self.ls_journal.append()
        title = new_jobject.metadata['title']
        self.ls_journal.set(iter,
            COLUMN_TITLE, title)
        mime = new_jobject.metadata['mime_type']
        self.ls_journal.set(iter,
            COLUMN_MIME, mime)
        self.ls_journal.set(iter,
            COLUMN_JOBJECT, new_jobject)

    def datastore_updated_cb(self,  uid):
        new_jobject = datastore.get(uid)
        iter = self.ls_journal.get_iter_first()
        for row in self.ls_journal:
            jobject = row[COLUMN_JOBJECT]
            if jobject.object_id == uid:
                title = new_jobject.metadata['title']
                self.ls_journal.set_value(iter,
                    COLUMN_TITLE, title)
                break
            iter = self.ls_journal.iter_next(iter)
        object_id = \
            self.selected_journal_entry.object_id
        if object_id == uid:
            self.set_form_fields(new_jobject)

    def datastore_deleted_cb(self,  uid):
        save_path = self.selected_path
        iter = self.ls_journal.get_iter_first()
        for row in self.ls_journal:
            jobject = row[COLUMN_JOBJECT]
            if jobject.object_id == uid:
                self.ls_journal.remove(iter)
                break
            iter = self.ls_journal.iter_next(iter)

        try:
            self.selection_journal.select_path(
                save_path)
            self.tv_journal.grab_focus()
        except:
            self.title_entry.set_text('')
            description_textbuffer = \
                self.description_textview.get_buffer()
            description_textbuffer.set_text('')
            tags_textbuffer = \
                self.tags_textview.get_buffer()
            tags_textbuffer.set_text('')
            self.btn_save.props.sensitive = False
            self.btn_delete.props.sensitive = False
            self.image.clear()
            self.image.show()
</pre>
<p>The <strong>uid</strong> passed to each callback method is the <strong>object id</strong> of the Journal object that has been added, updated, or deleted.&#160; If an entry is added to the Journal I get the Journal object from the datastore by its uid, then add it to the gtk.ListStore for the gtk.TreeModel I'm using to list out Journal entries.&#160; If an entry is updated or deleted I need to account for the possibility that the Journal entry I am viewing or editing may have been updated or removed.&#160;&#160;&#160; I use the uid to figure out which row in the gtk.ListStore needs to be removed or modified by looping through the entries in the gtk.ListStore looking for a match.
  <br/></p>
<p>Now you know everything you'll ever need to know to work with the Journal.
  <br/></p></body></html>