Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/src/jarabe/journal/journalactivity.py
blob: 1b841e983242fcc78b1cd8b321712ae8b1147d06 (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
# Copyright (C) 2006, Red Hat, Inc.
# Copyright (C) 2007, 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

import logging
from gettext import gettext as _
from gettext import ngettext
import uuid

import gtk
import dbus
import statvfs
import os
import gobject

from sugar.graphics.window import Window
from sugar.graphics.alert import Alert, ErrorAlert, ConfirmationAlert
from sugar.graphics.icon import Icon

from sugar.bundle.bundle import ZipExtractException, RegistrationException
from sugar import env
from sugar.activity import activityfactory
from sugar import wm

from jarabe.model import bundleregistry
from jarabe.journal.journaltoolbox import MainToolbox, DetailToolbox
from jarabe.journal.journaltoolbox import EditToolbox
from jarabe.journal.listview import ListView
from jarabe.journal.listmodel import ListModel
from jarabe.journal.detailview import DetailView
from jarabe.journal.volumestoolbar import VolumesToolbar
from jarabe.journal import misc
from jarabe.journal.journalentrybundle import JournalEntryBundle
from jarabe.journal.objectchooser import ObjectChooser
from jarabe.journal.modalalert import ModalAlert
from jarabe.journal import model
from jarabe.journal.journalwindow import JournalWindow


J_DBUS_SERVICE = 'org.laptop.Journal'
J_DBUS_INTERFACE = 'org.laptop.Journal'
J_DBUS_PATH = '/org/laptop/Journal'

_SPACE_TRESHOLD = 52428800
_BUNDLE_ID = 'org.laptop.JournalActivity'

_journal = None
_mount_point = None


class JournalActivityDBusService(dbus.service.Object):
    def __init__(self, parent):
        self._parent = parent
        session_bus = dbus.SessionBus()
        bus_name = dbus.service.BusName(J_DBUS_SERVICE,
            bus=session_bus, replace_existing=False, allow_replacement=False)
        logging.debug('bus_name: %r', bus_name)
        dbus.service.Object.__init__(self, bus_name, J_DBUS_PATH)

    @dbus.service.method(J_DBUS_INTERFACE,
        in_signature='s', out_signature='')
    def ShowObject(self, object_id):
        """Pop-up journal and show object with object_id"""

        logging.debug('Trying to show object %s', object_id)

        if self._parent.show_object(object_id):
            self._parent.reveal()

    def _chooser_response_cb(self, chooser, response_id, chooser_id):
        logging.debug('JournalActivityDBusService._chooser_response_cb')
        if response_id == gtk.RESPONSE_ACCEPT:
            object_id = chooser.get_selected_object_id()
            self.ObjectChooserResponse(chooser_id, object_id)
        else:
            self.ObjectChooserCancelled(chooser_id)
        chooser.destroy()
        del chooser

    @dbus.service.method(J_DBUS_INTERFACE, in_signature='is',
                         out_signature='s')
    def ChooseObject(self, parent_xid, what_filter=''):
        chooser_id = uuid.uuid4().hex
        if parent_xid > 0:
            parent = gtk.gdk.window_foreign_new(parent_xid)
        else:
            parent = None
        chooser = ObjectChooser(parent, what_filter)
        chooser.connect('response', self._chooser_response_cb, chooser_id)
        chooser.show()

        return chooser_id

    @dbus.service.signal(J_DBUS_INTERFACE, signature='ss')
    def ObjectChooserResponse(self, chooser_id, object_id):
        pass

    @dbus.service.signal(J_DBUS_INTERFACE, signature='s')
    def ObjectChooserCancelled(self, chooser_id):
        pass


class JournalActivity(JournalWindow):
    def __init__(self):
        logging.debug('STARTUP: Loading the journal')
        JournalWindow.__init__(self)

        self.set_title(_('Journal'))

        self._main_view = None
        self._secondary_view = None
        self._list_view = None
        self._detail_view = None
        self._main_toolbox = None
        self._edit_toolbox = None
        self._detail_toolbox = None
        self._volumes_toolbar = None
        self._editing_mode = False
        self._alert = Alert()
        self._error_alert = ErrorAlert()
        self._confirmation_alert = ConfirmationAlert()
        self._current_alert = None
        self.setup_handlers_for_alert_actions()

        self._info_alert = None
        self._selected_entries = []
        self._bundle_installation_allowed = True

        set_mount_point('/')

        self._setup_main_view()
        self._setup_secondary_view()

        self.add_events(gtk.gdk.ALL_EVENTS_MASK |
                        gtk.gdk.VISIBILITY_NOTIFY_MASK)
        self._realized_sid = self.connect('realize', self.__realize_cb)
        self.connect('visibility-notify-event',
                     self.__visibility_notify_event_cb)
        self.connect('window-state-event', self.__window_state_event_cb)
        self.connect('key-press-event', self._key_press_event_cb)
        self.connect('focus-in-event', self._focus_in_event_cb)

        model.created.connect(self.__model_created_cb)
        model.updated.connect(self.__model_updated_cb)
        model.deleted.connect(self.__model_deleted_cb)

        self._dbus_service = JournalActivityDBusService(self)

        self.iconify()

        self._critical_space_alert = None
        self._check_available_space()

    def __volume_error_cb(self, gobject, message, severity):
        alert = ErrorAlert(title=severity, msg=message)
        alert.connect('response', self.__alert_response_cb)
        self.add_alert(alert)
        alert.show()

    def _volume_error_cb(self, gobject, message, severity):
        self.update_error_alert(severity, message, None, None)

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

    def __realize_cb(self, window):
        wm.set_bundle_id(window.window, _BUNDLE_ID)
        activity_id = activityfactory.create_activity_id()
        wm.set_activity_id(window.window, str(activity_id))
        self.disconnect(self._realized_sid)
        self._realized_sid = None

    def can_close(self):
        return False

    def _setup_main_view(self):
        self._main_toolbox = MainToolbox()
        self._main_view = gtk.VBox()

        self._list_view = ListView()
        self._list_view.connect('detail-clicked', self.__detail_clicked_cb)
        self._list_view.connect('clear-clicked', self.__clear_clicked_cb)
        self._list_view.connect('volume-error', self.__volume_error_cb)
        self._main_view.pack_start(self._list_view)
        self._list_view.show()

        self._volumes_toolbar = VolumesToolbar()
        self._volumes_toolbar.connect('volume-changed',
                                      self.__volume_changed_cb)
        self._volumes_toolbar.connect('volume-error', self.__volume_error_cb)
        self._main_view.pack_start(self._volumes_toolbar, expand=False)

        search_toolbar = self._main_toolbox.search_toolbar
        search_toolbar.connect('query-changed', self._query_changed_cb)
        search_toolbar.set_mount_point('/')
        set_mount_point('/')

    def _setup_secondary_view(self):
        self._secondary_view = gtk.VBox()

        self._detail_toolbox = DetailToolbox()
        self._detail_toolbox.entry_toolbar.connect('volume-error',
                                                   self.__volume_error_cb)

        self._detail_view = DetailView()
        self._detail_view.connect('go-back-clicked', self.__go_back_clicked_cb)
        self._secondary_view.pack_end(self._detail_view)
        self._detail_view.show()

    def _key_press_event_cb(self, widget, event):
        keyname = gtk.gdk.keyval_name(event.keyval)
        if keyname == 'Escape':
            self.show_main_view()

    def __detail_clicked_cb(self, list_view, object_id):
        self._show_secondary_view(object_id)

    def __clear_clicked_cb(self, list_view):
        self._main_toolbox.search_toolbar.clear_query()

    def __go_back_clicked_cb(self, detail_view):
        self.show_main_view()

    def _query_changed_cb(self, toolbar, query):
        self._list_view.update_with_query(query)
        self.show_main_view()

    def show_main_view(self):
        if self._editing_mode:
            toolbox = EditToolbox()
        else:
            toolbox = self._main_toolbox

        self.set_toolbar_box(toolbox)
        toolbox.show()

        if self.canvas != self._main_view:
            self.set_canvas(self._main_view)
            self._main_view.show()

    def _show_secondary_view(self, object_id):
        metadata = model.get(object_id)
        try:
            self._detail_toolbox.entry_toolbar.set_metadata(metadata)
        except Exception:
            logging.exception('Exception while displaying entry:')

        self.set_toolbar_box(self._detail_toolbox)
        self._detail_toolbox.show()

        try:
            self._detail_view.props.metadata = metadata
        except Exception:
            logging.exception('Exception while displaying entry:')

        self.set_canvas(self._secondary_view)
        self._secondary_view.show()

    def show_object(self, object_id):
        metadata = model.get(object_id)
        if metadata is None:
            return False
        else:
            self._show_secondary_view(object_id)
            return True

    def __volume_changed_cb(self, volume_toolbar, mount_point):
        logging.debug('Selected volume: %r.', mount_point)
        self._main_toolbox.search_toolbar.set_mount_point(mount_point)
        set_mount_point(mount_point)
        self._main_toolbox.set_current_toolbar(0)

    def __model_created_cb(self, sender, **kwargs):
        self._check_for_bundle(kwargs['object_id'])
        self._main_toolbox.search_toolbar.refresh_filters()
        self._check_available_space()

    def __model_updated_cb(self, sender, **kwargs):
        self._check_for_bundle(kwargs['object_id'])

        if self.canvas == self._secondary_view and \
                kwargs['object_id'] == self._detail_view.props.metadata['uid']:
            self._detail_view.refresh()

        self._check_available_space()

    def __model_deleted_cb(self, sender, **kwargs):
        if self.canvas == self._secondary_view and \
                kwargs['object_id'] == self._detail_view.props.metadata['uid']:
            self.show_main_view()

    def _focus_in_event_cb(self, window, event):
        self.search_grab_focus()
        self._list_view.update_dates()

    def _check_for_bundle(self, object_id):
        if not self._bundle_installation_allowed:
            return

        registry = bundleregistry.get_registry()

        metadata = model.get(object_id)
        if metadata.get('progress', '').isdigit():
            if int(metadata['progress']) < 100:
                return

        bundle = misc.get_bundle(metadata)
        if bundle is None:
            return

        if registry.is_installed(bundle):
            logging.debug('_check_for_bundle bundle already installed')
            return

        if metadata['mime_type'] == JournalEntryBundle.MIME_TYPE:
            # JournalEntryBundle code takes over the datastore entry and
            # transforms it into the journal entry from the bundle -- we have
            # nothing more to do.
            try:
                registry.install(bundle, metadata['uid'])
            except (ZipExtractException, RegistrationException):
                logging.exception('Could not install bundle %s',
                        bundle.get_path())
            return

        try:
            registry.install(bundle)
        except (ZipExtractException, RegistrationException):
            logging.exception('Could not install bundle %s', bundle.get_path())
            return

        metadata['bundle_id'] = bundle.get_bundle_id()
        model.write(metadata)

    def set_bundle_installation_allowed(self, allowed):
        self._bundle_installation_allowed = allowed

    def search_grab_focus(self):
        search_toolbar = self._main_toolbox.search_toolbar
        search_toolbar.give_entry_focus()

    def __window_state_event_cb(self, window, event):
        logging.debug('window_state_event_cb %r', self)
        if event.changed_mask & gtk.gdk.WINDOW_STATE_ICONIFIED:
            state = event.new_window_state
            visible = not state & gtk.gdk.WINDOW_STATE_ICONIFIED
            self._list_view.set_is_visible(visible)

    def __visibility_notify_event_cb(self, window, event):
        logging.debug('visibility_notify_event_cb %r', self)
        visible = event.state != gtk.gdk.VISIBILITY_FULLY_OBSCURED
        self._list_view.set_is_visible(visible)

    def _check_available_space(self):
        """Check available space on device

            If the available space is below 50MB an alert will be
            shown which encourages to delete old journal entries.
        """

        if self._critical_space_alert:
            return
        stat = os.statvfs(env.get_profile_path())
        free_space = stat[statvfs.F_BSIZE] * stat[statvfs.F_BAVAIL]
        if free_space < _SPACE_TRESHOLD:
            self._critical_space_alert = ModalAlert()
            self._critical_space_alert.connect('destroy',
                                               self.__alert_closed_cb)
            self._critical_space_alert.show()

    def __alert_closed_cb(self, data):
        self.show_main_view()
        self.reveal()
        self._critical_space_alert = None

    def set_active_volume(self, mount):
        self._volumes_toolbar.set_active_volume(mount)

    def focus_search(self):
        """Become visible and give focus to the search entry
        """
        self.reveal()
        self.show_main_view()
        self.search_grab_focus()

    def switch_to_editing_mode(self, switch):
        # Toggle sensitivity of volume-toolbar buttons.
        self._volumes_toolbar.set_volume_buttons_sensitive(not switch,
                                                           get_mount_point())

        # (re)-switch, only if not already.
        if (switch) and (not self._editing_mode):
            self._editing_mode = True
            self.show_main_view()
        elif (not switch) and (self._editing_mode):
            self._editing_mode = False
            self.show_main_view()

    def get_list_view(self):
        return self._list_view

    def setup_handlers_for_alert_actions(self):
        self._error_alert.connect('response',
                                   self.__check_for_alert_action)
        self._confirmation_alert.connect('response',
                                   self.__check_for_alert_action)

    def __check_for_alert_action(self, alert, response_id):
        self.hide_alert()
        if self._callback is not None:
            if response_id == gtk.RESPONSE_OK:
                gobject.idle_add(self._callback, self._data, True)

    def update_title_and_message(self, alert, title, message):
        alert.props.title = title
        alert.props.msg = message

    def update_alert(self, alert):
        if self._current_alert is None:
            self.add_alert(alert)
        elif self._current_alert != alert:
            self.remove_alert(self._current_alert)
            self.add_alert(alert)

        self._current_alert = alert
        self._current_alert.show()

    def hide_alert(self):
        if self._current_alert is not None:
            self._current_alert.hide()

    def update_info_alert(self, title, message, callback, data):
        self.update_title_and_message(self._alert, title, message)
        self.update_alert(self._alert)
        if callback is not None:
            gobject.idle_add(callback, data)

    def update_error_alert(self, title, message, callback, data):
        self.update_title_and_message(self._error_alert, title,
                                       message)
        self._callback = callback
        self._data = data
        self.update_alert(self._error_alert)

    def update_confirmation_alert(self, title, message, callback,
                                  data):
        self.update_title_and_message(self._confirmation_alert, title,
                                       message)
        self._callback = callback
        self._data = data
        self.update_alert(self._confirmation_alert)

    def get_metadata_list(self, selected_state):
        metadata_list = []

        list_view_model = self.get_list_view().get_model()
        for index in range(0, len(list_view_model)):
            metadata = list_view_model.get_metadata(index)
            metadata_selected = \
                    list_view_model.get_selected_value(metadata['uid'])

            if ( (selected_state and metadata_selected) or \
                    ((not selected_state) and (not metadata_selected)) ):
                metadata_list.append(metadata)

        return metadata_list

    def is_editing_mode_present(self):
        return self._editing_mode

    def get_volumes_toolbar(self):
        return self._volumes_toolbar


def get_journal():
    global _journal
    if _journal is None:
        _journal = JournalActivity()
        _journal.show()
    return _journal


def start():
    get_journal()


def set_mount_point(mount_point):
    global _mount_point
    _mount_point = mount_point

def get_mount_point():
    return _mount_point