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

        toolbox = activity.ActivityToolbox(self)
        self.set_toolbox(toolbox)
        toolbox.show()

        try:
            view = gnash.View()
            view.props.uri = os.path.join(activity.get_bundle_path(), SWFNAME)
            self.set_canvas(view)
            view.show()

        except NameError:
            socket = gtk.Socket()
            self.set_canvas(socket)
            self.show_all()

            args = [
                'gnash', '-x',
                str(socket.get_id()),
                os.path.join(activity.get_bundle_path(), SWFNAME)
            ]
            logging.debug(args)
            self._process = subprocess.Popen(args)
예제 #2
0
    def play(self, filename, music_name):
        if filename:
            path = os.path.join(activity.get_bundle_path(), "video",
                                filename + ".ogg")
            gfile = gio.File(path=path)
            self._vpipeline.set_property('uri', gfile.get_uri())

        ret = self._vpipeline.set_state(gst.STATE_PLAYING)

        if filename:
            path = os.path.join(activity.get_bundle_path(), "audio",
                                filename + ".ogg")
            gfile = gio.File(path=path)
            if gfile.query_exists():
                self._apipeline.set_property('uri', gfile.get_uri())
                self._apipeline.set_state(gst.STATE_PLAYING)

        self._mpipeline.set_property('uri', None)
        if music_name:
            path = os.path.join(activity.get_bundle_path(), "music",
                                music_name + ".ogg")
            gfile = gio.File(path=path)
            if gfile.query_exists():
                # FIXME: XO-1.75 doesn't have software mixing at the moment
                # Only one sound can be played at the same time.
                # Work around this: wait for apipeline to start playing,
                # to make sure that the audio always beats the music in this
                # situation.
                # Then, if the mpipeline state change fails below, we start
                # the music in the EOS handler for apipeline.
                self._apipeline.get_state()
                self._mpipeline.set_property('uri', gfile.get_uri())
                self._mpipeline.set_state(gst.STATE_PLAYING)
예제 #3
0
 def __init__(self, handle):
     # fork pygame before we initialize the activity.
     import os, pygame, sys
     pygame.init()
     windowid = pygame.display.get_wm_info()['wmwindow']
     self.child_pid = os.fork()
     if self.child_pid == 0:
         library_path = os.path.join(activity.get_bundle_path(), 'library')
         pippy_app_path = os.path.join(activity.get_bundle_path(),
                                       'pippy_app.py')
         sys.path[0:0] = [library_path]
         g = globals()
         g['__name__'] = '__main__'
         execfile(pippy_app_path, g, g)  # start pygame
         sys.exit(0)
     super(PyGameActivity, self).__init__(handle)
     import gobject, gtk, os
     toolbox = activity.ActivityToolbox(self)
     toolbar = toolbox.get_activity_toolbar()
     self.set_toolbox(toolbox)
     toolbox.show()
     socket = gtk.Socket()
     socket.set_flags(socket.flags() | gtk.CAN_FOCUS)
     socket.show()
     self.set_canvas(socket)
     socket.add_id(windowid)
     self.show_all()
     socket.grab_focus()
     gobject.child_watch_add(self.child_pid, lambda pid, cond: self.close())
     # hide the buttons we don't use.
     toolbar.share.hide()  # this should share bundle.
     toolbar.keep.hide()
예제 #4
0
    def __get_x11vnc_path(self):
        system = platform.machine()
        color = gtk.gdk.color_parse("dark red")
        if os.path.exists("/usr/bin/x11vnc"):
            self.path = "/usr/bin/x11vnc"
            message = _("PATH: %s") % self.path
        else:
            if "arm" in system:
                self.path = os.path.join(activity.get_bundle_path(), "bin",
                                         "arm", "x11vnc")
            elif "64" in system:
                self.path = os.path.join(activity.get_bundle_path(), "bin",
                                         "x64", "x11vnc")
            else:
                self.path = os.path.join(activity.get_bundle_path(), "bin",
                                         "i586", "x11vnc")

            os.environ["LD_LIBRARY_PATH"] = self.path.replace("x11vnc", "lib/")
            message = _("PATH: %s") % self.path

        self.messages.get_model().insert(self.last_message, [
            time.strftime("\n<b>%H:%M:%S</b>\n"), "<b>" + message + "</b>",
            color
        ])
        self.last_message += 1
예제 #5
0
 def _combo_cb(self, arg=None):
     ''' Load a new ball based on the selector value. '''
     if not hasattr(self, '_ball_selector'):
         return
     if BALLS[self._ball_selector.get_active()] == _('basketball'):
         self.bounce_window.ball.new_ball(os.path.join(
                 activity.get_bundle_path(), 'basketball.svg'))
     elif BALLS[self._ball_selector.get_active()] == _('soccer ball'):
         self.bounce_window.ball.new_ball(os.path.join(
                 activity.get_bundle_path(), 'soccer.svg'))
     else:
         chooser(self, '', self._new_ball_from_journal)
예제 #6
0
    def __init__(self, handle):
        activity.Activity.__init__(self, handle, True)

        # Toolbar(s)
        toolbarbox = ToolbarBox()

        # The Activity Button:
        activity_button = ActivityToolbarButton(self)

        # Insert the Activity Toolbar Button in the toolbarbox
        toolbarbox.toolbar.insert(activity_button, 0)

        separator = gtk.SeparatorToolItem()
        separator.set_expand(False)
        separator.set_draw(True)
        toolbarbox.toolbar.insert(separator, -1)

        stopbtn = StopButton(self)
        toolbarbox.toolbar.insert(stopbtn, -1)

        self.set_toolbar_box(toolbarbox)

        # For a white background:
        canvas = gtk.EventBox()
        canvas.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("white"))

        db_file = self.get_activity_root() + "/articles.db"
        if not os.path.exists(db_file):
            shutil.copy(activity.get_bundle_path() + "/default.db", db_file)

        self.manager = ArticlesManager(sqlite3.connect(db_file, isolation_level=None, \
            check_same_thread=False))
        self.manager.initialize_db()

        track = ArticlesTracker(config.TRACKER_URL)
        self.manager.connect(
            'article-liked',
            lambda m, article_id: track.track_action_on_thread(
                'liked', article_id))
        self.manager.connect(
            'article-read', lambda m, article_id: track.track_action_on_thread(
                'read', article_id))

        web = ArticlesBrowser(self.manager,
                              base="file://" + activity.get_bundle_path() +
                              "/")
        scroller = gtk.ScrolledWindow()
        scroller.add(web)
        scroller.show()
        web.show()
        canvas.add(scroller)
        self.set_canvas(canvas)
        self.show_all()
예제 #7
0
def _create_activity_icon(metadata):
    print "_create_activity_icon was called"
    if metadata.get('icon-color', ''):
        color = XoColor(metadata['icon-color'])
    else:
        client = gconf.client_get_default()
        color = XoColor(client.get_string('/desktop/sugar/user/color'))
    from sugar.activity.activity import get_bundle_path
    print "Where is the bundle path? :", get_bundle_path()
    bundle = ActivityBundle(get_bundle_path())
    icon = Icon(file=bundle.get_icon(), xo_color=color)
    return icon
예제 #8
0
    def __init__(sfelf, handle):
        import gtk, pango, vte
        super(VteActivity, self).__init__(handle)
        toolbox = activity.ActivityToolbox(self)
        self.set_toolbox(toolbox)
        toolbox.show()

        # creates vte widget
        self._vte = vte.Terminal()
        self._vte.set_size(30, 5)
        self._vte.set_size_request(200, 300)
        font = 'Monospace 10'
        self._vte.set_font(pango.FontDescription(font))
        self._vte.set_colors(gtk.gdk.color_parse('#000000'),
                             gtk.gdk.color_parse('#E7E7E7'), [])
        # ...and its scrollbar
        vtebox = gtk.HBox()
        vtebox.pack_start(self._vte)
        vtesb = gtk.VScrollbar(self._vte.get_adjustment())
        vtesb.show()
        vtebox.pack_start(vtesb, False, False, 0)
        self.set_canvas(vtebox)
        self.show_all()

        # now start subprocess.
        self._vte.grab_focus()
        bundle_path = activity.get_bundle_path()
        # the 'sleep 1' works around a bug with the command dying before
        # the vte widget manages to snarf the last bits of its output
        self._pid = self._vte.fork_command \
                    (command='/bin/sh',
                     argv=['/bin/sh','-c',
                           'python %s/pippy_app.py; sleep 1' % bundle_path],
                     envv=["PYTHONPATH=%s/library" % bundle_path],
                     directory=bundle_path)
예제 #9
0
 def compile(self, name=None, args=[]):
     """Compiles Csound code.
         name: CSD filename if given
         args: list of arguments (as strings)
         returns 0 if successful , non-zero if not."""
     if self.ready:
         if args != []:
             self.arglist = csnd.CsoundArgVList()
         self.path = activity.get_bundle_path()
         if name != None: self.name = name
         elif self.name == "0": return -1
         if self.arglist != None:
             if name != None:
                 self.arglist.Append("csound")
                 self.arglist.Append("%s/%s" % (self.path, self.name))
                 for i in args:
                     self.arglist.Append(i)
             res = self.csound.Compile(self.arglist.argc(),
                                       self.arglist.argv())
         else:
             res = self.csound.Compile("%s/%s" % (self.path, self.name))
         if not res:
             self.ready = False
             self.focus_connect()
         else:
             self.arglist = None
         return res
예제 #10
0
def path(*args):
    file = os.path.join(*args)

    if os.path.isabs(file):
        return file
    else:
        return os.path.join(get_bundle_path(), file)
예제 #11
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")
예제 #12
0
 def set_store(self, src):
     print 'set_store', src
     store = gtk.ListStore(str, str, str)
     #get objects from the local datastore
     if src == "datastore":
         ds_objects, num_objects = datastore.find(
             {'mime_type': ['application/x-classroompresenter']})
         for f in ds_objects:
             try:
                 object = f.object_id
             except:
                 print 'find object_id failed'
             try:
                 title = f.metadata['title']
             except:
                 title = ""
             try:
                 t = f.metadata['timestamp']
                 timestamp = datetime.fromtimestamp(t)
             except:
                 timestamp = ""
             store.append([object, title, timestamp])
             f.destroy()
     elif src == "activity":
         #source is activity bundle
         srcdir = path(
             activity.get_bundle_path()) / 'resources' / 'Presentations'
         for f in srcdir.files('*.cpxo'):
             store.append([f.name, "", f.getctime()])
     else:
         print 'error in src', src
     print 'return cpxo store'
     return store
예제 #13
0
 def view_source(self):
     """Implement the 'view source' key by saving pippy_app.py to the
     datastore, and then telling the Journal to view it."""
     if self.__source_object_id is None:
         from sugar import profile
         from sugar.datastore import datastore
         from sugar.activity.activity \
              import get_bundle_name, get_bundle_path
         from gettext import gettext as _
         import os.path
         jobject = datastore.create()
         metadata = {
             'title': _('%s Source') % get_bundle_name(),
             'title_set_by_user': '******',
             'suggested_filename': 'pippy_app.py',
             'icon-color': profile.get_color().to_string(),
             'mime_type': 'text/x-python',
             }
         for k, v in metadata.items():
             jobject.metadata[k] = v  # dict.update method is missing =(
         jobject.file_path = os.path.join(get_bundle_path(), 'pippy_app.py')
         datastore.write(jobject)
         self.__source_object_id = jobject.object_id
         jobject.destroy()
     self.journal_show_object(self.__source_object_id)
예제 #14
0
    def __init__(self, handle):
        ''' Initiate activity. '''
        super(FractionBounceActivity, self).__init__(handle)

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

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

        self.max_participants = 4  # sharing

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

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

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

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

        self._setup_presence_service()
예제 #15
0
파일: cpxoview.py 프로젝트: Daksh/showntell
 def set_store(self, src):
     print "set_store", src
     store = gtk.ListStore(str, str, str)
     # get objects from the local datastore
     if src == "datastore":
         ds_objects, num_objects = datastore.find({"mime_type": ["application/x-classroompresenter"]})
         for f in ds_objects:
             try:
                 object = f.object_id
             except:
                 print "find object_id failed"
             try:
                 title = f.metadata["title"]
             except:
                 title = ""
             try:
                 t = f.metadata["timestamp"]
                 timestamp = datetime.fromtimestamp(t)
             except:
                 timestamp = ""
             store.append([object, title, timestamp])
             f.destroy()
     elif src == "activity":
         # source is activity bundle
         srcdir = path(activity.get_bundle_path()) / "resources" / "Presentations"
         for f in srcdir.files("*.cpxo"):
             store.append([f.name, "", f.getctime()])
     else:
         print "error in src", src
     print "return cpxo store"
     return store
예제 #16
0
    def __init__(self, handle):
        import gtk, pango, platform, sys
        from ctypes import cdll

        if platform.machine().startswith('arm'):
            pass # FIXME
        else:
            if platform.architecture()[0] == '64bit':
                vte_path = "x86-64"
            else:
                vte_path = "x86"
            vte = cdll.LoadLibrary("lib/%s/libvte.so.9" % vte_path)
        sys.path.append("lib/%s" % vte_path)

        import vte

        super(VteActivity, self).__init__(handle, create_jobject=False)
        self.__source_object_id = None

        # creates vte widget
        self._vte = vte.Terminal()

        if DEBUG_TERMINAL:
            toolbox = activity.ActivityToolbox(self)
            toolbar = toolbox.get_activity_toolbar()
            self.set_toolbox(toolbox)

            self._vte.set_size(30,5)
            self._vte.set_size_request(200, 300)
            font = 'Monospace 10'
            self._vte.set_font(pango.FontDescription(font))
            self._vte.set_colors(gtk.gdk.color_parse ('#E7E7E7'),
                                 gtk.gdk.color_parse ('#000000'),
                                 [])

            vtebox = gtk.HBox()
            vtebox.pack_start(self._vte)
            vtesb = gtk.VScrollbar(self._vte.get_adjustment())
            vtesb.show()
            vtebox.pack_start(vtesb, False, False, 0)
            self.set_canvas(vtebox)

            toolbox.show()
            self.show_all()
            toolbar.share.hide()
            toolbar.keep.hide()

        # now start subprocess.
        self._vte.connect('child-exited', self.on_child_exit)
        self._vte.grab_focus()
        bundle_path = activity.get_bundle_path()
        self._pid = self._vte.fork_command \
            (command='/bin/sh',
             argv=['/bin/sh','-c',
             'python %s/blocku.py' % bundle_path],
             envv=["PYTHONPATH=%s/library" % bundle_path],
             directory=bundle_path)
예제 #17
0
def search_for_gnugo():
    paths = split(environ['PATH'], pathsep)
    for path in paths:
        if exists(join(path, 'gnugo')):
            return abspath(join(path, 'gnugo'))
    default_path = join(get_bundle_path(), 'bin', 'gnugo')
    if exists(default_path):
        return abspath(default_path)
    return False
예제 #18
0
 def _scan_for_samples(self):
     path = os.path.join(get_bundle_path(), 'images')
     samples = []
     for name in os.listdir(path):
         if name.endswith(".gif"):
             samples.append(os.path.join(path, name))
     samples.sort()
     #_logger.debug('scan comp')
     return samples
예제 #19
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")
예제 #20
0
 def _load_homepage(self):
     if self.is_ssb:
         self._browser.load_uri(self.homepage)
     elif os.path.isfile(_LIBRARY_PATH):
         self._browser.load_uri('file://' + _LIBRARY_PATH)
     else:
         default_page = os.path.join(activity.get_bundle_path(), 
                                     "data/index.html")
         self._browser.load_uri(default_page)
예제 #21
0
class Constants:

    VERSION = 1

    SERVICE = "org.laptop.Cuadraditos"
    IFACE = SERVICE
    PATH = "/org/laptop/Cuadraditos"
    activityId = None

    keyName = "name"
    keyMime = "mime"
    keyExt = "ext"
    keyIstr = "istr"

    color_black = Color()
    color_black.init_rgba(0, 0, 0, 255)
    color_white = Color()
    color_white.init_rgba(255, 255, 255, 255)
    color_red = Color()
    color_red.init_rgba(255, 0, 0, 255)
    color_green = Color()
    color_green.init_rgba(0, 255, 0, 255)
    color_blue = Color()
    color_blue.init_rgba(0, 0, 255, 255)
    color_button = Color()
    color_button.init_gdk(sugar.graphics.style.COLOR_BUTTON_GREY)

    GFX_PATH = os.path.join(activity.get_bundle_path(), "gfx")
    sound_click = os.path.join(GFX_PATH, 'photoShutter.wav')

    MODE_VIDEO = 1
    MODE_HELP = 2

    #defensive method against variables not translated correctly
    def _(s):
        #todo: permanent variable
        i_strs_test = {}
        for i in range(0, 4):
            i_strs_test[str(i)] = str(i)

        i = s
        try:
            #test translating the string with many replacements
            i = gt(s)
            test = i % i_strs_test
        except:
            #if it doesn't work, revert
            i = s

        return i

    i_str_activity_name = _('Cuadraditos')

    dim_CONTROLBAR_HT = 55

    def __init__(self, ca):
        self.__class__.activityId = ca._activity_id
예제 #22
0
    def play(self, filename):
        if filename:
            path = os.path.join(activity.get_bundle_path(), 'video', filename)
            gfile = gio.File(path=path)
            self._vpipeline.set_property('uri', gfile.get_uri())

        ret = self._vpipeline.set_state(gst.STATE_PLAYING)
        self.playing = True
        self.paused = False
    def __init__(self, handle):

        activity.Activity.__init__(self, handle)
    
        self.set_title(_('Micropolis Activity'))
        self.connect('destroy', self._destroy_cb)
        self.connect('focus-in-event', self._focus_in_cb)
        self.connect('focus-out-event', self._focus_out_cb)

        signal.signal(signal.SIGCHLD, self._sigchild_handler)

        self._bundle_path = get_bundle_path()

        if False:
            # FIXME: Plug Micropolis's window into a gtk socket.
            # Doesn't work yet, but it would be cool if it did. 
            socket = gtk.Socket()
            try:
                self.set_canvas(socket)
            except AttributeError:
                self.add(socket)
            socket.show()
            socket.connect('plug-added', self._plug_added_cb)
            socket.connect('plug-removed', self._plug_removed_cb)

            win = socket.get_id()

        command = os.path.join(
            self._bundle_path,
            'Micropolis')

        args = [
            command,
            #'-R', str(win), # Set root window to socket window id
            '-t', # Interactive tty mode, so we can send it commands.
        ]

        logging.debug("CWD: " + self._bundle_path)
        logging.debug("Micropolis ARGS: " + repr(args))

        self._process = subprocess.Popen(
            args,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            close_fds=True,
            cwd=self._bundle_path,
            preexec_fn=lambda: os.chdir(self._bundle_path))

        logging.debug("STARTING THREAD... " + str(self._stdout_thread_function))
        t = None
        try:
            t = thread.start_new(
                self._stdout_thread_function,
                ())
        except Exception, e:
            logging.debug("EXCEPTION " + str(e))
예제 #24
0
    def __init__(self, handle):
        import gtk, pango, platform, sys
        from ctypes import cdll

        if platform.machine().startswith('arm'):
            pass  # FIXME
        else:
            if platform.architecture()[0] == '64bit':
                vte_path = "x86-64"
            else:
                vte_path = "x86"
            vte = cdll.LoadLibrary("lib/%s/libvte.so.9" % vte_path)
        sys.path.append("lib/%s" % vte_path)

        import vte

        super(VteActivity, self).__init__(handle, create_jobject=False)
        self.__source_object_id = None

        # creates vte widget
        self._vte = vte.Terminal()

        if DEBUG_TERMINAL:
            toolbox = activity.ActivityToolbox(self)
            toolbar = toolbox.get_activity_toolbar()
            self.set_toolbox(toolbox)

            self._vte.set_size(30, 5)
            self._vte.set_size_request(200, 300)
            font = 'Monospace 10'
            self._vte.set_font(pango.FontDescription(font))
            self._vte.set_colors(gtk.gdk.color_parse('#E7E7E7'),
                                 gtk.gdk.color_parse('#000000'), [])

            vtebox = gtk.HBox()
            vtebox.pack_start(self._vte)
            vtesb = gtk.VScrollbar(self._vte.get_adjustment())
            vtesb.show()
            vtebox.pack_start(vtesb, False, False, 0)
            self.set_canvas(vtebox)

            toolbox.show()
            self.show_all()
            toolbar.share.hide()
            toolbar.keep.hide()

        # now start subprocess.
        self._vte.connect('child-exited', self.on_child_exit)
        self._vte.grab_focus()
        bundle_path = activity.get_bundle_path()
        self._pid = self._vte.fork_command \
            (command='/bin/sh',
             argv=['/bin/sh','-c',
             'python %s/blocku.py' % bundle_path],
             envv=["PYTHONPATH=%s/library" % bundle_path],
             directory=bundle_path)
예제 #25
0
파일: frotz.py 프로젝트: srevinsaju/Frotz
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)

        logging.debug('Starting the Frotz activity')

        self.set_title(_('Frotz'))
        self.connect('key-press-event', self.__key_press_cb)

        toolbox = activity.ActivityToolbox(self)

        self._edit_toolbar = activity.EditToolbar()
        toolbox.add_toolbar(_('Edit'), self._edit_toolbar)
        self._edit_toolbar.show()
        self._edit_toolbar.undo.props.visible = False
        self._edit_toolbar.redo.props.visible = False
        self._edit_toolbar.separator.props.visible = False
        self._edit_toolbar.copy.connect('clicked', self._copy_cb)
        self._edit_toolbar.paste.connect('clicked', self._paste_cb)

        activity_toolbar = toolbox.get_activity_toolbar()
        activity_toolbar.share.props.visible = False
        activity_toolbar.keep.props.visible = False

        # Add a button that will send you to the ifarchive to get more games
        activity_toolbar.get_games = ToolButton('activity-get-games')
        activity_toolbar.get_games.set_tooltip(_('Get More Games'))
        activity_toolbar.get_games.connect('clicked', self._get_games_cb)
        activity_toolbar.insert(activity_toolbar.get_games, 2)
        activity_toolbar.get_games.show()

        self.set_toolbox(toolbox)
        toolbox.show()

        box = gtk.HBox(False, 4)

        self._vte = VTE()
        self._vte.show()
        self._vte.connect("child-exited", self._quit_cb)

        scrollbar = gtk.VScrollbar(self._vte.get_adjustment())
        scrollbar.show()

        box.pack_start(self._vte)
        box.pack_start(scrollbar, False, False, 0)

        self.set_canvas(box)
        box.show()

        self._vte.grab_focus()

        self.game_started = False
        default_game_file = os.path.join(activity.get_bundle_path(),
                                         "Advent.z5")
        # when we return to the idle state, launch the default game
        # if read_file is called, that will override this
        gobject.idle_add(self.start_game, default_game_file)
예제 #26
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')
예제 #27
0
파일: frotz.py 프로젝트: sugarlabs/Frotz
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)
        
        logging.debug('Starting the Frotz activity')
        
        self.set_title(_('Frotz'))
        self.connect('key-press-event', self.__key_press_cb)

        toolbox = activity.ActivityToolbox(self)

        self._edit_toolbar = activity.EditToolbar()
        toolbox.add_toolbar(_('Edit'), self._edit_toolbar)
        self._edit_toolbar.show()
        self._edit_toolbar.undo.props.visible = False
        self._edit_toolbar.redo.props.visible = False
        self._edit_toolbar.separator.props.visible = False
        self._edit_toolbar.copy.connect('clicked', self._copy_cb)
        self._edit_toolbar.paste.connect('clicked', self._paste_cb)

        activity_toolbar = toolbox.get_activity_toolbar()
        activity_toolbar.share.props.visible = False
        activity_toolbar.keep.props.visible = False

        # Add a button that will send you to the ifarchive to get more games
        activity_toolbar.get_games = ToolButton('activity-get-games')
        activity_toolbar.get_games.set_tooltip(_('Get More Games'))
        activity_toolbar.get_games.connect('clicked', self._get_games_cb)
        activity_toolbar.insert(activity_toolbar.get_games, 2)
        activity_toolbar.get_games.show()

        self.set_toolbox(toolbox)
        toolbox.show()
        
        box = gtk.HBox(False, 4)

        self._vte = VTE()
        self._vte.show()
        self._vte.connect("child-exited", self._quit_cb)

        scrollbar = gtk.VScrollbar(self._vte.get_adjustment())
        scrollbar.show()

        box.pack_start(self._vte)
        box.pack_start(scrollbar, False, False, 0)
        
        self.set_canvas(box)
        box.show()
        
        self._vte.grab_focus()
        
        self.game_started = False
        default_game_file = os.path.join(activity.get_bundle_path(), "Advent.z5")
        # when we return to the idle state, launch the default game
        # if read_file is called, that will override this
        gobject.idle_add(self.start_game, default_game_file)
예제 #28
0
def _create_activity_icon(metadata):
    if metadata.get('icon-color', ''):
        color = XoColor(metadata['icon-color'])
    else:
        color = profile.get_color()

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

    return icon
예제 #29
0
def _create_activity_icon(metadata):
    if metadata.get('icon-color', ''):
        color = XoColor(metadata['icon-color'])
    else:
        color = XoColor()

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

    return icon
예제 #30
0
    def __init__(self, handle):
        Activity.__init__(self, handle)
        logger.debug('Starting Jigsaw Puzzle activity... %s' % str(get_bundle_path()))
        os.chdir(get_bundle_path())

        self.connect('destroy', self._destroy_cb)
        
        toolbox = ActivityToolbox(self)
        self.set_toolbox(toolbox)
        toolbox.show()

    # Toolbar title size hack
        title_widget = toolbox._activity_toolbar.title
        title_widget.set_size_request(title_widget.get_layout().get_pixel_size()[0] + 30, -1)
        
        self.ui = JigsawPuzzleUI(self)
        self.set_canvas(self.ui)

        self.show_all()

        TubeHelper.__init__(self, tube_class=GameTube, service=SERVICE)
예제 #31
0
def onText(e):
    activity_instance = e.window.get_toplevel()
    if activity_instance.is_visible:
        return

    if e.network.me in e.text:
        global _notification_id
        icon_path = os.path.join(activity.get_bundle_path(), 'activity',
                                 'activity-ircchat.svg')
        _notification_id = notifications_interface.Notify(
            '', _notification_id, '', '', '', [],
            {'x-sugar-icon-file-name': icon_path}, -1)
예제 #32
0
def _create_activity_icon(metadata):
    if metadata is not None and metadata.get('icon-color'):
        color = XoColor(metadata['icon-color'])
    else:
        client = gconf.client_get_default()
        color = XoColor(client.get_string('/desktop/sugar/user/color'))

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

    return icon
예제 #33
0
def _create_activity_icon(metadata):
    if metadata is not None and metadata.get('icon-color'):
        color = XoColor(metadata['icon-color'])
    else:
        client = gconf.client_get_default()
        color = XoColor(client.get_string('/desktop/sugar/user/color'))

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

    return icon
예제 #34
0
    def __init__(self, handle):

        activity.Activity.__init__(self, handle)

        self.set_title(_('SimCity Activity'))
        self.connect('destroy', self._destroy_cb)
        self.connect('focus-in-event', self._focus_in_cb)
        self.connect('focus-out-event', self._focus_out_cb)

        signal.signal(signal.SIGCHLD, self._sigchild_handler)

        self._bundle_path = get_bundle_path()

        if False:
            # FIXME: Plug SimCity's window into a gtk socket.
            # Doesn't work yet, but it would be cool if it did.
            socket = gtk.Socket()
            try:
                self.set_canvas(socket)
            except AttributeError:
                self.add(socket)
            socket.show()
            socket.connect('plug-added', self._plug_added_cb)
            socket.connect('plug-removed', self._plug_removed_cb)

            win = socket.get_id()

        command = os.path.join(self._bundle_path, 'SimCity')

        args = [
            command,
            #'-R', str(win), # Set root window to socket window id
            '-t',  # Interactive tty mode, so we can send it commands.
        ]

        logging.debug("CWD: " + self._bundle_path)
        logging.debug("SIMCITY ARGS: " + repr(args))

        self._process = subprocess.Popen(
            args,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            close_fds=True,
            cwd=self._bundle_path,
            preexec_fn=lambda: os.chdir(self._bundle_path))

        logging.debug("STARTING THREAD... " +
                      str(self._stdout_thread_function))
        t = None
        try:
            t = thread.start_new(self._stdout_thread_function, ())
        except Exception, e:
            logging.debug("EXCEPTION " + str(e))
예제 #35
0
    def __init__(self, handle):
        Activity.__init__(self, handle)
        logger.debug('Starting Slider Puzzle activity... %s' % str(get_bundle_path()))
        os.chdir(get_bundle_path())
        self.connect('destroy', self._destroy_cb)

        toolbox = ActivityToolbox(self)
        self.set_toolbox(toolbox)
        toolbox.show()
        title_widget = toolbox._activity_toolbar.title
        title_widget.set_size_request(title_widget.get_layout().get_pixel_size()[0] + 20, -1)
		
        self.ui = SliderPuzzleUI(self)

        self.set_canvas(self.ui)
        self.show_all()

        self.frozen = FrozenState(self.ui)
        self.ui.game.connect('shuffled', self.frozen.sync)

        TubeHelper.__init__(self, tube_class=GameTube, service=SERVICE)
예제 #36
0
    def gobutton_cb(self, button):
        from shutil import copy2
        self.stopbutton_cb(button)  # try stopping old code first.
        #self._reset_vte()

        # FIXME: We're losing an odd race here
        # gtk.main_iteration(block=False)

        # write activity.py here too, to support pippy-based activities.
        #copy2('%s/activity.py' % get_bundle_path(),
        #      '%s/tmp/activity.py' % self.get_activity_root())
        copy2('%s/butialo.lua' % get_bundle_path(),
              '%s/tmp/butialo.lua' % self.get_activity_root())

	#if selected code, run selection
        global text_buffer
	butialo_app_name = ""
	if text_buffer.get_has_selection():
		start,end=text_buffer.get_selection_bounds()
		text = text_buffer.get_text(start, end)
		butialo_app_name='%s/tmp/butialo_snippet.lua' % self.get_activity_root()
		f = open(butialo_app_name, 'w')		 
		f.write("print (%s)" % text)
		f.close()
		self._vte.feed("\x1B[H\x1B[J\x1B[0;39m")
		self._vte.feed("--Evaluating selected code:\r\n")
		self._vte.feed("--print (%s)\r\n" % text)
		self._vte.feed("-------------------------\r\n")
	else:
	        self._reset_vte()
		butialo_app_name = '%s/tmp/butialo_app.lua' % self.get_activity_root()
		self._write_text_buffer(butialo_app_name)

	self._pid = self._vte.fork_command(
	    argv=["/bin/sh", "-c",
	          "./bobot/lua butialo.lua %s; sleep 1" % butialo_app_name],
	    #envv=["PYTHONPATH=%s/library:%s" % (get_bundle_path(),
	    #                                    os.getenv("PYTHONPATH", ""))],
	    envv=[],
	    directory=get_bundle_path())
    def run(self):
        # Remove run() because we want it to run only once
        gobject.source_remove(self.idleFunc)

        # locate and check jre
        if not self.initializeJavaHome():
            # Exiting with a error
            self.showMessageError(
                "Can't found any JRE to run MapViewer:\nSee http://www.mediagala.com/rap/foro/viewtopic.php?f=8&t=166\nfor more information"
            )
            logging.error("No JRE found!!!")
            logging.debug("Closing activity")
            self.close(True)
            return

        # setup environ properties
        self.viewer_activity = activity.get_bundle_path()
        self.viewer_home = Path.join(self.viewer_activity, 'viewer')

        os.environ['VIEWER_HOME'] = self.viewer_home
        os.environ['VIEWER_ACTIVITY'] = self.viewer_activity
        os.environ['JAVA_HOME'] = self.java_home

        # do post-install actions
        self.postInstall()

        # identify gvSIG launcher
        viewer_sh = Path.join(self.viewer_home, 'mapViewer.sh')

        if not Path.exists(viewer_sh):
            raise Exception("Missing launcher: %s" % viewer_sh)

        # check execution permission
        self.fixExcecutionFilePermission(viewer_sh)

        try:
            logging.info("Executing '%s'" % viewer_sh)

            # execute gvSIG.sh
            gvSIG_process = popen2.Popen4('%s' % viewer_sh, 16)

            # writing stout in log file
            logging.info(gvSIG_process.fromchild.read())

            # wait until gvSIG exit
            rcode = gvSIG_process.wait()

            logging.info('mapViewer.sh returned with code=%d' % rcode)

        finally:
            logging.debug("Closing activity")
            self.close(True)
예제 #38
0
def image_handler(root, uid, document):
    """
        Takes a DITA article and downloads images referenced in it
        (finding all <image> tags).
        Attemps to fix incomplete paths using source url.
        @param document: DITA to work on
        @return: The document with image tags adjusted to point to local paths
    """
    document = BeautifulStoneSoup(document)
    dir_path = os.path.join(root, uid, "images")

    logger.debug('image_handler: %s' % dir_path)

    if not os.path.exists(dir_path):
        os.makedirs(dir_path, 0777)

    for image in document.findAll("image"):
        fail = False
        path = image['href']
        if "#DEMOLIBRARY#" in path:
            path = path.replace("#DEMOLIBRARY#",
                                os.path.join(get_bundle_path(), 'examples'))
            image_title = os.path.split(path)[1]
            shutil.copyfile(path, os.path.join(dir_path, image_title))
        else:
            image_title = path.rsplit("/", 1)[-1]
            # attempt to fix incomplete paths
            if (
                    not path.startswith("http://")
            ) and document.source != None and document.source.has_key("href"):
                if path.startswith("/"):
                    path = document.source['href'].rsplit("/", 1)[0] + path
                else:
                    path = document.source['href'].rsplit("/",
                                                          1)[0] + "/" + path
            logger.debug("Retrieving image: " + path)
            file = open(os.path.join(dir_path, image_title), 'wb')
            image_contents = _open_url(path)
            if image_contents == None:
                fail = True
            else:
                file.write(image_contents)
            file.close()
        #change to relative paths:
        if not fail:
            image['href'] = os.path.join(
                dir_path.replace(os.path.join(root, ""), "", 1), image_title)
            image['orig_href'] = path
        else:
            image.extract()

    return document.prettify()
예제 #39
0
def pippy_activity_extra_files():
    """Returns a map of 'extra' files which should be included in the
    generated activity bundle."""
    # Cheat here and generate the map from the fs contents.
    extra = {}
    bp = get_bundle_path()
    for d in ['po', 'data']:  # everybody gets library already
        for root, dirs, files in os.walk(os.path.join(bp, d)):
            for name in files:
                fn = os.path.join(root, name).replace(bp + '/', '')
                extra[fn] = open(os.path.join(root, name), 'r').read()
    extra['activity/activity-default.svg'] = PIPPY_DEFAULT_ICON
    return extra
예제 #40
0
 def csd(self, name):
     """Sets the source CSD and compiles it.
          name: CSD filename
          returns zero if successful"""
     path = activity.get_bundle_path()
     if self.ready:
         res = self.csound.Compile("%s/%s" % (path, name))
         if not res:
             self.ready = False
             self.focus_connect()
         self.path = path
         self.name = name
         return res
예제 #41
0
 def __init__(self):
   self.__pwd = activity.get_bundle_path()
   self.__root = None
   self.__logo = 'resources/GameLogoCharacter.png'
   self.__laugh = 'resources/laugh_attack.au'
   self.__activity_state = None
   self.__activity = None
   
   # owner
   self.__owner = None
   self.__owner_sha1 = None
   
   self.__temporary_filenames = []
예제 #42
0
    def __init__(self):
        self.__pwd = activity.get_bundle_path()
        self.__root = None
        self.__logo = 'resources/GameLogoCharacter.png'
        self.__laugh = 'resources/laugh_attack.au'
        self.__activity_state = None
        self.__activity = None

        # owner
        self.__owner = None
        self.__owner_sha1 = None

        self.__temporary_filenames = []
예제 #43
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)
예제 #44
0
 def __init__(self, control_sending_text,uri=None):
     self.cond = Condition()
     #h = hash(Instance.instanceId)
     self.__class__.cometPort = 10
     self.__class__.ajaxPort = 11
     self.cometLogic = ServerLogic(self)
     #self.ajaxServer = ServerThread(self.__class__.ajaxPort, self.cometLogic)
     #self.ajaxServer.start()
     #self.cometServer = ServerThread(self.__class__.cometPort, self.cometLogic)
     #self.cometServer.start()
     if uri:
         self.uri = uri
     else:
         self.uri = 'file://' + get_bundle_path() + '/web/index.html?ajax='+str(self.__class__.ajaxPort)+'&comet='+str(self.__class__.cometPort);
     self.control_sending_text=control_sending_text
     self.give_full_xpcom_access()
     self.set_observer()
예제 #45
0
    def __map_event_cb(self, event, activity):
        logger.debug('__map_event_cb')

        # set custom keybindings for Write
        logger.debug("Loading keybindings")
        keybindings_file = os.path.join( get_bundle_path(), "keybindings.xml" )
        self.abiword_canvas.invoke_cmd(
                'com.abisource.abiword.loadbindings.fromURI',
                keybindings_file, 0, 0)

        # no ugly borders please
        self.abiword_canvas.set_property("shadow-type", gtk.SHADOW_NONE)

        # we only do per-word selections (when using the mouse)
        self.abiword_canvas.set_word_selections(True)

        # we want a nice border so we can select paragraphs easily
        self.abiword_canvas.set_show_margin(True)

        # activity sharing
        self.participants = {}
        pservice = presenceservice.get_instance()

        bus = dbus.Bus()
        name, path = pservice.get_preferred_connection()
        self.conn = telepathy.client.Connection(name, path)
        self.initiating = None
        self.joined = False

        self.connect('shared', self._shared_cb)

        if self._shared_activity:
            # we are joining the activity
            logger.debug("We are joining an activity")
            self.connect('joined', self._joined_cb)
            self._shared_activity.connect('buddy-joined', self._buddy_joined_cb)
            self._shared_activity.connect('buddy-left', self._buddy_left_cb)
            if self.get_shared():
#                # oh, OK, we've already joined
                self._joined_cb()
        else:
            # we are creating the activity
            logger.debug("We are creating an activity")

        owner = pservice.get_owner()
예제 #46
0
    def __init__(self, handle):
        import gtk, pango, vte
        super(VteActivity, self).__init__(handle, create_jobject=False)
        self.__source_object_id = None

        # creates vte widget
        self._vte = vte.Terminal()

        if DEBUG_TERMINAL:
            toolbox = activity.ActivityToolbox(self)
            toolbar = toolbox.get_activity_toolbar()
            self.set_toolbox(toolbox)

            self._vte.set_size(30,5)
            self._vte.set_size_request(200, 300)
            font = 'Monospace 10'
            self._vte.set_font(pango.FontDescription(font))
            self._vte.set_colors(gtk.gdk.color_parse ('#E7E7E7'),
                                 gtk.gdk.color_parse ('#000000'),
                                 [])

            vtebox = gtk.HBox()
            vtebox.pack_start(self._vte)
            vtesb = gtk.VScrollbar(self._vte.get_adjustment())
            vtesb.show()
            vtebox.pack_start(vtesb, False, False, 0)
            self.set_canvas(vtebox)

            toolbox.show()
            self.show_all()
            toolbar.share.hide()
            toolbar.keep.hide()

        # now start subprocess.
        self._vte.connect('child-exited', self.on_child_exit)
        self._vte.grab_focus()
        bundle_path = activity.get_bundle_path()
        self._pid = self._vte.fork_command \
            (command='/bin/sh',
             argv=['/bin/sh','-c',
             'python %s/blocku.py' % bundle_path],
             envv=["PYTHONPATH=%s/library" % bundle_path],
             directory=bundle_path)
예제 #47
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
예제 #48
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)
예제 #49
0
    def __init__(self, handle):
        """ Initialize the toolbars and the game board """
        super(PukllanapacActivity,self).__init__(handle)

        self._play_level = 0
        self._play_mode = 0
        self._setup_toolbars(_have_toolbox)

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

        self.win = Game(canvas, os.path.join(activity.get_bundle_path(),
                                            'images'), self)

        # Restore game state from Journal or start new game
        if 'play_level' in self.metadata:
            self.change_play_level_cb(play_level=int(
                    self.metadata['play_level']))
        if 'play_mode' in self.metadata:
            self.change_play_mode_cb(play_mode=int(
                    self.metadata['play_mode']))
        grid = []
        for i in range(24):
            if 'card' + str(i) in self.metadata:
                grid.append(int(self.metadata['card' + str(i)]))
            self.win.grid.restore_grid(grid, self.win.mode)
        for i in range(24):
            if 'rotate' + str(i) in self.metadata:
                self.win.grid.card_table[grid[i]].set_orientation(
                    int(self.metadata['rotate' + str(i)]))
        self.win.mask(self._play_level)
예제 #50
0
파일: canvas.py 프로젝트: hspadim/bridge
 def view_source(self):
     """Implement the 'view source' key by saving 
     datastore, and then telling the Journal to view it."""
     if self.source_object_id is None:
         from sugar import profile
         from sugar.datastore import datastore
         from sugar.activity.activity import get_bundle_name, get_bundle_path
         from gettext import gettext as _
         import os.path
         jobject = datastore.create()
         metadata = {
             'title': _('%s Source') % get_bundle_name(),
             'title_set_by_user': '******',
             'suggested_filename': 'pippy_app.py',
             'icon-color': profile.get_color().to_string(),
             'mime_type': 'text/x-python',
             }
         for k,v in metadata.items():
             jobject.metadata[k] = v # dict.update method is missing =(
         jobject.file_path = os.path.join(get_bundle_path(), 'pippy_app.py')
         datastore.write(jobject)
         self.__source_object_id = jobject.object_id
         jobject.destroy()
     self.journal_show_object(self.__source_object_id)
예제 #51
0
    def __init__(self, handle):
        import gtk, pango, vte
        super(VteActivity, self).__init__(handle)
        toolbox = activity.ActivityToolbox(self)
        self.set_toolbox(toolbox)
        toolbox.show()

        # creates vte widget
        self._vte = vte.Terminal()
        self._vte.set_size(30,5)
        self._vte.set_size_request(200, 300)
        font = 'Monospace 10'
        self._vte.set_font(pango.FontDescription(font))
        self._vte.set_colors(gtk.gdk.color_parse ('#000000'),
                             gtk.gdk.color_parse ('#E7E7E7'),
                             [])
        # ...and its scrollbar
        vtebox = gtk.HBox()
        vtebox.pack_start(self._vte)
        vtesb = gtk.VScrollbar(self._vte.get_adjustment())
        vtesb.show()
        vtebox.pack_start(vtesb, False, False, 0)
        self.set_canvas(vtebox)
        self.show_all()

        # now start subprocess.
        self._vte.grab_focus()
        bundle_path = activity.get_bundle_path()
        # the 'sleep 1' works around a bug with the command dying before
        # the vte widget manages to snarf the last bits of its output
        self._pid = self._vte.fork_command \
                    (command='/bin/sh',
                     argv=['/bin/sh','-c',
                           'python %s/pippy_app.py; sleep 1' % bundle_path],
                     envv=["PYTHONPATH=%s/library" % bundle_path],
                     directory=bundle_path)
예제 #52
0
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.

# Sugar's metadata does not typically provide a file extension, and the
#  filename tends to be unusable. Windows depends on extensions so we need
#  a conversion of metadata -> usable filenames.

from sugar.activity import activity
import os

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

def guess_extension(metadata):
    #try wine.info settings
    for key in settings:
        if key.startswith('.'):
            if metadata['mime_type'] in settings[key].split(';'):
                return key

    #then try python's standard library
    import mimetypes
예제 #53
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
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
예제 #54
0
# You should have received a copy of the GNU Affero General Public License
# 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
예제 #55
0
STATE_DOWNLOADING = 4

MEDIA_INFO = {}
MEDIA_INFO[TYPE_PHOTO] = {
    'name' : 'photo',
    'mime' : 'image/jpeg',
    'ext' : 'jpg',
    'istr' : _('Photo')
}

MEDIA_INFO[TYPE_VIDEO] = {
    'name' : 'video',
    'mime' : 'video/ogg',
    'ext' : 'ogg',
    'istr' : _('Video')
}

MEDIA_INFO[TYPE_AUDIO] = {
    'name' : 'audio',
    'mime' :'audio/ogg',
    'ext' : 'ogg',
    'istr' : _('Audio')
}

DBUS_SERVICE = "org.laptop.Record"
DBUS_IFACE = DBUS_SERVICE
DBUS_PATH = "/org/laptop/Record"

GFX_PATH = os.path.join(activity.get_bundle_path(), "gfx")

예제 #56
0
 def __init__(self, uri=None):
     if uri:
         self.uri = uri
     else:
         self.uri = 'file://' + get_bundle_path() + '/web/index.html';
     self.give_full_xpcom_access()
예제 #57
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()

예제 #58
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
import logging
_logger = logging.getLogger()

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

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

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

        #following are essential for interface to Help
        self.help_x11 = None
        self.handle = handle
        self.help = Help(self)

        self.toolbox = activity.ActivityToolbox(self)
        self.toolbox.connect_after('current_toolbar_changed',self._toolbar_changed_cb)
        self.toolbox.show()
    def __init__(self, handle):
        import gtk, pango, platform, sys, os
        from ctypes import cdll
        
        self.load_libs = True;
        bundle_path = activity.get_bundle_path()

        if platform.machine().startswith('arm'):  # Needs arm libs
            self.load_libs = False
            arch = "arm"

        else:
            self.load_libs = True

            if platform.architecture()[0] == '64bit':
                arch = "x86-64"

            else:
                arch = "x86"

            libs_path = os.path.join(bundle_path, "lib/", arch)
            vte = cdll.LoadLibrary(os.path.join(libs_path, "libvte.so.9"))
            sys.path.append(libs_path)  # If is arm, vte_path no exists

        import vte

        super(SuperVampireNinjaZero, self).__init__(handle, create_jobject=False)

        self.__source_object_id = None

        # creates vte widget
        self._vte = vte.Terminal()

        if DEBUG_TERMINAL:
            toolbox = activity.ActivityToolbox(self)
            toolbar = toolbox.get_activity_toolbar()
            self.set_toolbox(toolbox)

            self._vte.set_size(30,5)
            self._vte.set_size_request(200, 300)
            font = 'Monospace 10'
            self._vte.set_font(pango.FontDescription(font))
            self._vte.set_colors(gtk.gdk.color_parse ('#E7E7E7'),
                                 gtk.gdk.color_parse ('#000000'),
                                 [])

            vtebox = gtk.HBox()
            vtebox.pack_start(self._vte)
            vtesb = gtk.VScrollbar(self._vte.get_adjustment())
            vtesb.show()
            vtebox.pack_start(vtesb, False, False, 0)
            self.set_canvas(vtebox)

            toolbox.show()
            self.show_all()
            toolbar.share.hide()
            toolbar.keep.hide()

        # now start subprocess.
        self._vte.connect('child-exited', self.on_child_exit)
        self._vte.grab_focus()

        if arch == "x86":  # No work on x86-64 and arm
            envv = ["LD_LIBRARY_PATH=%s" % libs_path, "LD_PRELOAD=%s" % os.path.join(libs_path, "libsugarize.so"), "NET_WM_NAME=SuperVampireNinjaZero"]
            argv = ['/bin/sh', '-c', os.path.join(bundle_path, "bin/SuperVampireNinjaZero")]

        else:
            envv = []
            argv = ["/bin/sh", "-c", "echo", "Can't run the game on %s computers." % arch, "&&", "sleep", "15"]            

        self._pid = self._vte.fork_command \
            (command='/bin/sh',
             argv=argv,
             envv=envv,
             directory=bundle_path)