Ticket #1109: 0001-some-PEP8-compliance-fixes.patch

File 0001-some-PEP8-compliance-fixes.patch, 129.0 KB (added by sascha_silbe, 12 years ago)

PEP8 compliance fixes for some of the files in sugar-toolkit

  • src/sugar/activity/__init__.py

    From 86033efa5ce3bff304bffee16de1f745e935bc11 Mon Sep 17 00:00:00 2001
    From: Sascha Silbe <sascha@silbe.org>
    Date: Wed, 29 Jul 2009 19:00:54 +0200
    Subject: [PATCH] some PEP8 compliance fixes
    
    ---
     src/sugar/activity/__init__.py         |   20 ++--
     src/sugar/activity/activity.py         |  256 +++++++++++++++++---------------
     src/sugar/activity/activityfactory.py  |   28 +++-
     src/sugar/activity/activityhandle.py   |   37 +++---
     src/sugar/activity/activityservice.py  |   12 +-
     src/sugar/activity/bundlebuilder.py    |   22 ++--
     src/sugar/activity/main.py             |   12 +-
     src/sugar/activity/namingalert.py      |   47 ++++---
     src/sugar/bundle/activitybundle.py     |   62 ++++----
     src/sugar/bundle/bundle.py             |    6 +-
     src/sugar/bundle/contentbundle.py      |   13 +-
     src/sugar/datastore/datastore.py       |   47 ++++---
     src/sugar/datastore/dbus_helpers.py    |   17 ++-
     src/sugar/env.py                       |   20 +--
     src/sugar/graphics/alert.py            |   38 +++---
     src/sugar/graphics/animator.py         |    2 +-
     src/sugar/graphics/canvastextview.py   |    4 +-
     src/sugar/graphics/colorbutton.py      |   28 ++--
     src/sugar/graphics/combobox.py         |    4 +-
     src/sugar/graphics/icon.py             |   35 +++--
     src/sugar/graphics/notebook.py         |   16 +-
     src/sugar/graphics/objectchooser.py    |    5 +-
     src/sugar/graphics/palette.py          |   74 ++++++---
     src/sugar/graphics/palettegroup.py     |    2 +-
     src/sugar/graphics/radiotoolbutton.py  |    2 +-
     src/sugar/graphics/roundbox.py         |    4 +-
     src/sugar/graphics/toggletoolbutton.py |    7 +-
     src/sugar/graphics/toolbox.py          |   12 +-
     src/sugar/graphics/toolbutton.py       |    4 +-
     src/sugar/graphics/tray.py             |    4 +-
     src/sugar/graphics/window.py           |   36 +++--
     src/sugar/network.py                   |    8 +-
     src/sugar/presence/__init__.py         |    2 +-
     src/sugar/presence/activity.py         |   28 ++--
     src/sugar/presence/buddy.py            |   58 ++++----
     src/sugar/presence/presenceservice.py  |   86 ++++++------
     src/sugar/profile.py                   |   29 +++--
     src/sugar/session.py                   |    4 +
     src/sugar/util.py                      |   65 ++++++---
     src/sugar/wm.py                        |    6 +-
     40 files changed, 662 insertions(+), 500 deletions(-)
    
    diff --git a/src/sugar/activity/__init__.py b/src/sugar/activity/__init__.py
    index 8d3ef2b..b69646c 100644
    a b  
    1818"""Activity implementation code for Sugar-based activities
    1919
    2020Each activity within the OLPC environment must provide two
    21 dbus services.  The first, patterned after the 
     21dbus services.  The first, patterned after the
    2222
    2323    sugar.activity.activityfactory.ActivityFactory
    2424
    25 class is responsible for providing a "create" method which 
    26 takes a small dictionary with values corresponding to a 
     25class is responsible for providing a "create" method which
     26takes a small dictionary with values corresponding to a
    2727
    2828    sugar.activity.activityhandle.ActivityHandle
    2929
    Each activity so registered is described by a 
    3333
    3434    sugar.activity.bundle.Bundle
    3535
    36 instance, which parses a specially formatted activity.info 
    37 file (stored in the activity directory's ./activity 
    38 subdirectory).  The 
     36instance, which parses a specially formatted activity.info
     37file (stored in the activity directory's ./activity
     38subdirectory).  The
    3939
    4040    sugar.activity.bundlebuilder
    4141
    42 module provides facilities for the standard setup.py module 
    43 which produces and registers bundles from activity source 
     42module provides facilities for the standard setup.py module
     43which produces and registers bundles from activity source
    4444directories.
    4545
    4646Once instantiated by the ActivityFactory's create method,
    47 each activity must provide an introspection API patterned 
     47each activity must provide an introspection API patterned
    4848after the
    4949
    5050    sugar.activity.activityservice.ActivityService
    5151
    52 class.  This class allows for querying the ID of the root 
     52class.  This class allows for querying the ID of the root
    5353window, requesting sharing across the network, and basic
    5454"what type of application are you" queries.
    5555"""
  • src/sugar/activity/activity.py

    diff --git a/src/sugar/activity/activity.py b/src/sugar/activity/activity.py
    index 9809928..f576bc2 100644
    a b  
    11"""Base class for activities written in Python
    22
    3 This is currently the only definitive reference for what an 
     3This is currently the only definitive reference for what an
    44activity must do to participate in the Sugar desktop.
    55
    66   A Basic Activity
    The convention is to call it ActivitynameActivity, but this is not required as 
    1010the activity.info file associated with your activity will tell the sugar-shell
    1111which class to start.
    1212
    13 For example the most minimal Activity:
     13For example the most minimal Activity:
     14
    1415
    15  
    1616   from sugar.activity import activity
    17    
     17
    1818   class ReadActivity(activity.Activity):
    1919        pass
    2020
    import dbus 
    6161import dbus.service
    6262import cjson
    6363
    64 from sugar import util       
     64from sugar import util
    6565from sugar.presence import presenceservice
    6666from sugar.activity.activityservice import ActivityService
    6767from sugar.activity.namingalert import NamingAlert
    from sugar.datastore import datastore 
    7777from sugar.session import XSMPClient
    7878from sugar import wm
    7979
     80
    8081_ = lambda msg: gettext.dgettext('sugar-toolkit', msg)
    8182
    8283SCOPE_PRIVATE = "private"
    J_DBUS_SERVICE = 'org.laptop.Journal' 
    8788J_DBUS_PATH = '/org/laptop/Journal'
    8889J_DBUS_INTERFACE = 'org.laptop.Journal'
    8990
     91
    9092class ActivityToolbar(gtk.Toolbar):
    91     """The Activity toolbar with the Journal entry title, sharing,
    92        Keep and Stop buttons
    93    
     93    """
     94    The Activity toolbar with the Journal entry title, sharing, Keep
     95    and Stop buttons
     96
    9497    All activities should have this toolbar. It is easiest to add it to your
    9598    Activity by using the ActivityToolbox.
    9699    """
     100
    97101    def __init__(self, activity):
    98102        gtk.Toolbar.__init__(self)
    99103
    class ActivityToolbar(gtk.Toolbar): 
    163167            self.share.combo.set_active(0)
    164168
    165169        self._updating_share = False
    166    
     170
    167171    def __share_changed_cb(self, combo):
    168172        if self._updating_share:
    169173            return
    class ActivityToolbar(gtk.Toolbar): 
    218222    def __max_participants_changed_cb(self, activity, pspec):
    219223        self._update_share()
    220224
     225
    221226class EditToolbar(gtk.Toolbar):
    222227    """Provides the standard edit toolbar for Activities.
    223  
     228
    224229    Members:
    225230        undo  -- the undo button
    226231        redo  -- the redo button
    227232        copy  -- the copy button
    228233        paste -- the paste button
    229234        separator -- A separator between undo/redo and copy/paste
    230    
     235
    231236    This class only provides the 'edit' buttons in a standard layout,
    232237    your activity will need to either hide buttons which make no sense for your
    233238    Activity, or you need to connect the button events to your own callbacks:
    234    
     239
    235240        ## Example from Read.activity:
    236241        # Create the edit toolbar:
    237242        self._edit_toolbar = EditToolbar(self._view)
    class EditToolbar(gtk.Toolbar): 
    240245        self._edit_toolbar.redo.props.visible = False
    241246        # Hide the separator too:
    242247        self._edit_toolbar.separator.props.visible = False
    243        
     248
    244249        # As long as nothing is selected, copy needs to be insensitive:
    245250        self._edit_toolbar.copy.set_sensitive(False)
    246251        # When the user clicks the button, call _edit_toolbar_copy_cb()
    247252        self._edit_toolbar.copy.connect('clicked', self._edit_toolbar_copy_cb)
    248        
     253
    249254        # Add the edit toolbar:
    250255        toolbox.add_toolbar(_('Edit'), self._edit_toolbar)
    251256        # And make it visible:
    252257        self._edit_toolbar.show()
    253258    """
     259
    254260    def __init__(self):
    255261        gtk.Toolbar.__init__(self)
    256262
    class EditToolbar(gtk.Toolbar): 
    279285        self.insert(self.paste, -1)
    280286        self.paste.show()
    281287
     288
    282289class ActivityToolbox(Toolbox):
    283290    """Creates the Toolbox for the Activity
    284    
     291
    285292    By default, the toolbox contains only the ActivityToolbar. After creating
    286293    the toolbox, you can add your activity specific toolbars, for example the
    287294    EditToolbar.
    288    
     295
    289296    To add the ActivityToolbox to your Activity in MyActivity.__init__() do:
    290    
    291         # Create the Toolbar with the ActivityToolbar: 
     297
     298        # Create the Toolbar with the ActivityToolbar:
    292299        toolbox = activity.ActivityToolbox(self)
    293300        ... your code, inserting all other toolbars you need, like EditToolbar
    294        
     301
    295302        # Add the toolbox to the activity frame:
    296303        self.set_toolbox(toolbox)
    297304        # And make it visible:
    298305        toolbox.show()
    299306    """
     307
    300308    def __init__(self, activity):
    301309        Toolbox.__init__(self)
    302        
     310
    303311        self._activity_toolbar = ActivityToolbar(activity)
    304312        self.add_toolbar(_('Activity'), self._activity_toolbar)
    305313        self._activity_toolbar.show()
    class ActivityToolbox(Toolbox): 
    307315    def get_activity_toolbar(self):
    308316        return self._activity_toolbar
    309317
     318
    310319class _ActivitySession(gobject.GObject):
     320
    311321    __gsignals__ = {
    312322        'quit-requested': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ([])),
    313323        'quit':           (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ([]))
    class _ActivitySession(gobject.GObject): 
    317327        gobject.GObject.__init__(self)
    318328
    319329        self._xsmp_client = XSMPClient()
    320         self._xsmp_client.connect('quit-requested', self.__sm_quit_requested_cb)
     330        self._xsmp_client.connect('quit-requested',
     331            self.__sm_quit_requested_cb)
    321332        self._xsmp_client.connect('quit', self.__sm_quit_cb)
    322333        self._xsmp_client.startup()
    323334
    class _ActivitySession(gobject.GObject): 
    354365    def __sm_quit_cb(self, client):
    355366        self.emit('quit')
    356367
     368
    357369class Activity(Window, gtk.Container):
    358370    """This is the base Activity class that all other Activities derive from.
    359371       This is where your activity starts.
    360    
     372
    361373    To get a working Activity:
    362374        0. Derive your Activity from this class:
    363375                class MyActivity(activity.Activity):
    364376                    ...
    365                    
     377
    366378        1. implement an __init__() method for your Activity class.
    367        
     379
    368380           Use your init method to create your own ActivityToolbar which will
    369            contain some standard buttons: 
     381           contain some standard buttons:
    370382                toolbox = activity.ActivityToolbox(self)
    371            
     383
    372384           Add extra Toolbars to your toolbox.
    373            
     385
    374386           You should setup Activity sharing here too.
    375            
     387
    376388           Finaly, your Activity may need some resources which you can claim
    377389           here too.
    378            
     390
    379391           The __init__() method is also used to make the distinction between
    380            being resumed from the Journal, or starting with a blank document. 
    381            
     392           being resumed from the Journal, or starting with a blank document.
     393
    382394        2. Implement read_file() and write_file()
    383            Most activities revolve around creating and storing Journal entries.
    384            For example, Write: You create a document, it is saved to the Journal
    385            and then later you resume working on the document.
    386            
     395           Most activities revolve around creating and storing Journal
     396           entries. For example, Write: You create a document, it is saved to
     397           the Journal and then later you resume working on the document.
     398
    387399           read_file() and write_file() will be called by sugar to tell your
    388            Activity that it should load or save the document the user is working
    389            on.
    390            
     400           Activity that it should load or save the document the user is
     401           working on.
     402
    391403        3. Implement our Activity Toolbars.
    392            The Toolbars are added to your Activity in step 1 (the toolbox), but
    393            you need to implement them somewhere. Now is a good time.
    394            
    395            There are a number of standard Toolbars. The most basic one, the one
    396            your almost absolutely MUST have is the ActivityToolbar. Without
    397            this, you're not really making a proper Sugar Activity (which may be
    398            okay, but you should really stop and think about why not!) You do
    399            this with the ActivityToolbox(self) call in step 1.
    400            
    401            Usually, you will also need the standard EditToolbar. This is the one
    402            which has the standard copy and paste buttons. You need to derive
    403            your own EditToolbar class from sugar.EditToolbar:
     404           The Toolbars are added to your Activity in step 1 (the toolbox),
     405           but you need to implement them somewhere. Now is a good time.
     406
     407           There are a number of standard Toolbars. The most basic one, the
     408           one your almost absolutely MUST have is the ActivityToolbar.
     409           Without this, you're not really making a proper Sugar Activity
     410           (which may be okay, but you should really stop and think about why
     411           not!) You do this with the ActivityToolbox(self) call in step 1.
     412
     413           Usually, you will also need the standard EditToolbar. This is the
     414           one which has the standard copy and paste buttons. You need to
     415           derive your own EditToolbar class from sugar.EditToolbar:
    404416                class EditToolbar(activity.EditToolbar):
    405417                    ...
    406                    
     418
    407419           See EditToolbar for the methods you should implement in your class.
    408            
     420
    409421           Finaly, your Activity will very likely need some activity specific
    410422           buttons and options you can create your own toolbars by deriving a
    411423           class from gtk.Toolbar:
    412424                class MySpecialToolbar(gtk.Toolbar):
    413425                    ...
    414                    
     426
    415427        4. Use your creativity. Make your Activity something special and share
    416428           it with your friends!
    417            
     429
    418430    Read through the methods of the Activity class below, to learn more about
    419     how to make an Activity work. 
    420    
     431    how to make an Activity work.
     432
    421433    Hint: A good and simple Activity to learn from is the Read activity. To
    422     create your own activity, you may want to copy it and use it as a template.
     434    create your own activity, you may want to copy it and use it as a
     435    template.
    423436    """
     437
    424438    __gtype_name__ = 'SugarActivity'
    425439
    426440    __gsignals__ = {
    class Activity(Window, gtk.Container): 
    429443    }
    430444
    431445    def __init__(self, handle, create_jobject=True):
    432         """Initialise the Activity 
    433        
     446        """Initialise the Activity
     447
    434448        handle -- sugar.activity.activityhandle.ActivityHandle
    435             instance providing the activity id and access to the 
    436             presence service which *may* provide sharing for this 
     449            instance providing the activity id and access to the
     450            presence service which *may* provide sharing for this
    437451            application
    438452
    439453        create_jobject -- boolean
    440454            define if it should create a journal object if we are
    441455            not resuming
    442456
    443         Side effects: 
    444        
    445             Sets the gdk screen DPI setting (resolution) to the 
     457        Side effects:
     458
     459            Sets the gdk screen DPI setting (resolution) to the
    446460            Sugar screen resolution.
    447            
     461
    448462            Connects our "destroy" message to our _destroy_cb
    449463            method.
    450        
     464
    451465            Creates a base gtk.Window within this window.
    452            
     466
    453467            Creates an ActivityService (self._bus) servicing
    454468            this application.
    455        
    456         Usage:       
     469
     470        Usage:
    457471            If your Activity implements __init__(), it should call
    458472            the base class __init()__ before doing Activity specific things.
    459            
     473
    460474        """
    461475        Window.__init__(self)
    462476
    class Activity(Window, gtk.Container): 
    501515        share_scope = SCOPE_PRIVATE
    502516
    503517        if handle.object_id:
    504             self._jobject = datastore.get(handle.object_id)           
     518            self._jobject = datastore.get(handle.object_id)
    505519            self.set_title(self._jobject.metadata['title'])
    506                
    507             if self._jobject.metadata.has_key('share-scope'):
     520
     521            if 'share-scope' in self._jobject.metadata:
    508522                share_scope = self._jobject.metadata['share-scope']
    509523
    510524        # handle activity share/join
    class Activity(Window, gtk.Container): 
    526540            else:
    527541                self.__joined_cb(self.shared_activity, True, None)
    528542        elif share_scope != SCOPE_PRIVATE:
    529             logging.debug("*** Act %s no existing mesh instance, but used to " \
    530                           "be shared, will share" % self._activity_id)
     543            logging.debug("*** Act %s no existing mesh instance, but used " \
     544                          "to be shared, will share" % self._activity_id)
    531545            # no existing mesh instance, but activity used to be shared, so
    532546            # restart the share
    533547            if share_scope == SCOPE_INVITE_ONLY:
    class Activity(Window, gtk.Container): 
    585599
    586600    def get_id(self):
    587601        """Returns the activity id of the current instance of your activity.
    588        
     602
    589603        The activity id is sort-of-like the unix process id (PID). However,
    590604        unlike PIDs it is only different for each new instance (with
    591605        create_jobject = True set) and stays the same everytime a user
    592         resumes an activity. This is also the identity of your Activity to other
    593         XOs for use when sharing.
     606        resumes an activity. This is also the identity of your Activity to
     607        other XOs for use when sharing.
    594608        """
    595609        return self._activity_id
    596610
    class Activity(Window, gtk.Container): 
    600614
    601615    def set_canvas(self, canvas):
    602616        """Sets the 'work area' of your activity with the canvas of your choice.
    603        
     617
    604618        One commonly used canvas is gtk.ScrolledWindow
    605619        """
    606620        Window.set_canvas(self, canvas)
    class Activity(Window, gtk.Container): 
    633647        logging.debug("Error creating activity datastore object: %s" % err)
    634648
    635649    def get_activity_root(self):
    636         """ FIXME: Deprecated. This part of the API has been moved 
     650        """ FIXME: Deprecated. This part of the API has been moved
    637651        out of this class to the module itself
    638652
    639653        Returns a path for saving Activity specific preferences, etc.
    640        
     654
    641655        Returns a path to the location in the filesystem where the activity can
    642656        store activity related data that doesn't pertain to the current
    643657        execution of the activity and thus cannot go into the DataStore.
    644        
     658
    645659        Currently, this will return something like
    646660        ~/.sugar/default/MyActivityName/
    647        
     661
    648662        Activities should ONLY save settings, user preferences and other data
    649         which isn't specific to a journal item here. If (meta-)data is in anyway
    650         specific to a journal entry, it MUST be stored in the DataStore.       
     663        which isn't specific to a journal item here. If (meta-)data is in
     664        anyway specific to a journal entry, it MUST be stored in the
     665        DataStore.
    651666        """
    652         if os.environ.has_key('SUGAR_ACTIVITY_ROOT') and \
    653            os.environ['SUGAR_ACTIVITY_ROOT']:
    654             return os.environ['SUGAR_ACTIVITY_ROOT']
    655         else:
    656             return '/'
     667        return os.environ.get('SUGAR_ACTIVITY_ROOT') or '/'
    657668
    658669    def read_file(self, file_path):
    659670        """
    660671        Subclasses implement this method if they support resuming objects from
    661672        the journal. 'file_path' is the file to read from.
    662        
     673
    663674        You should immediately open the file from the file_path, because the
    664675        file_name will be deleted immediately after returning from read_file().
    665676        Once the file has been opened, you do not have to read it immediately:
    666677        After you have opened it, the file will only be really gone when you
    667678        close it.
    668        
     679
    669680        Although not required, this is also a good time to read all meta-data:
    670         the file itself cannot be changed externally, but the title, description
    671         and other metadata['tags'] may change. So if it is important for you to
    672         notice changes, this is the time to record the originals.       
     681        the file itself cannot be changed externally, but the title,
     682        description and other metadata['tags'] may change. So if it is
     683        important for you to notice changes, this is the time to record the
     684        originals.
    673685        """
    674686        raise NotImplementedError
    675687
    class Activity(Window, gtk.Container): 
    677689        """
    678690        Subclasses implement this method if they support saving data to objects
    679691        in the journal. 'file_path' is the file to write to.
    680        
     692
    681693        If the user did make changes, you should create the file_path and save
    682694        all document data to it.
    683        
     695
    684696        Additionally, you should also write any metadata needed to resume your
    685         activity. For example, the Read activity saves the current page and zoom
    686         level, so it can display the page.
    687        
     697        activity. For example, the Read activity saves the current page and
     698        zoom level, so it can display the page.
     699
    688700        Note: Currently, the file_path *WILL* be different from the one you
    689         received in file_read(). Even if you kept the file_path from file_read()
    690         open until now, you must still write the entire file to this file_path.     
     701        received in file_read(). Even if you kept the file_path from
     702        file_read() open until now, you must still write the entire file to
     703        this file_path.
    691704        """
    692705        raise NotImplementedError
    693706
    class Activity(Window, gtk.Container): 
    739752                                     gtk.gdk.INTERP_BILINEAR)
    740753
    741754        preview_data = []
     755
    742756        def save_func(buf, data):
    743757            data.append(buf)
    744758
    class Activity(Window, gtk.Container): 
    760774
    761775    def save(self):
    762776        """Request that the activity is saved to the Journal.
    763        
     777
    764778        This method is called by the close() method below. In general,
    765779        activities should not override this method. This method is part of the
    766780        public API of an Acivity, and should behave in standard ways. Use your
    767         own implementation of write_file() to save your Activity specific data.       
     781        own implementation of write_file() to save your Activity specific data.
    768782        """
    769783
    770784        if self._jobject is None:
    class Activity(Window, gtk.Container): 
    811825    def copy(self):
    812826        """Request that the activity 'Keep in Journal' the current state
    813827           of the activity.
    814        
     828
    815829        Activities should not override this method. Instead, like save() do any
    816830        copy work that needs to be done in write_file()
    817831        """
    class Activity(Window, gtk.Container): 
    877891
    878892    def _send_invites(self):
    879893        while self._invites_queue:
    880             buddy_key = self._invites_queue.pop()             
     894            buddy_key = self._invites_queue.pop()
    881895            buddy = self._pservice.get_buddy(buddy_key)
    882896            if buddy:
    883897                self.shared_activity.invite(
    class Activity(Window, gtk.Container): 
    887901
    888902    def invite(self, buddy_key):
    889903        """Invite a buddy to join this Activity.
    890        
     904
    891905        Side Effects:
    892906            Calls self.share(True) to privately share the activity if it wasn't
    893             shared before.           
     907            shared before.
    894908        """
    895909        self._invites_queue.append(buddy_key)
    896910
    class Activity(Window, gtk.Container): 
    902916
    903917    def share(self, private=False):
    904918        """Request that the activity be shared on the network.
    905        
     919
    906920        private -- bool: True to share by invitation only,
    907921            False to advertise as shared to everyone.
    908922
    class Activity(Window, gtk.Container): 
    915929        verb = private and 'private' or 'public'
    916930        logging.debug('Requesting %s share of activity %s.' %
    917931                      (verb, self._activity_id))
    918         self._share_id = self._pservice.connect("activity-shared", 
     932        self._share_id = self._pservice.connect("activity-shared",
    919933                                                self.__share_cb)
    920934        self._pservice.share_activity(self, private=private)
    921935
    class Activity(Window, gtk.Container): 
    973987
    974988    def close(self, skip_save=False):
    975989        """Request that the activity be stopped and saved to the Journal
    976        
     990
    977991        Activities should not override this method, but should implement
    978992        write_file() to do any state saving instead. If the application wants
    979993        to control wether it can close, it should override can_close().
    class Activity(Window, gtk.Container): 
    10041018
    10051019    def get_metadata(self):
    10061020        """Returns the jobject metadata or None if there is no jobject.
    1007        
    1008         Activities can set metadata in write_file() using:                   
     1021
     1022        Activities can set metadata in write_file() using:
    10091023            self.metadata['MyKey'] = "Something"
    1010            
    1011         and retrieve metadata in read_file() using:       
     1024
     1025        and retrieve metadata in read_file() using:
    10121026            self.metadata.get('MyKey', 'aDefaultValue')
    1013                
     1027
    10141028        Note: Make sure your activity works properly if one or more of the
    10151029        metadata items is missing. Never assume they will all be present.
    10161030        """
    class Activity(Window, gtk.Container): 
    10301044    # DEPRECATED
    10311045    _shared_activity = property(lambda self: self.shared_activity, None)
    10321046
    1033 _session = None
    10341047
     1048_session = None
    10351049def _get_session():
    10361050    global _session
    10371051
    def _get_session(): 
    10401054
    10411055    return _session
    10421056
     1057
    10431058def get_bundle_name():
    10441059    """Return the bundle name for the current process' bundle"""
    10451060    return os.environ['SUGAR_BUNDLE_NAME']
    1046    
     1061
     1062
    10471063def get_bundle_path():
    10481064    """Return the bundle path for the current process' bundle"""
    10491065    return os.environ['SUGAR_BUNDLE_PATH']
    10501066
     1067
    10511068def get_activity_root():
    10521069    """Returns a path for saving Activity specific preferences, etc."""
    1053     if os.environ.has_key('SUGAR_ACTIVITY_ROOT') and \
     1070    if 'SUGAR_ACTIVITY_ROOT' in os.environ and \
    10541071            os.environ['SUGAR_ACTIVITY_ROOT']:
    10551072        return os.environ['SUGAR_ACTIVITY_ROOT']
    10561073    else:
    10571074        raise RuntimeError("No SUGAR_ACTIVITY_ROOT set.")
    10581075
     1076
    10591077def show_object_in_journal(object_id):
    10601078    bus = dbus.SessionBus()
    10611079    obj = bus.get_object(J_DBUS_SERVICE, J_DBUS_PATH)
  • src/sugar/activity/activityfactory.py

    diff --git a/src/sugar/activity/activityfactory.py b/src/sugar/activity/activityfactory.py
    index e218a7c..fe96ee1 100644
    a b _RAINBOW_SERVICE_NAME = "org.laptop.security.Rainbow" 
    4949_RAINBOW_ACTIVITY_FACTORY_PATH = "/"
    5050_RAINBOW_ACTIVITY_FACTORY_INTERFACE = "org.laptop.security.Rainbow"
    5151
    52 # helper method to close all filedescriptors
    53 # borrowed from subprocess.py
     52
    5453try:
    5554    MAXFD = os.sysconf("SC_OPEN_MAX")
    5655except ValueError:
    5756    MAXFD = 256
     57
     58
    5859def _close_fds():
     60    # helper method to close all filedescriptors
     61    # borrowed from subprocess.py
    5962    for i in xrange(3, MAXFD):
    6063        try:
    6164            os.close(i)
    def _close_fds(): 
    6366        except Exception:
    6467            pass
    6568
     69
    6670def create_activity_id():
    6771    """Generate a new, unique ID for this activity"""
    6872    pservice = presenceservice.get_instance()
    def create_activity_id(): 
    8589            return act_id
    8690    raise RuntimeError("Cannot generate unique activity id.")
    8791
     92
    8893def get_environment(activity):
    8994    environ = os.environ.copy()
    9095
    def get_environment(activity): 
    107112        os.mkdir(tmp_dir)
    108113
    109114    environ['SUGAR_BUNDLE_PATH'] = activity.get_path()
    110     environ['SUGAR_BUNDLE_ID']   = activity.get_bundle_id()
     115    environ['SUGAR_BUNDLE_ID'] = activity.get_bundle_id()
    111116    environ['SUGAR_ACTIVITY_ROOT'] = activity_root
    112117    environ['PATH'] = bin_path + ':' + environ['PATH']
    113118    #environ['RAINBOW_STRACE_LOG'] = '1'
    114119
    115120    if activity.get_path().startswith(env.get_user_activities_path()):
    116         environ['SUGAR_LOCALEDIR'] = os.path.join(activity.get_path(), 'locale')
     121        environ['SUGAR_LOCALEDIR'] = os.path.join(activity.get_path(),
     122            'locale')
    117123
    118124    if activity.get_bundle_id() in [ 'org.laptop.WebActivity',
    119125                                     'org.laptop.GmailActivity',
    def get_environment(activity): 
    123129
    124130    return environ
    125131
     132
    126133def get_command(activity, activity_id=None, object_id=None, uri=None):
    127134    if not activity_id:
    128135        activity_id = create_activity_id()
    def get_command(activity, activity_id=None, object_id=None, uri=None): 
    148155
    149156    return command
    150157
     158
    151159def open_log_file(activity):
    152160    i = 1
    153161    while True:
    def open_log_file(activity): 
    162170                i += 1
    163171            elif e.errno == ENOSPC:
    164172                # not the end of the world; let's try to keep going.
    165                 return ('/dev/null', open('/dev/null','w'))
     173                return ('/dev/null', open('/dev/null', 'w'))
    166174            else:
    167175                raise e
    168176
     177
    169178class ActivityCreationHandler(gobject.GObject):
    170179    """Sugar-side activity creation interface
    171180
    class ActivityCreationHandler(gobject.GObject): 
    212221                                   'org.laptop.Log',
    213222                                   'org.laptop.Analyze'
    214223                                 ]:
    215             self._use_rainbow = False                   
    216    
     224            self._use_rainbow = False
     225
    217226        bus = dbus.SessionBus()
    218227
    219228        bus_object = bus.get_object(_SHELL_SERVICE, _SHELL_PATH)
    class ActivityCreationHandler(gobject.GObject): 
    223232           handle.object_id is None:
    224233            datastore = dbus.Interface(
    225234                    bus.get_object(_DS_SERVICE, _DS_PATH), _DS_INTERFACE)
    226             datastore.find({ 'activity_id': self._handle.activity_id }, [],
     235            datastore.find({'activity_id': self._handle.activity_id}, [],
    227236                           reply_handler=self._find_object_reply_handler,
    228237                           error_handler=self._find_object_error_handler,
    229238                           byte_arrays=True)
    class ActivityCreationHandler(gobject.GObject): 
    326335        logging.error("Datastore find failed %s" % err)
    327336        self._launch_activity()
    328337
     338
    329339def create(bundle, activity_handle=None):
    330340    """Create a new activity from its name."""
    331341    if not activity_handle:
    332342        activity_handle = ActivityHandle()
    333343    return ActivityCreationHandler(bundle, activity_handle)
    334344
     345
    335346def create_with_uri(bundle, uri):
    336347    """Create a new activity and pass the uri as handle."""
    337348    activity_handle = ActivityHandle(uri=uri)
    338349    return ActivityCreationHandler(bundle, activity_handle)
    339350
     351
    340352def create_with_object_id(bundle, object_id):
    341353    """Create a new activity and pass the object id as handle."""
    342354    activity_handle = ActivityHandle(object_id=object_id)
  • src/sugar/activity/activityhandle.py

    diff --git a/src/sugar/activity/activityhandle.py b/src/sugar/activity/activityhandle.py
    index f255fd5..6c1fe6e 100644
    a b  
    1919STABLE.
    2020"""
    2121
     22
    2223class ActivityHandle(object):
    2324    """Data structure storing simple activity metadata"""
    24     def __init__(
    25         self, activity_id=None, object_id=None, uri=None
    26     ):
     25
     26    def __init__(self, activity_id=None, object_id=None, uri=None):
    2727        """Initialise the handle from activity_id
    28        
     28
    2929        activity_id -- unique id for the activity to be
    3030            created
    31         object_id -- identity of the journal object 
    32             associated with the activity. It was used by 
    33             the journal prototype implementation, might 
    34             change when we do the real one. 
    35            
    36             When you resume an activity from the journal 
    37             the object_id will be passed in. It's optional 
    38             since new activities does not have an 
     31        object_id -- identity of the journal object
     32            associated with the activity. It was used by
     33            the journal prototype implementation, might
     34            change when we do the real one.
     35
     36            When you resume an activity from the journal
     37            the object_id will be passed in. It's optional
     38            since new activities does not have an
    3939            associated object (yet).
    40            
     40
    4141            XXX Not clear how this relates to the activity
    4242            id yet, i.e. not sure we really need both. TBF
    43         uri -- URI associated with the activity. Used when 
    44             opening an external file or resource in the 
    45             activity, rather than a journal object 
    46             (downloads stored on the file system for 
     43        uri -- URI associated with the activity. Used when
     44            opening an external file or resource in the
     45            activity, rather than a journal object
     46            (downloads stored on the file system for
    4747            example or web pages)
    4848        """
    4949        self.activity_id = activity_id
    class ActivityHandle(object): 
    5252
    5353    def get_dict(self):
    5454        """Retrieve our settings as a dictionary"""
    55         result = { 'activity_id' : self.activity_id }
     55        result = {'activity_id': self.activity_id}
    5656        if self.object_id:
    5757            result['object_id'] = self.object_id
    5858        if self.uri:
    class ActivityHandle(object): 
    6060
    6161        return result
    6262
     63
    6364def create_from_dict(handle_dict):
    6465    """Create a handle from a dictionary of parameters"""
    6566    result = ActivityHandle(
  • src/sugar/activity/activityservice.py

    diff --git a/src/sugar/activity/activityservice.py b/src/sugar/activity/activityservice.py
    index ff806f3..0d6cf03 100644
    a b _ACTIVITY_INTERFACE = "org.laptop.Activity" 
    3030
    3131class ActivityService(dbus.service.Object):
    3232    """Base dbus service object that each Activity uses to export dbus methods.
    33    
     33
    3434    The dbus service is separate from the actual Activity object so that we can
    3535    tightly control what stuff passes through the dbus python bindings."""
    3636
    3737    def __init__(self, activity):
    3838        """Initialise the service for the given activity
    39        
     39
    4040        activity -- sugar.activity.activity.Activity instance
    41        
     41
    4242        Creates dbus services that use the instance's activity_id
    43         as discriminants among all active services 
    44         of this type.  That is, the services are all available 
     43        as discriminants among all active services
     44        of this type.  That is, the services are all available
    4545        as names/paths derived from the instance's activity_id.
    46        
     46
    4747        The various methods exposed on dbus are just forwarded
    4848        to the client Activity object's equally-named methods.
    4949        """
  • src/sugar/activity/bundlebuilder.py

    diff --git a/src/sugar/activity/bundlebuilder.py b/src/sugar/activity/bundlebuilder.py
    index 555fe98..b11c7d0 100644
    a b from sugar.bundle.activitybundle import ActivityBundle 
    3636
    3737IGNORE_DIRS = ['dist', '.git']
    3838IGNORE_FILES = ['.gitignore', 'MANIFEST', '*.pyc', '*~', '*.bak', 'pseudo.po']
    39        
     39
    4040def list_files(base_dir, ignore_dirs=None, ignore_files=None):
    4141    result = []
    4242
    def list_files(base_dir, ignore_dirs=None, ignore_files=None): 
    4646        if ignore_files:
    4747            for pattern in ignore_files:
    4848                files = [f for f in files if not fnmatch(f, pattern)]
    49                
     49
    5050        rel_path = root[len(base_dir) + 1:]
    5151        for f in files:
    5252            result.append(os.path.join(rel_path, f))
    class Config(object): 
    8383        self.bundle_name = reduce(lambda x, y:x+y, self.activity_name.split())
    8484        self.bundle_root_dir = self.bundle_name + '.activity'
    8585        self.tar_root_dir = '%s-%d' % (self.bundle_name, self.version)
    86            
     86
    8787        if self.dist_name:
    8888            self.xo_name = self.tar_name = self.dist_name
    8989        else:
    class Builder(object): 
    103103        if not self.config.bundle.is_dir(po_dir):
    104104            logging.warn("Missing po/ dir, cannot build_locale")
    105105            return
    106        
     106
    107107        locale_dir = os.path.join(self.config.source_dir, 'locale')
    108108
    109109        if os.path.exists(locale_dir):
    class Builder(object): 
    154154                missing_files.append(path)
    155155
    156156        return missing_files
    157        
     157
    158158    def fix_manifest(self):
    159159        self.build()
    160160
    161161        manifest = self.config.bundle.manifest
    162        
     162
    163163        for path in self.check_manifest():
    164164            manifest.append(path)
    165        
     165
    166166        f = open(os.path.join(self.config.source_dir, "MANIFEST"), "wb")
    167167        for line in manifest:
    168168            f.write(line + "\n")
    class XOPackager(Packager): 
    186186    def package(self):
    187187        bundle_zip = zipfile.ZipFile(self.package_path, 'w',
    188188                                     zipfile.ZIP_DEFLATED)
    189        
     189
    190190        missing_files = self.builder.check_manifest()
    191191        if missing_files:
    192192            logging.warn('These files are not included in the manifest ' \
    class SourcePackager(Packager): 
    207207                                         self.config.tar_name)
    208208
    209209    def get_files(self):
    210         git_ls = subprocess.Popen(['git', 'ls-files'], stdout=subprocess.PIPE, 
     210        git_ls = subprocess.Popen(['git', 'ls-files'], stdout=subprocess.PIPE,
    211211                                  cwd=self.config.source_dir)
    212212        stdout, _ = git_ls.communicate()
    213213        if git_ls.returncode :
    214214            # Fall back to filtered list
    215215            return list_files(self.config.source_dir,
    216216                              IGNORE_DIRS, IGNORE_FILES)
    217        
     217
    218218        return [path.strip() for path in stdout.strip('\n').split('\n')]
    219219
    220220    def package(self):
    def cmd_dist_xo(config, args): 
    286286    if args:
    287287        print 'Usage: %prog dist_xo'
    288288        return
    289    
     289
    290290    packager = XOPackager(Builder(config))
    291291    packager.package()
    292292
  • src/sugar/activity/main.py

    diff --git a/src/sugar/activity/main.py b/src/sugar/activity/main.py
    index 721595c..93f34e6 100644
    a b from sugar.activity import activityhandle 
    3030from sugar.bundle.activitybundle import ActivityBundle
    3131from sugar import logger
    3232
     33
    3334def create_activity_instance(constructor, handle):
    3435    activity = constructor(handle)
    3536    activity.show()
    3637
     38
    3739def get_single_process_name(bundle_id):
    3840    return bundle_id
    3941
     42
    4043def get_single_process_path(bundle_id):
    4144    return '/' + bundle_id.replace('.', '/')
    4245
     46
    4347class SingleProcess(dbus.service.Object):
     48
    4449    def __init__(self, name_service, constructor):
    4550        self.constructor = constructor
    46    
     51
    4752        bus = dbus.SessionBus()
    4853        bus_name = dbus.service.BusName(name_service, bus=bus)
    4954        object_path = get_single_process_path(name_service)
    class SingleProcess(dbus.service.Object): 
    5459        handle = activityhandle.create_from_dict(handle_dict)
    5560        create_activity_instance(self.constructor, handle)
    5661
     62
    5763def main():
    5864    parser = OptionParser()
    5965    parser.add_option("-b", "--bundle-id", dest="bundle_id",
    def main(): 
    7783
    7884    if len(args) == 0:
    7985        print 'A python class must be specified as first argument.'
    80         sys.exit(1)   
     86        sys.exit(1)
    8187
    8288    bundle_path = os.environ['SUGAR_BUNDLE_PATH']
    8389    sys.path.append(bundle_path)
    def main(): 
    102108    module_name = splitted_module[0]
    103109    class_name = splitted_module[1]
    104110
    105     module = __import__(module_name)       
     111    module = __import__(module_name)
    106112    for comp in module_name.split('.')[1:]:
    107113        module = getattr(module, comp)
    108114
  • src/sugar/activity/namingalert.py

    diff --git a/src/sugar/activity/namingalert.py b/src/sugar/activity/namingalert.py
    index 11b7688..9533108 100644
    a b from sugar.graphics.canvastextview import CanvasTextView 
    3535
    3636from sugar.bundle.activitybundle import ActivityBundle
    3737
     38
    3839_ = lambda msg: gettext.dgettext('sugar-toolkit', msg)
    3940
     41
    4042def _get_icon_name(metadata):
    4143    file_name = None
    4244
    def _get_icon_name(metadata): 
    5355
    5456    return file_name
    5557
     58
    5659class NamingToolbar(gtk.Toolbar):
    5760    """ Toolbar of the naming alert
    5861    """
     62
    5963    __gtype_name__ = 'SugarNamingToolbar'
    6064
    6165    __gsignals__ = {
    class NamingToolbar(gtk.Toolbar): 
    6367                         gobject.TYPE_NONE,
    6468                         ([]))
    6569    }
     70
    6671    def __init__(self):
    6772        gtk.Toolbar.__init__(self)
    6873
    6974        client = gconf.client_get_default()
    7075        color = XoColor(client.get_string('/desktop/sugar/user/color'))
    7176        icon = Icon()
    72         icon.set_from_icon_name('activity-journal', 
     77        icon.set_from_icon_name('activity-journal',
    7378                                gtk.ICON_SIZE_LARGE_TOOLBAR)
    7479        icon.props.xo_color = color
    7580        self._add_widget(icon)
    class NamingToolbar(gtk.Toolbar): 
    7883
    7984        self._title = gtk.Label(_('Name this entry'))
    8085        self._add_widget(self._title)
    81        
     86
    8287        self._add_separator(True)
    8388
    8489        self._keep_button = ToolButton('dialog-ok', tooltip=_('Keep'))
    class NamingToolbar(gtk.Toolbar): 
    110115    def __keep_button_clicked_cb(self, widget, data=None):
    111116        self.emit('keep-clicked')
    112117
     118
    113119class FavoriteIcon(CanvasIcon):
     120
    114121    def __init__(self, favorite):
    115122        CanvasIcon.__init__(self, icon_name='emblem-favorite',
    116123                            box_width=style.GRID_CELL_SIZE * 3 / 5,
    class FavoriteIcon(CanvasIcon): 
    149156            elif event.detail == hippo.MOTION_DETAIL_LEAVE:
    150157                icon.props.fill_color = style.COLOR_TRANSPARENT.get_svg()
    151158
     159
    152160class NamingAlert(gtk.Window):
     161
    153162    __gtype_name__ = 'SugarNamingAlert'
    154163
    155164    def __init__(self, activity, bundle_path):
    class NamingAlert(gtk.Window): 
    170179        width = gtk.gdk.screen_width() - offset * 2
    171180        height = gtk.gdk.screen_height() - offset * 2
    172181        self.set_size_request(width, height)
    173         self.set_position(gtk.WIN_POS_CENTER_ALWAYS) 
     182        self.set_position(gtk.WIN_POS_CENTER_ALWAYS)
    174183        self.set_decorated(False)
    175184        self.set_resizable(False)
    176185        self.set_modal(True)
    class NamingAlert(gtk.Window): 
    212221                                 spacing=style.DEFAULT_SPACING)
    213222        body.append(header)
    214223
    215         descriptions = hippo.CanvasBox(orientation=hippo.ORIENTATION_HORIZONTAL,
    216                                spacing=style.DEFAULT_SPACING * 3,
    217                                padding_left=style.GRID_CELL_SIZE,
    218                                padding_right=style.GRID_CELL_SIZE,
    219                                padding_top=style.DEFAULT_SPACING * 3)
     224        descriptions = hippo.CanvasBox(
     225            orientation=hippo.ORIENTATION_HORIZONTAL,
     226            spacing=style.DEFAULT_SPACING * 3,
     227            padding_left=style.GRID_CELL_SIZE,
     228            padding_right=style.GRID_CELL_SIZE,
     229            padding_top=style.DEFAULT_SPACING * 3)
    220230
    221231        body.append(descriptions, hippo.PACK_EXPAND)
    222232
    class NamingAlert(gtk.Window): 
    230240
    231241        self._favorite_icon = self._create_favorite_icon()
    232242        header.append(self._favorite_icon)
    233        
     243
    234244        entry_icon = self._create_entry_icon()
    235245        header.append(entry_icon)
    236        
     246
    237247        self._title = self._create_title()
    238248        header.append(self._title, hippo.PACK_EXPAND)
    239        
     249
    240250        if gtk.widget_get_default_direction() == gtk.TEXT_DIR_RTL:
    241251            header.reverse()
    242252
    class NamingAlert(gtk.Window): 
    251261    def _create_favorite_icon(self):
    252262        favorite_icon = FavoriteIcon(False)
    253263        return favorite_icon
    254    
     264
    255265    def _create_entry_icon(self):
    256266        bundle_id = self._activity.metadata.get('activity', '')
    257267        if not bundle_id:
    class NamingAlert(gtk.Window): 
    259269
    260270        if bundle_id == '':
    261271            file_name = _get_icon_name(self._activity.metadata)
    262         else:   
     272        else:
    263273            activity_bundle = ActivityBundle(self._bundle_path)
    264274            file_name = activity_bundle.get_icon()
    265275        entry_icon = CanvasIcon(file_name=file_name)
    266         if self._activity.metadata.has_key('icon-color') and \
    267                 self._activity.metadata['icon-color']:
    268             entry_icon.props.xo_color = XoColor( \
     276        if self._activity.metadata.get('icon-color'):
     277            entry_icon.props.xo_color = XoColor(
    269278                self._activity.metadata['icon-color'])
    270279        return entry_icon
    271    
     280
    272281    def _create_title(self):
    273282        title = CanvasEntry()
    274283        title.set_background(style.COLOR_WHITE.get_html())
    class NamingAlert(gtk.Window): 
    302311    def _create_tags(self):
    303312        vbox = hippo.CanvasBox()
    304313        vbox.props.spacing = style.DEFAULT_SPACING
    305        
     314
    306315        text = hippo.CanvasText(text=_('Tags:'),
    307316                                font_desc=style.FONT_NORMAL.get_pango_desc())
    308317        text.props.color = style.COLOR_BUTTON_GREY.get_int()
    class NamingAlert(gtk.Window): 
    313322            text.props.xalign = hippo.ALIGNMENT_START
    314323
    315324        vbox.append(text)
    316        
     325
    317326        tags = self._activity.metadata.get('tags', '')
    318327        text_view = CanvasTextView(tags, box_height=style.GRID_CELL_SIZE * 2)
    319328        vbox.append(text_view, hippo.PACK_EXPAND)
  • src/sugar/bundle/activitybundle.py

    diff --git a/src/sugar/bundle/activitybundle.py b/src/sugar/bundle/activitybundle.py
    index 7877229..a59b2b2 100644
    a b from sugar import util 
    3131from sugar.bundle.bundle import Bundle, \
    3232    MalformedBundleException, NotInstalledException
    3333
     34
    3435class ActivityBundle(Bundle):
    3536    """A Sugar activity bundle
    36    
     37
    3738    See http://wiki.laptop.org/go/Activity_bundles for details
    3839    """
    3940
    class ActivityBundle(Bundle): 
    4849        Bundle.__init__(self, path)
    4950        self.activity_class = None
    5051        self.bundle_exec = None
    51        
     52
    5253        self._name = None
    5354        self._icon = None
    5455        self._bundle_id = None
    class ActivityBundle(Bundle): 
    8384        if not f:
    8485            logging.warning("Activity directory lacks a MANIFEST file.")
    8586            return []
    86        
    87         ret = [line.strip() for line in f.readlines()] 
     87
     88        ret = [line.strip() for line in f.readlines()]
    8889        f.close()
    8990        return ret
    90        
     91
    9192    def _read_manifest(self):
    92         """return a list with the lines in MANIFEST, with invalid lines replaced
    93         by empty lines.
    94        
    95         Since absolute order carries information on file history, it should 
     93        """Return a list with the lines in MANIFEST, with invalid lines
     94        replaced by empty lines.
     95
     96        Since absolute order carries information on file history, it should
    9697        be preserved. For instance, when renaming a file, you should leave
    9798        the new name on the same line as the old one.
    9899        """
    class ActivityBundle(Bundle): 
    111112            if line in lines[0:num]:
    112113                lines[num] = ""
    113114                logging.warning("Bundle %s: duplicate entry in MANIFEST: %s"
    114                                 % (self._name,line))
     115                                % (self._name, line))
    115116                continue
    116            
     117
    117118            # Remove MANIFEST
    118119            if line == "MANIFEST":
    119120                lines[num] = ""
    120121                logging.warning("Bundle %s: MANIFEST includes itself: %s"
    121                                 % (self._name,line))
    122                
     122                                % (self._name, line))
     123
    123124            # Remove invalid files
    124125            if not self.is_file(line):
    125126                lines[num] = ""
    126127                logging.warning("Bundle %s: invalid entry in MANIFEST: %s"
    127                                 % (self._name,line))
     128                                % (self._name, line))
    128129
    129130        return lines
    130    
     131
    131132    def get_files(self, manifest = None):
    132133        files = [line for line in (manifest or self.manifest) if line]
    133134
    class ActivityBundle(Bundle): 
    135136            files.append('MANIFEST')
    136137
    137138        return files
    138      
     139
    139140    def _parse_info(self, info_file):
    140141        cp = ConfigParser()
    141142        cp.readfp(info_file)
    class ActivityBundle(Bundle): 
    170171
    171172        if cp.has_option(section, 'mime_types'):
    172173            mime_list = cp.get(section, 'mime_types').strip(';')
    173             self._mime_types = [ mime.strip() for mime in mime_list.split(';') ]
     174            self._mime_types = [mime.strip() for mime in mime_list.split(';')]
    174175
    175176        if cp.has_option(section, 'show_launcher'):
    176177            if cp.get(section, 'show_launcher') == 'no':
    class ActivityBundle(Bundle): 
    251252        """Get the activity bundle id"""
    252253        return self._bundle_id
    253254
    254     # FIXME: this should return the icon data, not a filename, so that
    255     # we don't need to create a temp file in the zip case
    256255    def get_icon(self):
    257256        """Get the activity icon name"""
     257        # FIXME: this should return the icon data, not a filename, so that
     258        # we don't need to create a temp file in the zip case
    258259        icon_path = os.path.join('activity', self._icon + '.svg')
    259260        if self._zip_file is None:
    260261            return os.path.join(self._path, icon_path)
    261262        else:
    262263            icon_data = self.get_file(icon_path).read()
    263             temp_file, temp_file_path = tempfile.mkstemp(prefix=self._icon, suffix='.svg')
     264            temp_file, temp_file_path = tempfile.mkstemp(prefix=self._icon,
     265                suffix='.svg')
    264266            os.write(temp_file, icon_data)
    265267            os.close(temp_file)
    266268            return util.TempFilePath(temp_file_path)
    class ActivityBundle(Bundle): 
    297299        self._unzip(install_dir)
    298300
    299301        install_path = os.path.join(install_dir, self._zip_root_dir)
    300        
     302
    301303        # List installed files
    302304        manifestfiles = self.get_files(self._raw_manifest())
    303         paths  = []
     305        paths = []
    304306        for root, dirs_, files in os.walk(install_path):
    305307            rel_path = root[len(install_path) + 1:]
    306308            for f in files:
    307309                paths.append(os.path.join(rel_path, f))
    308                
     310
    309311        # Check the list against the MANIFEST
    310312        for path in paths:
    311313            if path in manifestfiles:
    312314                manifestfiles.remove(path)
    313315            elif path != "MANIFEST":
    314                 logging.warning("Bundle %s: %s not in MANIFEST"%
    315                                 (self._name,path))
     316                logging.warning("Bundle %s: %s not in MANIFEST" %
     317                                (self._name, path))
    316318                if strict_manifest:
    317319                    os.remove(os.path.join(install_path, path))
    318                    
     320
    319321        # Is anything in MANIFEST left over after accounting for all files?
    320322        if manifestfiles:
    321             err = ("Bundle %s: files in MANIFEST not included: %s"%
    322                    (self._name,str(manifestfiles)))
     323            err = ("Bundle %s: files in MANIFEST not included: %s" %
     324                   (self._name, str(manifestfiles)))
    323325            if strict_manifest:
    324326                raise MalformedBundleException(err)
    325327            else:
    class ActivityBundle(Bundle): 
    350352        mime_types = self.get_mime_types()
    351353        if mime_types is not None:
    352354            installed_icons_dir = os.path.join(xdg_data_home,
    353                                                'icons/sugar/scalable/mimetypes')
     355                'icons/sugar/scalable/mimetypes')
    354356            if not os.path.isdir(installed_icons_dir):
    355357                os.makedirs(installed_icons_dir)
    356358
    class ActivityBundle(Bundle): 
    389391        mime_types = self.get_mime_types()
    390392        if mime_types is not None:
    391393            installed_icons_dir = os.path.join(xdg_data_home,
    392                                                'icons/sugar/scalable/mimetypes')
     394                'icons/sugar/scalable/mimetypes')
    393395            if os.path.isdir(installed_icons_dir):
    394396                for f in os.listdir(installed_icons_dir):
    395397                    path = os.path.join(installed_icons_dir, f)
  • src/sugar/bundle/bundle.py

    diff --git a/src/sugar/bundle/bundle.py b/src/sugar/bundle/bundle.py
    index a1b2686..14fb7c9 100644
    a b class MalformedBundleException(Exception): 
    4646
    4747class Bundle(object):
    4848    """A Sugar activity, content module, etc.
    49    
     49
    5050    The bundle itself may be either a zip file or a directory
    5151    hierarchy, with metadata about the bundle stored various files
    5252    inside it.
    class Bundle(object): 
    7171        # manifest = self._get_file(self._infodir + '/contents')
    7272        # if manifest is None:
    7373        #     raise MalformedBundleException('No manifest file')
    74         # 
     74        #
    7575        # signature = self._get_file(self._infodir + '/contents.sig')
    7676        # if signature is None:
    7777        #     raise MalformedBundleException('No signature file')
    class Bundle(object): 
    124124                logging.debug('%s not found.' % filename)
    125125
    126126        return f
    127    
     127
    128128    def is_file(self, filename):
    129129        if self._zip_file is None:
    130130            path = os.path.join(self._path, filename)
  • src/sugar/bundle/contentbundle.py

    diff --git a/src/sugar/bundle/contentbundle.py b/src/sugar/bundle/contentbundle.py
    index 2d19417..1934fab 100644
    a b from sugar import env 
    2929from sugar.bundle.bundle import Bundle, NotInstalledException, \
    3030    MalformedBundleException
    3131
     32
    3233class ContentBundle(Bundle):
    3334    """A Sugar content bundle
    3435
    class ContentBundle(Bundle): 
    7879            try:
    7980                if int(version) != 1:
    8081                    raise MalformedBundleException(
    81                         'Content bundle %s has unknown host_version number %s' %
    82                         (self._path, version))
     82                        'Content bundle %s has unknown host_version ' \
     83                        'number %s' % (self._path, version))
    8384            except ValueError:
    8485                raise MalformedBundleException(
    8586                    'Content bundle %s has invalid host_version number %s' %
    class ContentBundle(Bundle): 
    209210    def get_start_uri(self):
    210211        return "file://" + urllib.pathname2url(self.get_start_path())
    211212
    212     # TODO treat ContentBundle in special way
    213     # needs rethinking while fixing ContentBundle support
    214213    def get_bundle_id(self):
     214        # TODO treat ContentBundle in special way
     215        # needs rethinking while fixing ContentBundle support
    215216        if self._bundle_class is not None:
    216217            return self._bundle_class
    217218        else:
    218219            return self._global_name
    219220
    220     # TODO treat ContentBundle in special way
    221     # needs rethinking while fixing ContentBundle support
    222221    def get_activity_version(self):
     222        # TODO treat ContentBundle in special way
     223        # needs rethinking while fixing ContentBundle support
    223224        return self._library_version
    224225
    225226    def is_installed(self):
  • src/sugar/datastore/datastore.py

    diff --git a/src/sugar/datastore/datastore.py b/src/sugar/datastore/datastore.py
    index 80d5936..602c848 100644
    a b import gobject 
    2929from sugar.datastore import dbus_helpers
    3030from sugar import mime
    3131
     32
    3233class DSMetadata(gobject.GObject):
     34
    3335    __gsignals__ = {
    3436        'updated': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE,
    3537                    ([]))
    class DSMetadata(gobject.GObject): 
    4143            self._props = {}
    4244        else:
    4345            self._props = props
    44        
     46
    4547        default_keys = ['activity', 'activity_id',
    4648                        'mime_type', 'title_set_by_user']
    4749        for key in default_keys:
    48             if not self._props.has_key(key):
    49                 self._props[key] = ''
     50            self._props.setdefault(key, '')
    5051
    5152    def __getitem__(self, key):
    5253        return self._props[key]
    5354
    5455    def __setitem__(self, key, value):
    55         if not self._props.has_key(key) or self._props[key] != value:
     56        if key not in self._props or self._props[key] != value:
    5657            self._props[key] = value
    5758            self.emit('updated')
    5859
    class DSMetadata(gobject.GObject): 
    6162
    6263    def __contains__(self, key):
    6364        return self._props.__contains__(key)
    64    
     65
    6566    def has_key(self, key):
    6667        return self._props.has_key(key)
    6768
    6869    def keys(self):
    6970        return self._props.keys()
    70    
     71
    7172    def get_dictionary(self):
    7273        return self._props
    7374
    class DSMetadata(gobject.GObject): 
    7576        return DSMetadata(self._props.copy())
    7677
    7778    def get(self, key, default=None):
    78         if self._props.has_key(key):
    79             return self._props[key]
    80         else:
    81             return default
     79        return self._props.get(key, default)
     80
    8281
    8382class DSObject(object):
     83
    8484    def __init__(self, object_id, metadata=None, file_path=None):
    8585        self.object_id = object_id
    8686        self._metadata = metadata
    class DSObject(object): 
    9393            metadata = DSMetadata(dbus_helpers.get_properties(self.object_id))
    9494            self._metadata = metadata
    9595        return self._metadata
    96    
     96
    9797    def set_metadata(self, metadata):
    9898        if self._metadata != metadata:
    9999            self._metadata = metadata
    class DSObject(object): 
    105105            self.set_file_path(dbus_helpers.get_filename(self.object_id))
    106106            self._owns_file = True
    107107        return self._file_path
    108    
     108
    109109    def set_file_path(self, file_path):
    110110        if self._file_path != file_path:
    111111            if self._file_path and self._owns_file:
    class DSObject(object): 
    129129
    130130    def __del__(self):
    131131        if not self._destroyed:
    132             logging.warning('DSObject was deleted without cleaning up first. ' \
    133                             'Call DSObject.destroy() before disposing it.')
     132            logging.warning('DSObject was deleted without cleaning up first.' \
     133                            ' Call DSObject.destroy() before disposing it.')
    134134            self.destroy()
    135135
    136136    def copy(self):
    137137        return DSObject(None, self._metadata.copy(), self._file_path)
    138138
     139
    139140def get(object_id):
    140141    logging.debug('datastore.get')
    141142    metadata = dbus_helpers.get_properties(object_id)
    def get(object_id): 
    144145    # TODO: register the object for updates
    145146    return ds_object
    146147
     148
    147149def create():
    148150    metadata = DSMetadata()
    149151    metadata['mtime'] = datetime.now().isoformat()
    150152    metadata['timestamp'] = int(time.time())
    151153    return DSObject(object_id=None, metadata=metadata, file_path=None)
    152154
     155
    153156def write(ds_object, update_mtime=True, transfer_ownership=False,
    154157          reply_handler=None, error_handler=None, timeout=-1):
    155158    logging.debug('datastore.write')
    def write(ds_object, update_mtime=True, transfer_ownership=False, 
    185188        # TODO: register the object for updates
    186189    logging.debug('Written object %s to the datastore.' % ds_object.object_id)
    187190
     191
    188192def delete(object_id):
    189193    logging.debug('datastore.delete')
    190194    dbus_helpers.delete(object_id)
    191195
     196
    192197def find(query, sorting=None, limit=None, offset=None, properties=None,
    193198         reply_handler=None, error_handler=None):
    194199
    def find(query, sorting=None, limit=None, offset=None, properties=None, 
    203208        query['limit'] = limit
    204209    if offset:
    205210        query['offset'] = offset
    206    
     211
    207212    props_list, total_count = dbus_helpers.find(query, properties,
    208213                                                reply_handler, error_handler)
    209    
     214
    210215    objects = []
    211216    for props in props_list:
    212217        object_id = props['uid']
    def find(query, sorting=None, limit=None, offset=None, properties=None, 
    217222
    218223    return objects, total_count
    219224
     225
    220226def copy(jobject, mount_point):
    221227
    222228    new_jobject = jobject.copy()
    223229    new_jobject.metadata['mountpoint'] = mount_point
    224230
    225     if jobject.metadata.has_key('title'):
     231    if 'title' in jobject.metadata:
    226232        filename = jobject.metadata['title']
    227233
    228         if jobject.metadata.has_key('mime_type'):
     234        if 'mime_type' in jobject.metadata:
    229235            mime_type = jobject.metadata['mime_type']
    230236            extension = mime.get_primary_extension(mime_type)
    231237            if extension:
    def copy(jobject, mount_point): 
    238244
    239245    write(new_jobject)
    240246
     247
    241248def mount(uri, options, timeout=-1):
    242249    return dbus_helpers.mount(uri, options, timeout=timeout)
    243250
     251
    244252def unmount(mount_point_id):
    245253    dbus_helpers.unmount(mount_point_id)
    246254
     255
    247256def mounts():
    248257    return dbus_helpers.mounts()
    249258
     259
    250260def complete_indexing():
    251261    return dbus_helpers.complete_indexing()
    252262
     263
    253264def get_unique_values(key):
    254265    return dbus_helpers.get_unique_values(key)
  • src/sugar/datastore/dbus_helpers.py

    diff --git a/src/sugar/datastore/dbus_helpers.py b/src/sugar/datastore/dbus_helpers.py
    index 9115382..f2650d7 100644
    a b DS_DBUS_PATH = "/org/laptop/sugar/DataStore" 
    3131
    3232_data_store = None
    3333
     34
    3435def _get_data_store():
    3536    global _data_store
    3637
    def _get_data_store(): 
    4142                                     DS_DBUS_INTERFACE)
    4243    return _data_store
    4344
     45
    4446def create(properties, filename, transfer_ownership=False):
    4547    object_id = _get_data_store().create(dbus.Dictionary(properties), filename,
    4648                    transfer_ownership)
    4749    logging.debug('dbus_helpers.create: ' + object_id)
    4850    return object_id
    4951
     52
    5053def update(uid, properties, filename, transfer_ownership=False,
    5154        reply_handler=None, error_handler=None, timeout=-1):
    5255    debug_props = properties.copy()
    53     if debug_props.has_key("preview"):
     56    if "preview" in debug_props:
    5457        debug_props["preview"] = "<omitted>"
    5558    logging.debug('dbus_helpers.update: %s, %s, %s, %s' %
    5659                  (uid, filename, debug_props, transfer_ownership))
    def update(uid, properties, filename, transfer_ownership=False, 
    6467        _get_data_store().update(uid, dbus.Dictionary(properties),
    6568                                 filename, transfer_ownership)
    6669
     70
    6771def delete(uid):
    6872    logging.debug('dbus_helpers.delete: %r' % uid)
    6973    _get_data_store().delete(uid)
    70        
     74
     75
    7176def get_properties(uid):
    7277    logging.debug('dbus_helpers.get_properties: %s' % uid)
    7378    return _get_data_store().get_properties(uid, byte_arrays=True)
    7479
     80
    7581def get_filename(uid):
    7682    filename = _get_data_store().get_filename(uid)
    7783    logging.debug('dbus_helpers.get_filename: %s, %s' % (uid, filename))
    7884    return filename
    7985
     86
    8087def find(query, properties, reply_handler, error_handler):
    8188    logging.debug('dbus_helpers.find: %r %r' % (query, properties))
    8289    if reply_handler and error_handler:
    def find(query, properties, reply_handler, error_handler): 
    8693    else:
    8794        return _get_data_store().find(query, properties, byte_arrays=True)
    8895
     96
    8997def mount(uri, options, timeout=-1):
    9098    return _get_data_store().mount(uri, options, timeout=timeout)
    9199
     100
    92101def unmount(mount_point_id):
    93102    _get_data_store().unmount(mount_point_id)
    94103
     104
    95105def mounts():
    96106    return _get_data_store().mounts()
    97107
     108
    98109def get_unique_values(key):
    99110    return _get_data_store().get_uniquevaluesfor(
    100111                                key, dbus.Dictionary({}, signature='ss'))
    101112
     113
    102114def complete_indexing():
    103115    return _get_data_store().complete_indexing()
    104 
  • src/sugar/env.py

    diff --git a/src/sugar/env.py b/src/sugar/env.py
    index 91e91d3..9646643 100644
    a b STABLE. 
    2222
    2323import os
    2424
     25
    2526def is_emulator():
    26     if os.environ.has_key('SUGAR_EMULATOR'):
    27         if os.environ['SUGAR_EMULATOR'] == 'yes':
    28             return True
    29     return False
     27    return os.environ.get('SUGAR_EMULATOR', 'no') == 'yes'
    3028
    31 def get_profile_path(path=None):
    32     if os.environ.has_key('SUGAR_PROFILE'):
    33         profile_id = os.environ['SUGAR_PROFILE']
    34     else:
    35         profile_id = 'default'
    3629
     30def get_profile_path(path=None):
     31    profile_id = os.environ.get('SUGAR_PROFILE', 'default')
    3732    base = os.path.join(os.path.expanduser('~/.sugar'), profile_id)
    3833    if not os.path.isdir(base):
    3934        try:
    def get_profile_path(path=None): 
    4136        except OSError:
    4237            print "Could not create user directory."
    4338
    44     if path != None:
     39    if path is not None:
    4540        return os.path.join(base, path)
    4641    else:
    4742        return base
    4843
     44
    4945def get_logs_path(path=None):
    5046    base = os.environ.get('SUGAR_LOGS_DIR', get_profile_path('logs'))
    51     if path != None:
     47    if path is not None:
    5248        return os.path.join(base, path)
    5349    else:
    5450        return base
    5551
     52
    5653def get_user_activities_path():
    5754    return os.path.expanduser('~/Activities')
    5855
     56
    5957def get_user_library_path():
    6058    return os.path.expanduser('~/Library')
  • src/sugar/graphics/alert.py

    diff --git a/src/sugar/graphics/alert.py b/src/sugar/graphics/alert.py
    index 2c3c4ca..b108d9d 100644
    a b import gtk 
    5050import gobject
    5151import hippo
    5252import math
    53        
     53
    5454from sugar.graphics import style
    5555from sugar.graphics.icon import Icon
    5656
    class Alert(gtk.EventBox): 
    111111        self._msg_label.set_alignment(0, 0.5)
    112112        self._msg_box.pack_start(self._msg_label, False)
    113113        self._hbox.pack_start(self._msg_box, False)
    114        
     114
    115115        self._buttons_box = gtk.HButtonBox()
    116116        self._buttons_box.set_layout(gtk.BUTTONBOX_END)
    117117        self._buttons_box.set_spacing(style.DEFAULT_SPACING)
    118118        self._hbox.pack_start(self._buttons_box)
    119        
     119
    120120        gobject.GObject.__init__(self, **kwargs)
    121121
    122         self.set_visible_window(True)       
    123         self.add(self._hbox)       
     122        self.set_visible_window(True)
     123        self.add(self._hbox)
    124124        self._title_label.show()
    125125        self._msg_label.show()
    126126        self._buttons_box.show()
    127127        self._msg_box.show()
    128128        self._hbox.show()
    129129        self.show()
    130        
    131     def do_set_property(self, pspec, value):       
     130
     131    def do_set_property(self, pspec, value):
    132132        """
    133133        Set alert property
    134134
    class _TimeoutIcon(hippo.CanvasText, hippo.CanvasItem): 
    299299
    300300    def __init__(self, **kwargs):
    301301        hippo.CanvasText.__init__(self, **kwargs)
    302        
     302
    303303        self.props.orientation = hippo.ORIENTATION_HORIZONTAL
    304304        self.props.border_left = style.DEFAULT_SPACING
    305305        self.props.border_right = style.DEFAULT_SPACING
    306            
     306
    307307    def do_paint_background(self, cr, damaged_box):
    308308        [width, height] = self.get_allocation()
    309        
     309
    310310        xval = width * 0.5
    311311        yval = height * 0.5
    312         radius = min(width * 0.5, height * 0.5)         
    313        
     312        radius = min(width * 0.5, height * 0.5)
     313
    314314        hippo.cairo_set_source_rgba32(cr, self.props.background_color)
    315         cr.arc(xval, yval, radius, 0, 2*math.pi)       
    316         cr.fill_preserve()   
     315        cr.arc(xval, yval, radius, 0, 2*math.pi)
     316        cr.fill_preserve()
    317317
    318318
    319319class TimeoutAlert(Alert):
    class TimeoutAlert(Alert): 
    362362        Alert.__init__(self, **kwargs)
    363363
    364364        self._timeout = timeout
    365        
     365
    366366        icon = Icon(icon_name='dialog-cancel')
    367367        self.add_button(gtk.RESPONSE_CANCEL, _('Cancel'), icon)
    368368        icon.show()
    369        
     369
    370370        self._timeout_text = _TimeoutIcon(
    371371            text=self._timeout,
    372372            color=style.COLOR_BUTTON_GREY.get_int(),
    373             background_color=style.COLOR_WHITE.get_int())   
     373            background_color=style.COLOR_WHITE.get_int())
    374374        canvas = hippo.Canvas()
    375375        canvas.set_root(self._timeout_text)
    376         canvas.show()                       
     376        canvas.show()
    377377        self.add_button(gtk.RESPONSE_OK, _('Continue'), canvas)
    378378
    379379        gobject.timeout_add_seconds(1, self.__timeout)
    380        
     380
    381381    def __timeout(self):
    382382        self._timeout -= 1
    383383        self._timeout_text.props.text = self._timeout
  • src/sugar/graphics/animator.py

    diff --git a/src/sugar/graphics/animator.py b/src/sugar/graphics/animator.py
    index 5d5b355..51c8ac3 100644
    a b class Animator(gobject.GObject): 
    3131        'completed': (gobject.SIGNAL_RUN_FIRST,
    3232                      gobject.TYPE_NONE, ([])),
    3333    }
    34    
     34
    3535    def __init__(self, duration, fps=20, easing=EASE_OUT_EXPO):
    3636        gobject.GObject.__init__(self)
    3737        self._animations = []
  • src/sugar/graphics/canvastextview.py

    diff --git a/src/sugar/graphics/canvastextview.py b/src/sugar/graphics/canvastextview.py
    index 481248d..4a2aaa4 100644
    a b class CanvasTextView(hippo.CanvasWidget): 
    2929        self.text_view_widget.props.right_margin = style.DEFAULT_SPACING
    3030        self.text_view_widget.props.wrap_mode = gtk.WRAP_WORD
    3131        self.text_view_widget.show()
    32        
     32
    3333        # TODO: These fields should expand vertically instead of scrolling
    3434        scrolled_window = gtk.ScrolledWindow()
    3535        scrolled_window.set_shadow_type(gtk.SHADOW_OUT)
    3636        scrolled_window.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
    3737        scrolled_window.add(self.text_view_widget)
    38        
     38
    3939        self.props.widget = scrolled_window
  • src/sugar/graphics/colorbutton.py

    diff --git a/src/sugar/graphics/colorbutton.py b/src/sugar/graphics/colorbutton.py
    index a5c7f0a..f69691c 100644
    a b from sugar.graphics.palette import Palette, ToolInvoker, WidgetInvoker 
    2929_ = lambda msg: gettext.dgettext('sugar-toolkit', msg)
    3030
    3131def get_svg_color_string(color):
    32     return '#%.2X%.2X%.2X' % (color.red / 257, color.green / 257, 
     32    return '#%.2X%.2X%.2X' % (color.red / 257, color.green / 257,
    3333                              color.blue / 257)
    3434
    3535class _ColorButton(gtk.Button):
    class _ColorButton(gtk.Button): 
    4040    As a preview an sugar.graphics.Icon is used. The fill color will be set to
    4141    the current color, and the stroke color is set to the font color.
    4242    """
    43    
     43
    4444    __gtype_name__ = 'SugarColorButton'
    4545    __gsignals__ = { 'color-set' : (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE,
    4646                                     tuple())}
    47    
     47
    4848    def __init__(self, **kwargs):
    4949        self._title = _('Choose a color')
    5050        self._color = gtk.gdk.Color(0, 0, 0)
    class _ColorButton(gtk.Button): 
    9292
    9393    def __palette_color_set_cb(self, palette):
    9494        self.emit('color-set')
    95    
     95
    9696    def __palette_color_changed(self, palette, pspec):
    9797        self.color = self._palette.color
    98    
     98
    9999    def do_style_set(self, previous_style):
    100100        self._preview.stroke_color = \
    101101            get_svg_color_string(self.style.fg[gtk.STATE_NORMAL])
    class _ColorButton(gtk.Button): 
    111111
    112112    def set_color(self, color):
    113113        assert isinstance(color, gtk.gdk.Color)
    114        
     114
    115115        if self._color.red == color.red and \
    116116           self._color.green == color.green and \
    117117           self._color.blue == color.blue:
    118118            return
    119        
     119
    120120        self._color = gtk.gdk.Color(color.red, color.green, color.blue)
    121121        self._preview.fill_color = get_svg_color_string(self._color)
    122122        if self._palette:
    class _ColorButton(gtk.Button): 
    201201        red = self._color.red / 257
    202202        green = self._color.green / 257
    203203        blue = self._color.blue / 257
    204        
     204
    205205        pixbuf.fill(red << 24 + green << 16 + blue << 8 + 0xff)
    206        
     206
    207207        context.set_icon_pixbuf(pixbuf)
    208208
    209209    def __drag_data_get_cb(self, widget, context, selection_data, info, time):
    class _ColorPalette(Palette): 
    258258        self._picker_hbox.pack_start(self._swatch_tray)
    259259        self._picker_hbox.pack_start(gtk.VSeparator(),
    260260                                     padding=style.DEFAULT_SPACING)
    261        
     261
    262262        self._chooser_table = gtk.Table(3, 2)
    263263        self._chooser_table.set_col_spacing(0, style.DEFAULT_PADDING)
    264264
    class _ColorPalette(Palette): 
    271271            self._create_color_scale(_('Blue'), self._BLUE, 2))
    272272
    273273        self._picker_hbox.add(self._chooser_table)
    274        
     274
    275275        self._picker_hbox.show_all()
    276276
    277277        self._build_swatches()
    class _ColorPalette(Palette): 
    300300
    301301        return scale
    302302
    303        
     303
    304304
    305305    def _build_swatches(self):
    306306        for child in self._swatch_tray.get_children():
    class _ColorPalette(Palette): 
    370370            return
    371371
    372372        self._color = color.copy()
    373        
     373
    374374        if self._scales:
    375375            self._scales[self._RED].set_value(self._color.red / 65535.0)
    376376            self._scales[self._GREEN].set_value(self._color.green / 65535.0)
    377377            self._scales[self._BLUE].set_value(self._color.blue / 65535.0)
    378        
     378
    379379        self.notify('color')
    380380
    381381    def get_color(self):
  • src/sugar/graphics/combobox.py

    diff --git a/src/sugar/graphics/combobox.py b/src/sugar/graphics/combobox.py
    index 4e094ab..fe18087 100644
    a b import gobject 
    2323import gtk
    2424
    2525class ComboBox(gtk.ComboBox):
    26     __gtype_name__ = 'SugarComboBox'   
     26    __gtype_name__ = 'SugarComboBox'
    2727
    2828    def __init__(self):
    2929        gtk.ComboBox.__init__(self)
    class ComboBox(gtk.ComboBox): 
    129129        None
    130130
    131131        """
    132         self._model.append([0, None, None, True])   
     132        self._model.append([0, None, None, True])
    133133
    134134    def get_active_item(self):
    135135        """
  • src/sugar/graphics/icon.py

    diff --git a/src/sugar/graphics/icon.py b/src/sugar/graphics/icon.py
    index 45f2de5..7b51c03 100644
    a b from sugar.util import LRU 
    3535
    3636_BADGE_SIZE = 0.45
    3737
     38
    3839class _SVGLoader(object):
     40
    3941    def __init__(self):
    4042        self._cache = LRU(50)
    4143
    class _SVGLoader(object): 
    6163        import rsvg # XXX this is very slow!  why?
    6264        return rsvg.Handle(data=icon)
    6365
     66
    6467class _IconInfo(object):
     68
    6569    def __init__(self):
    6670        self.file_name = None
    6771        self.attach_x = 0
    6872        self.attach_y = 0
    6973
     74
    7075class _BadgeInfo(object):
     76
    7177    def __init__(self):
    7278        self.attach_x = 0
    7379        self.attach_y = 0
    7480        self.size = 0
    7581        self.icon_padding = 0
    7682
     83
    7784class _IconBuffer(object):
     85
    7886    _surface_cache = LRU(50)
    7987    _loader = _SVGLoader()
    8088
    class _IconBuffer(object): 
    219227            self.stroke_color = None
    220228            self.fill_color = None
    221229
    222     def _get_insensitive_pixbuf (self, pixbuf, widget):
     230    def _get_insensitive_pixbuf(self, pixbuf, widget):
    223231        if not (widget and widget.style):
    224232            return pixbuf
    225233
    class _IconBuffer(object): 
    309317
    310318    xo_color = property(_get_xo_color, _set_xo_color)
    311319
     320
    312321class Icon(gtk.Image):
     322
    313323    __gtype_name__ = 'SugarIcon'
    314324
    315325    def __init__(self, **kwargs):
    class Icon(gtk.Image): 
    324334        if self._buffer.file_name != self.props.file:
    325335            self._buffer.file_name = self.props.file
    326336
    327         if self.props.pixel_size == -1:   
     337        if self.props.pixel_size == -1:
    328338            width, height = gtk.icon_size_lookup(self.props.icon_size)
    329339        else:
    330             width = height = self.props.pixel_size 
     340            width = height = self.props.pixel_size
    331341        if self._buffer.width != width or self._buffer.height != height:
    332342            self._buffer.width = width
    333343            self._buffer.height = height
    class Icon(gtk.Image): 
    497507    badge_name = gobject.property(
    498508        type=str, getter=get_badge_name, setter=set_badge_name)
    499509
     510
    500511class CanvasIcon(hippo.CanvasBox, hippo.CanvasItem):
     512
    501513    __gtype_name__ = 'CanvasIcon'
    502514
    503515    def __init__(self, **kwargs):
    class CanvasIcon(hippo.CanvasBox, hippo.CanvasItem): 
    904916
    905917    def get_palette_invoker(self):
    906918        return self._palette_invoker
    907    
     919
    908920    def set_palette_invoker(self, palette_invoker):
    909921        self._palette_invoker.detach()
    910922        self._palette_invoker = palette_invoker
    class CanvasIcon(hippo.CanvasBox, hippo.CanvasItem): 
    916928        from sugar.graphics.palette import Palette
    917929
    918930        self.set_palette(Palette(text))
    919    
     931
    920932    palette = property(get_palette, set_palette)
    921933
     934
    922935class CellRendererIcon(gtk.GenericCellRenderer):
    923     __gtype_name__ = 'SugarCellRendererIcon'
    924936
     937    __gtype_name__ = 'SugarCellRendererIcon'
    925938    __gsignals__ = {
    926939        'clicked': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, [object])
    927940    }
    class CellRendererIcon(gtk.GenericCellRenderer): 
    10061019        if self._buffer.background_color != value:
    10071020            self._buffer.background_color = value
    10081021
    1009     background_color = gobject.property(type=object, setter=set_background_color)
     1022    background_color = gobject.property(type=object,
     1023        setter=set_background_color)
    10101024
    10111025    def set_size(self, value):
    10121026        if self._buffer.width != value:
    class CellRendererIcon(gtk.GenericCellRenderer): 
    10591073
    10601074        return False
    10611075
    1062     def on_render(self, window, widget, background_area, cell_area, expose_area,
    1063                   flags):
     1076    def on_render(self, window, widget, background_area, cell_area,
     1077        expose_area, flags):
    10641078        has_prelit_colors = None not in [self._prelit_fill_color,
    10651079                                         self._prelit_stroke_color]
    10661080        if flags & gtk.CELL_RENDERER_PRELIT and has_prelit_colors and \
    class CellRendererIcon(gtk.GenericCellRenderer): 
    10861100        cr.rectangle(expose_area)
    10871101        cr.paint()
    10881102
     1103
    10891104def get_icon_state(base_name, perc, step=5):
    10901105    strength = round(perc / step) * step
    10911106    icon_theme = gtk.icon_theme_get_default()
    def get_icon_state(base_name, perc, step=5): 
    10971112
    10981113        strength = strength + step
    10991114
     1115
    11001116def get_icon_file_name(icon_name):
    11011117    icon_theme = gtk.icon_theme_get_default()
    11021118    info = icon_theme.lookup_icon(icon_name, gtk.ICON_SIZE_LARGE_TOOLBAR, 0)
    def get_icon_file_name(icon_name): 
    11051121    filename = info.get_filename()
    11061122    del info
    11071123    return filename
    1108 
  • src/sugar/graphics/notebook.py

    diff --git a/src/sugar/graphics/notebook.py b/src/sugar/graphics/notebook.py
    index 4965b24..65d3522 100644
    a b  
    1717
    1818"""Notebook class
    1919
    20 This class create a gtk.Notebook() widget supporting 
     20This class create a gtk.Notebook() widget supporting
    2121a close button in every tab when the 'can-close-tabs' gproperty
    2222is enabled (True)
    2323
    class Notebook(gtk.Notebook): 
    3838
    3939    def __init__(self, **kwargs):
    4040        # Initialise the Widget
    41         #
    42         #    Side effects: 
     41
     42        #    Side effects:
    4343        #        Set the 'can-close-tabs' property using **kwargs
    4444        #        Set True the scrollable notebook property
    45        
     45
    4646        gobject.GObject.__init__(self, **kwargs)
    4747
    4848        self._can_close_tabs = None
    class Notebook(gtk.Notebook): 
    108108
    109109        tab_box.show_all()
    110110        event_box.add(tab_box)
    111        
     111
    112112        return event_box
    113113
    114114    def add_page(self, text_label, widget):
    class Notebook(gtk.Notebook): 
    130130        # Add a new page to the notebook
    131131        if self._can_close_tabs:
    132132            eventbox = self._create_custom_tab(text_label, widget)
    133             self.append_page(widget, eventbox)         
     133            self.append_page(widget, eventbox)
    134134        else:
    135135            self.append_page(widget, gtk.Label(text_label))
    136            
     136
    137137        pages = self.get_n_pages()
    138138
    139139        # Set the new page
    140140        self.set_current_page(pages - 1)
    141141        self.show_all()
    142        
     142
    143143        return True
    144144
    145145    def _close_page(self, button, child):
  • src/sugar/graphics/objectchooser.py

    diff --git a/src/sugar/graphics/objectchooser.py b/src/sugar/graphics/objectchooser.py
    index fb3703d..e2ab9f5 100644
    a b J_DBUS_SERVICE = 'org.laptop.Journal' 
    3131J_DBUS_INTERFACE = 'org.laptop.Journal'
    3232J_DBUS_PATH = '/org/laptop/Journal'
    3333
     34
    3435class ObjectChooser(object):
     36
    3537    def __init__(self, title=None, parent=None, flags=None, buttons=None,
    3638                 what_filter=None):
    3739        # For backwards compatibility:
    class ObjectChooser(object): 
    5658        self._chooser_id = None
    5759        self._response_code = gtk.RESPONSE_NONE
    5860        self._what_filter = what_filter
    59        
     61
    6062    def run(self):
    6163        self._object_id = None
    6264
    class ObjectChooser(object): 
    127129        # Journal service disappeared from the bus
    128130        self._response_code = gtk.RESPONSE_CANCEL
    129131        self._cleanup()
    130 
  • src/sugar/graphics/palette.py

    diff --git a/src/sugar/graphics/palette.py b/src/sugar/graphics/palette.py
    index 88145d2..aa7638e 100644
    a b from sugar.graphics import style 
    3333from sugar.graphics.icon import Icon
    3434from sugar import _sugarext
    3535
    36 # Helper function to find the gap position and size of widget a
     36
    3737def _calculate_gap(a, b):
     38    """Helper function to find the gap position and size of widget a"""
    3839    # Test for each side if the palette and invoker are
    3940    # adjacent to each other.
    4041    gap = True
    def _calculate_gap(a, b): 
    4950        gap_side = gtk.POS_TOP
    5051    else:
    5152        gap = False
    52    
     53
    5354    if gap:
    5455        if gap_side == gtk.POS_BOTTOM or gap_side == gtk.POS_TOP:
    5556            gap_start = min(a.width, max(0, b.x - a.x))
    def _calculate_gap(a, b): 
    6566    else:
    6667        return False
    6768
     69
    6870class MouseSpeedDetector(gobject.GObject):
    6971
    7072    __gsignals__ = {
    class MouseSpeedDetector(gobject.GObject): 
    127129
    128130        return True
    129131
     132
    130133class Palette(gtk.Window):
    131134    PRIMARY = 0
    132135    SECONDARY = 1
    class Palette(gtk.Window): 
    142145                      gobject.TYPE_NONE, ([]))
    143146    }
    144147
    145     # DEPRECATED: label is passed with the primary-text property, accel_path
    146     # is set via the invoker property, and menu_after_content is not used
    147148    def __init__(self, label=None, accel_path=None, menu_after_content=False,
    148149                 text_maxlen=60, **kwargs):
    149 
     150        """
     151        DEPRECATED: label is passed with the primary-text property, accel_path
     152        is set via the invoker property, and menu_after_content is not used
     153        """
    150154        self.palette_state = self.PRIMARY
    151155
    152156        self._primary_text = None
    class Palette(gtk.Window): 
    166170        primary_box.pack_start(self._icon_box, expand=False)
    167171
    168172        labels_box = gtk.VBox()
    169         self._label_alignment = gtk.Alignment(xalign=0, yalign=0.5, 
     173        self._label_alignment = gtk.Alignment(xalign=0, yalign=0.5,
    170174                                              xscale=1, yscale=0.33)
    171         self._label_alignment.set_padding(0, 0, style.DEFAULT_SPACING, 
     175        self._label_alignment.set_padding(0, 0, style.DEFAULT_SPACING,
    172176                                          style.DEFAULT_SPACING)
    173177        self._label_alignment.add(labels_box)
    174178        self._label_alignment.show()
    class Palette(gtk.Window): 
    241245        self._menu_box = None
    242246        self._content = None
    243247        self._invoker_hids = []
    244        
     248
    245249        self.set_group_id("default")
    246250
    247251        # we set these for backward compatibility
    class Palette(gtk.Window): 
    278282        # Break the reference cycle. It looks like the gc is not able to free
    279283        # it, possibly because gtk.Menu memory handling is very special.
    280284        self.menu = None
    281        
     285
    282286    def _add_menu(self):
    283287        self._menu_box = gtk.VBox()
    284288        self._secondary_box.pack_start(self._menu_box)
    class Palette(gtk.Window): 
    307311        y = win_y + rectangle.y
    308312        width = rectangle.width
    309313        height = rectangle.height
    310        
     314
    311315        return gtk.gdk.Rectangle(x, y, width, height)
    312316
    313317    def set_invoker(self, invoker):
    314         for hid in self._invoker_hids[:]: 
     318        for hid in self._invoker_hids[:]:
    315319            self._invoker.disconnect(hid)
    316320            self._invoker_hids.remove(hid)
    317321
    class Palette(gtk.Window): 
    372376    secondary_text = gobject.property(type=str,
    373377                                      getter=get_secondary_text,
    374378                                      setter=set_secondary_text)
     379
    375380    def _show_icon(self):
    376381        self._label_alignment.set_padding(0, 0, 0, style.DEFAULT_SPACING)
    377382        self._icon_box.show()
    class Palette(gtk.Window): 
    608613        immediate = False
    609614
    610615        if self.is_up():
    611             self._popdown_anim.stop() 
     616            self._popdown_anim.stop()
    612617            return
    613618
    614619        if self._group_id:
    class Palette(gtk.Window): 
    665670
    666671
    667672class PaletteActionBar(gtk.HButtonBox):
     673
    668674    def add_action(self, label, icon_name=None):
    669675        button = gtk.Button(label)
    670676
    class PaletteActionBar(gtk.HButtonBox): 
    676682        self.pack_start(button)
    677683        button.show()
    678684
     685
    679686class _Menu(_sugarext.Menu):
    680     __gtype_name__ = 'SugarPaletteMenu'
    681687
     688    __gtype_name__ = 'SugarPaletteMenu'
    682689    __gsignals__ = {
    683690        'item-inserted': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ([]))
    684691    }
    class _Menu(_sugarext.Menu): 
    712719    def do_deactivate(self):
    713720        self._palette.hide()
    714721
     722
    715723class _PopupAnimation(animator.Animation):
     724
    716725    def __init__(self, palette):
    717726        animator.Animation.__init__(self, 0.0, 1.0)
    718727        self._palette = palette
    class _PopupAnimation(animator.Animation): 
    721730        if current == 1.0:
    722731            self._palette.show()
    723732
     733
    724734class _SecondaryAnimation(animator.Animation):
     735
    725736    def __init__(self, palette):
    726737        animator.Animation.__init__(self, 0.0, 1.0)
    727738        self._palette = palette
    class _SecondaryAnimation(animator.Animation): 
    730741        if current == 1.0:
    731742            self._palette.set_state(Palette.SECONDARY)
    732743
     744
    733745class _PopdownAnimation(animator.Animation):
     746
    734747    def __init__(self, palette):
    735748        animator.Animation.__init__(self, 0.0, 1.0)
    736749        self._palette = palette
    class _PopdownAnimation(animator.Animation): 
    739752        if current == 1.0:
    740753            self._palette.hide()
    741754
     755
    742756class Invoker(gobject.GObject):
    743     __gtype_name__ = 'SugarPaletteInvoker'
    744757
     758    __gtype_name__ = 'SugarPaletteInvoker'
    745759    __gsignals__ = {
    746760        'mouse-enter': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ([])),
    747761        'mouse-leave': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ([])),
    class Invoker(gobject.GObject): 
    851865        alignment = self.get_alignment(palette_dim)
    852866        rect = self._get_position_for_alignment(alignment, palette_dim)
    853867
    854         # In case our efforts to find an optimum place inside the screen failed,
    855         # just make sure the palette fits inside the screen if at all possible.
     868        # In case our efforts to find an optimum place inside the screen
     869        # failed, just make sure the palette fits inside the screen if at all
     870        # possible.
    856871        rect.x = max(0, rect.x)
    857872        rect.y = max(0, rect.y)
    858873
    class Invoker(gobject.GObject): 
    949964
    950965    def get_palette(self):
    951966        return self._palette
    952    
     967
    953968    def set_palette(self, palette):
    954969        if self._palette:
    955970            self._palette.props.invoker = None
    class Invoker(gobject.GObject): 
    962977    palette = gobject.property(
    963978        type=object, setter=set_palette, getter=get_palette)
    964979
     980
    965981class WidgetInvoker(Invoker):
     982
    966983    def __init__(self, parent=None, widget=None):
    967984        Invoker.__init__(self)
    968985
    class WidgetInvoker(Invoker): 
    9831000        self.notify('widget')
    9841001
    9851002        self._enter_hid = self._widget.connect('enter-notify-event',
    986                                                self.__enter_notify_event_cb)
     1003            self.__enter_notify_event_cb)
    9871004        self._leave_hid = self._widget.connect('leave-notify-event',
    988                                                self.__leave_notify_event_cb)
     1005            self.__leave_notify_event_cb)
    9891006        self._release_hid = self._widget.connect('button-release-event',
    990                                                  self.__button_release_event_cb)
     1007            self.__button_release_event_cb)
    9911008
    9921009        self.attach(parent)
    9931010
    class WidgetInvoker(Invoker): 
    10701087        return self._widget
    10711088    widget = gobject.property(type=object, getter=_get_widget, setter=None)
    10721089
     1090
    10731091class CanvasInvoker(Invoker):
     1092
    10741093    def __init__(self, parent=None):
    10751094        Invoker.__init__(self)
    10761095
    class CanvasInvoker(Invoker): 
    11071126            return gtk.gdk.Rectangle(x, y, width, height)
    11081127        else:
    11091128            return gtk.gdk.Rectangle()
    1110        
     1129
    11111130    def __motion_notify_event_cb(self, button, event):
    11121131        if event.detail == hippo.MOTION_DETAIL_ENTER:
    11131132            self.notify_mouse_enter()
    class CanvasInvoker(Invoker): 
    11261145    def get_toplevel(self):
    11271146        return hippo.get_canvas_for_item(self._item).get_toplevel()
    11281147
     1148
    11291149class ToolInvoker(WidgetInvoker):
     1150
    11301151    def __init__(self, parent=None):
    11311152        WidgetInvoker.__init__(self)
    11321153
    class ToolInvoker(WidgetInvoker): 
    11461167        else:
    11471168            return self.LEFT + self.RIGHT
    11481169
     1170
    11491171class CellRendererInvoker(Invoker):
     1172
    11501173    def __init__(self):
    11511174        Invoker.__init__(self)
    11521175
    class CellRendererInvoker(Invoker): 
    12301253        self.notify_mouse_leave()
    12311254
    12321255    def __button_release_event_cb(self, widget, event):
    1233         if event.button == 1 and self._point_in_cell_renderer(event.x, event.y):
     1256        if event.button == 1 and \
     1257            self._point_in_cell_renderer(event.x, event.y):
    12341258            tree_view = self._tree_view
    12351259            path, column_, x_, y_ = tree_view.get_path_at_pos(int(event.x),
    12361260                                                              int(event.y))
    12371261            self._cell_renderer.emit('clicked', path)
    12381262            # So the treeview receives it and knows a drag isn't going on
    12391263            return False
    1240         if event.button == 3 and self._point_in_cell_renderer(event.x, event.y):
     1264
     1265        if event.button == 3 and \
     1266            self._point_in_cell_renderer(event.x, event.y):
    12411267            self.notify_right_click()
    12421268            return True
     1269
    12431270        else:
    12441271            return False
    12451272
    class CellRendererInvoker(Invoker): 
    12711298
    12721299    def get_default_position(self):
    12731300        return self.AT_CURSOR
    1274 
  • src/sugar/graphics/palettegroup.py

    diff --git a/src/sugar/graphics/palettegroup.py b/src/sugar/graphics/palettegroup.py
    index e95b5aa..d3bccb5 100644
    a b class Group(gobject.GObject): 
    7676
    7777    def popdown(self):
    7878        for palette in self._palettes:
    79             if palette.is_up(): 
     79            if palette.is_up():
    8080                palette.popdown(immediate=True)
    8181
    8282    def _palette_popup_cb(self, palette):
  • src/sugar/graphics/radiotoolbutton.py

    diff --git a/src/sugar/graphics/radiotoolbutton.py b/src/sugar/graphics/radiotoolbutton.py
    index 11f962d..7264232 100644
    a b class RadioToolButton(gtk.RadioToolButton): 
    154154
    155155    def get_palette_invoker(self):
    156156        return self._palette_invoker
    157    
     157
    158158    def set_palette_invoker(self, palette_invoker):
    159159        self._palette_invoker.detach()
    160160        self._palette_invoker = palette_invoker
  • src/sugar/graphics/roundbox.py

    diff --git a/src/sugar/graphics/roundbox.py b/src/sugar/graphics/roundbox.py
    index 28644bc..b909c74 100644
    a b class CanvasRoundBox(hippo.CanvasBox, hippo.CanvasItem): 
    3535
    3636        # TODO: we should calculate radius depending on the height of the box.
    3737        self._radius = style.zoom(10)
    38        
     38
    3939        self.props.orientation = hippo.ORIENTATION_HORIZONTAL
    4040        self.props.border = self._BORDER_DEFAULT
    4141        self.props.border_left = self._radius
    4242        self.props.border_right = self._radius
    4343        self.props.border_color = style.COLOR_BLACK.get_int()
    44            
     44
    4545    def do_paint_background(self, cr, damaged_box):
    4646        [width, height] = self.get_allocation()
    4747
  • src/sugar/graphics/toggletoolbutton.py

    diff --git a/src/sugar/graphics/toggletoolbutton.py b/src/sugar/graphics/toggletoolbutton.py
    index 9bb2f58..c049c10 100644
    a b import gtk 
    2525from sugar.graphics.icon import Icon
    2626from sugar.graphics.palette import Palette, ToolInvoker
    2727
     28
    2829class ToggleToolButton(gtk.ToggleToolButton):
    2930    __gtype_name__ = "SugarToggleToolButton"
    3031
    class ToggleToolButton(gtk.ToggleToolButton): 
    5960
    6061    def get_palette_invoker(self):
    6162        return self._palette_invoker
    62    
     63
    6364    def set_palette_invoker(self, palette_invoker):
    6465        self._palette_invoker.detach()
    6566        self._palette_invoker = palette_invoker
    class ToggleToolButton(gtk.ToggleToolButton): 
    6970
    7071    def set_tooltip(self, text):
    7172        self.set_palette(Palette(text))
    72    
     73
    7374    def do_expose_event(self, event):
    7475        allocation = self.get_allocation()
    7576        child = self.get_child()
    class ToggleToolButton(gtk.ToggleToolButton): 
    8586                                  allocation.width, allocation.height)
    8687
    8788        gtk.ToggleToolButton.do_expose_event(self, event)
    88    
     89
    8990    palette = property(get_palette, set_palette)
  • src/sugar/graphics/toolbox.py

    diff --git a/src/sugar/graphics/toolbox.py b/src/sugar/graphics/toolbox.py
    index 1cfbe93..47a311d 100644
    a b class Toolbox(gtk.VBox): 
    3636
    3737    def __init__(self):
    3838        gtk.VBox.__init__(self)
    39        
     39
    4040        self._notebook = gtk.Notebook()
    4141        self._notebook.set_tab_pos(gtk.POS_BOTTOM)
    4242        self._notebook.set_show_border(False)
    class Toolbox(gtk.VBox): 
    5555                    border_bottom=style.LINE_WIDTH)
    5656        self._separator.set_root(box)
    5757        self.pack_start(self._separator, False)
    58        
     58
    5959        self._notebook.connect('notify::page', self._notify_page_cb)
    6060
    6161    def _notify_page_cb(self, notebook, pspec):
    6262        self.emit('current-toolbar-changed', notebook.props.page)
    63        
     63
    6464    def add_toolbar(self, name, toolbar):
    6565        label = gtk.Label(name)
    6666        width, height_ = label.size_request()
    class Toolbox(gtk.VBox): 
    6868        label.set_alignment(0.0, 0.5)
    6969
    7070        event_box = gtk.EventBox()
    71        
     71
    7272        alignment = gtk.Alignment(0.0, 0.0, 1.0, 1.0)
    7373        alignment.set_padding(0, 0, style.TOOLBOX_HORIZONTAL_PADDING,
    7474                              style.TOOLBOX_HORIZONTAL_PADDING)
    class Toolbox(gtk.VBox): 
    8383        if self._notebook.get_n_pages() > 1:
    8484            self._notebook.set_show_tabs(True)
    8585            self._separator.show()
    86                    
     86
    8787    def remove_toolbar(self, index):
    8888        self._notebook.remove_page(index)
    8989
    class Toolbox(gtk.VBox): 
    9696
    9797    def get_current_toolbar(self):
    9898        return self._notebook.get_current_page()
    99    
     99
    100100    current_toolbar = property(get_current_toolbar, set_current_toolbar)
    101101
  • src/sugar/graphics/toolbutton.py

    diff --git a/src/sugar/graphics/toolbutton.py b/src/sugar/graphics/toolbutton.py
    index 6205b8a..91cca17 100644
    a b class ToolButton(gtk.ToolButton): 
    129129
    130130    def get_palette_invoker(self):
    131131        return self._palette_invoker
    132    
     132
    133133    def set_palette_invoker(self, palette_invoker):
    134134        self._palette_invoker.detach()
    135135        self._palette_invoker = palette_invoker
    class ToolButton(gtk.ToolButton): 
    151151                                  allocation.width, allocation.height)
    152152
    153153        gtk.ToolButton.do_expose_event(self, event)
    154    
     154
    155155    def __button_clicked_cb(self, widget):
    156156        if self.palette:
    157157            self.palette.popdown(True)
  • src/sugar/graphics/tray.py

    diff --git a/src/sugar/graphics/tray.py b/src/sugar/graphics/tray.py
    index 5df7170..8b0abe7 100644
    a b class _TrayViewport(gtk.Viewport): 
    6464            adj = self.get_vadjustment()
    6565        adj.connect('changed', self._adjustment_changed_cb)
    6666        adj.connect('value-changed', self._adjustment_changed_cb)
    67            
     67
    6868    def scroll(self, direction):
    6969        if direction == _PREVIOUS_PAGE:
    7070            self._scroll_previous()
    class TrayIcon(gtk.ToolItem): 
    447447
    448448    def get_palette_invoker(self):
    449449        return self._palette_invoker
    450    
     450
    451451    def set_palette_invoker(self, palette_invoker):
    452452        self._palette_invoker.detach()
    453453        self._palette_invoker = palette_invoker
  • src/sugar/graphics/window.py

    diff --git a/src/sugar/graphics/window.py b/src/sugar/graphics/window.py
    index 9d6a6aa..ef9afd7 100644
    a b from sugar.graphics.icon import Icon 
    2626
    2727_UNFULLSCREEN_BUTTON_VISIBILITY_TIMEOUT = 2
    2828
     29
    2930class UnfullscreenButton(gtk.Window):
    3031
    3132    def __init__(self):
    class UnfullscreenButton(gtk.Window): 
    7576    def _screen_size_changed_cb(self, screen):
    7677        self._reposition()
    7778
     79
    7880class Window(gtk.Window):
     81
    7982    def __init__(self, **args):
    8083        self._enable_fullscreen_mode = True
    8184
    class Window(gtk.Window): 
    8992        self._alerts = []
    9093        self._canvas = None
    9194        self.tray = None
    92        
     95
    9396        self._vbox = gtk.VBox()
    9497        self._hbox = gtk.HBox()
    9598        self._vbox.pack_start(self._hbox)
    class Window(gtk.Window): 
    98101        self._event_box = gtk.EventBox()
    99102        self._hbox.pack_start(self._event_box)
    100103        self._event_box.show()
    101         self._event_box.add_events(gtk.gdk.POINTER_MOTION_HINT_MASK | gtk.gdk.POINTER_MOTION_MASK)
    102         self._event_box.connect('motion-notify-event', self.__motion_notify_cb)
     104        self._event_box.add_events(
     105            gtk.gdk.POINTER_MOTION_HINT_MASK | gtk.gdk.POINTER_MOTION_MASK)
     106        self._event_box.connect('motion-notify-event',
     107            self.__motion_notify_cb)
    103108
    104109        self.add(self._vbox)
    105110        self._vbox.show()
    class Window(gtk.Window): 
    117122
    118123        if canvas:
    119124            self._event_box.add(canvas)
    120        
     125
    121126        self._canvas = canvas
    122127
    123128    def get_canvas(self):
    class Window(gtk.Window): 
    128133    def set_toolbox(self, toolbox):
    129134        if self.toolbox:
    130135            self._vbox.remove(self.toolbox)
    131            
     136
    132137        self._vbox.pack_start(toolbox, False)
    133138        self._vbox.reorder_child(toolbox, 0)
    134        
     139
    135140        self.toolbox = toolbox
    136141
    137142    def set_tray(self, tray, position):
    138143        if self.tray:
    139             box = self.tray.get_parent() 
     144            box = self.tray.get_parent()
    140145            box.remove(self.tray)
    141                
     146
    142147        if position == gtk.POS_LEFT:
    143148            self._hbox.pack_start(tray, False)
    144149        elif position == gtk.POS_RIGHT:
    145150            self._hbox.pack_end(tray, False)
    146151        elif position == gtk.POS_BOTTOM:
    147152            self._vbox.pack_end(tray, False)
    148                    
     153
    149154        self.tray = tray
    150155
    151156    def add_alert(self, alert):
    class Window(gtk.Window): 
    154159            self._vbox.pack_start(alert, False)
    155160            if self.toolbox is not None:
    156161                self._vbox.reorder_child(alert, 1)
    157             else:   
     162            else:
    158163                self._vbox.reorder_child(alert, 0)
    159                
     164
    160165    def remove_alert(self, alert):
    161166        if alert in self._alerts:
    162167            self._alerts.remove(alert)
    163168            # if the alert is the visible one on top of the queue
    164             if alert.get_parent() is not None:                           
     169            if alert.get_parent() is not None:
    165170                self._vbox.remove(alert)
    166171                if len(self._alerts) >= 1:
    167172                    self._vbox.pack_start(self._alerts[0], False)
    class Window(gtk.Window): 
    169174                        self._vbox.reorder_child(self._alerts[0], 1)
    170175                    else:
    171176                        self._vbox.reorder_child(self._alert[0], 0)
    172                    
     177
    173178    def __window_realize_cb(self, window):
    174179        group = gtk.Window()
    175180        group.realize()
    class Window(gtk.Window): 
    255260        return self._enable_fullscreen_mode
    256261
    257262    enable_fullscreen_mode = gobject.property(type=object,
    258                                               setter=set_enable_fullscreen_mode,
    259                                               getter=get_enable_fullscreen_mode)
    260 
     263        setter=set_enable_fullscreen_mode,
     264        getter=get_enable_fullscreen_mode)
  • src/sugar/network.py

    diff --git a/src/sugar/network.py b/src/sugar/network.py
    index 0e25d73..834bd0f 100644
    a b import SocketServer 
    3131
    3232__authinfos = {}
    3333
     34
    3435def _add_authinfo(authinfo):
    3536    __authinfos[threading.currentThread()] = authinfo
    3637
     38
    3739def get_authinfo():
    3840    return __authinfos.get(threading.currentThread())
    3941
     42
    4043def _del_authinfo():
    4144    del __authinfos[threading.currentThread()]
    4245
    class ChunkedGlibHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): 
    124127            self.wfile.flush()
    125128        self.wfile.close()
    126129        self.rfile.close()
    127        
     130
    128131    def finish(self):
    129132        """Close the sockets when we're done, not before"""
    130133        pass
    class ChunkedGlibHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): 
    172175        self.end_headers()
    173176        return f
    174177
     178
    175179class GlibURLDownloader(gobject.GObject):
    176180    """Grabs a URL in chunks, returning to the mainloop after each chunk"""
    177181
    class GlibURLDownloader(gobject.GObject): 
    237241        self.cleanup(remove=True)
    238242
    239243    def _get_filename_from_headers(self, headers):
    240         if not headers.has_key("Content-Disposition"):
     244        if "Content-Disposition" not in headers:
    241245            return None
    242246
    243247        ftag = "filename="
  • src/sugar/presence/__init__.py

    diff --git a/src/sugar/presence/__init__.py b/src/sugar/presence/__init__.py
    index 1136c19..9756612 100644
    a b  
    1919
    2020Provides a simplified API for accessing the dbus service
    2121which coordinates native network presence and sharing
    22 information.  This includes both "buddies" and "shared 
     22information.  This includes both "buddies" and "shared
    2323activities".
    2424"""
  • src/sugar/presence/activity.py

    diff --git a/src/sugar/presence/activity.py b/src/sugar/presence/activity.py
    index 13abf5d..3102388 100644
    a b _logger = logging.getLogger('sugar.presence.activity') 
    3030
    3131class Activity(gobject.GObject):
    3232    """UI interface for an Activity in the presence service
    33    
     33
    3434    Activities in the presence service represent your and other user's
    3535    shared activities.
    36    
     36
    3737    Properties:
    38         id 
    39         color 
    40         name 
    41         type 
    42         joined 
     38        id
     39        color
     40        name
     41        type
     42        joined
    4343    """
    4444    __gsignals__ = {
    4545        'buddy-joined': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE,
    class Activity(gobject.GObject): 
    7474        self._ps_del_object = del_obj_cb
    7575        bobj = bus.get_object(self._PRESENCE_SERVICE, object_path)
    7676        self._activity = dbus.Interface(bobj, self._ACTIVITY_DBUS_INTERFACE)
    77         self._activity.connect_to_signal('BuddyHandleJoined', 
     77        self._activity.connect_to_signal('BuddyHandleJoined',
    7878                                         self._buddy_handle_joined_cb)
    7979        self._activity.connect_to_signal('BuddyLeft',
    8080                                         self._buddy_left_cb)
    class Activity(gobject.GObject): 
    211211
    212212    def _emit_buddy_left_signal(self, object_path):
    213213        """Generate buddy-left GObject signal with presence Buddy object
    214        
     214
    215215        XXX note use of _ps_new_object instead of _ps_del_object here
    216216        """
    217217        self.emit('buddy-left', self._ps_new_object(object_path))
    class Activity(gobject.GObject): 
    225225            self._handle_to_buddy_path.pop(handle, None)
    226226
    227227    def _emit_new_channel_signal(self, object_path):
    228         """Generate new-channel GObject signal with channel object path 
    229        
     228        """Generate new-channel GObject signal with channel object path
     229
    230230        New telepathy-python communications channel has been opened
    231231        """
    232232        self.emit('new-channel', object_path)
    class Activity(gobject.GObject): 
    255255
    256256    def get_buddy_by_handle(self, handle):
    257257        """Retrieve the Buddy object given a telepathy handle.
    258        
     258
    259259        buddy object paths are cached in self._handle_to_buddy_path,
    260260        so we can get the buddy without calling PS.
    261261        """
    class Activity(gobject.GObject): 
    378378    # GetChannels() wrapper
    379379
    380380    def get_channels(self):
    381         """Retrieve communications channel descriptions for the activity 
    382        
     381        """Retrieve communications channel descriptions for the activity
     382
    383383        Returns a tuple containing:
    384384            - the D-Bus well-known service name of the connection
    385385              (FIXME: this is redundant; in Telepathy it can be derived
  • src/sugar/presence/buddy.py

    diff --git a/src/sugar/presence/buddy.py b/src/sugar/presence/buddy.py
    index fab23d2..e08307d 100644
    a b import dbus 
    2626
    2727class Buddy(gobject.GObject):
    2828    """UI interface for a Buddy in the presence service
    29    
     29
    3030    Each buddy interface tracks a set of activities and properties
    31     that can be queried to provide UI controls for manipulating 
     31    that can be queried to provide UI controls for manipulating
    3232    the presence interface.
    33    
     33
    3434    Properties Dictionary:
    35         'key': public key, 
    36         'nick': nickname , 
    37         'color': color (XXX what format), 
    38         'current-activity': (XXX dbus path?), 
    39         'owner': (XXX dbus path?), 
     35        'key': public key,
     36        'nick': nickname ,
     37        'color': color (XXX what format),
     38        'current-activity': (XXX dbus path?),
     39        'owner': (XXX dbus path?),
    4040        'icon': (XXX pixel data for an icon?)
    4141    See __gproperties__
    4242    """
    class Buddy(gobject.GObject): 
    6666
    6767    def __init__(self, bus, new_obj_cb, del_obj_cb, object_path):
    6868        """Initialise the reference to the buddy
    69        
    70         bus -- dbus bus object 
    71         new_obj_cb -- callback to call when this buddy joins an activity 
    72         del_obj_cb -- callback to call when this buddy leaves an activity 
    73         object_path -- path to the buddy object 
     69
     70        bus -- dbus bus object
     71        new_obj_cb -- callback to call when this buddy joins an activity
     72        del_obj_cb -- callback to call when this buddy leaves an activity
     73        object_path -- path to the buddy object
    7474        """
    7575        gobject.GObject.__init__(self)
    7676        self._object_path = object_path
    class Buddy(gobject.GObject): 
    103103        self._joined_activity_signal.remove()
    104104        self._left_activity_signal.remove()
    105105        self._property_changed_signal.remove()
    106        
     106
    107107    def _get_properties_helper(self):
    108108        """Retrieve the Buddy's property dictionary from the service object
    109109        """
    class Buddy(gobject.GObject): 
    113113        return props
    114114
    115115    def do_get_property(self, pspec):
    116         """Retrieve a particular property from our property dictionary 
    117        
     116        """Retrieve a particular property from our property dictionary
     117
    118118        pspec -- XXX some sort of GTK specifier object with attributes
    119119            including 'name', 'active' and 'icon-name'
    120120        """
    class Buddy(gobject.GObject): 
    167167
    168168    def _joined_activity_cb(self, object_path):
    169169        """Handle dbus signal by emitting a GObject signal
    170        
     170
    171171        Stores the activity in activities dictionary as well
    172172        """
    173173        if not self._activities.has_key(object_path):
    class Buddy(gobject.GObject): 
    176176
    177177    def _emit_left_activity_signal(self, object_path):
    178178        """Emit activity left signal with Activity object
    179        
     179
    180180        XXX this calls self._ps_new_object instead of self._ps_del_object,
    181181            which would seem to be the incorrect callback?
    182182        """
    class Buddy(gobject.GObject): 
    185185
    186186    def _left_activity_cb(self, object_path):
    187187        """Handle dbus signal by emitting a GObject signal
    188        
     188
    189189        Also removes from the activities dictionary
    190190        """
    191191        if self._activities.has_key(object_path):
    class Buddy(gobject.GObject): 
    193193        gobject.idle_add(self._emit_left_activity_signal, object_path)
    194194
    195195    def _handle_property_changed_signal(self, prop_list):
    196         """Emit property-changed signal with property dictionary 
    197        
    198         Generates a property-changed signal with the results of 
     196        """Emit property-changed signal with property dictionary
     197
     198        Generates a property-changed signal with the results of
    199199        _get_properties_helper()
    200200        """
    201201        self._properties = self._get_properties_helper()
    class Buddy(gobject.GObject): 
    209209
    210210    def get_icon_pixbuf(self):
    211211        """Retrieve Buddy's icon as a GTK pixel buffer
    212        
     212
    213213        XXX Why aren't the icons coming in as SVG?
    214214        """
    215215        if self.props.icon and len(self.props.icon):
    class Buddy(gobject.GObject): 
    221221            return None
    222222
    223223    def get_joined_activities(self):
    224         """Retrieve the set of all activities which this buddy has joined 
    225        
    226         Uses the GetJoinedActivities method on the service 
    227         object to produce object paths, wraps each in an 
    228         Activity object. 
    229        
     224        """Retrieve the set of all activities which this buddy has joined
     225
     226        Uses the GetJoinedActivities method on the service
     227        object to produce object paths, wraps each in an
     228        Activity object.
     229
    230230        returns list of presence Activity objects
    231231        """
    232232        try:
  • src/sugar/presence/presenceservice.py

    diff --git a/src/sugar/presence/presenceservice.py b/src/sugar/presence/presenceservice.py
    index a7fd1a4..ddd4967 100644
    a b _logger = logging.getLogger('sugar.presence.presenceservice') 
    4040
    4141
    4242class PresenceService(gobject.GObject):
    43     """UI-side interface to the dbus presence service 
    44    
     43    """UI-side interface to the dbus presence service
     44
    4545    This class provides UI programmers with simplified access
    4646    to the dbus service of the same name.  It allows for observing
    4747    various events from the presence service as GObject events,
    class PresenceService(gobject.GObject): 
    6868
    6969    _PS_BUDDY_OP = DBUS_PATH + "/Buddies/"
    7070    _PS_ACTIVITY_OP = DBUS_PATH + "/Activities/"
    71    
     71
    7272
    7373    def __init__(self, allow_offline_iface=True):
    7474        """Initialise the service and attempt to connect to events
    class PresenceService(gobject.GObject): 
    9999
    100100    _ps_ = None
    101101    def _get_ps(self):
    102         """Retrieve dbus interface to PresenceService 
    103        
    104         Also registers for updates from various dbus events on the 
     102        """Retrieve dbus interface to PresenceService
     103
     104        Also registers for updates from various dbus events on the
    105105        interface.
    106        
    107         If unable to retrieve the interface, we will temporarily 
    108         return an _OfflineInterface object to allow the calling 
    109         code to continue functioning as though it had accessed a 
     106
     107        If unable to retrieve the interface, we will temporarily
     108        return an _OfflineInterface object to allow the calling
     109        code to continue functioning as though it had accessed a
    110110        real presence service.
    111        
    112         If successful, caches the presence service interface 
     111
     112        If successful, caches the presence service interface
    113113        for use by other methods and returns that interface
    114114        """
    115115        if not self._ps_:
    116116            try:
    117117                # NOTE: We need to follow_name_owner_changes here
    118                 #       because we can not connect to a signal unless 
     118                #       because we can not connect to a signal unless
    119119                #       we follow the changes or we start the service
    120120                #       before we connect.  Starting the service here
    121121                #       causes a major bottleneck during startup
    122122                ps = dbus.Interface(
    123123                    self._bus.get_object(DBUS_SERVICE,
    124124                                         DBUS_PATH,
    125                                          follow_name_owner_changes=True), 
     125                                         follow_name_owner_changes=True),
    126126                    DBUS_INTERFACE
    127127                )
    128128            except dbus.exceptions.DBusException, err:
    class PresenceService(gobject.GObject): 
    135135                    return _OfflineInterface()
    136136                raise RuntimeError("Failed to connect to the presence service.")
    137137            else:
    138                 self._ps_ = ps 
     138                self._ps_ = ps
    139139                ps.connect_to_signal('BuddyAppeared',
    140140                                     self._buddy_appeared_cb)
    141141                ps.connect_to_signal('BuddyDisappeared',
    class PresenceService(gobject.GObject): 
    149149                ps.connect_to_signal('PrivateInvitation',
    150150                                     self._private_invitation_cb)
    151151        return self._ps_
    152        
     152
    153153    _ps = property(
    154154        _get_ps, None, None,
    155155        """DBUS interface to the PresenceService
    class PresenceService(gobject.GObject): 
    158158
    159159    def _new_object(self, object_path):
    160160        """Turn new object path into (cached) Buddy/Activity instance
    161        
     161
    162162        object_path -- full dbus path of the new object, must be
    163163            prefixed with either of _PS_BUDDY_OP or _PS_ACTIVITY_OP
    164        
     164
    165165        Note that this method is called throughout the class whenever
    166         the representation of the object is required, it is not only 
     166        the representation of the object is required, it is not only
    167167        called when the object is first discovered.  The point is to only have
    168168        _one_ Python object for any D-Bus object represented by an object path,
    169169        effectively wrapping the D-Bus object in a single Python GObject.
    170        
     170
    171171        returns presence Buddy or Activity representation
    172172        """
    173173        obj = None
    class PresenceService(gobject.GObject): 
    225225            # we could use a LRU cache limited to some value.
    226226            del self._objcache[object_path]
    227227            obj.destroy()
    228            
     228
    229229        return False
    230230
    231231    def _buddy_disappeared_cb(self, object_path):
    class PresenceService(gobject.GObject): 
    282282
    283283    def get_activities(self):
    284284        """Retrieve set of all activities from service
    285        
     285
    286286        returns list of Activity objects for all object paths
    287287            the service reports exist (using GetActivities)
    288288        """
    class PresenceService(gobject.GObject): 
    317317            )
    318318
    319319    def get_activities_async(self, reply_handler=None, error_handler=None):
    320         """Retrieve set of all activities from service asyncronously 
     320        """Retrieve set of all activities from service asyncronously
    321321        """
    322322
    323323        if not reply_handler:
    324324            logging.error('Function get_activities_async called without' \
    325                           'a reply handler. Can not run.') 
     325                          'a reply handler. Can not run.')
    326326            return
    327327
    328328        self._ps.GetActivities(
    class PresenceService(gobject.GObject): 
    351351
    352352    def get_buddies(self):
    353353        """Retrieve set of all buddies from service
    354        
     354
    355355        returns list of Buddy objects for all object paths
    356356            the service reports exist (using GetBuddies)
    357357        """
    class PresenceService(gobject.GObject): 
    386386            )
    387387
    388388    def get_buddies_async(self, reply_handler=None, error_handler=None):
    389         """Retrieve set of all buddies from service asyncronously 
     389        """Retrieve set of all buddies from service asyncronously
    390390        """
    391391
    392392        if not reply_handler:
    393393            logging.error('Function get_buddies_async called without' \
    394                           'a reply handler. Can not run.') 
     394                          'a reply handler. Can not run.')
    395395            return
    396396
    397397        self._ps.GetBuddies(
    class PresenceService(gobject.GObject): 
    402402
    403403    def get_buddy(self, key):
    404404        """Retrieve single Buddy object for the given public key
    405        
     405
    406406        key -- buddy's public encryption key
    407        
    408         returns single Buddy object or None if the activity 
    409             is not found using GetBuddyByPublicKey on the 
     407
     408        returns single Buddy object or None if the activity
     409            is not found using GetBuddyByPublicKey on the
    410410            service
    411411        """
    412412        try:
    class PresenceService(gobject.GObject): 
    479479
    480480    def share_activity(self, activity, properties=None, private=True):
    481481        """Ask presence service to ask the activity to share itself publicly.
    482        
    483         Uses the AdvertiseActivity method on the service to ask for the 
    484         sharing of the given activity.  Arranges to emit activity-shared 
     482
     483        Uses the AdvertiseActivity method on the service to ask for the
     484        sharing of the given activity.  Arranges to emit activity-shared
    485485        event with:
    486        
     486
    487487            (success, Activity, err)
    488        
     488
    489489        on success/failure.
    490        
     490
    491491        returns None
    492492        """
    493493        actid = activity.get_id()
    class PresenceService(gobject.GObject): 
    528528
    529529class _OfflineInterface( object ):
    530530    """Offline-presence-service interface
    531    
     531
    532532    Used to mimic the behaviour of a real PresenceService sufficiently
    533533    to avoid crashing client code that expects the given interface.
    534    
    535     XXX we could likely return a "MockOwner" object reasonably 
     534
     535    XXX we could likely return a "MockOwner" object reasonably
    536536    easily, but would it be worth it?
    537537    """
    538538    def raiseException( self, *args, **named ):
    539539        """Raise dbus.exceptions.DBusException"""
    540         raise dbus.exceptions.DBusException( 
     540        raise dbus.exceptions.DBusException(
    541541            """PresenceService Interface not available"""
    542542        )
    543543    GetActivities = raiseException
    class _OfflineInterface( object ): 
    546546    GetBuddyByPublicKey = raiseException
    547547    GetOwner = raiseException
    548548    GetPreferredConnection = raiseException
    549     def ShareActivity( 
     549    def ShareActivity(
    550550        self, actid, atype, name, properties,
    551551        reply_handler, error_handler,
    552552    ):
    class _OfflineInterface( object ): 
    559559
    560560class _MockPresenceService(gobject.GObject):
    561561    """Test fixture allowing testing of items that use PresenceService
    562    
     562
    563563    See PresenceService for usage and purpose
    564564    """
    565565    __gsignals__ = {
  • src/sugar/profile.py

    diff --git a/src/sugar/profile.py b/src/sugar/profile.py
    index 6e5a1bf..339d5aa 100644
    a b from sugar import env 
    2929from sugar import util
    3030from sugar.graphics.xocolor import XoColor
    3131
     32
    3233_profile = None
    3334
     35
    3436class Profile(object):
    3537    """Local user's current options/profile information
    36    
    37     User settings were previously stored in an INI-style 
    38     configuration file. We moved to gconf now. The deprected 
     38
     39    User settings were previously stored in an INI-style
     40    configuration file. We moved to gconf now. The deprected
    3941    API is kept around to not break activities still using it.
    4042
    4143    The profile is also responsible for loading the user's
    4244    public and private ssh keys from disk.
    43    
     45
    4446    Attributes:
    45        
     47
    4648        pubkey -- public ssh key
    47         privkey_hash -- SHA has of the child's public key 
     49        privkey_hash -- SHA has of the child's public key
    4850    """
     51
    4952    def __init__(self, path):
    5053        self._pubkey = None
    5154        self._privkey_hash = None
    class Profile(object): 
    138141            client.set_string("/desktop/sugar/user/color", color)
    139142        if cp.has_option('Jabber', 'Server'):
    140143            server = cp.get('Jabber', 'Server')
    141             client.set_string("/desktop/sugar/collaboration/jabber_server", 
     144            client.set_string("/desktop/sugar/collaboration/jabber_server",
    142145                              server)
    143146        if cp.has_option('Date', 'Timezone'):
    144147            timezone = cp.get('Date', 'Timezone')
    class Profile(object): 
    165168                client.set_bool("/desktop/sugar/power/extreme", True)
    166169        if cp.has_option('Shell', 'FavoritesLayout'):
    167170            layout = cp.get('Shell', 'FavoritesLayout')
    168             client.set_string("/desktop/sugar/desktop/favorites_layout", 
     171            client.set_string("/desktop/sugar/desktop/favorites_layout",
    169172                              layout)
    170173        del cp
    171174        try:
    class Profile(object): 
    191194            '#export SUGAR_LOGGER_LEVEL=debug\n\n' \
    192195            '# Uncomment the following line to enable core dumps\n' \
    193196            '#ulimit -c unlimited\n'
    194         fd.write(text)       
     197        fd.write(text)
    195198        fd.close()
    196199
     200
    197201def get_profile():
    198202    global _profile
    199203
    def get_profile(): 
    203207
    204208    return _profile
    205209
     210
    206211def get_nick_name():
    207212    client = gconf.client_get_default()
    208     return client.get_string("/desktop/sugar/user/nick")   
     213    return client.get_string("/desktop/sugar/user/nick")
     214
    209215
    210216def get_color():
    211217    client = gconf.client_get_default()
    212     color = client.get_string("/desktop/sugar/user/color")   
     218    color = client.get_string("/desktop/sugar/user/color")
    213219    return XoColor(color)
    214220
     221
    215222def get_pubkey():
    216223    return get_profile().pubkey
  • src/sugar/session.py

    diff --git a/src/sugar/session.py b/src/sugar/session.py
    index 0978be8..4ebc590 100644
    a b import os 
    2323
    2424from sugar import _sugarext
    2525
     26
    2627class XSMPClient(_sugarext.SMClientXSMP):
     28
    2729    def __init__(self):
    2830        _sugarext.SMClientXSMP.__init__(self)
    2931
     32
    3033class SessionManager(object):
     34
    3135    def __init__(self):
    3236        address = _sugarext.xsmp_init()
    3337        os.environ['SESSION_MANAGER'] = address
  • src/sugar/util.py

    diff --git a/src/sugar/util.py b/src/sugar/util.py
    index 26bbe83..00c7a14 100644
    a b import logging 
    3131import atexit
    3232import traceback
    3333
     34ACTIVITY_ID_LEN = 40
     35
     36
    3437_ = lambda msg: gettext.dgettext('sugar-toolkit', msg)
    3538
     39
    3640def printable_hash(in_hash):
    3741    """Convert binary hash data into printable characters."""
    3842    printable = ""
    def printable_hash(in_hash): 
    4044        printable = printable + binascii.b2a_hex(char)
    4145    return printable
    4246
     47
    4348def sha_data(data):
    4449    """sha1 hash some bytes."""
    4550    sha_hash = hashlib.sha1()
    4651    sha_hash.update(data)
    4752    return sha_hash.digest()
    4853
     54
    4955def unique_id(data = ''):
    5056    """Generate a likely-unique ID for whatever purpose
    51    
     57
    5258    data -- suffix appended to working data before hashing
    53    
     59
    5460    Returns a 40-character string with hexidecimal digits
    55     representing an SHA hash of the time, a random digit 
     61    representing an SHA hash of the time, a random digit
    5662    within a constrained range and the data passed.
    57    
    58     Note: these are *not* crypotographically secure or 
    59         globally unique identifiers.  While they are likely 
    60         to be unique-enough, no attempt is made to make 
     63
     64    Note: these are *not* crypotographically secure or
     65        globally unique identifiers.  While they are likely
     66        to be unique-enough, no attempt is made to make
    6167        perfectly unique values.
    6268    """
    6369    data_string = "%s%s%s" % (time.time(), random.randint(10000, 100000), data)
    6470    return printable_hash(sha_data(data_string))
    6571
    6672
    67 ACTIVITY_ID_LEN = 40
    68 
    6973def is_hex(s):
    7074    try:
    7175        int(s, 16)
    7276    except ValueError:
    7377        return False
    7478
    75     return True
     79    return True
     80
    7681
    7782def validate_activity_id(actid):
    7883    """Validate an activity ID."""
    def validate_activity_id(actid): 
    8489        return False
    8590    return True
    8691
     92
    8793def set_proc_title(title):
    8894    """Sets the process title so ps and top show more
    8995       descriptive names.  This does not modify argv[0]
    9096       and only the first 15 characters will be shown.
    9197
    9298       title -- the title you wish to change the process
    93                 title to 
     99                title to
    94100
    95101       Returns True on success.  We don't raise exceptions
    96102       because if something goes wrong here it is not a big
    def set_proc_title(title): 
    106112    except Exception:
    107113        return False
    108114
     115
    109116class Node(object):
     117
    110118    __slots__ = ['prev', 'next', 'me']
     119
    111120    def __init__(self, prev, me):
    112121        self.prev = prev
    113122        self.me = me
    114123        self.next = None
    115124
     125
    116126class LRU:
    117127    """
    118128    Implementation of a length-limited O(1) LRU queue.
    class LRU: 
    120130    http://pype.sourceforge.net
    121131    Copyright 2003 Josiah Carlson.
    122132    """
     133
    123134    # pylint: disable-msg=W0102,W0612
    124135    def __init__(self, count, pairs=[]):
    125136        self.count = max(count, 1)
    class LRU: 
    128139        self.last = None
    129140        for key, value in pairs:
    130141            self[key] = value
     142
    131143    def __contains__(self, obj):
    132144        return obj in self.d
     145
    133146    def __getitem__(self, obj):
    134147        a = self.d[obj].me
    135148        self[a[0]] = a[1]
    136149        return a[1]
     150
    137151    def __setitem__(self, obj, val):
    138152        if obj in self.d:
    139153            del self[obj]
    class LRU: 
    155169            a.next = None
    156170            del self.d[a.me[0]]
    157171            del a
     172
    158173    def __delitem__(self, obj):
    159174        nobj = self.d[obj]
    160175        if nobj.prev:
    class LRU: 
    166181        else:
    167182            self.last = nobj.prev
    168183        del self.d[obj]
     184
    169185    def __iter__(self):
    170186        cur = self.first
    171187        while cur != None:
    172188            cur2 = cur.next
    173189            yield cur.me[1]
    174190            cur = cur2
     191
    175192    def iteritems(self):
    176193        cur = self.first
    177194        while cur != None:
    178195            cur2 = cur.next
    179196            yield cur.me
    180197            cur = cur2
     198
    181199    def iterkeys(self):
    182200        return iter(self.d)
     201
    183202    def itervalues(self):
    184203        for i, j in self.iteritems():
    185204            yield j
     205
    186206    def keys(self):
    187207        return self.d.keys()
    188208
     209
    189210units = [['%d year',   '%d years',   356 * 24 * 60 * 60],
    190211         ['%d month',  '%d months',  30 * 24 * 60 * 60],
    191212         ['%d week',   '%d weeks',   7 * 24 * 60 * 60],
    NOW = _('Seconds ago') 
    203224# "[2 minutes] in the past", or "[3 years, 1 month] earlier"
    204225ELAPSED = _('%s ago')
    205226
    206 # Explanation of the following hack:
    207 # The xgettext utility extracts plural forms by reading the strings included as
    208 # parameters of ngettext(). As our plurals are not passed to ngettext()
    209 # straight away because there needs to be a calculation before we know which
    210 # strings need to be used, then we need to call ngettext() in a fake way so
    211 # xgettext will pick them up as plurals.
    212227
    213228def ngettext(singular, plural, n):
     229    # Explanation of this hack:
     230    # The xgettext utility extracts plural forms by reading the strings
     231    # included as parameters of ngettext(). As our plurals are not passed to
     232    # ngettext() straight away because there needs to be a calculation before
     233    # we know which strings need to be used, then we need to call ngettext()
     234    # in a fake way so xgettext will pick them up as plurals.
    214235    pass
    215236
     237
    216238# TRANS: Relative dates (eg. 1 month and 5 days).
    217239ngettext('%d year',   '%d years',   1)
    218240ngettext('%d month',  '%d months',  1)
    del ngettext 
    228250# gettext perfs hack (#7959)
    229251_i18n_timestamps_cache = LRU(60)
    230252
     253
    231254def timestamp_to_elapsed_string(timestamp, max_levels=2):
    232255    levels = 0
    233256    time_period = ''
    def timestamp_to_elapsed_string(timestamp, max_levels=2): 
    265288
    266289    return ELAPSED % time_period
    267290
     291
    268292_tracked_paths = {}
    269293
     294
    270295class TempFilePath(str):
     296
    271297    def __new__(cls, path=None):
    272298        if path is None:
    273299            fd, path = tempfile.mkstemp()
    class TempFilePath(str): 
    284310    def __del__(self):
    285311        if _tracked_paths[self] == 1:
    286312            del _tracked_paths[self]
    287            
     313
    288314            if os.path.exists(self):
    289315                os.unlink(self)
    290316                logging.debug('TempFilePath deleted %r' % self)
    class TempFilePath(str): 
    293319        else:
    294320            _tracked_paths[self] -= 1
    295321
     322
    296323def _cleanup_temp_files():
    297324    logging.debug('_cleanup_temp_files')
    298325    for path in _tracked_paths.keys():
    def _cleanup_temp_files(): 
    301328        except:
    302329            logging.error(traceback.format_exc())
    303330
    304 atexit.register(_cleanup_temp_files)
    305331
     332atexit.register(_cleanup_temp_files)
  • src/sugar/wm.py

    diff --git a/src/sugar/wm.py b/src/sugar/wm.py
    index 4ec9a12..d813d94 100644
    a b  
    1616# Boston, MA 02111-1307, USA.
    1717
    1818"""
    19 UNSTABLE. Used only internally by Activity and jarabe. 
     19UNSTABLE. Used only internally by Activity and jarabe.
    2020"""
    2121
    2222import gtk
    2323
     24
    2425def get_activity_id(wnck_window):
    2526    window = gtk.gdk.window_foreign_new(wnck_window.get_xid())
    2627    prop_info = window.property_get('_SUGAR_ACTIVITY_ID', 'STRING')
    def get_activity_id(wnck_window): 
    2930    else:
    3031        return prop_info[2]
    3132
     33
    3234def get_bundle_id(wnck_window):
    3335    window = gtk.gdk.window_foreign_new(wnck_window.get_xid())
    3436    prop_info = window.property_get('_SUGAR_BUNDLE_ID', 'STRING')
    def get_bundle_id(wnck_window): 
    3739    else:
    3840        return prop_info[2]
    3941
     42
    4043def set_activity_id(window, activity_id):
    4144    window.property_change('_SUGAR_ACTIVITY_ID', 'STRING', 8,
    4245                           gtk.gdk.PROP_MODE_REPLACE, activity_id)
    4346
     47
    4448def set_bundle_id(window, bundle_id):
    4549    window.property_change('_SUGAR_BUNDLE_ID', 'STRING', 8,
    4650                           gtk.gdk.PROP_MODE_REPLACE, bundle_id)