Example #1
0
def _store_identifiers(serial_number, uuid_, backup_url):
    """  Stores the serial number, uuid and backup_url
    in the identifier folder inside the profile directory
    so that these identifiers can be used for backup. """

    identifier_path = os.path.join(env.get_profile_path(), 'identifiers')
    if not os.path.exists(identifier_path):
        os.mkdir(identifier_path)

    if os.path.exists(os.path.join(identifier_path, 'sn')):
        os.remove(os.path.join(identifier_path, 'sn'))
    serial_file = open(os.path.join(identifier_path, 'sn'), 'w')
    serial_file.write(serial_number)
    serial_file.close()

    if os.path.exists(os.path.join(identifier_path, 'uuid')):
        os.remove(os.path.join(identifier_path, 'uuid'))
    uuid_file = open(os.path.join(identifier_path, 'uuid'), 'w')
    uuid_file.write(uuid_)
    uuid_file.close()

    if os.path.exists(os.path.join(identifier_path, 'backup_url')):
        os.remove(os.path.join(identifier_path, 'backup_url'))
    backup_url_file = open(os.path.join(identifier_path, 'backup_url'), 'w')
    backup_url_file.write(backup_url)
    backup_url_file.close()
Example #2
0
    def __init__(self):
        gobject.GObject.__init__(self)

        self._friends = {}
        self._path = os.path.join(env.get_profile_path(), 'friends')

        self.load()
Example #3
0
    def _hash_private_key(self):
        key_path = os.path.join(env.get_profile_path(), 'owner.key')

        if not os.path.exists(key_path):
            return None

        try:
            f = open(key_path, 'r')
            lines = f.readlines()
            f.close()
        except IOError:
            logging.exception('Error reading private key')
            return None

        key = ""
        begin_found = False
        end_found = False
        for l in lines:
            l = l.strip()
            if l.startswith('-----BEGIN DSA PRIVATE KEY-----'):
                begin_found = True
                continue
            if l.startswith('-----END DSA PRIVATE KEY-----'):
                end_found = True
                continue
            key += l
        if not (len(key) and begin_found and end_found):
            logging.error('Error parsing public key.')
            return None

        # hash it
        key_hash = util.sha_data(key)
        return util.printable_hash(key_hash)
def _store_identifiers(serial_number, uuid_, backup_url):
    """  Stores the serial number, uuid and backup_url
    in the identifier folder inside the profile directory
    so that these identifiers can be used for backup. """

    identifier_path = os.path.join(env.get_profile_path(), 'identifiers')
    if not os.path.exists(identifier_path):
        os.mkdir(identifier_path)

    if os.path.exists(os.path.join(identifier_path, 'sn')):
        os.remove(os.path.join(identifier_path, 'sn'))
    serial_file = open(os.path.join(identifier_path, 'sn'), 'w')
    serial_file.write(serial_number)
    serial_file.close()

    if os.path.exists(os.path.join(identifier_path, 'uuid')):
        os.remove(os.path.join(identifier_path, 'uuid'))
    uuid_file = open(os.path.join(identifier_path, 'uuid'), 'w')
    uuid_file.write(uuid_)
    uuid_file.close()

    if os.path.exists(os.path.join(identifier_path, 'backup_url')):
        os.remove(os.path.join(identifier_path, 'backup_url'))
    backup_url_file = open(os.path.join(identifier_path, 'backup_url'), 'w')
    backup_url_file.write(backup_url)
    backup_url_file.close()
Example #5
0
    def _hash_private_key(self):
        key_path = os.path.join(env.get_profile_path(), 'owner.key')

        if not os.path.exists(key_path):
            return None

        try:
            f = open(key_path, 'r')
            lines = f.readlines()
            f.close()
        except IOError:
            logging.exception('Error reading private key')
            return None

        key = ""
        begin_found = False
        end_found = False
        for l in lines:
            l = l.strip()
            if l.startswith('-----BEGIN DSA PRIVATE KEY-----'):
                begin_found = True
                continue
            if l.startswith('-----END DSA PRIVATE KEY-----'):
                end_found = True
                continue
            key += l
        if not (len(key) and begin_found and end_found):
            logging.error('Error parsing public key.')
            return None

        # hash it
        key_hash = util.sha_data(key)
        return util.printable_hash(key_hash)
Example #6
0
def create_profile(name, color=None):
    if not color:
        color = XoColor()

    client = gconf.client_get_default()
    client.set_string('/desktop/sugar/user/nick', name)
    client.set_string('/desktop/sugar/user/color', color.to_string())
    client.suggest_sync()

    if profile.get_pubkey() and profile.get_profile().privkey_hash:
        logging.info('Valid key pair found, skipping generation.')
        return

    # Generate keypair
    import commands
    keypath = os.path.join(env.get_profile_path(), 'owner.key')
    if os.path.exists(keypath):
        os.rename(keypath, keypath + '.broken')
        logging.warning('Existing private key %s moved to %s.broken',
                        keypath, keypath)

    if os.path.exists(keypath + '.pub'):
        os.rename(keypath + '.pub', keypath + '.pub.broken')
        logging.warning('Existing public key %s.pub moved to %s.pub.broken',
                        keypath, keypath)

    cmd = "ssh-keygen -q -t dsa -f %s -C '' -N ''" % (keypath, )
    (s, o) = commands.getstatusoutput(cmd)
    if s != 0:
        logging.error('Could not generate key pair: %d %s', s, o)
Example #7
0
def create_profile(name, color=None):
    if not color:
        color = XoColor()

    client = gconf.client_get_default()
    client.set_string('/desktop/sugar/user/nick', name)
    client.set_string('/desktop/sugar/user/color', color.to_string())
    client.suggest_sync()

    if profile.get_pubkey() and profile.get_profile().privkey_hash:
        logging.info('Valid key pair found, skipping generation.')
        return

    # Generate keypair
    import commands
    keypath = os.path.join(env.get_profile_path(), 'owner.key')
    if os.path.exists(keypath):
        os.rename(keypath, keypath + '.broken')
        logging.warning('Existing private key %s moved to %s.broken', keypath,
                        keypath)

    if os.path.exists(keypath + '.pub'):
        os.rename(keypath + '.pub', keypath + '.pub.broken')
        logging.warning('Existing public key %s.pub moved to %s.pub.broken',
                        keypath, keypath)

    cmd = "ssh-keygen -q -t dsa -f %s -C '' -N ''" % (keypath, )
    (s, o) = commands.getstatusoutput(cmd)
    if s != 0:
        logging.error('Could not generate key pair: %d %s', s, o)
Example #8
0
def get_environment(activity):
    environ = os.environ.copy()

    bin_path = os.path.join(activity.get_path(), 'bin')

    activity_root = env.get_profile_path(activity.get_bundle_id())
    if not os.path.exists(activity_root):
        os.mkdir(activity_root)

    data_dir = os.path.join(activity_root, 'instance')
    if not os.path.exists(data_dir):
        os.mkdir(data_dir)

    data_dir = os.path.join(activity_root, 'data')
    if not os.path.exists(data_dir):
        os.mkdir(data_dir)

    tmp_dir = os.path.join(activity_root, 'tmp')
    if not os.path.exists(tmp_dir):
        os.mkdir(tmp_dir)

    environ['SUGAR_BUNDLE_PATH'] = activity.get_path()
    environ['SUGAR_BUNDLE_ID'] = activity.get_bundle_id()
    environ['SUGAR_ACTIVITY_ROOT'] = activity_root
    environ['PATH'] = bin_path + ':' + environ['PATH']

    if activity.get_path().startswith(env.get_user_activities_path()):
        environ['SUGAR_LOCALEDIR'] = os.path.join(activity.get_path(),
            'locale')

    return environ
Example #9
0
    def __init__(self):
        gobject.GObject.__init__(self)

        self._friends = {}
        self._path = os.path.join(env.get_profile_path(), 'friends')

        self.load()
Example #10
0
def _setup_env(display, scaling, emulator_pid):
    os.environ['SUGAR_EMULATOR'] = 'yes'
    os.environ['GABBLE_LOGFILE'] = os.path.join(
            env.get_profile_path(), 'logs', 'telepathy-gabble.log')
    os.environ['SALUT_LOGFILE'] = os.path.join(
            env.get_profile_path(), 'logs', 'telepathy-salut.log')
    os.environ['MC_LOGFILE'] = os.path.join(
            env.get_profile_path(), 'logs', 'mission-control.log')
    os.environ['STREAM_ENGINE_LOGFILE'] = os.path.join(
            env.get_profile_path(), 'logs', 'telepathy-stream-engine.log')
    os.environ['DISPLAY'] = ':%d' % (display)
    os.environ['SUGAR_EMULATOR_PID'] = emulator_pid
    os.environ['MC_ACCOUNT_DIR'] = os.path.join(
            env.get_profile_path(), 'accounts')

    if scaling:
        os.environ['SUGAR_SCALING'] = scaling
Example #11
0
def get_profile():
    global _profile

    if not _profile:
        path = os.path.join(env.get_profile_path(), 'config')
        _profile = Profile(path)

    return _profile
 def _write_to_temp_file(self, data):
     tmp_dir = os.path.join(env.get_profile_path(), 'data')
     f, file_path = tempfile.mkstemp(dir=tmp_dir)
     try:
         os.write(f, data)
     finally:
         os.close(f)
     return file_path
Example #13
0
def get_profile():
    global _profile

    if not _profile:
        path = os.path.join(env.get_profile_path(), 'config')
        _profile = Profile(path)

    return _profile
Example #14
0
 def _write_to_temp_file(self, data):
     tmp_dir = os.path.join(env.get_profile_path(), 'data')
     f, file_path = tempfile.mkstemp(dir=tmp_dir)
     try:
         os.write(f, data)
     finally:
         os.close(f)
     return file_path
Example #15
0
def _setup_env(display, scaling, emulator_pid):
    os.environ['SUGAR_EMULATOR'] = 'yes'
    os.environ['GABBLE_LOGFILE'] = os.path.join(env.get_profile_path(), 'logs',
                                                'telepathy-gabble.log')
    os.environ['SALUT_LOGFILE'] = os.path.join(env.get_profile_path(), 'logs',
                                               'telepathy-salut.log')
    os.environ['MC_LOGFILE'] = os.path.join(env.get_profile_path(), 'logs',
                                            'mission-control.log')
    os.environ['STREAM_ENGINE_LOGFILE'] = os.path.join(
        env.get_profile_path(), 'logs', 'telepathy-stream-engine.log')
    os.environ['DISPLAY'] = ':%d' % (display)
    os.environ['SUGAR_EMULATOR_PID'] = emulator_pid
    os.environ['MC_ACCOUNT_DIR'] = os.path.join(env.get_profile_path(),
                                                'accounts')

    if scaling:
        os.environ['SUGAR_SCALING'] = scaling
Example #16
0
    def __popup_cb(self, palette):
        stat = os.statvfs(env.get_profile_path())
        free_space = stat[statvfs.F_BSIZE] * stat[statvfs.F_BAVAIL]
        total_space = stat[statvfs.F_BSIZE] * stat[statvfs.F_BLOCKS]

        fraction = (total_space - free_space) / float(total_space)
        self._progress_bar.props.fraction = fraction
        self._free_space_label.props.label = _('%(free_space)d MB Free') % \
                {'free_space': free_space / (1024 * 1024)}
Example #17
0
    def __popup_cb(self, palette):
        stat = os.statvfs(env.get_profile_path())
        free_space = stat[statvfs.F_BSIZE] * stat[statvfs.F_BAVAIL]
        total_space = stat[statvfs.F_BSIZE] * stat[statvfs.F_BLOCKS]

        fraction = (total_space - free_space) / float(total_space)
        self._progress_bar.props.fraction = fraction
        self._free_space_label.props.label = _('%(free_space)d MB Free') % \
                {'free_space': free_space / (1024 * 1024)}
Example #18
0
 def _load_pubkey(self):
     key_path = os.path.join(env.get_profile_path(), 'owner.key.pub')
     try:
         f = open(key_path, "r")
         lines = f.readlines()
         f.close()
     except IOError, e:
         logging.error("Error reading public key: %s" % e)
         return None
Example #19
0
 def _hash_private_key(self):
     key_path = os.path.join(env.get_profile_path(), 'owner.key')
     try:
         f = open(key_path, "r")
         lines = f.readlines()
         f.close()
     except IOError, e:
         logging.error("Error reading private key: %s" % e)
         return None
Example #20
0
    def _get_space(self):
        stat = os.statvfs(env.get_profile_path())
        free_space = stat[statvfs.F_BSIZE] * stat[statvfs.F_BAVAIL]
        total_space = stat[statvfs.F_BSIZE] * stat[statvfs.F_BLOCKS]

        free_space = self._get_MBs(free_space)
        total_space = self._get_MBs(total_space)
        used_space = total_space - free_space

        return free_space, used_space, total_space
Example #21
0
def handle_key_press(key):
    tmp_dir = os.path.join(env.get_profile_path(), 'data')
    fd, file_path = tempfile.mkstemp(dir=tmp_dir)
    os.close(fd)

    window = gtk.gdk.get_default_root_window()
    width, height = window.get_size()
    x_orig, y_orig = window.get_origin()

    screenshot = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, has_alpha=False,
                                    bits_per_sample=8, width=width,
                                    height=height)
    screenshot.get_from_drawable(window, window.get_colormap(), x_orig,
                                    y_orig, 0, 0, width, height)
    screenshot.save(file_path, 'png')

    client = gconf.client_get_default()
    color = client.get_string('/desktop/sugar/user/color')

    content_title = None
    shell_model = shell.get_model()
    zoom_level = shell_model.zoom_level

    # TRANS: Nouns of what a screenshot contains
    if zoom_level == shell_model.ZOOM_MESH:
        content_title = _('Mesh')
    elif zoom_level == shell_model.ZOOM_GROUP:
        content_title = _('Group')
    elif zoom_level == shell_model.ZOOM_HOME:
        content_title = _('Home')
    elif zoom_level == shell_model.ZOOM_ACTIVITY:
        activity = shell_model.get_active_activity()
        if activity != None:
            content_title = activity.get_title()
            if content_title == None:
                content_title = _('Activity')

    if content_title is None:
        title = _('Screenshot')
    else:
        title = _('Screenshot of \"%s\"') % content_title

    jobject = datastore.create()
    try:
        jobject.metadata['title'] = title
        jobject.metadata['keep'] = '0'
        jobject.metadata['buddies'] = ''
        jobject.metadata['preview'] = _get_preview_data(screenshot)
        jobject.metadata['icon-color'] = color
        jobject.metadata['mime_type'] = 'image/png'
        jobject.file_path = file_path
        datastore.write(jobject, transfer_ownership=True)
    finally:
        jobject.destroy()
        del jobject
Example #22
0
 def get_file_path(self, fetch=True):
     # we have to create symlink since its a common practice
     # to create hardlinks to jobject files
     # and w/o this, it wouldn't work since we have file from mounted device
     if self._file_path is None:
         data_path = os.path.join(env.get_profile_path(), 'data')
         self._file_path = tempfile.mktemp(
                 prefix='rawobject', dir=data_path)
         if not os.path.exists(data_path):
             os.makedirs(data_path)
         os.symlink(self.object_id, self._file_path)
     return self._file_path
Example #23
0
    def __accept_activate_cb(self, menu_item):
        #TODO: figure out the best place to get rid of that temp file
        extension = mime.get_primary_extension(self.file_transfer.mime_type)
        if extension is None:
            extension = '.bin'
        fd, file_path = tempfile.mkstemp(suffix=extension,
                prefix=self._sanitize(self.file_transfer.title),
                dir=os.path.join(env.get_profile_path(), 'data'))
        os.close(fd)
        os.unlink(file_path)

        self.file_transfer.accept(file_path)
Example #24
0
 def get_file_path(self, fetch=True):
     # we have to create symlink since its a common practice
     # to create hardlinks to jobject files
     # and w/o this, it wouldn't work since we have file from mounted device
     if self._file_path is None:
         data_path = os.path.join(env.get_profile_path(), 'data')
         self._file_path = tempfile.mktemp(prefix='rawobject',
                                           dir=data_path)
         if not os.path.exists(data_path):
             os.makedirs(data_path)
         os.symlink(self.object_id, self._file_path)
     return self._file_path
Example #25
0
    def convert_profile(self):
        cp = ConfigParser()
        path = os.path.join(env.get_profile_path(), 'config')
        cp.read([path])

        client = gconf.client_get_default()

        if cp.has_option('Buddy', 'NickName'):
            name = cp.get('Buddy', 'NickName')
            # decode nickname from ascii-safe chars to unicode
            nick = name.decode('utf-8')
            client.set_string('/desktop/sugar/user/nick', nick)
        if cp.has_option('Buddy', 'Color'):
            color = cp.get('Buddy', 'Color')
            client.set_string('/desktop/sugar/user/color', color)
        if cp.has_option('Jabber', 'Server'):
            server = cp.get('Jabber', 'Server')
            client.set_string('/desktop/sugar/collaboration/jabber_server',
                              server)
        if cp.has_option('Date', 'Timezone'):
            timezone = cp.get('Date', 'Timezone')
            client.set_string('/desktop/sugar/date/timezone', timezone)
        if cp.has_option('Frame', 'HotCorners'):
            delay = float(cp.get('Frame', 'HotCorners'))
            client.set_int('/desktop/sugar/frame/corner_delay', int(delay))
        if cp.has_option('Frame', 'WarmEdges'):
            delay = float(cp.get('Frame', 'WarmEdges'))
            client.set_int('/desktop/sugar/frame/edge_delay', int(delay))
        if cp.has_option('Server', 'Backup1'):
            backup1 = cp.get('Server', 'Backup1')
            client.set_string('/desktop/sugar/backup_url', backup1)
        if cp.has_option('Sound', 'Volume'):
            volume = float(cp.get('Sound', 'Volume'))
            client.set_int('/desktop/sugar/sound/volume', int(volume))
        if cp.has_option('Power', 'AutomaticPM'):
            state = cp.get('Power', 'AutomaticPM')
            if state.lower() == 'true':
                client.set_bool('/desktop/sugar/power/automatic', True)
        if cp.has_option('Power', 'ExtremePM'):
            state = cp.get('Power', 'ExtremePM')
            if state.lower() == 'true':
                client.set_bool('/desktop/sugar/power/extreme', True)
        if cp.has_option('Shell', 'FavoritesLayout'):
            layout = cp.get('Shell', 'FavoritesLayout')
            client.set_string('/desktop/sugar/desktop/favorites_layout',
                              layout)
        del cp
        try:
            os.unlink(path)
        except OSError:
            logging.error('Error removing old profile.')
Example #26
0
    def convert_profile(self):
        cp = ConfigParser()
        path = os.path.join(env.get_profile_path(), 'config')
        cp.read([path])

        client = gconf.client_get_default()

        if cp.has_option('Buddy', 'NickName'):
            name = cp.get('Buddy', 'NickName')
            # decode nickname from ascii-safe chars to unicode
            nick = name.decode("utf-8")
            client.set_string("/desktop/sugar/user/nick", nick)
        if cp.has_option('Buddy', 'Color'):
            color = cp.get('Buddy', 'Color')
            client.set_string("/desktop/sugar/user/color", color)
        if cp.has_option('Jabber', 'Server'):
            server = cp.get('Jabber', 'Server')
            client.set_string("/desktop/sugar/collaboration/jabber_server", 
                              server)
        if cp.has_option('Date', 'Timezone'):
            timezone = cp.get('Date', 'Timezone')
            client.set_string("/desktop/sugar/date/timezone", timezone)
        if cp.has_option('Frame', 'HotCorners'):
            delay = float(cp.get('Frame', 'HotCorners'))
            client.set_int("/desktop/sugar/frame/corner_delay", int(delay))
        if cp.has_option('Frame', 'WarmEdges'):
            delay = float(cp.get('Frame', 'WarmEdges'))
            client.set_int("/desktop/sugar/frame/edge_delay", int(delay))
        if cp.has_option('Server', 'Backup1'):
            backup1 = cp.get('Server', 'Backup1')
            client.set_string("/desktop/sugar/backup_url", backup1)
        if cp.has_option('Sound', 'Volume'):
            volume = float(cp.get('Sound', 'Volume'))
            client.set_int("/desktop/sugar/sound/volume", int(volume))
        if cp.has_option('Power', 'AutomaticPM'):
            state = cp.get('Power', 'AutomaticPM')
            if state.lower() == "true":
                client.set_bool("/desktop/sugar/power/automatic", True)
        if cp.has_option('Power', 'ExtremePM'):
            state = cp.get('Power', 'ExtremePM')
            if state.lower() == "true":
                client.set_bool("/desktop/sugar/power/extreme", True)
        if cp.has_option('Shell', 'FavoritesLayout'):
            layout = cp.get('Shell', 'FavoritesLayout')
            client.set_string("/desktop/sugar/desktop/favorites_layout", 
                              layout)
        del cp
        try:
            os.unlink(path)
        except OSError:
            logging.error('Error removing old profile.')
Example #27
0
    def _check_available_space(self):
        """Check available space on device

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

        if self._critical_space_alert:
            return
        stat = os.statvfs(env.get_profile_path())
        free_space = stat[statvfs.F_BSIZE] * stat[statvfs.F_BAVAIL]
        if free_space < _SPACE_TRESHOLD:
            self._critical_space_alert = ModalAlert()
            self._critical_space_alert.connect("destroy", self.__alert_closed_cb)
            self._critical_space_alert.show()
Example #28
0
def _save_session_info():
    # Save our DBus Session Bus address somewhere it can be found
    #
    # WARNING!!! this is going away at some near future point, do not rely on it
    #
    session_info_file = os.path.join(env.get_profile_path(), "session.info")
    f = open(session_info_file, "w")

    cp = ConfigParser()
    cp.add_section('Session')
    cp.set('Session', 'dbus_address', os.environ['DBUS_SESSION_BUS_ADDRESS'])
    cp.set('Session', 'display', gtk.gdk.display_get_default().get_name())
    cp.write(f)

    f.close()
Example #29
0
def check_profile():
    profile = get_profile()

    path = os.path.join(os.path.expanduser('~/.sugar'), 'debug')
    if not os.path.exists(path):
        profile.create_debug_file()

    path = os.path.join(env.get_profile_path(), 'config')
    if os.path.exists(path):
        profile.convert_profile()

    if not profile.is_valid():
        win = IntroWindow()
        win.show_all()
        gtk.main()
Example #30
0
    def _check_available_space(self):
        """Check available space on device

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

        if self._critical_space_alert:
            return
        stat = os.statvfs(env.get_profile_path())
        free_space = stat[statvfs.F_BSIZE] * stat[statvfs.F_BAVAIL]
        if free_space < _SPACE_TRESHOLD:
            self._critical_space_alert = ModalAlert()
            self._critical_space_alert.connect('destroy',
                                               self.__alert_closed_cb)
            self._critical_space_alert.show()
    def __init__(self):
        ppath = env.get_profile_path()
        self._cachepath = os.path.join(ppath, "cache", "buddy-icons", "cache")

        # Ensure cache directory exists
        if not os.path.exists(os.path.dirname(self._cachepath)):
            os.makedirs(os.path.dirname(self._cachepath))

        if not os.path.exists(self._cachepath):
            self._cache = {}
            # account object-path, md5 and server token of the last avatar
            # uploaded
            self._acct = '/'
            self._md5 = ''
            self._token = ''
        else:
            self._load_cache()
Example #32
0
def audioOut(file=None):
    """Compile a .csd file and start csound to run it. If a string is given as argument, it write a wave file on disk instead of sending sound to hp. (file = [None])"""
    global temp_path
    import os
    if temp_path is None:
        from sugar import env
        import os.path
        temp_path = env.get_profile_path() + '/pippy'
        if not os.path.isdir(temp_path):
            os.mkdir(temp_path)
    path = temp_path
    csd = open(path + "/temp.csd", "w")
    csd.write("<CsoundSynthesizer>\n\n")
    csd.write("<CsOptions>\n")
    if file == None:
        csd.write("-+rtaudio=alsa -odevaudio -m0 -d -b256 -B512\n")
    else:
        file = path + "/" + str(file) + ".wav"
        csd.write("-+rtaudio=alsa -o%s -m0 -W -d -b256 -B512\n" % file)
    csd.write("</CsOptions>\n\n")
    csd.write("<CsInstruments>\n\n")
    csd.write("sr=16000\n")
    csd.write("ksmps=50\n")
    csd.write("nchnls=1\n\n")
    for line in orchlines:
        csd.write(line)
    csd.write("\n</CsInstruments>\n\n")
    csd.write("<CsScore>\n\n")
    csd.write("f1 0 2048 10 1\n")
    csd.write("f2 0 2048 10 1 0 .33 0 .2 0 .143 0 .111\n")
    csd.write("f3 0 2048 10 1 .5 .33 .25 .2 .175 .143 .125 .111 .1\n")
    csd.write("f10 0 2048 10 1 0 0 .3 0 .2 0 0 .1\n")
    csd.write("f99 0 2048 7 1 2048 1\n")
    csd.write("f100 0 2048 7 0. 10 1. 1900 1. 132 0.\n")
    for line in scorelines:
        csd.write(line)
    csd.write("e\n")
    csd.write("\n</CsScore>\n")
    csd.write("\n</CsoundSynthesizer>")
    csd.close()
 
    os.system('csound ' + path + '/temp.csd >/dev/null 2>/dev/null')
Example #33
0
    def _load_favorites(self):
        favorites_path = env.get_profile_path('favorite_activities')
        if os.path.exists(favorites_path):
            favorites_data = simplejson.load(open(favorites_path))

            favorite_bundles = favorites_data['favorites']
            if not isinstance(favorite_bundles, dict):
                raise ValueError('Invalid format in %s.' % favorites_path)
            if favorite_bundles:
                first_key = favorite_bundles.keys()[0]
                if not isinstance(first_key, basestring):
                    raise ValueError('Invalid format in %s.' % favorites_path)

                first_value = favorite_bundles.values()[0]
                if first_value is not None and \
                   not isinstance(first_value, dict):
                    raise ValueError('Invalid format in %s.' % favorites_path)

            self._last_defaults_mtime = float(favorites_data['defaults-mtime'])
            self._favorite_bundles = favorite_bundles
Example #34
0
    def _load_pubkey(self):
        key_path = os.path.join(env.get_profile_path(), 'owner.key.pub')

        if not os.path.exists(key_path):
            return None

        try:
            f = open(key_path, 'r')
            lines = f.readlines()
            f.close()
        except IOError:
            logging.exception('Error reading public key')
            return None

        magic = 'ssh-dss '
        for l in lines:
            l = l.strip()
            if not l.startswith(magic):
                continue
            return l[len(magic):]
        else:
            logging.error('Error parsing public key.')
            return None
Example #35
0
    def _load_pubkey(self):
        key_path = os.path.join(env.get_profile_path(), 'owner.key.pub')

        if not os.path.exists(key_path):
            return None

        try:
            f = open(key_path, 'r')
            lines = f.readlines()
            f.close()
        except IOError:
            logging.exception('Error reading public key')
            return None

        magic = 'ssh-dss '
        for l in lines:
            l = l.strip()
            if not l.startswith(magic):
                continue
            return l[len(magic):]
        else:
            logging.error('Error parsing public key.')
            return None
def get_environment(activity):
    environ = os.environ.copy()

    bin_path = os.path.join(activity.get_path(), 'bin')

    activity_root = env.get_profile_path(activity.get_bundle_id())
    if not os.path.exists(activity_root):
        os.mkdir(activity_root)

    data_dir = os.path.join(activity_root, 'instance')
    if not os.path.exists(data_dir):
        os.mkdir(data_dir)

    data_dir = os.path.join(activity_root, 'data')
    if not os.path.exists(data_dir):
        os.mkdir(data_dir)

    tmp_dir = os.path.join(activity_root, 'tmp')
    if not os.path.exists(tmp_dir):
        os.mkdir(tmp_dir)

    environ['SUGAR_BUNDLE_PATH'] = activity.get_path()
    environ['SUGAR_BUNDLE_ID']   = activity.get_bundle_id()
    environ['SUGAR_ACTIVITY_ROOT'] = activity_root
    environ['PATH'] = bin_path + ':' + environ['PATH']
    #environ['RAINBOW_STRACE_LOG'] = '1'

    if activity.get_path().startswith(env.get_user_activities_path()):
        environ['SUGAR_LOCALEDIR'] = os.path.join(activity.get_path(), 'locale')

    if activity.get_bundle_id() in [ 'org.laptop.WebActivity', 
                                     'org.laptop.GmailActivity',
                                     'org.laptop.WikiBrowseActivity'
                                   ]:
        environ['RAINBOW_CONSTANT_UID'] = 'yes'

    return environ
Example #37
0
    def uninstall(self, install_path, force=False, delete_profile=False):
        if os.path.islink(install_path):
            # Don't remove the actual activity dir if it's a symbolic link
            # because we may be removing user data.
            os.unlink(install_path)
            return

        xdg_data_home = os.getenv('XDG_DATA_HOME',
                                  os.path.expanduser('~/.local/share'))

        mime_dir = os.path.join(xdg_data_home, 'mime')
        installed_mime_path = os.path.join(mime_dir, 'packages',
                                           '%s.xml' % self._bundle_id)
        if os.path.exists(installed_mime_path):
            os.remove(installed_mime_path)
            os.spawnlp(os.P_WAIT, 'update-mime-database',
                       'update-mime-database', mime_dir)

        mime_types = self.get_mime_types()
        if mime_types is not None:
            installed_icons_dir = os.path.join(xdg_data_home,
                'icons/sugar/scalable/mimetypes')
            if os.path.isdir(installed_icons_dir):
                for f in os.listdir(installed_icons_dir):
                    path = os.path.join(installed_icons_dir, f)
                    if os.path.islink(path) and \
                       os.readlink(path).startswith(install_path):
                        os.remove(path)

        if delete_profile:
            bundle_profile_path = env.get_profile_path(self._bundle_id)
            if os.path.exists(bundle_profile_path):
                os.chmod(bundle_profile_path, 0775)
                shutil.rmtree(bundle_profile_path, ignore_errors=True)

        self._uninstall(install_path)
    def __init__(self, ps, bus, test_num, randomize):
        self._cp = ConfigParser()
        self._section = "Info"
        self._test_activities = []
        self._test_cur_act = ""
        self._change_timeout = 0

        self._cfg_file = os.path.join(env.get_profile_path(), 'test-buddy-%d' % test_num)

        (pubkey, privkey, registered) = self._load_config()
        if not pubkey or not len(pubkey) or not privkey or not len(privkey):
            (pubkey, privkey) = _get_new_keypair(test_num)

        if not pubkey or not privkey:
            raise RuntimeError("Couldn't get or create test buddy keypair")

        self._save_config(pubkey, privkey, registered)
        privkey_hash = util.printable_hash(util._sha_data(privkey))

        nick = _get_random_name()
        from sugar.graphics import xocolor
        color = xocolor.XoColor().to_string()
        icon = _get_random_image()

        _logger.debug("pubkey is %s" % pubkey)
        GenericOwner.__init__(self, ps, bus,
                'keyid/' + pubkey_to_keyid(pubkey),
                key=pubkey, nick=nick, color=color, icon=icon,
                registered=registered, key_hash=privkey_hash)

        # we already know our own nick, color, key
        self._awaiting = None

        # Only do the random stuff if randomize is true
        if randomize:
            self._ps.connect('connection-status', self._ps_connection_status_cb)
Example #39
0
    def uninstall(self, install_path, force=False, delete_profile=False):
        if os.path.islink(install_path):
            # Don't remove the actual activity dir if it's a symbolic link
            # because we may be removing user data.
            os.unlink(install_path)
            return

        xdg_data_home = os.getenv('XDG_DATA_HOME',
                                  os.path.expanduser('~/.local/share'))

        mime_dir = os.path.join(xdg_data_home, 'mime')
        installed_mime_path = os.path.join(mime_dir, 'packages',
                                           '%s.xml' % self._bundle_id)
        if os.path.exists(installed_mime_path):
            os.remove(installed_mime_path)
            os.spawnlp(os.P_WAIT, 'update-mime-database',
                       'update-mime-database', mime_dir)

        mime_types = self.get_mime_types()
        if mime_types is not None:
            installed_icons_dir = os.path.join(
                xdg_data_home, 'icons/sugar/scalable/mimetypes')
            if os.path.isdir(installed_icons_dir):
                for f in os.listdir(installed_icons_dir):
                    path = os.path.join(installed_icons_dir, f)
                    if os.path.islink(path) and \
                       os.readlink(path).startswith(install_path):
                        os.remove(path)

        if delete_profile:
            bundle_profile_path = env.get_profile_path(self._bundle_id)
            if os.path.exists(bundle_profile_path):
                os.chmod(bundle_profile_path, 0775)
                shutil.rmtree(bundle_profile_path, ignore_errors=True)

        self._uninstall(install_path)
Example #40
0
        exit(0)

    # matches the host part in
    # - user@host:path
    # - host:path
    m = re.match('(\w+\@)?(\w|.+?):', backup_url)
    if not m or not m.group(2):
        sys.stderr.write("Cannot extract backup host from %s\n" % backup_url)
        exit(1)
    backup_host = m.group(2)

    backup_ctrl_url = 'http://' + backup_host + '/backup/1'

    sn = get_sn()

    ds_path = env.get_profile_path('datastore')
    pk_path = os.path.join(env.get_profile_path(), 'owner.key')

    # Check backup server availability.
    # On 503 ("too busy") apply exponential back-off
    # over 10 attempts. Combined with the staggered sleep
    # in ds-backup.sh, this should keep thundering herds
    # under control. We are also holding a flock to prevent
    # local races.
    # With range(1,7) we sleep up to 64 minutes.

    # Get the documents path in a localization independent way
    documents_path = get_documents_path()
    home_path = os.path.expanduser('~')

    # Make sure home_path ends in a /
Example #41
0
def main():
    gobject.idle_add(_shell_started_cb)

    logsmanager.setup()
    logger.start('shell')

    _save_session_info()
    _start_matchbox()
    _setup_translations()

    hw_manager = hardwaremanager.get_manager()
    hw_manager.startup()

    icons_path = os.path.join(config.data_path, 'icons')
    gtk.icon_theme_get_default().append_search_path(icons_path)

    # Do initial setup if needed
    if not get_profile().is_valid():
        win = intro.IntroWindow()
        win.show_all()
        gtk.main()

    if os.environ.has_key("SUGAR_TP_DEBUG"):
        # Allow the user time to start up telepathy connection managers
        # using the Sugar DBus bus address
        import time
        from telepathy.client import ManagerRegistry

        registry = ManagerRegistry()
        registry.LoadManagers()

        debug_flags = os.environ["SUGAR_TP_DEBUG"].split(',')
        for cm_name in debug_flags:
            if cm_name not in ["gabble", "salut"]:
                continue

            try:
                cm = registry.services[cm_name]
            except KeyError:
               print RuntimeError("%s connection manager not found!" % cm_name)

            while not check_cm(cm['busname']):
                print "Waiting for %s on: DBUS_SESSION_BUS_ADDRESS=%s" % \
                    (cm_name, os.environ["DBUS_SESSION_BUS_ADDRESS"])
                try:
                    time.sleep(5)
                except KeyboardInterrupt:
                    print "Got Ctrl+C, continuing..."
                    break

    model = ShellModel()
    shell = Shell(model)
    service = ShellService(shell)

    if os.environ.has_key("SUGARBOT_EMULATOR"):
        sys.path.append(os.environ['SUGARBOT_PATH'])
        from sugarbotlauncher import SugarbotLauncher
        sbLauncher = SugarbotLauncher(shell, model)

    try:
        gtk.main()
    except KeyboardInterrupt:
        print 'Ctrl+C pressed, exiting...'

    session_info_file = os.path.join(env.get_profile_path(), "session.info")
    os.remove(session_info_file)
Example #42
0
import os
import gtk
import hulahop
from sugar import env
from sugar.activity import activity
from path import path
hulahop.startup(os.path.join(env.get_profile_path(), 'gecko'))

from hulahop.webview import WebView

BUNDLEPATH = path(activity.get_bundle_path()) / 'tw'
DATAPATH = path(activity.get_activity_root()) / 'data'
TESTFILE = BUNDLEPATH / 'slides.html'
WORKFILE = 'file://' + DATAPATH / 'slides.html'

class Htmlview(gtk.VBox):
    def __init__(self):
        gtk.VBox.__init__(self)
        #vbox = gtk.VBox(False, 8)
        wv = WebView()
        print 'show', WORKFILE, path(WORKFILE).exists()
        wv.load_uri(WORKFILE)
        wv.show()
        self.pack_start(wv, True, True, 0)
        #self.add(wv)
        self.show_all()

Example #43
0
 def _write_favorites_file(self):
     path = env.get_profile_path('favorite_activities')
     favorites_data = {'defaults-mtime': self._last_defaults_mtime,
                       'favorites': self._favorite_bundles}
     simplejson.dump(favorites_data, open(path, 'w'), indent=1)
Example #44
0
    def _configure_vte(self):
        conf = ConfigParser.ConfigParser()
        conf_file = os.path.join(env.get_profile_path(), 'terminalrc')

        if os.path.isfile(conf_file):
            f = open(conf_file, 'r')
            conf.readfp(f)
            f.close()
        else:
            conf.add_section('terminal')

        if conf.has_option('terminal', 'font'):
            font = conf.get('terminal', 'font')
        else:
            font = 'Monospace 8'
            conf.set('terminal', 'font', font)
        self.set_font(pango.FontDescription(font))

        if conf.has_option('terminal', 'fg_color'):
            fg_color = conf.get('terminal', 'fg_color')
        else:
            fg_color = '#000000'
            conf.set('terminal', 'fg_color', fg_color)
        if conf.has_option('terminal', 'bg_color'):
            bg_color = conf.get('terminal', 'bg_color')
        else:
            bg_color = '#FFFFFF'
            conf.set('terminal', 'bg_color', bg_color)
        self.set_colors(gtk.gdk.color_parse(fg_color),
                        gtk.gdk.color_parse(bg_color), [])

        if conf.has_option('terminal', 'cursor_blink'):
            blink = conf.getboolean('terminal', 'cursor_blink')
        else:
            blink = False
            conf.set('terminal', 'cursor_blink', blink)

        self.set_cursor_blinks(blink)

        if conf.has_option('terminal', 'bell'):
            bell = conf.getboolean('terminal', 'bell')
        else:
            bell = False
            conf.set('terminal', 'bell', bell)
        self.set_audible_bell(bell)

        if conf.has_option('terminal', 'scrollback_lines'):
            scrollback_lines = conf.getint('terminal', 'scrollback_lines')
        else:
            scrollback_lines = 1000
            conf.set('terminal', 'scrollback_lines', scrollback_lines)

        self.set_scrollback_lines(scrollback_lines)
        self.set_allow_bold(True)

        if conf.has_option('terminal', 'scroll_on_keystroke'):
            scroll_key = conf.getboolean('terminal', 'scroll_on_keystroke')
        else:
            scroll_key = False
            conf.set('terminal', 'scroll_on_keystroke', scroll_key)
        self.set_scroll_on_keystroke(scroll_key)

        if conf.has_option('terminal', 'scroll_on_output'):
            scroll_output = conf.getboolean('terminal', 'scroll_on_output')
        else:
            scroll_output = False
            conf.set('terminal', 'scroll_on_output', scroll_output)
        self.set_scroll_on_output(scroll_output)

        if conf.has_option('terminal', 'emulation'):
            emulation = conf.get('terminal', 'emulation')
        else:
            emulation = 'xterm'
            conf.set('terminal', 'emulation', emulation)
        self.set_emulation(emulation)

        if conf.has_option('terminal', 'visible_bell'):
            visible_bell = conf.getboolean('terminal', 'visible_bell')
        else:
            visible_bell = False
            conf.set('terminal', 'visible_bell', visible_bell)
        self.set_visible_bell(visible_bell)
        conf.write(open(conf_file, 'w'))
Example #45
0
def _migrate_old_wifi_connections():
    """Migrate connections.cfg from Sugar-0.94 and previous to NetworkManager
    system-wide connections
    """

    profile_path = env.get_profile_path()
    config_path = os.path.join(profile_path, 'nm', 'connections.cfg')
    if not os.path.exists(config_path):
        return

    config = ConfigParser.ConfigParser()
    try:
        if not config.read(config_path):
            logging.error('Error reading the nm config file')
            return
    except ConfigParser.ParsingError:
        logging.exception('Error reading the nm config file')
        return

    for section in config.sections():
        try:
            settings = Settings()
            settings.connection.id = section
            ssid = config.get(section, 'ssid')
            settings.wireless.ssid = dbus.ByteArray(ssid)
            uuid = config.get(section, 'uuid')
            settings.connection.uuid = uuid
            nmtype = config.get(section, 'type')
            settings.connection.type = nmtype
            autoconnect = bool(config.get(section, 'autoconnect'))
            settings.connection.autoconnect = autoconnect

            if config.has_option(section, 'timestamp'):
                timestamp = int(config.get(section, 'timestamp'))
                settings.connection.timestamp = timestamp

            if config.has_option(section, 'key-mgmt'):
                settings.wireless_security = WirelessSecurity()
                mgmt = config.get(section, 'key-mgmt')
                settings.wireless_security.key_mgmt = mgmt
                security = config.get(section, 'security')
                settings.wireless.security = security
                key = config.get(section, 'key')
                if mgmt == 'none':
                    settings.wireless_security.wep_key = key
                    auth_alg = config.get(section, 'auth-alg')
                    settings.wireless_security.auth_alg = auth_alg
                elif mgmt == 'wpa-psk':
                    settings.wireless_security.psk = key
                    if config.has_option(section, 'proto'):
                        value = config.get(section, 'proto')
                        settings.wireless_security.proto = value
                    if config.has_option(section, 'group'):
                        value = config.get(section, 'group')
                        settings.wireless_security.group = value
                    if config.has_option(section, 'pairwise'):
                        value = config.get(section, 'pairwise')
                        settings.wireless_security.pairwise = value
        except ConfigParser.Error:
            logging.exception('Error reading section')
        else:
            add_connection(settings)

    os.unlink(config_path)
Example #46
0
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

import os
import time
import hulahop
import gtk

from sugar.activity import activity
from sugar import env

from sugar.graphics.toolbarbox import ToolbarBox
from sugar.activity.widgets import StopButton

hulahop.startup(os.path.join(env.get_profile_path(), 'gecko'))
from hulahop.webview import WebView

BASEPATH = os.path.abspath(os.path.dirname(__file__))


class DesafioMundial(activity.Activity):
    def __init__(self, handle):

        activity.Activity.__init__(self, handle, False)

        toolbar = ToolbarBox()
        separator = gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar.toolbar.insert(separator, -1)
Example #47
0
if HASTOOLBARBOX:
    from sugar.graphics.toolbarbox import ToolbarButton
    from sugar.activity.widgets import ActivityToolbarButton
    from sugar.activity.widgets import StopButton

# labyrinth sources are shipped inside the 'src' subdirectory
sys.path.append(os.path.join(activity.get_bundle_path(), 'src'))

import UndoManager
import MMapArea
import utils

EMPTY = -800

DEFAULT_FONTS = ['Sans', 'Serif', 'Monospace']
USER_FONTS_FILE_PATH = env.get_profile_path('fonts')
GLOBAL_FONTS_FILE_PATH = '/etc/sugar_fonts'


def stop_editing(main_area):
    if len(main_area.selected) == 1:
        if hasattr(main_area.selected[0], 'textview'):
            main_area.selected[0].remove_textview()


class MyMenuItem(MenuItem):
    def __init__(self,
                 text_label=None,
                 icon_name=None,
                 text_maxlen=60,
                 xo_color=None,