Пример #1
0
    def __init__(self, nickname, properties=None):
        """
        Initializes a player.

        @param nickname: The players name.
        @param properties: A list containing features.
        """
        gobject.GObject.__init__(self)
        self._logger = logging.getLogger('player.' + nickname)
        self._logger.setLevel(constants.LOG_LEVEL)

        # players properties
        self.nickname = nickname
        self.position = Point(0,0)
        self.trace = dict()

        # set colors of the current player as default
        self.color_fill = profile.get_color().get_fill_color()
        self.color_stroke = profile.get_color().get_stroke_color()

        # the players features
        if properties is None:
            self.feature_collection = geojson.FeatureCollection(features=list())
        else:
            self.feature_collection = geojson.FeatureCollection(features=properties)
Пример #2
0
    def __init__(self, handle):
        """ Initialize the toolbars and the game board """
        super(PathsActivity, self).__init__(handle)
        self.nick = profile.get_nick_name()
        if profile.get_color() is not None:
            self.colors = profile.get_color().to_string().split(',')
        else:
            self.colors = ['#A0FFA0', '#FF8080']

        self._setup_toolbars(_have_toolbox)
        self._setup_dispatch_table()

        # Create a canvas
        canvas = gtk.DrawingArea()
        canvas.set_size_request(gtk.gdk.screen_width(), \
                                gtk.gdk.screen_height())
        self.set_canvas(canvas)
        canvas.show()
        self.show_all()

        self._game = Game(canvas, parent=self, colors=self.colors)
        self._setup_presence_service()

        # Restore game state from Journal or start new game
        if 'deck' in self.metadata:
            self._restore()
        else:
            self._game.new_game()
Пример #3
0
    def __init__(self, handle):
        ''' Initiate activity. '''
        super(FractionBounceActivity, self).__init__(handle)

        self.nick = profile.get_nick_name()
        if profile.get_color() is not None:
            self.colors = profile.get_color().to_string().split(',')
        else:
            self.colors = ['#A0FFA0', '#FF8080']

        self.add_events(gtk.gdk.VISIBILITY_NOTIFY_MASK)
        self.connect('visibility-notify-event', self.__visibility_notify_cb)

        self.max_participants = 4  # sharing

        self._setup_toolbars()
        self._setup_dispatch_table()
        canvas = self._setup_canvas()

        # Read any custom fractions from the project metadata
        if 'custom' in self.metadata:
            custom = self.metadata['custom']
        else:
            custom = None

        # Initialize the canvas
        self.bounce_window = Bounce(canvas, activity.get_bundle_path(), self)

        # Restore any custom fractions
        if custom is not None:
            fractions = custom.split(',')
            for f in fractions:
                self.bounce_window.add_fraction(f)

        self._setup_presence_service()
Пример #4
0
    def set_toggled(self, button, category):
        """
        Switches the empty Button and the tagged category button clicked.
        Also, sets the appropriate liststore for the combobox.

        @param button: Toggled button (can be omittted).
        @param category: The corresponding category to set.
        """
        self._logger.debug("set_toggled()")

        self.toggled = category

        # set liststore
        combo = self.toolbar.combobox
        combo.set_model(self.toolbar.description_sets[category])

        color_fill = profile.get_color().get_fill_color()
        color_stroke = profile.get_color().get_stroke_color()

#        self._logger.debug("storage type: %s", self.selected.get_property("storage-type"))
        self._set_selected(get_gtkimage_from_plugin(category,
                                                    color_stroke,
                                                    color_fill,
                                                    self.IMG_SIZE))
        combo.queue_draw()
Пример #5
0
    def reset_toggled(self, button):
        """
        Resets toggled property and combobox liststore.

        @param button: The reset button (can be omitted by passing None).
        @note: If a tag was selected within the L{geotagmodel.GeotagModel},
        the tag will be deleted.
        """
        self.toggled = NONE_CATEGORY

        # reset liststore
        combo = self.toolbar.combobox
        combo.set_model(self.EMPTY_LIST_STORE)

        # reset selected widget
        color_fill = profile.get_color().get_fill_color()
        color_stroke = profile.get_color().get_stroke_color()
        self._set_selected(get_gtkimage_from_plugin(NONE_CATEGORY,
                                                    color_stroke,
                                                    color_fill,
                                                    self.IMG_SIZE))

        self.reset_selected_btn.set_active(True)
        self.selected.queue_draw()
        combo.queue_draw()
Пример #6
0
    def __init__(self, handle):
        """ Initialize the toolbars and the game board """
        super(PathsActivity, self).__init__(handle)
        self.nick = profile.get_nick_name()
        if profile.get_color() is not None:
            self.colors = profile.get_color().to_string().split(',')
        else:
            self.colors = ['#A0FFA0', '#FF8080']

        self._setup_toolbars(_have_toolbox)
        self._setup_dispatch_table()

        # Create a canvas
        canvas = gtk.DrawingArea()
        canvas.set_size_request(gtk.gdk.screen_width(), \
                                gtk.gdk.screen_height())
        self.set_canvas(canvas)
        canvas.show()
        self.show_all()

        self._game = Game(canvas, parent=self, colors=self.colors)
        self._setup_presence_service()

        # Restore game state from Journal or start new game
        if 'deck' in self.metadata:
            self._restore()
        else:
            self._game.new_game()
Пример #7
0
    def set_color(self, fill=profile.get_color().get_fill_color(), \
                  stroke=profile.get_color().get_stroke_color()):
        """
        Sets the xo colors for this player.

        @param fill: hex string for fill color.
        @param stroke: hex string for stroke color.
        """
        self.color_stroke = stroke
        self.color_fill   = fill
Пример #8
0
 def _get_colors(self):
     colors = None
     if self._tw.running_sugar:
         if profile.get_color() is not None:
             colors = profile.get_color().to_string()
     else:
         colors = self._activity.get_colors()
     if colors is None:
         colors = '%s,%s' % (DEFAULT_TURTLE_COLORS[0],
                             DEFAULT_TURTLE_COLORS[1])
     return colors.split(',')
Пример #9
0
 def _get_colors(self):
     colors = None
     if self._tw.running_sugar:
         if profile.get_color() is not None:
             colors = profile.get_color().to_string()
     else:
         colors = self._activity.get_colors()
     if colors is None:
         colors = '%s,%s' % (DEFAULT_TURTLE_COLORS[0],
                             DEFAULT_TURTLE_COLORS[1])
     return colors.split(',')
Пример #10
0
def get_xo_icon(color_stroke=None, color_fill=None, size=(20,20)):
    """
    @param color_stroke: The stroke color as hex string (default is players stroke).
    @param color_fill: The fill color as hex string (default is players fill).
    @param size: A tupel of size in pixels: (width,height).
    @return: The XO icon with given colors and size
    """
    if (color_stroke == None) or (color_fill == None):
        color_stroke = profile.get_color().get_stroke_color()
        color_fill = profile.get_color().get_fill_color()
    name = os.path.join(constants.BUNDLE_PATH, 'icons/computer-xo.svg')
    return load_svg_image(name, color_stroke, color_fill, size)
Пример #11
0
    def __members_changed_cb(self, adhoc_manager, channel, has_members):
        if channel == self._channel:
            if has_members == True:
                self._state_color = profile.get_color()
            else:
                color = '%s,%s' % (profile.get_color().get_stroke_color(),
                                   style.COLOR_TRANSPARENT.get_svg())
                self._state_color = XoColor(color)

            if not self._filtered:
                self.props.base_color = self._state_color
                self._palette_icon.props.xo_color = self._state_color
                self.alpha = 1.0
            else:
                self.alpha = _FILTERED_ALPHA
Пример #12
0
    def _update(self):
        state = self._device_state

        if (state >= network.NM_DEVICE_STATE_PREPARE) and \
           (state <= network.NM_DEVICE_STATE_IP_CONFIG):
            self._icon.props.base_color = self._inactive_color
            self._icon.props.pulse_color = profile.get_color()
            self._palette.set_connecting()
            self._icon.props.pulsing = True
        elif state == network.NM_DEVICE_STATE_ACTIVATED:
            address = self._device_props.Get(network.NM_DEVICE_IFACE, 'Ip4Address')
            self._palette.set_connected_with_channel(self._channel, address)
            self._icon.props.base_color = profile.get_color()
            self._icon.props.pulsing = False
        self._update_text()
Пример #13
0
    def __init__(self, channel):
        CanvasPulsingIcon.__init__(self,
                                   icon_name=self._ICON_NAME + str(channel),
                                   size=style.STANDARD_ICON_SIZE, cache=True)
        self._bus = dbus.SystemBus()
        self._channel = channel
        self._disconnect_item = None
        self._connect_item = None
        self._palette_icon = None
        self._filtered = False

        get_adhoc_manager_instance().connect('members-changed',
                                             self.__members_changed_cb)
        get_adhoc_manager_instance().connect('state-changed',
                                             self.__state_changed_cb)

        self.connect('button-release-event', self.__button_release_event_cb)

        pulse_color = XoColor('%s,%s' % (style.COLOR_BUTTON_GREY.get_svg(),
                                         style.COLOR_TRANSPARENT.get_svg()))
        self.props.pulse_color = pulse_color
        self._state_color = XoColor('%s,%s' % \
                                       (profile.get_color().get_stroke_color(),
                                        style.COLOR_TRANSPARENT.get_svg()))
        self.props.base_color = self._state_color
        self._palette = self._create_palette()
        self.set_palette(self._palette)
        self._palette_icon.props.xo_color = self._state_color
Пример #14
0
 def _show_via_journal(self, url):
     """Ask the journal to display a URL"""
     import os
     import time
     from sugar import profile
     from sugar.activity.activity import show_object_in_journal
     from sugar.datastore import datastore
     logger.debug('Create journal entry for URL: %s', url)
     jobject = datastore.create()
     metadata = {
         'title': "%s: %s" % (_('URL from Chat'), url),
         'title_set_by_user': '******',
         'icon-color': profile.get_color().to_string(),
         'mime_type': 'text/uri-list',
     }
     for k, v in metadata.items():
         jobject.metadata[k] = v
     file_path = os.path.join(get_activity_root(), 'instance',
                              '%i_' % time.time())
     open(file_path, 'w').write(url + '\r\n')
     os.chmod(file_path, 0755)
     jobject.set_file_path(file_path)
     datastore.write(jobject)
     show_object_in_journal(jobject.object_id)
     jobject.destroy()
     os.unlink(file_path)
Пример #15
0
 def open_url(self, url):
     """Ask the journal to open an URL for us."""
     from sugar import profile
     from shutil import rmtree
     from sugar.datastore import datastore
     from sugar.activity.activity import show_object_in_journal
     from tempfile import mkdtemp
     tmpfolder = mkdtemp('.tmp', 'url', os.path.join(self.get_activity_root(), 'instance'))
     tmpfilepath = os.path.join(tmpfolder, 'url')
     try:
         tmpfile = open(tmpfilepath, 'w')
         tmpfile.write(url)
         tmpfile.close()
         os.chmod(tmpfolder, 0755)
         os.chmod(tmpfilepath, 0755)
         jobject = datastore.create()
         metadata = {
             'title': url,
             'title_set_by_user': '******',
             'buddies': '',
             'preview': '',
             'icon-color': profile.get_color().to_string(),
             'mime_type': 'text/uri-list',
         }
         for k, v in metadata.items():
             jobject.metadata[k] = v # the dict.update method is missing =(
         jobject.file_path = tmpfilepath
         datastore.write(jobject)
         show_object_in_journal(jobject.object_id)
         jobject.destroy()
     finally:
         rmtree(tmpfilepath, ignore_errors=True) # clean up!
Пример #16
0
    def __init__(self, title, mimetype, evaluation='', can_check=True):
        gtk.HBox.__init__(self)

        if can_check:
            self._checkbutton = gtk.CheckButton()
            self._checkbutton.connect('toggled', self._toggled)
        label = gtk.Label("<b>%s</b>" % (title))
        label.set_use_markup(True)
        icon = Icon(pixel_size=52)
        icon.props.icon_name = mime.get_mime_icon(mimetype)
        icon.props.xo_color = profile.get_color()
        evaluation = gtk.Label(evaluation)
        button = gtk.ToolButton()
        button.connect('clicked', lambda w: self.emit('show-info'))
        icon_info = Icon(pixel_size=24)
        icon_info.props.icon_name = 'info-small'
        button.set_icon_widget(icon_info)
        if can_check:
            self.pack_start(self._checkbutton, False, True, 5)
        self.pack_start(icon, False, True, 5)
        self.pack_start(label, False, True, 5)
        self.pack_end(button, False, True, 5)
        self.pack_end(evaluation, False, True, 5)
        self.title = title
        self.mimetype = mimetype

        self.show_all()
Пример #17
0
    def _update_properties(self, properties):
        if 'Mode' in properties:
            self._mode = properties['Mode']
            self._color = None
        if 'Ssid' in properties:
            self._ssid = properties['Ssid']
            self._display_name = network.ssid_to_display_name(self._ssid)
            self._color = None
        if 'Strength' in properties:
            self._strength = properties['Strength']
        if 'Flags' in properties:
            self._flags = properties['Flags']
        if 'Frequency' in properties:
            self._frequency = properties['Frequency']

        if self._color == None:
            if self._mode == network.NM_802_11_MODE_ADHOC and \
                    network.is_sugar_adhoc_network(self._ssid):
                self._color = profile.get_color()
            else:
                sha_hash = hashlib.sha1()
                data = self._ssid + hex(self._flags)
                sha_hash.update(data)
                digest = hash(sha_hash.digest())
                index = digest % len(xocolor.colors)

                self._color = xocolor.XoColor('%s,%s' %
                                              (xocolor.colors[index][0],
                                               xocolor.colors[index][1]))
        self._update()
Пример #18
0
    def __init__(self, handle):
        ''' Initialize the toolbars and the work surface '''
        super(BBoardActivity, self).__init__(handle)

        self.datapath = get_path(activity, 'instance')

        self._hw = get_hardware()

        self._playback_buttons = {}
        self._audio_recordings = {}
        self.colors = profile.get_color().to_string().split(',')

        self._setup_toolbars()
        self._setup_canvas()

        self.slides = []
        self._setup_workspace()

        self._buddies = [profile.get_nick_name()]
        self._setup_presence_service()

        self._thumbs = []
        self._thumbnail_mode = False

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

        self._dirty = False
Пример #19
0
 def _load_game(self, button):
     chooser = ObjectChooser(_('Choose memorize game'),
             parent=self.activity,
             flags=gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT)
     jobject = ''
     try:
         result = chooser.run()
         if result == gtk.RESPONSE_ACCEPT:
             logging.debug('ObjectChooser: %r', 
                           chooser.get_selected_object())
             jobject = chooser.get_selected_object()
             if not jobject or  not jobject.file_path:
                 return
     finally:
         chooser.destroy()
         del chooser
         
     if jobject and jobject.file_path:   
         title = jobject.metadata['title']
         if jobject.metadata.has_key('icon-color'):
             color = jobject.metadata['icon-color']
         else:
             color = profile.get_color().to_string()
         self.emit('game_changed', jobject.file_path, 4,
                   'file', title, color)
          
         if self.jobject != None:
             self.jobject.destroy()
         self.jobject = jobject
Пример #20
0
 def open_url(self, url):
     """Ask the journal to open an URL for us."""
     from sugar import profile
     from shutil import rmtree
     from sugar.datastore import datastore
     from sugar.activity.activity import show_object_in_journal
     from tempfile import mkdtemp
     tmpfolder = mkdtemp('.tmp', 'url',
                         os.path.join(self.get_activity_root(), 'instance'))
     tmpfilepath = os.path.join(tmpfolder, 'url')
     try:
         tmpfile = open(tmpfilepath, 'w')
         tmpfile.write(url)
         tmpfile.close()
         os.chmod(tmpfolder, 0755)
         os.chmod(tmpfilepath, 0755)
         jobject = datastore.create()
         metadata = {
             'title': url,
             'title_set_by_user': '******',
             'buddies': '',
             'preview': '',
             'icon-color': profile.get_color().to_string(),
             'mime_type': 'text/uri-list',
         }
         for k, v in metadata.items():
             jobject.metadata[k] = v  # the dict.update method is missing =(
         jobject.file_path = tmpfilepath
         datastore.write(jobject)
         show_object_in_journal(jobject.object_id)
         jobject.destroy()
     finally:
         rmtree(tmpfilepath, ignore_errors=True)  # clean up!
Пример #21
0
 def view_source(self):
     """Implement the 'view source' key by saving pippy_app.py to the
     datastore, and then telling the Journal to view it."""
     if self.__source_object_id is None:
         from sugar import profile
         from sugar.datastore import datastore
         from sugar.activity.activity \
              import get_bundle_name, get_bundle_path
         from gettext import gettext as _
         import os.path
         jobject = datastore.create()
         metadata = {
             'title': _('%s Source') % get_bundle_name(),
             'title_set_by_user': '******',
             'suggested_filename': 'pippy_app.py',
             'icon-color': profile.get_color().to_string(),
             'mime_type': 'text/x-python',
             }
         for k, v in metadata.items():
             jobject.metadata[k] = v  # dict.update method is missing =(
         jobject.file_path = os.path.join(get_bundle_path(), 'pippy_app.py')
         datastore.write(jobject)
         self.__source_object_id = jobject.object_id
         jobject.destroy()
     self.journal_show_object(self.__source_object_id)
Пример #22
0
def myblock(tw, title):
    ''' Save heap to journal (Sugar only) '''

    import os.path
    from gettext import gettext as _

    from sugar.activity import activity
    from sugar.datastore import datastore
    from sugar import profile

    from TurtleArt.tautils import get_path, data_to_file

    # Save JSON-encoded heap to temporary file
    heap_file = os.path.join(get_path(activity, 'instance'),
                             str(title) + '.txt')
    data_to_file(tw.lc.heap, heap_file)

    # Create a datastore object
    dsobject = datastore.create()

    # Write any metadata (specifically set the title of the file
    #                     and specify that this is a plain text file).
    dsobject.metadata['title'] = str(title)
    dsobject.metadata['icon-color'] = profile.get_color().to_string()
    dsobject.metadata['mime_type'] = 'text/plain'
    dsobject.set_file_path(heap_file)
    datastore.write(dsobject)
    dsobject.destroy()
Пример #23
0
 def _save_recording(self):
     if os.path.exists(os.path.join(self.datapath, 'output.ogg')):
         _logger.debug('Saving recording to Journal...')
         obj_id = self._get_audio_obj_id()
         copyfile(os.path.join(self.datapath, 'output.ogg'),
                  os.path.join(self.datapath, '%s.ogg' % (obj_id)))
         dsobject = self._search_for_audio_note(obj_id)
         if dsobject is None:
             dsobject = datastore.create()
         if dsobject is not None:
             _logger.debug(self.dsobjects[self.i].metadata['title'])
             dsobject.metadata['title'] = _('Audio recording by %s') % \
                 (self.metadata['title'])
             dsobject.metadata['icon-color'] = \
                 profile.get_color().to_string()
             dsobject.metadata['tags'] = obj_id
             dsobject.metadata['mime_type'] = 'audio/ogg'
             dsobject.set_file_path(
                 os.path.join(self.datapath, '%s.ogg' % (obj_id)))
             datastore.write(dsobject)
             dsobject.destroy()
         self._add_playback_button(
             profile.get_nick_name(), self.colors,
             os.path.join(self.datapath, '%s.ogg' % (obj_id)))
         if hasattr(self, 'chattube') and self.chattube is not None:
             self._share_audio()
     else:
         _logger.debug('Nothing to save...')
     return
Пример #24
0
 def get_icon_colors_from_sugar(self):
     ''' Returns the icon colors from the Sugar profile '''
     if self._using_gconf:
         client = gconf.client_get_default()
         return client.get_string('/desktop/sugar/user/color')
     else:
         return profile.get_color().to_string()
Пример #25
0
 def read_file(self, file_path):
     if self.metadata['mime_type'] == 'application/x-memorize-project':
         self.toolbox.set_current_toolbar(_TOOLBAR_PLAY)
         if self.metadata.has_key('icon-color'):
             color = self.metadata['icon-color']
         else:
             color = profile.get_color().to_string()
         self.game.change_game(None, file_path, 4, 'file',
                               self.metadata['title'], color)
Пример #26
0
    def _add_link(self):
        ''' take screenshot and add link info to the model '''
        for link in self.model.data['shared_links']:
            if link['hash'] == sha.new(self.current).hexdigest():
                _logger.debug('_add_link: link exist already a=%s b=%s' %(
                    link['hash'], sha.new(self.current).hexdigest()))
                return
        buf = self._get_screenshot()
        timestamp = time.time()
        self.model.add_link(self.current, self.webtitle, buf,
                            profile.get_nick_name(),
                            profile.get_color().to_string(), timestamp)

        if self.messenger is not None:
            self.messenger._add_link(self.current, self.webtitle,       
                                     profile.get_color().to_string(),
                                     profile.get_nick_name(),
                                     base64.b64encode(buf), timestamp)
Пример #27
0
    def _set_mail(self, mail):
        if mail == self._mail:
            return

        self._mail = mail
        if mail:
            self.props.xo_color = profile.get_color()
        else:
            self.props.stroke_color = style.COLOR_BUTTON_GREY.get_svg()
            self.props.fill_color = style.COLOR_TRANSPARENT.get_svg()
Пример #28
0
    def __init__(self):
        Icon.__init__(self, icon_name='downloads')

        self._profile_colors = profile.get_color()

        self._count = 0
        self._time_out = None

        self.set_normal()

        self.show()
Пример #29
0
def get_user_stroke_color(type='gdk'):
    """Returns the user stroke color"""
    color = profile.get_color()

    if type == 'gdk':
        rcolor = gtk.gdk.Color(color.get_stroke_color())

    elif type == 'str':
        rcolor = color.get_stroke_color()

    return rcolor
Пример #30
0
    def __init__(self, activity, **kwargs):
        ToolButton.__init__(self, **kwargs)
        self.props.tooltip = _('Keep')
        self.props.accelerator = '<Ctrl>S'

        color = profile.get_color()
        keep_icon = Icon(icon_name='document-save', xo_color=color)
        keep_icon.show()

        self.set_icon_widget(keep_icon)
        self.connect('clicked', self.__keep_button_clicked_cb, activity)
Пример #31
0
def _create_activity_icon(metadata):
    if metadata.get('icon-color', ''):
        color = XoColor(metadata['icon-color'])
    else:
        color = profile.get_color()

    from sugar.activity.activity import get_bundle_path
    bundle = ActivityBundle(get_bundle_path())
    icon = Icon(file=bundle.get_icon(), xo_color=color)

    return icon
Пример #32
0
def get_user_stroke_color(type='gdk'):
    """Returns the user stroke color"""
    color = profile.get_color()

    if type == 'gdk':
        rcolor = gtk.gdk.Color(color.get_stroke_color())

    elif type == 'str':
        rcolor = color.get_stroke_color()

    return rcolor
Пример #33
0
 def show_in_journal(self):
     '''send the generated .xo bundle to the journal'''
     jobject = datastore.create()
     jobject.metadata['title'] = self.title
     jobject.metadata['mime_type'] = 'application/vnd.olpc-sugar'
     jobject.metadata['icon-color'] = profile.get_color().to_string()
     jobject.file_path = self.xo_path
     
     datastore.write(jobject)
     
     activity.show_object_in_journal(jobject.object_id) 
Пример #34
0
def _seed_xs_cookie():
    ''' Create a HTTP Cookie to authenticate with the Schoolserver
    '''
    client = gconf.client_get_default()
    backup_url = client.get_string('/desktop/sugar/backup_url')
    if not backup_url:
        _logger.debug('seed_xs_cookie: Not registered with Schoolserver')
        return

    jabber_server = client.get_string(
        '/desktop/sugar/collaboration/jabber_server')

    pubkey = profile.get_profile().pubkey
    cookie_data = {'color': profile.get_color().to_string(),
                   'pkey_hash': sha.new(pubkey).hexdigest()}

    db_path = os.path.join(_profile_path, 'cookies.sqlite')
    try:
        cookies_db = sqlite3.connect(db_path)
        c = cookies_db.cursor()

        c.execute('''CREATE TABLE IF NOT EXISTS
                     moz_cookies 
                     (id INTEGER PRIMARY KEY,
                      name TEXT,
                      value TEXT,
                      host TEXT,
                      path TEXT,
                      expiry INTEGER,
                      lastAccessed INTEGER,
                      isSecure INTEGER,
                      isHttpOnly INTEGER)''')

        c.execute('''SELECT id
                     FROM moz_cookies
                     WHERE name=? AND host=? AND path=?''',
                  ('xoid', jabber_server, '/'))
        
        if c.fetchone():
            _logger.debug('seed_xs_cookie: Cookie exists already')
            return

        expire = int(time.time()) + 10*365*24*60*60
        c.execute('''INSERT INTO moz_cookies (name, value, host, 
                                              path, expiry, lastAccessed,
                                              isSecure, isHttpOnly)
                     VALUES(?,?,?,?,?,?,?,?)''',
                  ('xoid', cjson.encode(cookie_data), jabber_server,
                   '/', expire, 0, 0, 0 ))
        cookies_db.commit()
        cookies_db.close()
    except sqlite3.Error, e:
        _logger.error('seed_xs_cookie: %s' % e)
 def _save_recording_cb(self, button=None):
     savename = self._sounds[self._selected_sound].lower() + '.ogg'
     if os.path.exists(os.path.join(self.datapath, 'output.ogg')):
         dsobject = datastore.create()
         dsobject.metadata['title'] = savename
         dsobject.metadata['icon-color'] = \
             profile.get_color().to_string()
         dsobject.metadata['mime_type'] = 'audio/ogg'
         dsobject.set_file_path(os.path.join(self.datapath, 'output.ogg'))
         datastore.write(dsobject)
         dsobject.destroy()
     return
Пример #36
0
    def save_byte_array(self, path, title= None, color= None):
        if color == None:
            color = profile.get_color().to_string()
        _logger.debug('Save new game in datastore')

        # Saves the zip in datastore
        gameObject = datastore.create()
        gameObject.metadata['title'] = title
        gameObject.metadata['mime_type'] = 'application/x-memorize-project'
        gameObject.metadata['icon-color'] = color
        gameObject.file_path = path
        datastore.write(gameObject)
Пример #37
0
def save_document(sftp, subject, document, mimetype):
    path = os.path.join(MYFILES, document)
    sftp.get(os.path.join(subject, document), path)

    jobject = datastore.create()
    jobject.metadata['title'] = document
    jobject.metadata['icon-color'] = \
            profile.get_color().to_string()
    jobject.metadata['mime_type'] = mimetype
    jobject.file_path = path
    datastore.write(jobject)

    save_log(sftp, 'Saving document: %s' % (document))
Пример #38
0
 def __init__(self, handle):
     activity.Activity.__init__(self, handle, create_jobject=False)
     self.max_participants = 1
     self._progress_bar = None
     self._message_box = None
     self._media_combo_model = None
     self._media_combo = None
     self._backup_button = None
     self._backup = None
     self._hal_devices = {}
     self._color = profile.get_color()
     self._setup_widgets()
     self._find_media()
Пример #39
0
    def _export_turtleblocks(self, alert):
        data = self.game.tu.current
        step = 75
        first = data[0] * step
        second = data[1] * step
        third = data[2] * step
        fourth = data[3] * step
        fifth = data[4] * step

        turtle_data = (
            '[[0, ["start", 219], 248, 92, [null, 1]],'
            + '[1, ["repeat", 189], 266, 138, [0, 2, 3, null]],'
            + '[2, ["number", 4], 322, 138, [1, null]],'
            + '[3, "forward", 284, 180, [1, 4, 5]],'
            + ('[4, ["number", %s], 348, 180, [3, null]],' % first)
            + '[5, "right", 284, 222, [3, 6, 7]],'
            + '[6, ["number", 90], 342, 222, [5, null]],'
            + '[7, "forward", 284, 264, [5, 8, 9]],'
            + ('[8, ["number", %s], 348, 264, [7, null]],' % second)
            + '[9, "right", 284, 306, [7, 10, 11]],'
            + '[10, ["number", 90], 342, 306, [9, null]],'
            + '[11, "forward", 284, 348, [9, 12, 13]],'
            + ('[12, ["number", %s], 348, 348, [11, null]],' % third)
            + '[13, "right", 284, 390, [11, 14, 15]],'
            + '[14, ["number", 90], 342, 390, [13, null]],'
            + '[15, "forward", 284, 432, [13, 16, 17]],'
            + ('[16, ["number", %s], 348, 432, [15, null]],' % fourth)
            + '[17, "right", 284, 474, [15, 18, 19]],'
            + '[18, ["number", 90], 342, 474, [17, null]],'
            + '[19, "forward", 284, 516, [17, 20, 21]],'
            + ('[20, ["number", %s], 348, 516, [19, null]],' % fifth)
            + '[21, "right", 284, 558, [19, 22, null]],'
            + '[22, ["number", 90], 342, 558, [21, null]]]'
        )

        file_path = os.path.join(self.datapath, "output.tb")
        with open(file_path, "w") as file:
            file.write(turtle_data)

        dsobject = datastore.create()
        dsobject.metadata["title"] = "%s %s" % (self.metadata["title"], _("TurtleBlocks"))
        dsobject.metadata["icon-color"] = profile.get_color().to_string()
        dsobject.metadata["mime_type"] = "application/x-turtle-art"
        dsobject.metadata["activity"] = "org.laptop.TurtleArtActivity"
        dsobject.set_file_path(file_path)
        datastore.write(dsobject)
        dsobject.destroy()
        os.remove(file_path)

        gobject.timeout_add(1000, self._remove_alert, alert)
Пример #40
0
    def _export_turtleblocks(self, alert):
        data = self.game.tu.current
        step = 75
        first = data[0] * step
        second = data[1] * step
        third = data[2] * step
        fourth = data[3] * step
        fifth = data[4] * step

        turtle_data = '[[0, ["start", 219], 248, 92, [null, 1]],' +\
                      '[1, ["repeat", 189], 266, 138, [0, 2, 3, null]],' +\
                      '[2, ["number", 4], 322, 138, [1, null]],' +\
                      '[3, "forward", 284, 180, [1, 4, 5]],' +\
                      ('[4, ["number", %s], 348, 180, [3, null]],' % first) +\
                      '[5, "right", 284, 222, [3, 6, 7]],' +\
                      '[6, ["number", 90], 342, 222, [5, null]],' +\
                      '[7, "forward", 284, 264, [5, 8, 9]],' +\
                      ('[8, ["number", %s], 348, 264, [7, null]],' % second) +\
                      '[9, "right", 284, 306, [7, 10, 11]],' +\
                      '[10, ["number", 90], 342, 306, [9, null]],' +\
                      '[11, "forward", 284, 348, [9, 12, 13]],' +\
                      ('[12, ["number", %s], 348, 348, [11, null]],'% third)  +\
                      '[13, "right", 284, 390, [11, 14, 15]],' +\
                      '[14, ["number", 90], 342, 390, [13, null]],' +\
                      '[15, "forward", 284, 432, [13, 16, 17]],' +\
                      ('[16, ["number", %s], 348, 432, [15, null]],'% fourth)  +\
                      '[17, "right", 284, 474, [15, 18, 19]],' +\
                      '[18, ["number", 90], 342, 474, [17, null]],' +\
                      '[19, "forward", 284, 516, [17, 20, 21]],' +\
                      ('[20, ["number", %s], 348, 516, [19, null]],'% fifth)  +\
                      '[21, "right", 284, 558, [19, 22, null]],' +\
                      '[22, ["number", 90], 342, 558, [21, null]]]'

        file_path = os.path.join(self.datapath, 'output.tb')
        with open(file_path, "w") as file:
            file.write(turtle_data)

        dsobject = datastore.create()
        dsobject.metadata['title'] = '%s %s' % (self.metadata['title'],
                                                _('TurtleBlocks'))
        dsobject.metadata['icon-color'] = profile.get_color().to_string()
        dsobject.metadata['mime_type'] = 'application/x-turtle-art'
        dsobject.metadata['activity'] = 'org.laptop.TurtleArtActivity'
        dsobject.set_file_path(file_path)
        datastore.write(dsobject)
        dsobject.destroy()
        os.remove(file_path)

        gobject.timeout_add(1000, self._remove_alert, alert)
Пример #41
0
	def __init__(self,handle):
		activity.Activity.__init__(self,handle)
		self._name = handle
		self.set_title( 'graph' )

		# Attach sugar toolbox
		toolbox = activity.ActivityToolbox( self )
		self.set_toolbox( toolbox )
		toolbox.show()

		# Create the main container
		self._main_view = gtk.VBox()

		# Read the user's profile
		prof = profile.get_profile()

		# Import our class and load it
		self.graph = Graph()

		# Setup the color scheme
		c1 = profile.get_color().get_fill_color()
		c2 = profile.get_color().get_stroke_color()
		#self.graph.set_colors( c1, c2 )

		# Remove the widget's parent
		if self.graph.widget.parent:
			self.graph.widget.parent.remove( self.graph.widget )

		# Attach the widget to our window
		self._main_view.pack_start( self.graph.widget )

		# Display everything
		self.graph.widget.show()
		self._main_view.show()
		self.set_canvas( self._main_view )
		self.show_all()
Пример #42
0
    def __init__(self, owner, tablet_mode):
        gtk.ScrolledWindow.__init__(self)

        if owner is None:
            self._owner = {'nick': profile.get_nick_name(),
                           'color': profile.get_color().to_string()}
        else:
            self._owner = owner

        self._tablet_mode = tablet_mode

        # Auto vs manual scrolling:
        self._scroll_auto = True
        self._scroll_value = 0.0
        self._last_msg_sender = None
        # Track last message, to combine several messages:
        self._last_msg = None
        self._chat_log = ''
        self._row_counter = 0

        # We need access to individual messages for resizing
        # TODO: use a signal for this
        self._rb_list = []
        self._grid_list = []
        self._message_list = []

        self._conversation = gtk.VBox()
        # self._conversation.set_row_spacing(style.DEFAULT_PADDING)
        # self._conversation.set_border_width(0)
        self._conversation.set_size_request(
            gtk.gdk.screen_width() - style.GRID_CELL_SIZE, -1)

        # OSK padding for conversation
        self._dy = 0

        evbox = gtk.EventBox()
        evbox.modify_bg(
            gtk.STATE_NORMAL, style.COLOR_WHITE.get_gdk_color())
        evbox.add(self._conversation)
        self._conversation.show()

        self.set_policy(gtk.POLICY_NEVER, gtk.POLICY_ALWAYS)
        self.add_with_viewport(evbox)
        evbox.show()

        vadj = self.get_vadjustment()
        vadj.connect('changed', self._scroll_changed_cb)
        vadj.connect('value-changed', self._scroll_value_changed_cb)
Пример #43
0
 def __init__(self,jobject=None):
     LicenseWidget.__init__(self,"#ffffff,#ffffff")
     self._jobject = jobject
     if jobject:
         self._color_selected = XoColor(self._jobject.metadata['icon-color'])
     else:
         self._color_selected = profile.get_color()
     default, license = self.load_license()
     icon_name = self.uri_to_icon(license)
     ToolButton.__init__(self)
     icon = Icon(icon_name,icon_size=self._icon_size,xo_color=XoColor("#ffffff,#ffffff"))
     icon.show()
     self.set_icon_widget(icon)
     self.props.sensitive = True
     self.set_tooltip(self._format_tooltip(license))
     self.make_menu(self.get_palette(),XoColor("#ffffff,#ffffff"),self._color_selected,icon_name)
Пример #44
0
    def __init__(self, title, comment, evaluation, student, mimetype):
        super(InfoDialogHW, self).__init__("info",
                                            'Informacion del documento')

        hbox = gtk.HBox()
        self.content_vbox.pack_start(hbox, True)

        previewbox = gtk.VBox()
        preview = Icon(pixel_size=300)
        preview.props.icon_name = mime.get_mime_icon(mimetype)
        preview.props.xo_color = profile.get_color()
        previewbox.pack_start(preview, False)
        hbox.pack_start(previewbox, False, padding=5)

        vbox = gtk.VBox()
        hbox.pack_end(vbox, True, padding=20)

        title_label = gtk.Label(
            '<span font_desc="15"><b>%s</b></span>' % title)
        title_label.set_use_markup(True)
        vbox.pack_start(title_label, False)

        commet_box = gtk.VBox()
        commet_label = gtk.Label('<i>%s</i>' % comment)
        commet_label.set_use_markup(True)
        commet_label.set_line_wrap(True)
        commet_box.pack_start(commet_label, False, padding=30)
        vbox.pack_start(commet_box, True)

        box = gtk.HBox()
        student_label = gtk.Label('%s' % student)
        box.pack_end(student_label, False)
        
        evaluation = evaluation.split('|')
        evaluation = '<b>%s</b>\n%s' % (evaluation[0], evaluation[1])
        evaluation_t = gtk.Label('%s' % evaluation)
        evaluation_t.set_use_markup(True)
        evaluation_t.set_line_wrap_mode(gtk.WRAP_WORD)
        evaluation_t.set_line_wrap(True)
        box.pack_start(evaluation_t, False)

        bbox = gtk.HBox()
        self.content_vbox.pack_end(bbox, False)
        self.content_vbox.pack_end(box, False)

        self.show_all()
Пример #45
0
    def __init__(self, file_path):
        stat = os.stat(file_path)
        metadata = {
            'uid': file_path,
            'title': os.path.basename(file_path),
            'timestamp': stat.st_mtime,
            'mime_type': gio.content_type_guess(filename=file_path),
            'activity': '',
            'activity_id': '',
            'icon-color': get_color().to_string(),
            'description': file_path,
        }

        self.object_id = file_path
        self._metadata = DSMetadata(metadata)
        self._file_path = None
        self._destroyed = False
Пример #46
0
	def start_game(self,numPlayers):
		self._create_domino()
		self.placed_pieces = []
		self.players = []
		auto_player = SimpleAutoPlayer(self,0)
		auto_player.set_pieces(self.take_pieces(7)) 
		self.players.append(auto_player)					
		for n in range(1,numPlayers):
			#print "bucle creacion jugadores",n
			player = DominoPlayer(self,n)
			player.set_pieces(self.take_pieces(7)) 
			self.players.append(player)					

		# comienza a jugar el primer jugador
		self.players[0].play()
		self.ui_player = self.players[1]
		self.ui_player.color = profile.get_color()
		self.ui_player.name = profile.get_nick_name()
    def _build_series(self):
        self.series = []

        interfaces = get_wireless_interfaces()
        if len(interfaces) > 0:
            series = WirelessDataSeries(series_name=profile.get_nick_name(),
                                        series_color=profile.get_color(),
                                        interface=interfaces[0])
            self.series.append(series)
            self.graph.add_series(series)
            for interface in interfaces[1:]:
                series_name = "%s-%s" % (profile.get_nick_name(), interface)
                series_colors = xocolor.colors[hash(series_name) %
                                               len(xocolor.colors)]
                series_xocolor = xocolor.XoColor(",".join(series_colors))
                series = WirelessDataSeries(series_name=series_name,
                                            series_color=series_xocolor,
                                            interface=interface)
                self.series.append(series)
                self.graph.add_series(series)
Пример #48
0
    def __notification_received_cb(self, **kwargs):
        logging.debug('__notification_received_cb')
        icon = NotificationIcon()

        hints = kwargs['hints']

        icon_file_name = hints.get('x-sugar-icon-file-name', '')
        if icon_file_name:
            icon.props.icon_filename = icon_file_name
        else:
            icon.props.icon_name = 'application-octet-stream'

        icon_colors = hints.get('x-sugar-icon-colors', '')
        if not icon_colors:
            icon_colors = profile.get_color()
        icon.props.xo_color = icon_colors

        duration = kwargs.get('expire_timeout', -1)
        if duration == -1:
            duration = _NOTIFICATION_DURATION

        self.add_notification(icon, gtk.CORNER_TOP_RIGHT, duration)
Пример #49
0
    def _initialize_journal_object(self):
        title = _('%s Activity') % get_bundle_name()
        icon_color = get_color().to_string()

        jobject = datastore.create()
        jobject.metadata['title'] = title
        jobject.metadata['title_set_by_user'] = '******'
        jobject.metadata['activity'] = self.get_bundle_id()
        jobject.metadata['activity_id'] = self.get_id()
        jobject.metadata['keep'] = '0'
        jobject.metadata['preview'] = ''
        jobject.metadata['share-scope'] = SCOPE_PRIVATE
        jobject.metadata['icon-color'] = icon_color
        jobject.metadata['launch-times'] = str(int(time.time()))
        jobject.file_path = ''

        # FIXME: We should be able to get an ID synchronously from the DS,
        # then call async the actual create.
        # http://bugs.sugarlabs.org/ticket/2169
        datastore.write(jobject)

        return jobject
Пример #50
0
    def _save_as_html_cb(self, button=None):
        ''' Export an HTML version of the slideshow to the Journal. '''
        self._save_button.set_icon('save-in-progress')
        results = save_html(self._dsobjects, profile.get_nick_name(),
                            self._colors, self._tmp_path)
        html_file = os.path.join(self._tmp_path, 'tmp.html')
        tmp_file = open(html_file, 'w')
        tmp_file.write(results)
        tmp_file.close()

        dsobject = datastore.create()
        dsobject.metadata['title'] = profile.get_nick_name() + ' ' + \
                                     _('Portfolio')
        dsobject.metadata['icon-color'] = profile.get_color().to_string()
        dsobject.metadata['mime_type'] = 'text/html'
        dsobject.set_file_path(html_file)
        dsobject.metadata['activity'] = 'org.laptop.WebActivity'
        datastore.write(dsobject)
        dsobject.destroy()

        gobject.timeout_add(250, self._save_button.set_icon, 'save-as-html')
        return
Пример #51
0
    def __init__(self, mesh_mgr, channel):
        CanvasPulsingIcon.__init__(self, icon_name=_OLPC_MESH_ICON_NAME,
                                   size=style.STANDARD_ICON_SIZE, cache=True)
        self._bus = dbus.SystemBus()
        self._channel = channel
        self._mesh_mgr = mesh_mgr
        self._disconnect_item = None
        self._connect_item = None
        self._filtered = False
        self._device_state = None
        self._active = False
        device = mesh_mgr.mesh_device

        self.connect('button-release-event', self.__button_release_event_cb)

        interface_props = dbus.Interface(device, dbus.PROPERTIES_IFACE)
        interface_props.Get(network.NM_DEVICE_IFACE, 'State',
                            reply_handler=self.__get_device_state_reply_cb,
                            error_handler=self.__get_device_state_error_cb)
        interface_props.Get(network.NM_OLPC_MESH_IFACE, 'ActiveChannel',
                            reply_handler=self.__get_active_channel_reply_cb,
                            error_handler=self.__get_active_channel_error_cb)

        self._bus.add_signal_receiver(self.__device_state_changed_cb,
                                      signal_name='StateChanged',
                                      path=device.object_path,
                                      dbus_interface=network.NM_DEVICE_IFACE)
        self._bus.add_signal_receiver(self.__wireless_properties_changed_cb,
                                      signal_name='PropertiesChanged',
                                      path=device.object_path,
                                      dbus_interface=network.NM_OLPC_MESH_IFACE)

        pulse_color = XoColor('%s,%s' % (style.COLOR_BUTTON_GREY.get_svg(),
                                         style.COLOR_TRANSPARENT.get_svg()))
        self.props.pulse_color = pulse_color
        self.props.base_color = profile.get_color()
        self._palette = self._create_palette()
        self.set_palette(self._palette)
Пример #52
0
    def __init__(self, handle):
        super(PeterActivity, self).__init__(handle)

        # Get user's Sugar colors
        sugarcolors = profile.get_color().to_string().split(',')
        colors = [[
            int(sugarcolors[0][1:3], 16),
            int(sugarcolors[0][3:5], 16),
            int(sugarcolors[0][5:7], 16)
        ],
                  [
                      int(sugarcolors[1][1:3], 16),
                      int(sugarcolors[1][3:5], 16),
                      int(sugarcolors[1][5:7], 16)
                  ]]

        # No sharing
        self.max_participants = 1
        self.datapath = os.path.join(activity.get_activity_root(), 'instance')

        # Build the activity toolbar.
        toolbox = ToolbarBox()

        activity_button = ActivityToolbarButton(self)
        toolbox.toolbar.insert(activity_button, 0)
        activity_button.show()

        self._add_speed_slider(toolbox.toolbar)

        cyan = ToolButton('cyan')
        toolbox.toolbar.insert(cyan, -1)
        cyan.set_tooltip(_('Next pattern'))
        cyan.connect('clicked', self._button_cb, 'cyan')
        cyan.set_sensitive(False)
        cyan.show()

        green = ToolButton('green')
        toolbox.toolbar.insert(green, -1)
        green.set_tooltip(_('Draw'))
        green.connect('clicked', self._button_cb, 'green')
        green.show()

        red = ToolButton('red')
        toolbox.toolbar.insert(red, -1)
        red.set_tooltip(_('Stop'))
        red.connect('clicked', self._button_cb, 'red')
        red.show()

        separator = gtk.SeparatorToolItem()
        separator.props.draw = True
        toolbox.toolbar.insert(separator, -1)
        separator.show()

        label = gtk.Label('')
        label.set_use_markup(True)
        label.show()
        labelitem = gtk.ToolItem()
        labelitem.add(label)
        toolbox.toolbar.insert(labelitem, -1)
        labelitem.show()

        export = ToolButton('export-turtleblocks')
        toolbox.toolbar.insert(export, -1)
        export.set_tooltip(_('Export to TurtleBlocks'))
        export.connect('clicked', self._export_turtleblocks_cb)
        export.show()

        separator = gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbox.toolbar.insert(separator, -1)
        separator.show()

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

        toolbox.show()
        self.set_toolbox(toolbox)

        # Create the game instance.
        self.game = Spirolaterals.Spirolaterals(colors)

        # Build the Pygame canvas.
        self._pygamecanvas = \
            sugargame.canvas.PygameCanvas(self)
        # Note that set_canvas implicitly calls
        # read_file when resuming from the Journal.
        self.set_canvas(self._pygamecanvas)
        self.game.canvas = self._pygamecanvas

        gtk.gdk.screen_get_default().connect('size-changed',
                                             self.__configure_cb)

        # Start the game running.
        self.game.set_cyan_button(cyan)
        self.game.set_label(label)
        self._speed_range.set_value(200)
        self._pygamecanvas.run_pygame(self.game.run)
Пример #53
0
# -*- coding: utf-8 -*-
#
# Copyright (C) 2012 S. Daniel Francis <*****@*****.**>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.

import gtk
from sugar import profile
profile_color = profile.get_color()
fill_color = gtk.gdk.color_parse(profile_color.get_fill_color())
stroke_color = gtk.gdk.color_parse(profile_color.get_stroke_color())

get_fill_color = lambda widget: fill_color
get_stroke_color = lambda widget: stroke_color
Пример #54
0
def myblock(tw, args):
    ''' Record and playback a sound (Sugar only) '''
    import os
    import gst
    import gobject
    gobject.threads_init()

    from TurtleArt.tautils import get_path
    from TurtleArt.tagplay import play_audio_from_file
    from sugar.datastore import datastore
    from sugar import profile

    from gettext import gettext as _

    class Grecord:
        ''' A class for creating a gstreamer session for recording audio. '''
        def __init__(self, tw):
            ''' Set up the stream. We save to a raw .wav file and then
            convert the sound to .ogg for saving. '''
            datapath = get_path(tw.parent, 'instance')
            self.capture_file = os.path.join(datapath, 'output.wav')
            self.save_file = os.path.join(datapath, 'output.ogg')
            self._eos_cb = None

            self._can_limit_framerate = False
            self._recording = False

            self._audio_transcode_handler = None
            self._transcode_id = None

            self._pipeline = gst.Pipeline("Record")
            self._create_audiobin()
            self._pipeline.add(self._audiobin)

            bus = self._pipeline.get_bus()
            bus.add_signal_watch()
            bus.connect('message', self._bus_message_handler)

        def _create_audiobin(self):
            ''' Assemble all the pieces we need. '''
            src = gst.element_factory_make("alsasrc", "absrc")

            # attempt to use direct access to the 0,0 device, solving
            # some A/V sync issues
            src.set_property("device", "plughw:0,0")
            hwdev_available = src.set_state(gst.STATE_PAUSED) != \
                gst.STATE_CHANGE_FAILURE
            src.set_state(gst.STATE_NULL)
            if not hwdev_available:
                src.set_property("device", "default")

            srccaps = gst.Caps(
                "audio/x-raw-int,rate=16000,channels=1,depth=16")

            # guarantee perfect stream, important for A/V sync
            rate = gst.element_factory_make("audiorate")

            # without a buffer here, gstreamer struggles at the start
            # of the recording and then the A/V sync is bad for the
            # whole video (possibly a gstreamer/ALSA bug -- even if it
            # gets caught up, it should be able to resync without
            # problem)
            queue = gst.element_factory_make("queue", "audioqueue")
            queue.set_property("leaky", True)  # prefer fresh data
            queue.set_property("max-size-time", 5000000000)  # 5 seconds
            queue.set_property("max-size-buffers", 500)

            enc = gst.element_factory_make("wavenc", "abenc")

            sink = gst.element_factory_make("filesink", "absink")
            sink.set_property("location", self.capture_file)

            self._audiobin = gst.Bin("audiobin")
            self._audiobin.add(src, rate, queue, enc, sink)

            src.link(rate, srccaps)
            gst.element_link_many(rate, queue, enc, sink)

        def is_recording(self):
            ''' Are we recording? '''
            return self._recording

        def _get_state(self):
            ''' What is the state of our gstreamer pipeline? '''
            return self._pipeline.get_state()[1]

        def start_recording_audio(self):
            ''' Start the stream in order to start recording. '''
            if self._get_state() == gst.STATE_PLAYING:
                return
            self._pipeline.set_state(gst.STATE_PLAYING)
            self._recording = True

        def stop_recording_audio(self):
            ''' Stop recording and then convert the results into a
            .ogg file using a new stream. '''
            self._pipeline.set_state(gst.STATE_NULL)
            self._recording = False

            if not os.path.exists(self.capture_file) or \
                    os.path.getsize(self.capture_file) <= 0:
                return

            # Remove previous transcoding results.
            if os.path.exists(self.save_file):
                os.remove(self.save_file)

            line = 'filesrc location=' + self.capture_file + \
                ' name=audioFilesrc ! wavparse name=audioWavparse \
! audioconvert name=audioAudioconvert ! vorbisenc name=audioVorbisenc \
! oggmux name=audioOggmux ! filesink name=audioFilesink'

            audioline = gst.parse_launch(line)

            # vorbis_enc = audioline.get_by_name('audioVorbisenc')

            audioFilesink = audioline.get_by_name('audioFilesink')
            audioFilesink.set_property("location", self.save_file)

            audioBus = audioline.get_bus()
            audioBus.add_signal_watch()
            self._audio_transcode_handler = audioBus.connect(
                'message', self._onMuxedAudioMessageCb, audioline)
            self._transcode_id = gobject.timeout_add(200,
                                                     self._transcodeUpdateCb,
                                                     audioline)
            audioline.set_state(gst.STATE_PLAYING)

        def _transcodeUpdateCb(self, pipe):
            ''' Where are we in the transcoding process? '''
            position, duration = self._query_position(pipe)
            if position != gst.CLOCK_TIME_NONE:
                value = position * 100.0 / duration
                value = value / 100.0
            return True

        def _query_position(self, pipe):
            ''' Where are we in the stream? '''
            try:
                position, format = pipe.query_position(gst.FORMAT_TIME)
            except BaseException:
                position = gst.CLOCK_TIME_NONE

            try:
                duration, format = pipe.query_duration(gst.FORMAT_TIME)
            except BaseException:
                duration = gst.CLOCK_TIME_NONE

            return (position, duration)

        def _onMuxedAudioMessageCb(self, bus, message, pipe):
            ''' Clean up at end of stream.'''
            if message.type != gst.MESSAGE_EOS:
                return True

            gobject.source_remove(self._audio_transcode_handler)
            self._audio_transcode_handler = None
            gobject.source_remove(self._transcode_id)
            self._transcode_id = None
            pipe.set_state(gst.STATE_NULL)
            pipe.get_bus().remove_signal_watch()
            pipe.get_bus().disable_sync_message_emission()

            os.remove(self.capture_file)
            return False

        def _bus_message_handler(self, bus, message):
            ''' Handle any messages associated with the stream. '''
            t = message.type
            if t == gst.MESSAGE_EOS:
                if self._eos_cb:
                    cb = self._eos_cb
                    self._eos_cb = None
                    cb()
            elif t == gst.MESSAGE_ERROR:
                # TODO: if we come out of suspend/resume with errors, then
                # get us back up and running...  TODO: handle "No space
                # left on the resource.gstfilesink.c" err, debug =
                # message.parse_error()
                pass

    # We store the audio-record stream instance as tw.grecord so that
    # we can use it repeatedly.
    if not hasattr(tw, 'grecord'):
        tw.grecord = Grecord(tw)

    # Sometime we need to parse multiple arguments, e.g., save, savename
    save_name = '%s_%s' % (tw.activity.name, _('sound'))
    cmd = args[0].lower()
    if len(args) > 1:
        save_name = str(args[1])

    if cmd == 'start' or cmd == _('start').lower():
        tw.grecord.start_recording_audio()
    elif cmd == 'stop' or cmd == _('stop').lower():
        tw.grecord.stop_recording_audio()
    elif cmd == 'play' or cmd == _('play').lower():
        play_audio_from_file(tw.lc, tw.grecord.save_file)
    elif cmd == 'save' or cmd == _('save').lower():
        if os.path.exists(tw.grecord.save_file) and tw.running_sugar:
            dsobject = datastore.create()
            dsobject.metadata['title'] = save_name
            dsobject.metadata['icon-color'] = profile.get_color().to_string()
            dsobject.metadata['mime_type'] = 'audio/ogg'
            dsobject.set_file_path(tw.grecord.save_file)
            datastore.write(dsobject)
            dsobject.destroy()
Пример #55
0
 def get_icon_colors_from_sugar(self):
     ''' Returns the icon colors from the Sugar profile '''
     return profile.get_color().to_string()
Пример #56
0
    def __init__(self, client, event):
        gtk.Window.__init__(self)
        self._client = client
        self._event = event

        self.set_decorated(False)
        self.set_position(gtk.WIN_POS_CENTER_ALWAYS)
        self.set_border_width(style.LINE_WIDTH)

        window = gtk.VBox()
        self.add(window)

        toolbar = gtk.Toolbar()
        window.pack_start(toolbar, False)

        icon = Icon()
        icon.set_from_icon_name('emblem-warning', gtk.ICON_SIZE_LARGE_TOOLBAR)
        icon.props.xo_color = profile.get_color()
        tool_item = gtk.ToolItem()
        tool_item.add(icon)
        toolbar.insert(tool_item, -1)

        separator = gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_size_request(style.DEFAULT_SPACING, -1)
        toolbar.insert(separator, -1)

        title = gtk.Label(_('Submit failure report'))
        tool_item = gtk.ToolItem()
        tool_item.add(title)
        toolbar.insert(tool_item, -1)

        separator = gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar.insert(separator, -1)

        submit = ToolButton('dialog-ok', tooltip=_('Submit'))
        submit.connect('clicked', lambda button: self._submit())
        toolbar.insert(submit, -1)

        cancel = ToolButton('dialog-cancel', tooltip=_('Cancel'))
        cancel.connect('clicked', lambda button: self.destroy())
        toolbar.insert(cancel, -1)

        bg = gtk.EventBox()
        bg.modify_bg(gtk.STATE_NORMAL, style.COLOR_WHITE.get_gdk_color())
        window.pack_start(bg)

        canvas = gtk.VBox()
        canvas.set_border_width(style.DEFAULT_SPACING)
        canvas.props.spacing = style.DEFAULT_SPACING
        bg.add(canvas)

        box = gtk.HBox()
        box.props.spacing = style.DEFAULT_SPACING
        canvas.pack_start(box, False)
        if 'icon' in event:
            icon = Icon(file=event['icon'], pixel_size=style.XLARGE_ICON_SIZE)
        else:
            icon = Icon()
            icon.set_from_icon_name('emblem-warning',
                                    gtk.ICON_SIZE_LARGE_TOOLBAR)
        box.pack_start(icon, False)
        label = gtk.Label()
        label.props.use_markup = True
        if 'solution' in event:
            activity_name = '%(name)s-%(version)s' % event['solution'][0]
        else:
            activity_name = event['context']
        label.props.label = '<b>%s</b>\n%s' % (activity_name, event['error'])
        label.props.wrap = True
        box.pack_start(label, False)

        frame = gtk.Frame(
            _('Optionally, describe the problem in common sentences'))
        canvas.pack_start(frame)
        self._message = gtk.TextView()
        scrolled = gtk.ScrolledWindow()
        scrolled.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
        scrolled.set_border_width(style.DEFAULT_PADDING)
        scrolled.add(self._message)
        frame.add(scrolled)

        frame = gtk.Frame(_('Log'))
        canvas.pack_start(frame)
        text = gtk.TextView()
        text.props.editable = False
        if 'trace' in event:
            text.props.buffer.props.text = '\n'.join(event['trace'])
        scrolled = gtk.ScrolledWindow()
        scrolled.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        scrolled.set_border_width(style.DEFAULT_PADDING)
        scrolled.add(text)
        frame.add(scrolled)

        self.show_all()
        self.set_focus(self._message)

        self.connect('realize', self.__realize_cb)

        gap = style.GRID_CELL_SIZE
        width = gtk.gdk.screen_width() - gap * 2
        height = gtk.gdk.screen_height() - gap * 2
        self.set_size_request(width, height)
        self.move(gap, gap)
Пример #57
0
    def _setup_workspace(self):
        ''' Prepare to render the datastore entries. '''
        self._colors = profile.get_color().to_string().split(',')

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

        self._width = gtk.gdk.screen_width()
        self._height = gtk.gdk.screen_height()
        self._scale = gtk.gdk.screen_height() / 900.

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

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

        self._title = Sprite(
            self._sprites, 0, 0,
            svg_str_to_pixbuf(
                genblank(self._width, int(TITLEH * self._scale),
                         self._colors)))
        self._title.set_label_attributes(int(titlef * self._scale),
                                         rescale=False)
        self._preview = Sprite(
            self._sprites, int(
                (self._width - int(PREVIEWW * self._scale)) / 2),
            int(PREVIEWY * self._scale),
            svg_str_to_pixbuf(
                genblank(int(PREVIEWW * self._scale),
                         int(PREVIEWH * self._scale), self._colors)))

        self._full_screen = Sprite(
            self._sprites, int((self._width - int(FULLW * self._scale)) / 2),
            int(PREVIEWY * self._scale),
            svg_str_to_pixbuf(
                genblank(int(FULLW * self._scale), int(FULLH * self._scale),
                         self._colors)))

        self._description = Sprite(
            self._sprites, int(DESCRIPTIONX * self._scale),
            int(DESCRIPTIONY * self._scale),
            svg_str_to_pixbuf(
                genblank(int(self._width - (2 * DESCRIPTIONX * self._scale)),
                         int(DESCRIPTIONH * self._scale), self._colors)))
        self._description.set_label_attributes(int(descriptionf * self._scale))

        self._description2 = Sprite(
            self._sprites, int(SHORTX * self._scale),
            int(SHORTY * self._scale),
            svg_str_to_pixbuf(
                genblank(int(self._width - (2 * SHORTX * self._scale)),
                         int(SHORTH * self._scale), self._colors)))
        self._description2.set_label_attributes(int(descriptionf *
                                                    self._scale))

        self._my_canvas = Sprite(
            self._sprites, 0, 0,
            gtk.gdk.Pixmap(self._canvas.window, self._width, self._height, -1))
        self._my_gc = self._my_canvas.images[0].new_gc()
        self._my_canvas.set_layer(BOTTOM)

        self._clear_screen()

        self._find_starred()
        self.i = 0
        self._show_slide()

        self._playing = False
        self._rate = 10