예제 #1
0
    def __init__(self, handle):
    
        activity.Activity.__init__(self, handle)
        """ Create the official Sugar toolbox at the top of the screen"""
        toolbox = activity.ActivityToolbox(self)
        self.set_toolbox(toolbox)
        toolbox.show()
        
        file_location = activity.get_activity_root() + \
                        "/data/reckonprimer_report.txt" 
        file_handle = open(file_location, 'w')
        file_handle.write("Report: " + profile.get_nick_name() + \
                          strftime(" %Y-%m-%d %H:%M:%S") + "\n")        
        file_handle.close()
        
        title = "Report: " + profile.get_nick_name() + \
                strftime(" %Y-%m-%d %H:%M:%S")
        mime = "text/plain"
        file_path = activity.get_activity_root() + \
                    "/data/reckonprimer_report.txt"
        favorite = "1"
        tags = "ReckonPrimer"
        
        journal_object = datastore.create()
        journal_object.metadata['title'] = title
        journal_object.metadata['mime_type'] = mime
        journal_object.file_path = file_path  
        journal_object.metadata['keep'] = favorite
        journal_object.metadata['tags'] = tags
        journal_object.metadata['icon-color'] = '#AFD600,#5B615C' 
        datastore.write( journal_object )
        journal_object.destroy()

        self.run_session()
예제 #2
0
    def favicon(self, webview, icono):
        d = urllib.urlopen(icono)
        if os.path.exists(activity.get_activity_root() + "/data/Favicons/" +
                          icono.split("/")[-1]):
            os.remove("Favicons/" + icono.split("/")[-1])
        fav = open(
            activity.get_activity_root() + "/data/Favicons/" +
            icono.split("/")[-1], "a")
        for x in d.readlines():
            fav.write(x)

        fav.close()

        self.favicon_i.set_from_file(activity.get_activity_root() +
                                     "/data/Favicons/" + icono.split("/")[-1])
예제 #3
0
 def event_received_cb(self, text):
     ''' Data is passed as tuples: cmd:text '''
     _logger.debug('<<< %s' % (text[0]))
     if text[0] == 's':  # shared journal objects
         e, data = text.split(':')
         self._load(data)
     elif text[0] == 'j':  # Someone new has joined
         e, buddy = text.split(':')
         _logger.debug('%s has joined' % (buddy))
         if buddy not in self._buddies:
             self._buddies.append(buddy)
         if self.initiating:
             self._send_event('J:%s' % (profile.get_nick_name()))
             self._share_slides()
             self._share_audio()
     elif text[0] == 'J':  # Everyone must share
         e, buddy = text.split(':')
         self.waiting = False
         if buddy not in self._buddies:
             self._buddies.append(buddy)
             _logger.debug('%s has joined' % (buddy))
         self._share_slides()
         self._share_audio()
     elif text[0] == 'a':  # audio recording
         e, data = text.split(':')
         nick, colors, base64 = self._data_loader(data)
         path = os.path.join(activity.get_activity_root(),
                             'instance', 'nick.ogg')
         base64_to_file(activity, base64, path)
         self._add_playback_button(nick, colors, path)
예제 #4
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)
예제 #5
0
def download_activity(_id, row, progress_function):
    """Download (and install) an activity"""
    store_list = get_store_list()
    #print 'store', store_list
    activity_obj = store_list[_id]

    name = activity_obj[2]
    name = name.lower()
    name = name.replace(' ', '_')
    n = activity_obj[0]
    web = 'http://activities.sugarlabs.org/es-ES/sugar/downloads/latest/'
    web = web + n + '/addon-' + n + '-latest.xo'
    version = activity_obj[4]

    def progress_changed(block, block_size, total_size):
        downloaded = block * block_size
        progress = downloaded * 100 / total_size
        #print 'la ro', row
        progress_function(row, progress)

    xo = name + '-' + version + '.xo'
    #print 'alan', web, xo
    file_path = os.path.join(activity.get_activity_root(), "data", xo)

    _logger.info(_("Downloading activity (%s)") % name)
    urllib.urlretrieve(web,
                       file_path,
                       reporthook=progress_changed)

    _logger.info(_("Installing activity (%s)") % name)
    install_activity(file_path, row, progress_function)
예제 #6
0
    def __copy_activate_cb(self, menu_item):
        file_name = os.path.basename(urlparse.urlparse(self._url).path)
        if '.' in file_name:
            base_name, extension = file_name.split('.')
            extension = '.' + extension
        else:
            base_name = file_name
            extension = ''

        temp_path = os.path.join(activity.get_activity_root(), 'instance')
        fd, temp_file = tempfile.mkstemp(dir=temp_path, prefix=base_name,
                                               suffix=extension)
        os.close(fd)
        os.chmod(temp_file, 0664)

        cls = components.classes['@mozilla.org/network/io-service;1']
        io_service = cls.getService(interfaces.nsIIOService)
        uri = io_service.newURI(self._url, None, None)

        cls = components.classes['@mozilla.org/file/local;1']
        target_file = cls.createInstance(interfaces.nsILocalFile)
        target_file.initWithPath(temp_file)
		
        cls = components.classes[ \
                '@mozilla.org/embedding/browser/nsWebBrowserPersist;1']
        persist = cls.createInstance(interfaces.nsIWebBrowserPersist)
        persist.persistFlags = 1 # PERSIST_FLAGS_FROM_CACHE
        listener = xpcom.server.WrapObject(_ImageProgressListener(temp_file),
                                           interfaces.nsIWebProgressListener)
        persist.progressListener = listener
        persist.saveURI(uri, None, None, None, None, target_file)
예제 #7
0
    def abrir(self):
        actRoot = activity.get_activity_root()
        saveFolder = actRoot + "/data/saves/"
        saveFile = saveFolder + self.archivo

        file1 = open(saveFile + ".hst", "rb")
        pikH = pickle.Unpickler(file1)
        historia = pikH.load()

        file2 = open(saveFile + ".opr", "rb")
        pikO = pickle.Unpickler(file2)
        eo = pikO.load()

        if eo.tipo == 0:
            operacion = Suma(self.funcionesDigitos)
        elif eo.tipo == 1:
            operacion = Resta(self.funcionesDigitos)
        elif eo.tipo == 2:
            operacion = Multiplicacion(self.funcionesDigitos)
        elif eo.tipo == 3:
            operacion = Division(self.funcionesDigitos)

        historia.actual = 0
        for i in xrange(len(historia.suc)):
            historia.setPosicion(i, operacion)

        return (historia, operacion)
예제 #8
0
    def promptForSaveToFile(self, launcher, window_context,
                            default_file, suggested_file_extension,
                            force_prompt=False):
        file_class = components.classes['@mozilla.org/file/local;1']
        dest_file = file_class.createInstance(interfaces.nsILocalFile)

        if default_file:
            default_file = default_file.encode('utf-8', 'replace')
            base_name, extension = os.path.splitext(default_file)
        else:
            base_name = ''
            if suggested_file_extension:
                extension = '.' + suggested_file_extension
            else:
                extension = ''

        temp_path = os.path.join(activity.get_activity_root(), 'instance')
        if not os.path.exists(temp_path):
            os.makedirs(temp_path)
        fd, file_path = tempfile.mkstemp(dir=temp_path, prefix=base_name, suffix=extension)
        os.close(fd)
        os.chmod(file_path, 0644)
        dest_file.initWithPath(file_path)

        requestor = window_context.queryInterface(interfaces.nsIInterfaceRequestor)
        dom_window = requestor.getInterface(interfaces.nsIDOMWindow)
        _dest_to_window[file_path] = dom_window
        
        return dest_file
예제 #9
0
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)

        self.bundle_path = activity.get_bundle_path()

        try:
            activity_root = activity.get_activity_root()
            wine_prefix = os.path.join(activity_root, 'data', 'wine')
        except AttributeError:
            try:
                activity_root = os.environ['SUGAR_ACTIVITY_ROOT']
                wine_prefix = os.path.join(activity_root, 'data', 'wine')
            except KeyError:
                activity_root = None
                wine_prefix = os.path.expanduser('~/.wine')

        self.settings = {}
        f = open(os.path.join(self.bundle_path, 'activity', 'wine.info'), 'U')
        for line in f.readlines():
            if '=' in line:
                key, value = line.rstrip('\n').split('=')
                self.settings[key] = value
        f.close()

        try:
            self.desktop_parent = gtk.EventBox()
            self.desktop_parent.show()
            self.set_canvas(self.desktop_parent)
        except AttributeError:
            # remove any children of the window that Sugar may have added
            for widget in self.get_children():
                self.remove(widget)

            self.desktop_parent = self

        os.environ['LD_LIBRARY_PATH'] = "%s:%s" % (os.path.join(
            self.bundle_path, 'lib'), os.environ.get('LD_LIBRARY_PATH', ''))
        os.environ['PATH'] = "%s:%s" % (os.path.join(
            self.bundle_path, 'bin'), os.environ.get('PATH', ''))
        os.environ['WINEPREFIX'] = wine_prefix
        os.environ['WINELOADER'] = os.path.join(self.bundle_path, 'bin/wine')
        os.environ['WINESERVER'] = os.path.join(self.bundle_path,
                                                'bin/wineserver')
        os.environ['WINEDLLPATH'] = os.path.join(self.bundle_path, 'lib/wine')

        self.desktop_name = str(os.getpid())
        os.environ['WINE_DESKTOP_NAME'] = self.desktop_name

        firstrun = not os.path.exists(wine_prefix)

        self.setup_prefix(firstrun)

        self.desktop_parent.connect('map', self.on_parent_map)

        self.wine_pid = None

        self.to_run = []
        self.tempfiles = []

        self.set_title("Wine")
예제 #10
0
    def __init__(self, handle):
        """ Constructor
        """
        # Call super class "Activity" constructor method
        super(ScreencastActivity, self).__init__(handle)

        # User interface object
        self._ui = sc_ui.ScreencastUserInterface(self)

        # Set video file
        directory = os.path.join(get_activity_root(), "data")
        if not os.path.exists(directory):
            os.makedir(directory)

        self._videofile = os.path.join(directory, "screencast.ogg")

        # Gstreamer interface object
        self._gst = sc_gst.ScreencastGstreamer(self._videofile)

        # State
        self._state = "stopped"

        # Connect user interface signals
        self._ui.connect('recordbutton-clicked', self.recordbuttonClicked)
        self._ui.connect('stopbutton-clicked', self.stopbuttonClicked)

        # Connect gstreamer interface signals
        self._gst.connect('update-info', self.updateInfo)

        # Show user interface
        self._ui.showInterface()
예제 #11
0
def download_activity(_id, row, progress_function):
    """Download (and install) an activity"""
    store_list = get_store_list()
    #print 'store', store_list
    activity_obj = store_list[_id]

    name = activity_obj[2]
    name = name.lower()
    name = name.replace(' ', '_')
    n = activity_obj[0]
    web = 'http://activities.sugarlabs.org/es-ES/sugar/downloads/latest/'
    web = web + n + '/addon-' + n + '-latest.xo'
    version = activity_obj[4]

    def progress_changed(block, block_size, total_size):
        downloaded = block * block_size
        progress = downloaded * 100 / total_size
        #print 'la ro', row
        progress_function(row, progress)

    xo = name + '-' + version + '.xo'
    #print 'alan', web, xo
    file_path = os.path.join(activity.get_activity_root(), "data", xo)

    _logger.info(_("Downloading activity (%s)") % name)
    urllib.urlretrieve(web, file_path, reporthook=progress_changed)

    _logger.info(_("Installing activity (%s)") % name)
    install_activity(file_path, row, progress_function)
def get_path(activity, subpath):
    """ Find a Rainbow-approved place for temporary files. """
    try:
        return (os.path.join(activity.get_activity_root(), subpath))
    except:
        # Early versions of Sugar didn't support get_activity_root()
        return (os.path.join(os.environ['HOME'], ".sugar/default", SERVICE,
                             subpath))
예제 #13
0
 def __init__(self):
     gobject.GObject.__init__(self)    
     
     self._config = ConfigParser.RawConfigParser()
     self.config_path = activity.get_activity_root()
     self.config_path = os.path.join(self.config_path,
                                     'data/bookmarklets.ini')
     self._config.read(self.config_path)
예제 #14
0
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)

        self.bundle_path = activity.get_bundle_path()

        try:
            activity_root = activity.get_activity_root()
            wine_prefix = os.path.join(activity_root, 'data', 'wine')
        except AttributeError:
            try:
                activity_root = os.environ['SUGAR_ACTIVITY_ROOT']
                wine_prefix = os.path.join(activity_root, 'data', 'wine')
            except KeyError:
                activity_root = None
                wine_prefix = os.path.expanduser('~/.wine')

        self.settings = {}
        f = open(os.path.join(self.bundle_path, 'activity', 'wine.info'), 'U')
        for line in f.readlines():
            if '=' in line:
                key, value = line.rstrip('\n').split('=')
                self.settings[key] = value
        f.close()

        try:
            self.desktop_parent = gtk.EventBox()
            self.desktop_parent.show()
            self.set_canvas(self.desktop_parent)
        except AttributeError:
            # remove any children of the window that Sugar may have added
            for widget in self.get_children():
                self.remove(widget)

            self.desktop_parent = self

        os.environ['LD_LIBRARY_PATH'] = "%s:%s" % (os.path.join(self.bundle_path, 'lib'), os.environ.get('LD_LIBRARY_PATH', ''))
        os.environ['PATH'] = "%s:%s" % (os.path.join(self.bundle_path, 'bin'), os.environ.get('PATH', ''))
        os.environ['WINEPREFIX'] = wine_prefix
        os.environ['WINELOADER'] = os.path.join(self.bundle_path, 'bin/wine')
        os.environ['WINESERVER'] = os.path.join(self.bundle_path, 'bin/wineserver')
        os.environ['WINEDLLPATH'] = os.path.join(self.bundle_path, 'lib/wine')

        self.desktop_name = str(os.getpid())
        os.environ['WINE_DESKTOP_NAME'] = self.desktop_name

        firstrun = not os.path.exists(wine_prefix)

        self.setup_prefix(firstrun)

        self.desktop_parent.connect('map', self.on_parent_map)

        self.wine_pid = None

        self.to_run = []
        self.tempfiles = []

        self.set_title("Wine")
예제 #15
0
파일: ssb.py 프로젝트: lucian1900/Webified
 def __init__(self, title, uri):
     self.title = title
     self.name = title.replace(' ', '')
     self.uri = uri
     self.bundle_id = '%s.%sActivity' % (DOMAIN_PREFIX, self.name)        
     
     self.bundle_path = activity.get_bundle_path()
     self.data_path = os.path.join(activity.get_activity_root(), 'data')
     self.temp_path = tempfile.mkdtemp() # make sure there's no collisions
     self.ssb_path = os.path.join(self.temp_path, self.name + '.activity')
예제 #16
0
    def tm_ap_loadGame(self,player):
        #loads a game file into memory, doesn't actually start the game
        menuOptions=["Name:"]
        menuButtons=[MENU_PATH+"Blank.gif"]

        for file in os.listdir(os.path.join(activity.get_activity_root(),"data/")):
            menuOptions.append("Name:"+file)
            menuButtons.append(MENU_PATH+"Blank.gif")

        player.currentMenu=Menu(menuOptions,player,MENU_PATH+"mafh_splash.gif",menuButtons,"Save Files")
예제 #17
0
파일: ssb.py 프로젝트: lucian1900/Webified
def copy_profile():
    '''get the data from the bundle and into the profile'''
    ssb_data_path = os.path.join(activity.get_bundle_path(), 'data/ssb_data')
    data_path = os.path.join(activity.get_activity_root(), 'data')

    if os.path.isdir(ssb_data_path):
        # we can't use shutil.copytree for the entire dir
        for i in os.listdir(ssb_data_path):
            src = os.path.join(ssb_data_path, i)
            dst = os.path.join(data_path, i)
            if not os.path.exists(dst):
                if os.path.isdir(src):
                    shutil.copytree(src, dst)
                else: # is there a better way?
                    shutil.copy(src, dst)
예제 #18
0
 def destroy_window(self, data=None):
     print "ende"
     app_path = "%s/result.txt" % (os.path.join(
         activity.get_activity_root(), "data"))
     file = open(app_path, "a")
     file.write(time.strftime("%d %m %Y %H:%M:%S", time.localtime()))
     file.write(" Add %d/%d td %d" % (self.add_q, self.add, self.add_td))
     file.write(" Sub %d/%d td %d" % (self.sub_q, self.sub, self.sub_td))
     file.write(" Mul %d/%d td %d" % (self.mult_q, self.mult, self.mult_td))
     file.write(" Div %d/%d td %d" % (self.div_q, self.div, self.div_td))
     file.write("\n")
     #        file.write(" add %d td %d, sub %d td %d, mult %d td %d" %(self.add,self.add_td,self.sub,self.sub_td,self.mult,self.mult_td))
     file.flush()
     file.close()
     gtk.main_quit()
     return True
예제 #19
0
    def __init__(self, filepath=None):
        PREINSTALLED = [(_('Giraffe'), "giraffe-blank.dita")]

        root = os.path.join(get_activity_root(), 'tmp', 'book')
        shutil.rmtree(root, True)

        if not filepath:
            Book.__init__(self, PREINSTALLED, root)
        else:
            zip = zipfile.ZipFile(filepath, 'r')
            for i in zip.namelist():
                path = os.path.join(root, i)
                os.makedirs(os.path.dirname(path), 0775)
                file(path, 'wb').write(zip.read(i))
            zip.close()

            Book.__init__(self, [], root)
예제 #20
0
    def guardar(self):
        actRoot = activity.get_activity_root()
        saveFolder = actRoot + "/data/saves/"
        
        if not os.path.exists(saveFolder):
            os.makedirs(saveFolder)
        
        saveFile = saveFolder + self.archivo        

        file1 = open(saveFile + ".hst", "wb")
        pikH = pickle.Pickler(file1)
        pikH.dump(self.historia)


        file2 = open(saveFile + ".opr", "wb")
        pikO = pickle.Pickler(file2)
        pikO.dump(self.operacion)
예제 #21
0
    def load(self, services):
        # Init DB
        db = os.path.join(activity.get_activity_root(), "data")
        fullname = os.path.join(db, self.db_filename)
        self.db_fn = fullname
        #for testing, remove db
        #subprocess.call("rm -rf " + fullname, shell=True)
        if os.path.isfile(fullname):
            self.con = sqlite3.connect(fullname)
            self.cur = self.con.cursor()
            self.cur.execute("-- types unicode")
        else:
            # Check for Database Setup
            self.con = sqlite3.connect(fullname)
            self.cur = self.con.cursor()
            self.cur.execute("-- types unicode")
            # Create image, sound folders
            self.imagepath = os.path.join(db, 'image')
            subprocess.call("mkdir -p " + self.imagepath, shell=True)
            self.soundpath = os.path.join(db, 'sound')
            subprocess.call("mkdir -p " + self.soundpath, shell=True)
            # Setup New Database
            self.cur.execute(
                "CREATE TABLE 'categories' ('id' INTEGER PRIMARY KEY AUTOINCREMENT, 'text' TEXT);"
            )
            self.cur.execute(
                "CREATE TABLE 'questions' ('id' INTEGER PRIMARY KEY AUTOINCREMENT, 'prompt' TEXT, 'response' TEXT, 'image_fn' TEXT, 'sound_fn' TEXT, 'map' TEXT, 'answer_link' VARCHAR ( 1024 ));"
            )
            self.cur.execute(
                "CREATE TABLE 'leitner' ('id' INTEGER PRIMARY KEY AUTOINCREMENT, 'question_id' INT, 'count_found' INT, 'count_notfound' INT, 'box' INT, 'time' INT, 'day' INT);"
            )
            self.cur.execute(
                "CREATE TABLE 'catlink' ('id' INTEGER PRIMARY KEY AUTOINCREMENT, 'parent_id' INT, 'child_id' INT);"
            )
            self.cur.execute(
                "CREATE TABLE 'quizlink' ('id' INTEGER PRIMARY KEY AUTOINCREMENT, 'quiz_id' INT, 'question_id' INT);"
            )

            self.con.commit()

            print "* database created"

        if debug_info: print "- database loaded"
        return True
예제 #22
0
    def get_source(self, async_cb, async_err_cb):
        cls = components.classes[ \
                '@mozilla.org/embedding/browser/nsWebBrowserPersist;1']
        persist = cls.createInstance(interfaces.nsIWebBrowserPersist)
        # get the source from the cache
        persist.persistFlags = \
                interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_FROM_CACHE

        temp_path = os.path.join(activity.get_activity_root(), 'instance')
        file_path = os.path.join(temp_path, '%i' % time.time())        
        cls = components.classes["@mozilla.org/file/local;1"]
        local_file = cls.createInstance(interfaces.nsILocalFile)
        local_file.initWithPath(file_path)

        progresslistener = GetSourceListener(file_path, async_cb, async_err_cb)
        persist.progressListener = xpcom.server.WrapObject(
            progresslistener, interfaces.nsIWebProgressListener)

        uri = self.web_navigation.currentURI            
        persist.saveURI(uri, self.doc_shell, None, None, None, local_file)
예제 #23
0
    def __init__(self):
        db_path = os.path.join(activity.get_activity_root(),
                               'data', 'places.db')

        self._connection = sqlite3.connect(db_path)
        cursor = self._connection.cursor()

        cursor.execute('select * from sqlite_master where name == "places"')
        if cursor.fetchone() == None:
            cursor.execute("""create table places (
                                uri         text,
                                title       text,
                                bookmark    boolean,
                                gecko_flags integer,
                                visits      integer,
                                last_visit  timestamp
                              );
                           """)
        else:
            self._cleanup()
예제 #24
0
파일: box.py 프로젝트: Gopaal/2014-interns
 def _show_via_journal(self, url):
     """Ask the journal to display a URL"""
     logging.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 = 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)
예제 #25
0
    def __init__(self, handle):
        gtk.gdk.threads_init()

        activity.Activity.__init__(self, handle)
        
        #the config file goes in the data directory of the activity!
        configFilePath = self.get_activity_root() #
        configFilePath += "/data/config.txt"
        
        self._config = configure.Configuration(configFilePath)
        
        self._ms = mailstore.MailStore(path_join(activity.get_activity_root(), 'data'))
        
        toolbox = mailactivityToolbox(self)
        self.set_toolbox(toolbox)
        toolbox.show()
        
        toolbox.current_toolbar = 1 # default to 'Read' for now
        bgsrt = BGSRT(self)
        bgsrt.start()
예제 #26
0
    def __init__(self, game_path=None):
        self.data = {}

        if game_path is None:
            game_path = get_activity_root()

        if isdir(game_path):
            self.game_path = game_path
        else:
            _logger.error('Game_path not found in %s' % game_path)
            return

        self.data['face'] = ''
        self.data['align'] = '1'

        try:
            self.dtd = libxml2.parseDTD(None, join(get_bundle_path(),
                    'memorize.dtd'))
        except libxml2.parserError, e:
            _logger.error('Init: no memorize.dtd found ' +str(e))
            self.dtd = None
예제 #27
0
def init():
    if _catalog:
        return

    png_dir = join(get_activity_root(), 'data', 'icons', 'smilies')
    svg_dir = join(get_bundle_path(), 'icons', 'smilies')

    if not exists(png_dir):
        os.makedirs(png_dir)

    for index, (name, hint, codes) in enumerate(THEME):
        png_path = join(png_dir, name + '.png')
        if exists(png_path):
            pixbuf = gtk.gdk.pixbuf_new_from_file(png_path)
        else:
            pixbuf = _from_svg_at_size(join(svg_dir, name + '.svg'),
                                       SMILIES_SIZE, SMILIES_SIZE, None, True)
            pixbuf.save(png_path, 'png')
        for i in codes:
            _catalog[i] = pixbuf
        THEME[index] = (png_path, hint, codes)
예제 #28
0
파일: smilies.py 프로젝트: i5o/chat
def init():
    if _catalog:
        return

    png_dir = join(get_activity_root(), 'data', 'icons', 'smilies')
    svg_dir = join(get_bundle_path(), 'icons', 'smilies')

    if not exists(png_dir):
        os.makedirs(png_dir)

    for index, (name, hint, codes) in enumerate(THEME):
        png_path = join(png_dir, name + '.png')
        if exists(png_path):
            pixbuf = gtk.gdk.pixbuf_new_from_file(png_path)
        else:
            pixbuf = _from_svg_at_size(
                    join(svg_dir, name + '.svg'),
                    SMILIES_SIZE, SMILIES_SIZE, None, True)
            pixbuf.save(png_path, 'png')
        for i in codes:
            _catalog[i] = pixbuf
        THEME[index] = (png_path, hint, codes)
예제 #29
0
    def save_image(self, widget):
        """
        Save the curren phase to image and show alert
        """

        w, h = self.get_size()
        pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8,
                    int(w / 1.70), h - 55)

        shot = pixbuf.get_from_drawable(self.window, self.get_colormap(),
                    w - int(w / 1.70), 55, 0, 0, int(w / 1.70), h - 55)

        path = os.path.join(activity.get_activity_root(), "instance",
            "shot.png")

        shot.save(path, "png")
        journal_entry = datastore.create()
        journal_entry.metadata['title'] = "%s %s" % \
            (self.metadata['title'], _("Image"))
        journal_entry.metadata['icon-color'] = profile.get_color().to_string()
        journal_entry.metadata['mime_type'] = "image/png"
        journal_entry.set_file_path(path)
        datastore.write(journal_entry)
        journal_entry.destroy()

        # Alert
        HAS_ALERT = False
        try:
            from sugar.graphics.alert import NotifyAlert
            HAS_ALERT = True
        except:
            pass

        if HAS_ALERT:
            alert = NotifyAlert(5)
            alert.props.title =_('Image saved')
            alert.props.msg = _('An image of the current phase of the moon has been saved to the Journal')
            alert.connect('response', lambda x, y: self.remove_alert(x))
            self.add_alert(alert)
예제 #30
0
def set_environment(is_Xo):
    global application_bundle_path, application_data_path, clics_path, about_path, manual_path, new_clics_path, db_downloaded, db_default, icons_path, views_path
    if is_Xo : #Sets environment for a XO-laptop.
        
        application_data_path = os.path.join(activity.get_activity_root(), 'data')
        application_bundle_path = activity.get_bundle_path()
        
        clics_path = os.path.join(application_bundle_path , 'data/clics') 
        new_clics_path = application_data_path + '/clics'
        about_path = application_bundle_path + '/data/clics/about'
        manual_path = application_bundle_path + '/data/clics/sugar_clic_help'
        
        db_downloaded = os.path.join(application_data_path , 'downloaded.xml')
        db_default = os.path.join(application_bundle_path , 'data/default.xml')
        
        img_app_path = os.path.join(application_bundle_path, 'img/app') 
        views_path = os.path.join(img_app_path, 'appViews')
        icons_path = os.path.join(img_app_path, 'appIcons')
        
    else: #Sets environment for a UNIX computer.
        
        current_path = os.getcwd()
        application_data_path = os.path.join(current_path, 'new/data')
        application_bundle_path = current_path
        
        clics_path = os.path.join(application_bundle_path , 'data/clics')
        new_clics_path = application_data_path + '/clics'
        about_path = application_bundle_path + '/data/clics/about'
        manual_path = application_bundle_path + '/data/clics/sugar_clic_help'
        
        db_downloaded = os.path.join(application_data_path , 'downloaded.xml')
        db_default = os.path.join(application_bundle_path , 'data/default.xml')
        
        img_app_path = os.path.join(application_bundle_path, 'img/app') 
        views_path = os.path.join(img_app_path, 'appViews')
        icons_path = os.path.join(img_app_path, 'appIcons')
        
    __create_clics_path()
예제 #31
0
파일: Config.py 프로젝트: fdanesse/TamTam
    f = open("DEBUG")
    l = f.read(10)
    f.close()
    if len(l):
            DEBUG = int(l)
    else:
            DEBUG = 99
else:
    DEBUG = int(os.getenv("TAMTAM_DEBUG", "0"))

logging.debug("Debug Level %d" % (DEBUG))

#PATHS

TAM_TAM_ROOT = get_bundle_path()
INSTANCE_DIR = join(get_activity_root(), 'instance')
TMP_DIR = join(get_activity_root(), 'tmp')

logging.debug('INFO: loaded TAMTAM_ROOT=%s' % TAM_TAM_ROOT)

DATA_DIR = join(get_activity_root(), 'data')
SNDS_INFO_DIR = join(get_activity_root(), 'data', 'snds_info')
FILES_DIR = join(TAM_TAM_ROOT, "common", "Resources")
SOUNDS_DIR = join(FILES_DIR, "Sounds", "")
IMAGE_ROOT = join(FILES_DIR, "Images", "")

for i in (INSTANCE_DIR, DATA_DIR, SNDS_INFO_DIR, TMP_DIR):
    if not os.path.isdir(i):
            os.makedirs(i)

#PLUGIN
예제 #32
0
from sugar.graphics.alert import Alert
from sugar.datastore import datastore

from charts import Chart
from readers import FreeSpaceReader
from readers import JournalReader
from readers import TurtleReader
import charthelp

# GUI Colors
_COLOR1 = utils.get_user_fill_color()
_COLOR2 = utils.get_user_stroke_color()
_WHITE = gtk.gdk.color_parse("white")

# Paths
_ACTIVITY_DIR = os.path.join(activity.get_activity_root(), "data/")
_CHART_FILE = utils.get_chart_file(_ACTIVITY_DIR)

# Logging
_logger = logging.getLogger('analyze-journal-activity')
_logger.setLevel(logging.DEBUG)
logging.basicConfig()


class ChartArea(gtk.DrawingArea):
    def __init__(self, parent):
        """A class for Draw the chart"""
        super(ChartArea, self).__init__()
        self._parent = parent
        self.add_events(gtk.gdk.EXPOSURE_MASK | gtk.gdk.VISIBILITY_NOTIFY_MASK)
        self.connect("expose-event", self._expose_cb)
예제 #33
0
파일: textarea.py 프로젝트: Daksh/showntell
# 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, time
from path import path
import pygtk
import gtk
import logging
import subprocess
from sugar.activity import activity

import pygst
pygst.require("0.10")
import gst

AUDIOPATH = path(activity.get_activity_root()) / 'data' / 'temp.wav'

class TextArea(gtk.HBox):

        # Constructor
        def __init__(self, deck, work_path):
            gtk.HBox.__init__(self)

            self.__logger = logging.getLogger('TextArea')
            self.__deck = deck
            self.__work_path = work_path
            self.__text_area = gtk.Entry()
            self.render_text_area()
            self.__deck.connect('slide-redraw', self.update_text)
            self.__text_area.connect('changed', self.text_changed)
            self.__logger.debug("Constructed")
예제 #34
0
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

import os
import gtk
import urllib
import logging

from sugar.activity import activity
from sugar.bundle.activitybundle import ActivityBundle

# Paths
LIST_DOWNLOAD = "http://people.sugarlabs.org/ignacio/store.lst"
LIST_DOWNLOAD_MIRROR1 = "http://people.sugarlabs.org/aguz/store.lst"
LIST_DOWNLOAD_MIRROR2 = "http://www.fing.edu.uy/~aaguiar/files/store.lst"
LIST_PATH = os.path.join(activity.get_bundle_path(), 'store.lst')
ICONS_DIR = os.path.join(activity.get_activity_root(), 'data')
TMP_DIR = os.path.join(activity.get_activity_root(), "tmp")

downloading = False

# Logging
_logger = logging.getLogger('install-activity')
_logger.setLevel(logging.DEBUG)
logging.basicConfig()

from gettext import gettext as _


def get_logger():
    return _logger
예제 #35
0
    def updateByName(self,name,player,screen):
#########Title menu buttons############################################
        if name=="Return to Title":
            self.tm_return(player)

        elif name=="Controls":
            self.tm_controls(player)

        elif name=="Exit Game":
            self.tm_exitGame()

        elif name=="Continue":
            self.tm_ap_continue(player,screen)

        elif name=="Level Select":
            self.tm_ap_levelSelect()

        elif name=="Load Game":
            self.tm_ap_loadGame(player)

        elif name=="New Game":
            self.tm_ap_newGame(player)

        elif name=="Play Custom Map":
            self.tm_cp_playCustomMap()

        elif name=="New Custom Map":
            self.tm_cp_newCustomMap()

        elif name=="Share Map":
            self.tm_cp_shareMap()

        elif name=="Local Cooperative Play":
            self.tm_np_localCooperativePlay()

        elif name=="Local Treasure Trekkers Play":
            self.tm_np_localTreasureTrekkersPlay()

        elif name=="View Scoreboard":
            self.tm_np_viewScoreboard()

        elif name=="View Bestiary":
            self.tm_em_viewBestiary()

        elif name=="View Awards":
            self.tm_em_viewAwards()

        elif name=="View Statistics":
            self.tm_em_viewStatistics()

#########Pause Menu Buttons######################################
        elif name=="Save" and self.name !="Pause Menu":
          dataList=player.toString()
          FILE=open(os.path.join(activity.get_activity_root(),"data/"+player.name+".txt"),"w")
          FILE.write(simplejson.dumps(dataList))
          FILE.close()
          #do save stuff
        
        elif name=="Main Menu":
          player.traversal=False
          player.currentMenu=player.MainMenu
          player.mainMenu=True
        
        elif name=="Return to Game":
          player.traversal=True
          player.mainMenu=False
			
        elif name=="OFF":  #was disable
          if player.previousMenu.currentOption==3:
            player.critDifficulty=0
          elif player.previousMenu.currentOption==4:
            player.divDifficulty=0
          elif player.previousMenu.currentOption==5:
            player.geomDifficulty=0
          player.currentMenu=player.previousMenu
        
        elif name=="ON":   #was easy
          if player.previousMenu.currentOption==3:
            player.critDifficulty=1
          elif player.previousMenu.currentOption==4:
            player.divDifficulty=1
          elif player.previousMenu.currentOption==5:
            player.geomDifficulty=1
          player.currentMenu=player.previousMenu

#########Attack Menu Buttons###################################################
        elif name[0:5]=="Name:":
          if len(name)==5:
            player.nameEntry=True
            player.mainMenu=False
          else:
            player.name=name[5:len(name)]
            FILE=open(os.path.join(activity.get_activity_root(),"data/"+player.name),"r")
            data=simplejson.loads(FILE.read())
            print(data)
            player.fromData(data)
            player.currentMenu=player.previousMenu

        elif name=="Attack":
          if player.critDifficulty>0:
            seed()
            crit=randint(0,2)
            if crit==1:
              if not player.atkTutorial:
                player.popUp=PopUp(10,10,["Sometimes when you attack,","you get a critical hit!","If you answer correctly","you will deal normal damage","plus the answer to the question"])
                player.atkTutorial=True
              else:
                player.popUp=None
              player.curBattle.critical(player)
            else:
              player.curBattle.attack(player.battlePlayer,"basic")
          else:
            player.curBattle.attack(player.battlePlayer,"basic")
        
        elif name=="0" or name=="1"or name=="2" or name=="3" or name=="4" or name=="5" or name=="6" or name=="7"or name=="8"or name=="9":
          if len(player.battlePlayer.currentInput)<7:
            player.battlePlayer.currentInput+=name

        elif name=="Clear":
          player.battlePlayer.currentInput=""

        elif name=="Enter Answer":
          if not player.battlePlayer.currentInput =="":
            if player.battlePlayer.currentAnswer==int(player.battlePlayer.currentInput):
              player.curBattle.attack(player.battlePlayer,"critical")
            else:
              tup=self.player.multiplicationStats[self.player.critDifficulty-1]
              tup=(tup[0],tup[1]+1)
              self.player.multiplicationStats[self.player.critDifficulty-1]=tup
              player.curBattle.attack(player.battlePlayer,"basic")
          else:
            tup=self.player.multiplicationStats[self.player.critDifficulty-1]
            tup=(tup[0],tup[1]+1)
            self.player.multiplicationStats[self.player.critDifficulty-1]=tup
            player.curBattle.attack(player.battlePlayer,"basic")
        
        elif name=="Special":
          if not player.speTutorial:
            player.popUp=PopUp(10,10,["To hit with a special attack","Power up your sword to exactly 1","by adding together the fractions"])
            player.speTutorial=True
          else:
            player.popUp=None
          player.curBattle.divisionAttack()
          player.previousMenu=self
        
        elif name[1:2]=="/":
	      player.battlePlayer.fractionSum += float(name[0])/float(name[2])
	      player.curBattle.checkFraction()
        
        elif name=="Magic":
          player.previousMenu=self
          if not player.magTutorial:
            player.popUp=PopUp(10,10,["Different spells have different effects.","Try casting them on different enemies"])
          else:
            player.popUp=None
          player.curBattle.magic(player)
        
        elif name=="Fire" or name=="Lightning" or name=="Heal" or name=="Missile":
          if not player.magTutorial:
            player.popUp=PopUp(10,10,["To cast magic, match the","the sections on your iStone","to the glyph on screen","When the glyph is complete,","you can cast a magic spell!"])
          else:
            player.popUp=None
          player.battlePlayer.currentProb1=""
          player.battlePlayer.currentProb2=""
          player.battlePlayer.currentInput=""
          player.curBattle.startGlyph(name)
	
        elif name=="Fire1" or name=="Fire2" or name=="Fire3" or name=="Fire4" or name=="Heal1" or name=="Heal2" or name=="Heal3" or name=="Heal4" or name=="Lightning1" or name=="Lightning2" or name=="Lightning3" or name=="Lightning4" or name=="Missile1" or name=="Missile2" or name=="Missile3" or name=="Missile4":
	      player.curBattle.checkGlyph(name)
        
        elif name=="Scan":
          player.scanTutorial=True
          player.curBattle.scanEnemy()
        
        elif name=="Weapon" or name=="Armor" or name=="Accessory":
          if not player.invTutorial:
            player.invTutorial=True
            message=["This shows your inventory","To equip or use an item:","  press check or enter"]
            player.popUp=PopUp(10,10,message)
          else:
            player.popUp=None

          self.createInventory(player)
  
        elif name[0:9]=="Equipment":
          if not player.statTutorial:
            player.statTutorial=True
            message=["This shows your equipment and stats","HP is your health points","ATT is your attack power","and DEF is your defense power"]
            player.popUp=PopUp(10,10,message)
          else:
            player.popUp=None

          player.battlePlayer.equip(player.battlePlayer.inv_Ar[int(name[9:len(name)])])
          player.invTutorial=True
          player.currentMenu=player.statsMenu
          player.currentRoomGroup.draw(screen)
        
        elif name=="Wrong":
          print("Wrong choice")
        
        elif name=="Enter":
          player.currentMenu=player.divMenu
        
        elif name=="Not":
          player.migrateMessages("Incorrect glyph.  Spell fizzles")
          tup=self.player.divisionStats[self.player.divDifficulty-1]
          tup=(tup[0],tup[1]+1)
          self.player.divisionStats[self.player.divDifficulty-1]=tup
          player.curBattle.glyphGroup.empty()
          player.curBattle.glyphOverlayGroup.empty()
          player.curBattle.playerTurn=False
          player.currentMenu=player.curBattle.battleMenu
        
        elif name=="LoseContinue":
            player.currentX=player.dgn.start[0]
            player.currentY=player.dgn.start[1]
            player.playerFacing=1
            self.tm_ap_loadGame(player)
            player.dgnMap.updateMacro(player)
            player.traversal=True
            player.mainMenu=False
            player.battlePlayer.MHP-=2
            player.battlePlayer.HP=player.battlePlayer.MHP
            player.currentRoomGroup.draw(screen)
            pygame.display.flip()
        
        elif name=="LoseExit":
          for i in range(6):
            player.migrateMessages("")
            player.__init__(0,0)
            player.traversal=False
            player.mainMenu=True
            player.currentMenu=player.MainMenu
            #player.currentMenu.draw(player,screen,0,0,45)
            pygame.display.flip()

        else:
	        player.currentMenu=player.MainMenu
예제 #36
0
import os
import gtk
import urllib
import logging

from sugar.activity import activity
from sugar.bundle.activitybundle import ActivityBundle
from gettext import gettext as _

# Paths
LIST_DOWNLOAD = _("http://people.sugarlabs.org/ignacio/store.lst")
LIST_DOWNLOAD_MIRROR1 = _("http://people.sugarlabs.org/aguz/store.lst")
LIST_DOWNLOAD_MIRROR2 = _("http://www.fing.edu.uy/~aaguiar/files/store.lst")
LIST_PATH = os.path.join(activity.get_bundle_path(), _('store.lst'))
ICONS_DIR = os.path.join(activity.get_activity_root(), 'data')
TMP_DIR = os.path.join(activity.get_activity_root(), "tmp")

downloading = False

# Logging
_logger = logging.getLogger('install-activity')
_logger.setLevel(logging.DEBUG)
logging.basicConfig()

from gettext import gettext as _


def get_logger():
    return _logger
예제 #37
0
#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import gtk
import sqlite3
import os
import shutil

from sugar.activity import activity
datos = activity.get_activity_root() + "/data/datos/"
if not os.path.exists(datos + "Claves.py"):
    nuevo = open(datos + "Claves.py", "w")
    nuevo.write("primera=True")
    nuevo.close()


class Bases_de_Datos():
    def limpiar(self, entry, event):
        entry.set_text("")

    def aceptar(self, widget, entry, dialog, entry0):
        self.clave = entry.get_text()
        self.usuario = entry0.get_text()

        if self.usuario and self.clave:
            nuevo = open(datos + "Claves.py")
            nuevo.write("primera=%s \nusuario=%s \nclave=%s" %
                        ("False", self.usuario, self.clave))
            nuevo.close()

            pos_anterior = os.getcwd()  # Guardo la direccion actual
예제 #38
0
#    along with ReSiStance.  If not, see <http://www.gnu.org/licenses/>.
#########################################################################

import os
import sys

RSS_NAME = 'ReSiStance'
RSS_COMPACT_NAME = 'resistance'
RSS_VERSION = '0.9.1'
RSS_DESCRIPTION = 'ReSiStance is a RSS feeds reader'
RSS_URL = 'http://www.igalia.com'

try: 
    from sugar.activity import bundlebuilder
    from sugar.activity import activity
    HOME_PATH = os.path.join(activity.get_activity_root(), 'data')
except ImportError:
    HOME_PATH = os.path.expanduser('~')

RSS_CONF_FOLDER = os.path.join(HOME_PATH, RSS_COMPACT_NAME)
RSS_CONF_FILE = os.path.join(RSS_CONF_FOLDER, '%s.conf' % RSS_COMPACT_NAME)
RSS_DB_DIR = os.path.join(RSS_CONF_FOLDER, 'feeds')
OLD_RSS_DB_FILE = os.path.join(RSS_CONF_FOLDER, '%s' % 'feeds.db')
RSS_DB_SUMMARY_FILE = os.path.join(RSS_CONF_FOLDER, '%s' % 'feed-summaries.db')

DEFAULT_SYSTEM_APP_DIR = os.path.join(sys.prefix,
                                      'share',
                                      RSS_COMPACT_NAME)
APP_DIR = DEFAULT_SYSTEM_APP_DIR

if not os.path.exists(APP_DIR):
예제 #39
0
    f = open("DEBUG")
    l = f.read(10)
    f.close()
    if len(l):
        DEBUG = int(l)
    else:
        DEBUG = 99
else:
    DEBUG = int(os.getenv("TAMTAM_DEBUG", "0"))

logging.debug("Debug Level %d" % (DEBUG))

#PATHS

TAM_TAM_ROOT = get_bundle_path()
INSTANCE_DIR = join(get_activity_root(), 'instance')
TMP_DIR = join(get_activity_root(), 'tmp')

logging.debug('INFO: loaded TAMTAM_ROOT=%s' % TAM_TAM_ROOT)

DATA_DIR = join(get_activity_root(), 'data')
SNDS_INFO_DIR = join(get_activity_root(), 'data', 'snds_info')
FILES_DIR = join(TAM_TAM_ROOT, "common", "Resources")
SOUNDS_DIR = join(FILES_DIR, "Sounds", "")
IMAGE_ROOT = join(FILES_DIR, "Images", "")

for i in (INSTANCE_DIR, DATA_DIR, SNDS_INFO_DIR, TMP_DIR):
    if not os.path.isdir(i):
        os.makedirs(i)

#PLUGIN
예제 #40
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)
예제 #41
0
COLOR_BG_BUTTONS = (
    (gtk.STATE_NORMAL, "#027F01"),
    (gtk.STATE_ACTIVE, "#CCFF99"),
    (gtk.STATE_PRELIGHT, "#016D01"),
    (gtk.STATE_SELECTED, "#CCFF99"),
    (gtk.STATE_INSENSITIVE, "#027F01"),
)
OLD_COLOR_BG_BUTTONS = (
    (gtk.STATE_NORMAL, "#027F01"),
    (gtk.STATE_ACTIVE, "#014D01"),
    (gtk.STATE_PRELIGHT, "#016D01"),
    (gtk.STATE_SELECTED, "#027F01"),
    (gtk.STATE_INSENSITIVE, "#027F01"),
)

SESSION_PATH = os.path.join(get_activity_root(), 'tmp', '.session')
if os.path.isdir(SESSION_PATH):
    shutil.rmtree(SESSION_PATH)
os.mkdir(SESSION_PATH)


def path(*args):
    file = os.path.join(*args)

    if os.path.isabs(file):
        return file
    else:
        return os.path.join(get_bundle_path(), file)


def pixbuf(file, size=None):
예제 #42
0
import zipfile
from gobject import SIGNAL_RUN_FIRST, TYPE_PYOBJECT
from gettext import gettext as _

from sugar.activity.activity import get_bundle_path, get_activity_root

import net
from infoslicer.processing.Article import Article
from infoslicer.processing import Article_Builder

logger = logging.getLogger('infoslicer')

wiki = None
custom = None

image_root = os.path.join(get_activity_root(), 'data', 'book')


class Book(gobject.GObject):
    __gsignals__ = {
        'article-selected': (SIGNAL_RUN_FIRST, None, [TYPE_PYOBJECT]),
        'article-added': (SIGNAL_RUN_FIRST, None, [TYPE_PYOBJECT]),
        'article-deleted': (SIGNAL_RUN_FIRST, None, [TYPE_PYOBJECT])
    }

    def get_article(self):
        return self._article

    def set_article(self, title):
        if self._article and self._article.article_title == title:
            return
예제 #43
0
from sugar.graphics.alert import Alert
from sugar.datastore import datastore

from charts import Chart
from readers import FreeSpaceReader
from readers import JournalReader
from readers import TurtleReader
import charthelp

# GUI Colors
_COLOR1 = utils.get_user_fill_color()
_COLOR2 = utils.get_user_stroke_color()
_WHITE = gtk.gdk.color_parse("white")

# Paths
_ACTIVITY_DIR = os.path.join(activity.get_activity_root(), "data/")
_CHART_FILE = utils.get_chart_file(_ACTIVITY_DIR)

# Logging
_logger = logging.getLogger('analyze-journal-activity')
_logger.setLevel(logging.DEBUG)
logging.basicConfig()


class ChartArea(gtk.DrawingArea):

    def __init__(self, parent):
        """A class for Draw the chart"""
        super(ChartArea, self).__init__()
        self._parent = parent
        self.add_events(gtk.gdk.EXPOSURE_MASK | gtk.gdk.VISIBILITY_NOTIFY_MASK)
예제 #44
0
파일: htmlview.py 프로젝트: Daksh/showntell
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()

예제 #45
0
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

import subprocess
import time
import gobject
import gtk, os

import sys

from sugar.activity import activity

descargas = os.path.join(activity.get_activity_root(), "data/Descargas/")
if not os.path.exists(descargas): os.mkdir(descargas)

class Descargar(gtk.Window):	

	def comenzar_descarga(self):
		print "La descarga comenzara"
		os.system("reset")
		salida = "/tmp/out_abrowse%d" % time.time()
		args = "%s %s %s %s %s" % ("wget", "-P", descargas, self.url, "--no-check-certificate")

		entrada = "/tmp/in_abrowse%d" % time.time()

		self.descargar = subprocess.Popen(args, shell=True, stdout=open(salida, "w+b"), stderr=open(salida, "r+b"), universal_newlines=True)
		salida1 = open(salida, "r")		
예제 #46
0
import telepathy.client
from sugar.presence import presenceservice
from sugar.graphics.tray import HTray
from sugar import profile
from sugar.graphics.alert import Alert, ConfirmationAlert
from sugar.graphics.icon import Icon
from sugar import mime

import ssb
# get the profile saved in the ssb bundle, if needed
ssb.copy_profile()

PROFILE_VERSION = 1

_profile_version = 0
_profile_path = os.path.join(activity.get_activity_root(), 'data/gecko')
_version_file = os.path.join(_profile_path, 'version')

if os.path.exists(_version_file):
    f = open(_version_file)
    _profile_version = int(f.read())
    f.close()

if _profile_version < PROFILE_VERSION:
    if not os.path.exists(_profile_path):
        os.mkdir(_profile_path)

    shutil.copy('cert8.db', _profile_path)
    os.chmod(os.path.join(_profile_path, 'cert8.db'), 0660)

    f = open(_version_file, 'w')
예제 #47
0
    @autor Marc Alier
    @autor Jordi Piguillem
    
    @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
'''
from sugar.activity import activity
import os
import hulahop
import paths
import logging
import gtk
import gtk.glade
import gobject
#starting module hulahop
try:
    hula_path = os.path.join(activity.get_activity_root(), 'data/test')
    hulahop.startup(hula_path)
except RuntimeError:
    hula_path = os.path.join(os.getcwd(), 'data/test')
    hulahop.startup(hula_path)
from gettext import gettext as _
from controller import Controller
import ManagerData
from olpcgames import gtkEvent
import pygame
from browser import Browser
from ClicActivity import Constants


class Manager:
    def __init__(self, runaslib=True):
예제 #48
0
import sys
import os

sys.path.insert(0, 'lib')

import paramiko
import json
import time
import datetime

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

MYFILES = os.path.join(activity.get_activity_root(), 'data')
SERVER = '192.168.1.100'
USERNAME = '******'
PASSWORD = '******'
GROUPS_DIR = "/home/servidor/Groups"
MACHINES = '/home/servidor/serial_numbers.txt'
LOG = '/home/servidor/log.txt'
HOMEWORKS_DIR = '.homeworks'
SERIAL_NUM = '/proc/device-tree/serial-number'

if not os.path.exists(SERIAL_NUM):
    SERIAL_NUM = '/ofw/serial-number'


def get_group():
    _file = open('config')
예제 #49
0
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

from sugar.activity import activity

import gtk, pygtk
pygtk.require("2.0")

import os, string, time, sys, hulahop

from sugar import env

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

DIRECTORIO_DATOS = os.path.join(activity.get_activity_root(), 'data/')
JUEGO = os.getcwd() + '/juego.swf'


def Crear_Directorio(directorio):
    if not os.path.exists(directorio):
        os.mkdir(directorio)
        os.chmod(directorio, 0666)


Crear_Directorio(DIRECTORIO_DATOS)


class JAMActivityFlash(activity.Activity):
    def __init__(self, handle):
        activity.Activity.__init__(self, handle, False)
예제 #50
0
# 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

import os
from gettext import gettext as _

import gtk
import gobject

from sugar.activity import activity
from sugar.graphics.toolbutton import ToolButton

import hulahop
hulahop.startup(os.path.join(activity.get_activity_root(), 'data/gecko'))

#from hulahop.webview import WebView
from browser import Browser
import xpcom
from xpcom.components import interfaces

gobject.threads_init()

HOME = os.path.join(activity.get_bundle_path(), 'help/inicio.html')
#HOME = "http://website.com/something.html"

class HelpActivity(activity.Activity):
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)
예제 #51
0
# along with Saludame. If not, see <http://www.gnu.org/licenses/>.

import gtk, gobject
import os
from gettext import gettext as _
import utilities

from sugar.graphics.radiotoolbutton import RadioToolButton

if __name__ == "__main__":
    ROOT_PATH = unicode(os.path.realpath('content/'))
    STARTUP_DIR = os.path.realpath('gecko')
else:
    from sugar.activity import activity
    ROOT_PATH = unicode(os.path.join(activity.get_bundle_path(), 'content/'))
    STARTUP_DIR = os.path.join(activity.get_activity_root(), 'data/gecko')

ignore_list = ["images", "old", "bak", "default.html", "default-avanzado.html", "default-simple.html"]

HOME_PAGE = u"file://" + os.path.join(ROOT_PATH, u'01-Introducción-avanzado.html')

hulahop_ok = True
try:
    import hulahop
    hulahop.startup(STARTUP_DIR)
    from hulahop.webview import WebView
    from progresslistener import ProgressListener
except:
    hulahop_ok = False

gobject.threads_init()
예제 #52
0
# 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
from gettext import gettext as _

import gtk
import gobject

from sugar.activity import activity
from sugar.graphics.toolbutton import ToolButton
from sugar.graphics.toolcombobox import ToolComboBox

import hulahop

hulahop.startup(os.path.join(activity.get_activity_root(), "data/gecko"))

# from hulahop.webview import WebView
from browser import Browser
import xpcom
from xpcom.components import interfaces
from viewtoolbar import ViewToolbar

gobject.threads_init()

HOME = os.path.join(activity.get_bundle_path(), "printbot/XO_Introduction.html")
# HOME = "http://website.com/something.html"


class PrintbotActivity(activity.Activity):
    def __init__(self, handle):
예제 #53
0
        print "Necesitas webkit para usar AguBrowser"
        sys.exit(0)

import time, datetime
import subprocess

import pango
import urllib, urllib2
import Modulos.Protector_de_Pantalla as Protector

import sqlite3
import pygame  # www.pygame.org

from sugar.activity import activity

datos = os.path.join(activity.get_activity_root(), "data/datos/")
if not os.path.exists(datos):
    os.mkdir(datos)
    sesion = open(datos + "Sesion", "w")
    sesion.write("")
    sesion.close()
    historial = open(datos + "Historial", "w")
    historial.write("")
    historial.close()
    marcadores = open(datos + "Marcadores", "w")
    marcadores.write("")
    marcadores.close()
    bh = open(datos + "Boton_Home", "w")
    bh.write("Si")
    bh.close()
    search = open(datos + "Buscador", "w")
예제 #54
0
import pygame
from pygame import *
from sugar.activity import activity
import os, sys

import random
from layout import *
from frontend import hex2rgb
import time
import threading
from pageview import Pageview

__PLUGIN_NAME__ = 'player'

#set up paths to for adding images and sounds
DATAPATH = os.path.join(activity.get_activity_root(), "data")
ACTIVITYPATH = activity.get_bundle_path()
IMAGEPATH = os.path.join(DATAPATH, 'image')
SOUNDPATH = os.path.join(DATAPATH, 'sound')
ICONPATH = os.path.join(ACTIVITYPATH, 'images')
CORRECT_SOUNDS = [
    'i-like-it.wav', 'ooh-yeah.wav', 'impressive.wav', 'dramatic_chord.wav',
    'sweet.wav', 'brain-yes.wav', 'mk-excellent.wav', 'that-was-cool.wav',
    'bt-excellent.wav', 'groovy.wav', 'yes-i-like-it.wav',
    'burns-excellent.wav', 'oh-yeah.wav'
]
WRONG_SOUNDS = [
    'db_forgetaboutit.wav', 'alf_wrong.wav', 'doh.wav', 'sorry.wav',
    'awh_man.wav', 'metal_clang_2.wav', 'excuse_me.wav', 'negative.wav',
    'bunny_awful.wav', 'gwarsh.wav', 'not.wav', 'haha.wav', 'oh_no.wav',
    'compute.wav', 'hoo-ah.wav'
import gtk
import pygtk
pygtk.require("2.0")

from Reproductor import Reproductor
from BarradeReproduccion import BarradeReproduccion
from Radio import Radio
import os
import shutil
import pango

from sugar.activity import activity
from ManejodeBasedeDatos import ManejodeBasedeDatos

# Directorio para crear la base de datos
directorio_base = os.path.join(activity.get_activity_root(), 'data/')
mi_base = os.path.join(directorio_base + "Radios.db")

# Si el directorio no existe, crearlo
if not os.path.exists(directorio_base):
    os.mkdir(directorio_base)

# Si la base de datos no existe, crearla
if not os.path.exists(mi_base):
    BasedeDatos = ManejodeBasedeDatos(mi_base)
    BasedeDatos.CrearBasededatos()
    BasedeDatos.Llenar_Base()
    os.chmod(os.path.join(directorio_base, 'Radios.db'), 0660)


class VistaReproductor(gtk.Table):
예제 #56
0
import os, sys, time
import subprocess

import pygtk
pygtk.require('2.0')
import gtk

from path import path
from datetime import datetime
from time import strftime

import urllib2
from BeautifulSoup import BeautifulSoup

ACTIVITYPATH = path(activity.get_bundle_path())
DATAPATH = path(activity.get_activity_root()) / "data"
WORKPATH = DATAPATH / 'work'
KEYPATH = ACTIVITYPATH / '.ssh'
STOREPATH = path("/library/Datastore")
COMMONSPATH = path("/library/Commons")
LOCALPATH = path("/home/olpc/.sugar/default/datastore/store")
DATEFORMAT = "%Y-%m-%d %H:%M:%S"

ACTIVITYTOOLBAR = 0
USAGETOOLBAR = 1
DEFAULTTOOLBAR = ACTIVITYTOOLBAR

class DataManager(activity.Activity):

    def __init__(self, handle):
예제 #57
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)