Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/src/jarabe/journal/palettes.py
blob: 740b65a0b9529a6de4cf957feae71fcc44958600 (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
# Copyright (C) 2008 One Laptop Per Child
# Copyright (C) 2012, Walter Bender  <walter@sugarlabs.org>
# Copyright (C) 2012, Gonzalo Odiard <gonzalo@laptop.org>
# Copyright (C) 2012, Martin Abente  <tch@sugarlabs.org>
# Copyright (C) 2012, Ajay Garg      <ajay@activitycentral.com>
#
# 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 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

from gettext import gettext as _
from gettext import ngettext
import logging
import os

import gobject
import gtk
import gconf
import gio
import glib
import time

from sugar import _sugarext

from sugar.graphics import style
from sugar.graphics.palette import Palette
from sugar.graphics.menuitem import MenuItem
from sugar.graphics.icon import Icon
from sugar.graphics.xocolor import XoColor
from sugar import mime

from jarabe.model import friends
from jarabe.model import filetransfer
from jarabe.model import mimeregistry
from jarabe.journal import misc
from jarabe.journal import model

friends_model = friends.get_model()

_copy_menu_helper = None

class ObjectPalette(Palette):

    __gtype_name__ = 'ObjectPalette'

    __gsignals__ = {
        'detail-clicked': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE,
                           ([str])),
        'volume-error': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE,
                         ([str, str])),
    }

    def __init__(self, metadata, detail=False):

        self._metadata = metadata

        activity_icon = Icon(icon_size=gtk.ICON_SIZE_LARGE_TOOLBAR)
        activity_icon.props.file = misc.get_icon_name(metadata)
        color = misc.get_icon_color(metadata)
        activity_icon.props.xo_color = color

        if 'title' in metadata:
            title = gobject.markup_escape_text(metadata['title'])
        else:
            title = glib.markup_escape_text(_('Untitled'))

        Palette.__init__(self, primary_text=title,
                         icon=activity_icon)

        if misc.get_activities(metadata) or misc.is_bundle(metadata):
            if metadata.get('activity_id', ''):
                resume_label = _('Resume')
                resume_with_label = _('Resume with')
            else:
                resume_label = _('Start')
                resume_with_label = _('Start with')
            menu_item = MenuItem(resume_label, 'activity-start')
            menu_item.connect('activate', self.__start_activate_cb)
            self.menu.append(menu_item)
            menu_item.show()

            menu_item = MenuItem(resume_with_label, 'activity-start')
            self.menu.append(menu_item)
            menu_item.show()
            start_with_menu = StartWithMenu(self._metadata)
            menu_item.set_submenu(start_with_menu)

        else:
            menu_item = MenuItem(_('No activity to start entry'))
            menu_item.set_sensitive(False)
            self.menu.append(menu_item)
            menu_item.show()

        menu_item = MenuItem(_('Copy to'))
        icon = Icon(icon_name='edit-copy', xo_color=color,
                    icon_size=gtk.ICON_SIZE_MENU)
        menu_item.set_image(icon)
        self.menu.append(menu_item)
        menu_item.show()
        copy_menu = CopyMenu()
        copy_menu_helper = get_copy_menu_helper()

        metadata_list = []
        metadata_list.append(metadata)
        copy_menu_helper.insert_copy_to_menu_items(copy_menu,
                                                   metadata_list,
                                                   False,
                                                   False,
                                                   False)
        copy_menu.connect('volume-error', self.__volume_error_cb)
        menu_item.set_submenu(copy_menu)

        if self._metadata['mountpoint'] == '/':
            menu_item = MenuItem(_('Duplicate'))
            icon = Icon(icon_name='edit-duplicate', xo_color=color,
                        icon_size=gtk.ICON_SIZE_MENU)
            menu_item.set_image(icon)
            menu_item.connect('activate', self.__duplicate_activate_cb)
            self.menu.append(menu_item)
            menu_item.show()

        menu_item = MenuItem(_('Send to'), 'document-send')
        self.menu.append(menu_item)
        menu_item.show()

        friends_menu = FriendsMenu()
        friends_menu.connect('friend-selected', self.__friend_selected_cb)
        menu_item.set_submenu(friends_menu)

        if detail == True:
            menu_item = MenuItem(_('View Details'), 'go-right')
            menu_item.connect('activate', self.__detail_activate_cb)
            self.menu.append(menu_item)
            menu_item.show()

        menu_item = MenuItem(_('Erase'), 'list-remove')
        menu_item.connect('activate', self.__erase_activate_cb)
        self.menu.append(menu_item)
        menu_item.show()

    def __start_activate_cb(self, menu_item):
        misc.resume(self._metadata)

    def __duplicate_activate_cb(self, menu_item):
        file_path = model.get_file(self._metadata['uid'])
        try:
            model.copy(self._metadata, '/')
        except IOError, e:
            logging.exception('Error while copying the entry. %s', e.strerror)
            self.emit('volume-error',
                      _('Error while copying the entry. %s') % e.strerror,
                      _('Error'))

    def __erase_activate_cb(self, menu_item):
        model.delete(self._metadata['uid'])

    def __detail_activate_cb(self, menu_item):
        self.emit('detail-clicked', self._metadata['uid'])

    def __volume_error_cb(self, menu_item, message, severity):
        self.emit('volume-error', message, severity)

    def __friend_selected_cb(self, menu_item, buddy):
        logging.debug('__friend_selected_cb')
        file_name = model.get_file(self._metadata['uid'])

        if not file_name or not os.path.exists(file_name):
            logging.warn('Entries without a file cannot be sent.')
            self.emit('volume-error',
                      _('Entries without a file cannot be sent.'),
                      _('Warning'))
            return

        title = str(self._metadata['title'])
        description = str(self._metadata.get('description', ''))
        mime_type = str(self._metadata['mime_type'])

        if not mime_type:
            mime_type = mime.get_for_file(file_name)

        filetransfer.start_transfer(buddy, file_name, title, description,
                                    mime_type)


class CopyMenu(gtk.Menu):
    __gtype_name__ = 'JournalCopyMenu'

    __gsignals__ = {
        'volume-error': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE,
                         ([str, str])),
    }

    def __init__(self):
        gobject.GObject.__init__(self)


class ActionItem(gobject.GObject):
    """
    This class implements the course of actions that happens when clicking
    upon an Action-Item (eg. Batch-Copy-Toolbar-button;
                             Actual-Batch-Copy-To-Journal-button;
                             Actual-Batch-Copy-To-Documents-button;
                             Actual-Batch-Copy-To-Mounted-Drive-button;
                             Actual-Batch-Copy-To-Clipboard-button;
                             Single-Copy-To-Journal-button;
                             Single-Copy-To-Documents-button;
                             Single-Copy-To-Mounted-Drive-button;
                             Single-Copy-To-Clipboard-button;
                             Batch-Erase-Button;
                             Select-None-Toolbar-button;
                             Select-All-Toolbar-button
    """

    def __init__(self, label, metadata_list, show_editing_alert,
                 show_progress_info_alert, batch_mode,
                 need_to_popup_options,
                 operate_on_deselected_entries,
                 switch_to_normal_mode_after_completion,
                 show_post_selected_confirmation,
                 show_not_completed_ops_info):
        gobject.GObject.__init__(self)

        self._label = label

        # Make a copy.
        self._immutable_metadata_list = []
        for metadata in metadata_list:
            self._immutable_metadata_list.append(metadata)

        self._metadata_list = metadata_list
        self._show_progress_info_alert = show_progress_info_alert
        self._batch_mode = batch_mode
        self._operate_on_deselected_entries = \
                operate_on_deselected_entries
        self._switch_to_normal_mode_after_completion = \
                switch_to_normal_mode_after_completion
        self._show_post_selected_confirmation = \
                show_post_selected_confirmation
        self._show_not_completed_ops_info = \
                show_not_completed_ops_info

        actionable_signal = self._get_actionable_signal()

        if need_to_popup_options:
            self.connect(actionable_signal, self._fill_and_pop_up_options)
        else:
            if show_editing_alert:
                self.connect(actionable_signal, self._show_editing_alert)
            else:
                self.connect(actionable_signal, self._pre_operate_per_action)

    def _get_actionable_signal(self):
        """
        Some widgets like 'buttons' have 'clicked' as actionable signal;
        some like 'menuitems' have 'activate' as actionable signal.
        """

        raise NotImplementedError

    def _fill_and_pop_up_options(self):
        """
        Eg. Batch-Copy-Toolbar-button does not do anything by itself
        useful; but rather pops-up the actual 'copy-to' options.
        """

        raise NotImplementedError

    def _show_editing_alert(self, widget_clicked):
        """
        Upon clicking the actual operation button (eg.
        Batch-Erase-Button and Batch-Copy-To-Clipboard button; BUT NOT
        Batch-Copy-Toolbar-button, since it does not do anything
        actually useful, but only pops-up the actual 'copy-to' options.
        """

        alert_parameters = self._get_editing_alert_parameters()
        title = alert_parameters[0]
        message = alert_parameters[1]
        operation = alert_parameters[2]

        from jarabe.journal.journalactivity import get_journal
        get_journal().update_confirmation_alert(title, message,
                                                self._pre_operate_per_action,
                                                None)

    def _get_editing_alert_parameters(self):
        """
        Get the alert parameters for widgets that can show editing
        alert.
        """

        self._metadata_list = self._get_metadata_list()
        entries_len = len(self._metadata_list)

        title = self._get_editing_alert_title()
        message = self._get_editing_alert_message(entries_len)
        operation = self._get_editing_alert_operation()

        return (title, message, operation)

    def _get_list_model_len(self):
        """
        Get the total length of the model under view.
        """

        from jarabe.journal.journalactivity import get_journal
        journal = get_journal()

        return len(journal.get_list_view().get_model())

    def _get_metadata_list(self):
        """
        For batch-mode, get the metadata list, according to button-type.
        For eg, Select-All-Toolbar-button operates on non-selected entries;
        while othere operate on selected-entries.

        For single-mode, simply copy from the
        "immutable_metadata_list".
        """

        if self._batch_mode:
            from jarabe.journal.journalactivity import get_journal
            journal = get_journal()

            if self._operate_on_deselected_entries:
                return journal.get_metadata_list(False)
            else:
                return journal.get_metadata_list(True)
        else:
            metadata_list = []
            for metadata in self._immutable_metadata_list:
                metadata_list.append(metadata)
            return metadata_list

    def _get_editing_alert_title(self):
        raise NotImplementedError

    def _get_editing_alert_message(self, entries_len):
        raise NotImplementedError

    def _get_editing_alert_operation(self):
        raise NotImplementedError

    def _is_metadata_list_empty(self):
        return (self._metadata_list is None) or \
                (len(self._metadata_list) == 0)

    def _pre_operate_per_action(self, obj, ok_clicked=False):
        """
        This is the stage, just before the FIRST metadata gets into its
        processing cycle.
        """

        # Show waiting cursor (only for batch mode)
        if self._batch_mode:
            self.get_root_window().set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))

        self._skip_all = False

        # Also, get the initial length of the model.
        self._model_len = self._get_list_model_len()

        # For batch-operations, fetch the metadata list again.
        self._metadata_list = self._get_metadata_list()

        # Set the initial length of metadata-list.
        self._metadata_list_initial_len = len(self._metadata_list)

        self._metadata_processed = 0

        # Next, proceed with the metadata
        self._pre_operate_per_metadata_per_action()

    def _pre_operate_per_metadata_per_action(self):
        """
        This is the stage, just before EVERY metadata gets into doing
        its actual work.
        """

        from jarabe.journal.journalactivity import get_journal

        # If there is still some metadata left, proceed with the
        # metadata operation.
        # Else, proceed to post-operations.
        if len(self._metadata_list) > 0:
            metadata = self._metadata_list.pop(0)

            # If info-alert needs to be shown, show the alert, and
            # arrange for actual operation.
            # Else, proceed to actual operation directly.
            if self._show_progress_info_alert:
                current_len = len(self._metadata_list)

                # TRANS: Do not translate the two %d, and the %s.
                info_alert_message = _('( %d / %d ) %s') % (
                        self._metadata_list_initial_len - current_len,
                        self._metadata_list_initial_len, metadata['title'])

                get_journal().update_info_alert(self._get_info_alert_title() + ' ...',
                                                info_alert_message,
                                                self._operate_per_metadata_per_action,
                                                metadata)
            else:
                self._operate_per_metadata_per_action(metadata)
        else:
            self._post_operate_per_action()

    def _get_info_alert_title(self):
        raise NotImplementedError

    def _operate_per_metadata_per_action(self, metadata):
        """
        This is just a code-convenient-function, which allows
        runtime-overriding. It just delegates to the actual
        "self._operate" method, the actual which is determined at
        runtime.
        """

        # Pass the callback for the post-operation-for-metadata. This
        # will ensure that async-operations on the metadata are taken
        # care of.
        if self._operate(metadata) is False:
            return
        else:
            self._metadata_processed = self._metadata_processed + 1


    def _operate(self, metadata):
        """
        Actual, core, productive stage for EVERY metadata.
        """

        raise NotImplementedError

    def  _post_operate_per_metadata_per_action(self, metadata):
        """
        This is the stage, just after EVERY metadata has been
        processed.
        """

        # Toggle the corresponding checkbox - but only for batch-mode.
        if self._batch_mode:
            from jarabe.journal.journalactivity import get_journal
            list_view = get_journal().get_list_view()

            list_view.do_ui_select_change(metadata)
            list_view.do_backend_select_change(metadata)

        # Call the next ...
        self._pre_operate_per_metadata_per_action()

    def _post_operate_per_action(self):
        """
        This is the stage, just after the LAST metadata has been
        processed.
        """

        from jarabe.journal.journalactivity import get_journal
        journal = get_journal()

        # Show post-operation confirmation message, if applicable.
        if self._show_post_selected_confirmation:
            entries_len = \
                    self._get_post_selection_alert_message_entries_len()
            message = \
                    self._get_post_selection_alert_message(entries_len)
            journal.update_error_alert(self._get_editing_alert_operation(),
                                      message,
                                      self._process_switching_mode,
                                      None)
        else:
            self._process_switching_mode(None, False)

        # Retain the old cursor.
        if self._batch_mode:
            self.get_root_window().set_cursor(gtk.gdk.Cursor(gtk.gdk.LEFT_PTR))

    def _process_switching_mode(self, metadata, ok_clicked=False):
        from jarabe.journal.journalactivity import get_journal
        journal = get_journal()

        # Necessary to do this, when the alert needs to be hidden,
        # WITHOUT user-intervention.
        journal.hide_alert()

    def _refresh(self):
        from jarabe.journal.journalactivity import get_journal
        get_journal().get_list_view().refresh()

    def _handle_error_alert(self, error_message, metadata):
        """
        This handles any error scenarios. Examples are of entries that
        display the message "Entries without a file cannot be copied."
        This is kind of controller-functionl the model-function is
        "self._set_error_info_alert".
        """

        if self._skip_all:
            self._post_operate_per_metadata_per_action(metadata)
        else:
            self._set_error_info_alert(error_message, metadata)

    def _set_error_info_alert(self, error_message, metadata):
        """
        This method displays the error alert.
        """

        current_len = len(self._metadata_list)

        # TRANS: Do not translate the two %d, and the three %s.
        info_alert_message = _('( %d / %d ) Error while %s %s : %s') % (
                self._metadata_list_initial_len - current_len,
                self._metadata_list_initial_len,
                self._get_info_alert_title(),
                metadata['title'],
                error_message)

        # Only show the alert, if allowed to.
        if self._show_not_completed_ops_info:
            from jarabe.journal.journalactivity import get_journal
            get_journal().update_error_alert(self._get_info_alert_title()  + ' ...',
                                             info_alert_message,
                                             self._process_error_skipping,
                                             metadata)
        else:
            self._process_error_skipping(self._skip_all, metadata)

    def _process_error_skipping(self, metadata, skip_all):
        # The operation for the current metadata is finished (kinda
        # pseudo ...)
        self._post_operate_per_metadata_per_action(metadata)

    def _file_path_valid(self, metadata):
        file_path = model.get_file(metadata['uid'])
        if not file_path or not os.path.exists(file_path):
            logging.warn('Entries without a file cannot be copied.')
            error_message =  _('Entries without a file cannot be copied.')
            if self._batch_mode:
                self._handle_error_alert(error_message, metadata)
            else:
                self.emit('volume-error', error_message, _('Warning'))
            return False
        else:
            return True

    def _metadata_copy_valid(self, metadata, mount_point):
        self._set_bundle_installation_allowed(False)

        try:
            model.copy(metadata, mount_point)
            return True
        except Exception, e:
            logging.exception('Error while copying the entry. %s', e)
            error_message = _('Error while copying the entry. %s') % e
            if self._batch_mode:
                self._handle_error_alert(error_message, metadata)
            else:
                self.emit('volume-error', error_message, _('Error'))
            return False
        finally:
            self._set_bundle_installation_allowed(True)

    def _metadata_write_valid(self, metadata):
        operation = self._get_info_alert_title()
        self._set_bundle_installation_allowed(False)

        try:
            model.write(metadata, update_mtime=False)
            return True
        except Exception, e:
            logging.exception('Error while writing the metadata. %s', e)
            error_message = _('Error occurred while %s : %s.') % \
                    (operation, e,)
            if self._batch_mode:
                self._handle_error_alert(error_message, metadata)
            else:
                self.emit('volume-error', error_message, _('Error'))
            return False
        finally:
            self._set_bundle_installation_allowed(True)

    def _set_bundle_installation_allowed(self, allowed):
        """
        This method serves only as a "delegating" method.
        This has been done to aid easy configurability.
        """
        from jarabe.journal.journalactivity import get_journal
        journal = get_journal()

        if self._batch_mode:
            journal.set_bundle_installation_allowed(allowed)


class BaseCopyMenuItem(MenuItem, ActionItem):
    __gsignals__ = {
            'volume-error': (gobject.SIGNAL_RUN_FIRST,
                             gobject.TYPE_NONE, ([str, str])),
            }

    def __init__(self, metadata_list, label, show_editing_alert,
                 show_progress_info_alert, batch_mode):
        MenuItem.__init__(self, label)
        ActionItem.__init__(self, label, metadata_list, show_editing_alert,
                            show_progress_info_alert, batch_mode,
                            need_to_popup_options=False,
                            operate_on_deselected_entries=False,
                            switch_to_normal_mode_after_completion=True,
                            show_post_selected_confirmation=False,
                            show_not_completed_ops_info=True)

    def _get_actionable_signal(self):
        return 'activate'

    def _get_editing_alert_title(self):
        return _('Copy')

    def _get_editing_alert_message(self, entries_len):
        return ngettext('Do you want to copy %d entry to %s?',
                        'Do you want to copy %d entries to %s?',
                        entries_len) % (entries_len, self._label)

    def _get_editing_alert_operation(self):
        return _('Copy')

    def _get_info_alert_title(self):
        return _('Copying')


class VolumeMenu(BaseCopyMenuItem):
    def __init__(self, metadata_list, label, mount_point,
                 show_editing_alert, show_progress_info_alert,
                 batch_mode):
        BaseCopyMenuItem.__init__(self, metadata_list, label,
                                  show_editing_alert,
                                  show_progress_info_alert, batch_mode)
        self._mount_point = mount_point

    def _operate(self, metadata):
        if not self._file_path_valid(metadata):
            return False
        if not self._metadata_copy_valid(metadata, self._mount_point):
            return False

        # This is sync-operation. Thus, call the callback.
        self._post_operate_per_metadata_per_action(metadata)


class ClipboardMenu(BaseCopyMenuItem):
    def __init__(self, metadata_list, show_editing_alert,
                 show_progress_info_alert, batch_mode):
        BaseCopyMenuItem.__init__(self, metadata_list, _('Clipboard'),
                                  show_editing_alert,
                                  show_progress_info_alert,
                                  batch_mode)
        self._temp_file_path_list = []

    def _operate(self, metadata):
        if not self._file_path_valid(metadata):
            return False

        clipboard = gtk.Clipboard()
        clipboard.set_with_data([('text/uri-list', 0, 0)],
                                self.__clipboard_get_func_cb,
                                self.__clipboard_clear_func_cb,
                                metadata)

    def __clipboard_get_func_cb(self, clipboard, selection_data, info,
                                metadata):
        # Get hold of a reference so the temp file doesn't get deleted
        self._temp_file_path = model.get_file(metadata['uid'])
        logging.debug('__clipboard_get_func_cb %r', self._temp_file_path)
        selection_data.set_uris(['file://' + self._temp_file_path])

    def __clipboard_clear_func_cb(self, clipboard, metadata):
        # Release and delete the temp file
        self._temp_file_path = None

        # This is async-operation; and this is the ending point.
        self._post_operate_per_metadata_per_action(metadata)


class DocumentsMenu(BaseCopyMenuItem):
    def __init__(self, metadata_list, show_editing_alert,
                 show_progress_info_alert, batch_mode):
        BaseCopyMenuItem.__init__(self, metadata_list, _('Documents'),
                                  show_editing_alert,
                                  show_progress_info_alert,
                                  batch_mode)

    def _operate(self, metadata):
        if not self._file_path_valid(metadata):
            return False
        if not self._metadata_copy_valid(metadata,
                                         model.get_documents_path()):
            return False

        # This is sync-operation. Call the post-operation now.
        self._post_operate_per_metadata_per_action(metadata)


class FriendsMenu(gtk.Menu):
    __gtype_name__ = 'JournalFriendsMenu'

    __gsignals__ = {
        'friend-selected': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE,
                            ([object])),
    }

    def __init__(self):
        gobject.GObject.__init__(self)

        if filetransfer.file_transfer_available():
            friends_model = friends.get_model()
            for friend in friends_model:
                if friend.is_present():
                    menu_item = MenuItem(text_label=friend.get_nick(),
                                         icon_name='computer-xo',
                                         xo_color=friend.get_color())
                    menu_item.connect('activate', self.__item_activate_cb,
                                      friend)
                    self.append(menu_item)
                    menu_item.show()

            if not self.get_children():
                menu_item = MenuItem(_('No friends present'))
                menu_item.set_sensitive(False)
                self.append(menu_item)
                menu_item.show()
        else:
            menu_item = MenuItem(_('No valid connection found'))
            menu_item.set_sensitive(False)
            self.append(menu_item)
            menu_item.show()

    def __item_activate_cb(self, menu_item, friend):
        self.emit('friend-selected', friend)


class StartWithMenu(gtk.Menu):
    __gtype_name__ = 'JournalStartWithMenu'

    def __init__(self, metadata):
        gobject.GObject.__init__(self)

        self._metadata = metadata

        for activity_info in misc.get_activities(metadata):
            menu_item = MenuItem(activity_info.get_name())
            menu_item.set_image(Icon(file=activity_info.get_icon(),
                                     icon_size=gtk.ICON_SIZE_MENU))
            menu_item.connect('activate', self.__item_activate_cb,
                              activity_info.get_bundle_id())
            self.append(menu_item)
            menu_item.show()

        if not self.get_children():
            if metadata.get('activity_id', ''):
                resume_label = _('No activity to resume entry')
            else:
                resume_label = _('No activity to start entry')
            menu_item = MenuItem(resume_label)
            menu_item.set_sensitive(False)
            self.append(menu_item)
            menu_item.show()

    def __item_activate_cb(self, menu_item, service_name):
        mime_type = self._metadata.get('mime_type', '')
        if mime_type:
            mime_registry = mimeregistry.get_registry()
            mime_registry.set_default_activity(mime_type, service_name)
        misc.resume(self._metadata, service_name)


class BuddyPalette(Palette):
    def __init__(self, buddy):
        self._buddy = buddy

        nick, colors = buddy
        buddy_icon = Icon(icon_name='computer-xo',
                          icon_size=style.STANDARD_ICON_SIZE,
                          xo_color=XoColor(colors))

        Palette.__init__(self, primary_text=glib.markup_escape_text(nick),
                         icon=buddy_icon)

        # TODO: Support actions on buddies, like make friend, invite, etc.



class CopyMenuHelper(gtk.Menu):
    __gtype_name__ = 'JournalCopyMenuHelper'

    __gsignals__ = {
            'volume-error': (gobject.SIGNAL_RUN_FIRST,
                             gobject.TYPE_NONE,
                             ([str, str])),
            }

    def insert_copy_to_menu_items(self, menu, metadata_list,
                                  show_editing_alert,
                                  show_progress_info_alert,
                                  batch_mode):
        self._metadata_list = metadata_list

        clipboard_menu = ClipboardMenu(metadata_list,
                                       show_editing_alert,
                                       show_progress_info_alert,
                                       batch_mode)
        clipboard_menu.set_image(Icon(icon_name='toolbar-edit',
                                      icon_size=gtk.ICON_SIZE_MENU))
        clipboard_menu.connect('volume-error', self.__volume_error_cb)
        menu.append(clipboard_menu)
        clipboard_menu.show()

        from jarabe.journal.journalactivity import get_mount_point

        if get_mount_point() != model.get_documents_path():
            documents_menu = DocumentsMenu(metadata_list,
                                           show_editing_alert,
                                           show_progress_info_alert,
                                           batch_mode)
            documents_menu.set_image(Icon(icon_name='user-documents',
                                          icon_size=gtk.ICON_SIZE_MENU))
            documents_menu.connect('volume-error', self.__volume_error_cb)
            menu.append(documents_menu)
            documents_menu.show()

        if get_mount_point() != '/':
            client = gconf.client_get_default()
            color = XoColor(client.get_string('/desktop/sugar/user/color'))
            journal_menu = VolumeMenu(metadata_list, _('Journal'), '/',
                                      show_editing_alert,
                                      show_progress_info_alert,
                                      batch_mode)
            journal_menu.set_image(Icon(icon_name='activity-journal',
                                        xo_color=color,
                                        icon_size=gtk.ICON_SIZE_MENU))
            journal_menu.connect('volume-error', self.__volume_error_cb)
            menu.append(journal_menu)
            journal_menu.show()

        volume_monitor = gio.volume_monitor_get()
        icon_theme = gtk.icon_theme_get_default()
        for mount in volume_monitor.get_mounts():
            if get_mount_point() == mount.get_root().get_path():
                continue

            volume_menu = VolumeMenu(metadata_list, mount.get_name(),
                                     mount.get_root().get_path(),
                                     show_editing_alert,
                                     show_progress_info_alert,
                                     batch_mode)
            for name in mount.get_icon().props.names:
                if icon_theme.has_icon(name):
                    volume_menu.set_image(Icon(icon_name=name,
                                               icon_size=gtk.ICON_SIZE_MENU))
                    break

            volume_menu.connect('volume-error', self.__volume_error_cb)
            menu.insert(volume_menu, -1)
            volume_menu.show()

    def __volume_error_cb(self, menu_item, message, severity):
        from jarabe.journal.journalactivity import get_journal
        journal = get_journal()
        journal._volume_error_cb(menu_item, message, severity)


def get_copy_menu_helper():
    global _copy_menu_helper
    if _copy_menu_helper is None:
        _copy_menu_helper = CopyMenuHelper()
    return _copy_menu_helper