示例#1
0
    def play(self, filename, music_name):
        if filename:
            path = os.path.join(activity.get_bundle_path(), "video",
                                filename + ".ogg")
            gfile = Gio.File.new_for_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.new_for_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.new_for_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)
    def __init__(self, handle):
        # fork pygame before we initialize the activity.

        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')
            app_path = os.path.join(activity.get_bundle_path(), 'app.py')
            sys.path[0:0] = [library_path]
            g = globals()
            g['__name__'] = '__main__'
            execfile(app_path, g, g) # start pygame
            sys.exit(0)

        super(PyGameActivity, self).__init__(handle)

        toolbarbox = ToolbarBox()
        self.set_toolbar_box(toolbarbox)

        toolbar = toolbarbox.toolbar

        socket = Gtk.Socket()
        socket.set_can_focus(True)
        socket.add_id(windowid)
        self.set_canvas(socket)
        self.show_all()

        socket.grab_focus()
        GObject.child_watch_add(self.child_pid, lambda pid, cond: self.close())
示例#3
0
    def __init__(self, handle):
        # fork pygame before we initialize the activity.

        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')
            app_path = os.path.join(activity.get_bundle_path(), 'app.py')
            sys.path[0:0] = [library_path]
            g = globals()
            g['__name__'] = '__main__'
            execfile(app_path, g, g)  # start pygame
            sys.exit(0)

        super(PyGameActivity, self).__init__(handle)

        toolbarbox = ToolbarBox()
        self.set_toolbar_box(toolbarbox)

        toolbar = toolbarbox.toolbar

        socket = Gtk.Socket()
        socket.set_can_focus(True)
        socket.add_id(windowid)
        self.set_canvas(socket)
        self.show_all()

        socket.grab_focus()
        GObject.child_watch_add(self.child_pid, lambda pid, cond: self.close())
示例#4
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)
        toolbar_box = ToolbarBox()

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

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

        stop_button = StopButton(self)
        toolbar_box.toolbar.insert(stop_button, -1)
        stop_button.show()
        self.set_toolbar_box(toolbar_box)
        toolbar_box.show()

        self.ui = JigsawPuzzleUI(self)
        self.set_canvas(self.ui)

        self.show_all()

        TubeHelper.__init__(self, tube_class=GameTube, service=SERVICE)
示例#5
0
    def __get_x11vnc_path(self):
        system = platform.machine()
        color = 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
def get_index_uri():
    index_path = os.path.join(activity.get_bundle_path(),
                              'html/%s/index.html' % get_current_language())

    if not os.path.isfile(index_path):
        index_path = os.path.join(activity.get_bundle_path(),
                                  'html/index.html')
    return 'file://' + index_path
示例#7
0
def get_index_uri(loader='installer'):
    """ Returns static/installer.html if jupyter doesn't exist, else loads static/init.html """
    os.chdir(activity.get_bundle_path())
    index_path = os.path.join(activity.get_bundle_path(),
                              'static/{}.html'.format(loader))
    if not os.path.isfile(index_path):
        index_path = os.path.join(activity.get_bundle_path(),
                                  'static/{}.html'.format(loader))
    return 'file://' + index_path
示例#8
0
def get_index_uri():
    index_path = os.path.join(
        activity.get_bundle_path(),
        'html/%s/index.html' % get_current_language())

    if not os.path.isfile(index_path):
        index_path = os.path.join(
            activity.get_bundle_path(), 'html/index.html')
    return 'file://' + index_path
示例#9
0
    def __init__(self, layout_name, selected=False):
        super(Gtk.Image, self).__init__()

        if selected:
            path = os.path.join(activity.get_bundle_path(), 'layouts',
                                'format-' + layout_name + '-selected.png')
        else:
            path = os.path.join(activity.get_bundle_path(), 'layouts',
                                'format-' + layout_name + '.png')
        pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
            path, style.GRID_CELL_SIZE, style.GRID_CELL_SIZE)
        self.set_from_pixbuf(pixbuf)
        self.show()
示例#10
0
    def __init__(self, layout_name, selected=False):
        super(Gtk.Image, self).__init__()

        if selected:
            path = os.path.join(activity.get_bundle_path(), 'layouts',
                                'format-' + layout_name + '-selected.png')
        else:
            path = os.path.join(activity.get_bundle_path(), 'layouts',
                                'format-' + layout_name + '.png')
        pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
            path, style.GRID_CELL_SIZE, style.GRID_CELL_SIZE)
        self.set_from_pixbuf(pixbuf)
        self.show()
示例#11
0
    def __init__(self, font_name, selected=False):
        super(Gtk.Image, self).__init__()

        if selected:
            path = os.path.join(
                activity.get_bundle_path(), 'pytagcloud', 'fonts',
                font_name.replace(' ', '-') + '-selected.png')
        else:
            path = os.path.join(
                activity.get_bundle_path(), 'pytagcloud', 'fonts',
                font_name.replace(' ', '-') + '.png')
        pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
            path, style.SMALL_ICON_SIZE, style.SMALL_ICON_SIZE)
        self.set_from_pixbuf(pixbuf)
        self.show()
示例#12
0
    def __init__(self, font_name, selected=False):
        super(Gtk.Image, self).__init__()

        if selected:
            path = os.path.join(activity.get_bundle_path(), 'pytagcloud',
                                'fonts',
                                font_name.replace(' ', '-') + '-selected.png')
        else:
            path = os.path.join(activity.get_bundle_path(), 'pytagcloud',
                                'fonts',
                                font_name.replace(' ', '-') + '.png')
        pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
            path, style.SMALL_ICON_SIZE, style.SMALL_ICON_SIZE)
        self.set_from_pixbuf(pixbuf)
        self.show()
示例#13
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 BaseException:
                 print 'find object_id failed'
             try:
                 title = f.metadata['title']
             except BaseException:
                 title = ""
             try:
                 t = f.metadata['timestamp']
                 timestamp = datetime.fromtimestamp(t)
             except BaseException:
                 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
示例#14
0
    def __init__(self, handle):
        """ Initialize the toolbars and the game board """
        super(RecallActivity, self).__init__(handle)

        self.path = activity.get_bundle_path()

        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._restoring = False
        self._setup_toolbars(True)
        self._setup_dispatch_table()

        # Create a canvas
        canvas = Gtk.DrawingArea()
        canvas.set_size_request(Gdk.Screen.width(), Gdk.Screen.height())
        self.set_canvas(canvas)
        canvas.show()
        self.show_all()

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

        if "dotlist" in self.metadata:
            self._restore()
        else:
            self._game.new_game()
 def _freeze(self, journal=True):
     """ returns a json writable object representation capable of being used to restore our current status """
     return ({
         'image_dir': os.path.join(get_bundle_path(), 'images'),
         'filename': self.yy
     }, self.game._freeze(journal=journal), self.game.get_nr_pieces(),
             self.timer._freeze())
示例#16
0
文件: activity.py 项目: i5o/whatis
    def is_the_correct(self, x, y):
        for option in self.options:
            data = self.options[option]
            if (x >= data["min_x"] and x <= data["max_x"]) and \
               (y >= data["min_y"] and y <= data["max_y"]):
                break

        cursor = Gdk.Cursor.new(Gdk.CursorType.WATCH)
        self._parent.get_window().set_cursor(cursor)
        self.disconnect(self._id)
        self._id = None

        if option == self.current_option:
            self.finished = True
            image = random.choice(IMAGES_OK)
            message = "☺ ☺ ☺ ☺ ☺"
            self.queue_draw()
        else:
            image = random.choice(IMAGES_BAD)
            message = "☹ ☹ ☹ ☹ ☹"

        self._parent.word_label.set_text(message)
        image_path = os.path.join(activity.get_bundle_path(),
                                  "images", image)

        self._face = image_path
        self.draw_face(self._face)

        GObject.timeout_add(2000, self.new_game)
示例#17
0
    def __init__(self, handle):
        """ Initialize the toolbars and the game board """
        super(RecallActivity, self).__init__(handle)

        self.path = activity.get_bundle_path()

        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._restoring = False
        self._setup_toolbars(True)

        # Create a canvas
        canvas = Gtk.DrawingArea()
        canvas.set_size_request(Gdk.Screen.width(), \
                                Gdk.Screen.height())
        self.set_canvas(canvas)
        canvas.show()
        self.show_all()

        self._game = Game(canvas,
                          parent=self,
                          path=self.path,
                          colors=self.colors)
        self._setup_collab()
        if 'dotlist' in self.metadata:
            self._restore()
        else:
            self._game.new_game()
示例#18
0
    def load_instruments(self):
        self._instruments_store = Gtk.ListStore(str, GdkPixbuf.Pixbuf, str)
        self._instruments_store.set_sort_column_id(0, Gtk.SortType.ASCENDING)
        self.instruments_iconview = Gtk.IconView(self._instruments_store)
        self.instruments_iconview.set_text_column(2)
        self.instruments_iconview.set_pixbuf_column(1)

        # load the images
        images_path = os.path.join(activity.get_bundle_path(),
                                   'instruments')
        logging.error('Loading instrument images from %s', images_path)
        for file_name in os.listdir(images_path):
            image_file_name = os.path.join(images_path, file_name)
            logging.error('Adding %s', image_file_name)
            pxb = GdkPixbuf.Pixbuf.new_from_file_at_size(
                image_file_name, 75, 75)
            #instrument_name = image_file_name[image_file_name.rfind('/'):]
            instrument_name = image_file_name[image_file_name.rfind('/') + 1:]
            instrument_name = instrument_name[:instrument_name.find('.')]
            instrument_desc = \
                self.instrumentDB.instNamed[instrument_name].nameTooltip
            self._instruments_store.append([instrument_name, pxb,
                                           instrument_desc])
        self.instruments_iconview.connect(
            'selection-changed', self.__instrument_iconview_activated_cb)
示例#19
0
    def make_mainview(self):
        """Create the activity view"""
        # Create global box
        vbox = Gtk.VBox(True)

        # Create webview
        self.webview = webview  = WebKit.WebView()
        webview.show()
        vbox.pack_start(webview, True, True, 0)
        vbox.show()

        # Activate Enyo interface
        self.enyo = Enyo(webview)
        self.enyo.connect("ready", self.init_context)
        self.enyo.connect("save-context", self.save_context)
        self.enyo.connect("refresh-screen", self.refresh)
        self.enyo.connect("set_categories", self.set_categories)

        # Go to first page
        web_app_page = os.path.join(activity.get_bundle_path(), "index.html")
        self.webview.load_uri('file://' + web_app_page+"?onsugar=1")

        # Display all
        self.set_canvas(vbox)
        vbox.show()
示例#20
0
    def got_msg(self, msg):
        pmsg = parse_irc(msg, self.server)

        e_data = self.events.data(raw=msg,
                                  msg=pmsg,
                                  text=pmsg[-1],
                                  network=self,
                                  window=windows.get_default(
                                      self, self.core.manager))

        if "!" in pmsg[0]:
            e_data.source, e_data.address = pmsg[0].split('!', 1)

        else:
            e_data.source, e_data.address = pmsg[0], ''

        if len(pmsg) > 2:
            e_data.target = pmsg[2]
        else:
            e_data.target = pmsg[-1]

        if len(pmsg) >= 4:
            channel = pmsg[2]
            msg = pmsg[3]
            if self.me in msg and not self.activity.has_toplevel_focus():
                self.activity.notify_user(e_data.source + _(" on ") + channel,
                                          msg)
                if _HAS_SOUND:
                    SOUNDS_PATH = os.path.join(get_bundle_path(), 'sounds')
                    SOUND = os.path.join(SOUNDS_PATH, 'alert.wav')
                    PLAYER.set_state(Gst.State.NULL)
                    PLAYER.set_property('uri', 'file://%s' % SOUND)
                    PLAYER.set_state(Gst.State.PLAYING)

        self.events.trigger('Raw', e_data)
示例#21
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)
示例#22
0
    def __load_error_cb(self, web_view, web_frame, uri, web_error):
        """Show Sugar's error page"""

        # Don't show error page if the load was interrupted by policy
        # change or the request is going to be handled by a
        # plugin. For example, if a file was requested for download or
        # an .ogg file is going to be played.
        if web_error.code in (
                WebKit.PolicyError.FRAME_LOAD_INTERRUPTED_BY_POLICY_CHANGE,
                WebKit.PluginError.WILL_HANDLE_LOAD):
            if self._inject_media_style:
                css_style_file = open(os.path.join(activity.get_bundle_path(),
                                                   "data/media-controls.css"))
                css_style = css_style_file.read().replace('\n', '')
                inject_style_script = \
                    "var style = document.createElement('style');" \
                    "style.innerHTML = '%s';" \
                    "document.body.appendChild(style);" % css_style
                web_view.execute_script(inject_style_script)
            return True

        data = {
            'page_title': _('This web page could not be loaded'),
            'title': _('This web page could not be loaded'),
            'message': _('"%s" could not be loaded. Please check for '
                         'typing errors, and make sure you are connected '
                         'to the Internet.') % uri,
            'btn_value': _('Try again'),
            'url': uri,
            }

        html = open(DEFAULT_ERROR_PAGE, 'r').read() % data
        web_frame.load_alternate_string(html, uri, uri)

        return True
示例#23
0
    def __init__(self, handle):
        super(VteActivity, self).__init__(handle)
        toolbox = ToolbarBox()
        self.set_toolbar_box(toolbox)
        toolbox.show()

        self.max_participants = 1

        toolbar_box = ToolbarBox()

        activity_button = ActivityButton(self)
        toolbar_box.toolbar.insert(activity_button, 0)
        activity_button.show()

        title_entry = TitleEntry(self)
        toolbar_box.toolbar.insert(title_entry, -1)
        title_entry.show()

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

        stop_button = StopButton(self)
        toolbar_box.toolbar.insert(stop_button, -1)
        stop_button.show()

        self.set_toolbar_box(toolbar_box)
        toolbar_box.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.connect('selection-changed', self._on_selection_changed_cb)
        self._vte.drag_dest_set(Gtk.DestDefaults.ALL, [], Gdk.DragAction.COPY)
        self._vte.connect('drag_data_received', self._on_drop_cb)
        # ...and its scrollbar
        vtebox = Gtk.HBox()
        vtebox.pack_start(self._vte, True, True, 0)
        vtesb = Gtk.VScrollbar()
        vtesb.show()
        vtebox.pack_start(vtesb, False, False, 0)
        self.set_canvas(vtebox)
        self.show_all()
        # now start subprocess.
        self._vte.connect("child-exited", self.on_child_exit)
        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.spawn_sync(
            Vte.PtyFlags.DEFAULT, bundle_path,
            ['/bin/sh', '-c',
             'python %s/show.py; sleep 1' % bundle_path],
            ["PYTHONPATH=%s/library" % bundle_path],
            GLib.SpawnFlags.DO_NOT_REAP_CHILD, None, None)
示例#24
0
def _get_local_settings(activity):
    """ return an activity-specific Gio.Settings
    """
    global _settings
    if _settings is None:

        # create schemas directory if missing
        path = os.path.join(get_activity_root(), 'data', 'schemas')
        if not os.access(path, os.F_OK):
            os.makedirs(path)

        # create compiled schema file if missing
        compiled = os.path.join(path, 'gschemas.compiled')
        if not os.access(compiled, os.R_OK):
            src = '%s.gschema.xml' % activity.get_bundle_id()
            lines = open(os.path.join(get_bundle_path(), src), 'r').readlines()
            open(os.path.join(path, src), 'w').writelines(lines)
            os.system('glib-compile-schemas %s' % path)
            os.remove(os.path.join(path, src))

        # create a local Gio.Settings based on the compiled schema
        source = Gio.SettingsSchemaSource.new_from_directory(path, None, True)
        schema = source.lookup(SETTINGS_SCHEMA_ID, True)
        _settings = Gio.Settings.new_full(schema, None, None)
    return _settings
示例#25
0
def create_activity(name, base_path, skeleton):
    path = os.path.expanduser(os.path.join(base_path,
                              '%s.activity' % name.replace(' ', '')))
    os.makedirs(path)
    activity_path = os.path.join(path, 'activity')
    os.mkdir(activity_path)

    # copy all the files in the skeleton directory
    skeleton_path = os.path.join(activity.get_bundle_path(), 'skeletons',
                                 skeleton)
    for cur, dirs, files in os.walk(skeleton_path):
        destination_path = os.path.join(path, cur[len(skeleton_path) + 1:])
        for directory in dirs:
            directory_path = os.path.join(destination_path, directory)
            try:
                os.mkdir(directory_path)
            except:
                logging.error('Error trying to create %s', directory_path)

        for file_name in files:
            shutil.copyfile(os.path.join(cur, file_name),
                            os.path.join(destination_path, file_name))

    # create activity.info file
    activity_info_path = os.path.join(activity_path, 'activity.info')
    with open(activity_info_path, 'w') as activity_info_file:
        activity_info_file.write(
            activity_info_template(name,
                                   (skeleton == 'Web (sugar >= 0.100)')))

    return path
示例#26
0
    def __init__(self, handle):
        """ Initialize the toolbars and the game board """
        try:
            super(SearchActivity, self).__init__(handle)
        except dbus.exceptions.DBusException as e:
            _logger.error(str(e))

        self.path = activity.get_bundle_path()
        self.all_scores = []

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

        self._setup_toolbars()
        self._setup_dispatch_table()

        # Create a canvas
        canvas = Gtk.DrawingArea()
        canvas.set_size_request(Gdk.Screen.width(),
                                Gdk.Screen.height())
        self.set_canvas(canvas)
        canvas.show()
        self.show_all()

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

        if 'dotlist' in self.metadata:
            self._restore()
        else:
            self._game.new_game()
示例#27
0
def create_activity(name, base_path, skeleton):
    path = os.path.expanduser(
        os.path.join(base_path, '%s.activity' % name.replace(' ', '')))
    os.makedirs(path)
    activity_path = os.path.join(path, 'activity')
    os.mkdir(activity_path)

    # copy all the files in the skeleton directory
    skeleton_path = os.path.join(activity.get_bundle_path(), 'skeletons',
                                 skeleton)
    for cur, dirs, files in os.walk(skeleton_path):
        destination_path = os.path.join(path, cur[len(skeleton_path) + 1:])
        for directory in dirs:
            directory_path = os.path.join(destination_path, directory)
            try:
                os.mkdir(directory_path)
            except:
                logging.error('Error trying to create %s', directory_path)

        for file_name in files:
            shutil.copyfile(os.path.join(cur, file_name),
                            os.path.join(destination_path, file_name))

    # create activity.info file
    activity_info_path = os.path.join(activity_path, 'activity.info')
    with open(activity_info_path, 'w') as activity_info_file:
        activity_info_file.write(
            activity_info_template(name, (skeleton == 'Web (sugar >= 0.100)')))

    return path
示例#28
0
 def _sample_loader(self):
     # Convert from thumbnail path to sample path
     basename = os.path.basename(self._selected_sample)[:-4]
     file_path = os.path.join(activity.get_bundle_path(), 'samples',
                              basename + '.json')
     self.get_window().set_cursor(Gdk.Cursor(Gdk.CursorType.LEFT_PTR))
     self.__load_game(file_path)
示例#29
0
 def __init__(self, handle):
     # fork pygame before we initialize the activity.
     import os
     import pygame
     import sys
     pygame.init()
     windowid = pygame.display.get_wm_info()['wmwindow']
     self.child_pid = os.fork()
     if self.child_pid == 0:
         bp = activity.get_bundle_path()
         library_path = os.path.join(bp, 'library')
         pippy_app_path = os.path.join(bp, '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)
     from gi.repository import GObject
     from gi.repository import Gtk
     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()
    def __init__(self, act):
        self._activity = act

        src_path = os.path.join(activity.get_bundle_path(),
                                "data/web-console.html")
        self._src_uri = "file://" + src_path

        self._extraction_dir = os.path.join(act.get_activity_root(),
                                            "instance")

        if not os.path.exists(self._extraction_dir):
            os.makedirs(self._extraction_dir)

        self._parent_dir = os.path.join(self._extraction_dir,
                                        "Web_Console_Files")
        if not os.path.exists(self._parent_dir):
            os.makedirs(self._parent_dir)

        self._storage_dir = os.path.join(self._parent_dir, "default")
        self._default_dir = self._storage_dir

        if os.path.exists(self._storage_dir):
            shutil.rmtree(self._storage_dir)
        os.makedirs(self._storage_dir)

        self._index_html_path = os.path.join(self._storage_dir, "index.html")

        self._load_status_changed_hid = None
        self._file_path = None
示例#31
0
    def __init__(self, handle):
        ''' Initialize the toolbar '''
        try:
            super(OneSupportActivity, self).__init__(handle)
        except dbus.exceptions.DBusException as e:
            _logger.error(str(e))

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

        if hasattr(self, 'metadata') and 'font_size' in self.metadata:
            self.font_size = int(self.metadata['font_size'])
        else:
            self.font_size = 8
        self.zoom_level = self.font_size / float(len(FONT_SIZES))
        _logger.debug('zoom level is %f' % self.zoom_level)

        # _check_gconf_settings()  # For debugging purposes

        self._setup_toolbars()
        self.modify_bg(Gtk.StateType.NORMAL,
                       style.COLOR_WHITE.get_gdk_color())

        self.bundle_path = activity.get_bundle_path()

        self._copy_entry = None
        self._paste_entry = None
        self._webkit = None
        self._clipboard_text = ''
        self._fixed = None
        self._notify_transfer_status = False

        get_power_manager().inhibit_suspend()
        self._launch_task_master()
示例#32
0
    def make_mainview(self):
        """Create the activity view"""
        # Create global box
        vbox = Gtk.VBox(True)

        # Create webview
        scrolled_window = Gtk.ScrolledWindow()
        self.webview = webview = WebKit.WebView()
        scrolled_window.add(webview)
        webview.show()
        vbox.pack_start(scrolled_window, True, True, 0)
        scrolled_window.show()

        # Activate Enyo interface
        self.enyo = Enyo(webview)
        self.enyo.connect("ready", self.init_context)
        self.enyo.connect("save-gallery", self.save_gallery)

        # Go to first page
        web_app_page = os.path.join(activity.get_bundle_path(),
                                    "html/index.html")
        self.webview.load_uri('file://' + web_app_page)

        # Display all
        self.set_canvas(vbox)
        vbox.show()
示例#33
0
    def run_game(self):
        self.__source_object_id = None
        bundle_path = activity.get_bundle_path()

        # creates vte widget
        self._vte = Vte.Terminal()
        self._vte.connect('child-exited', self.exit_with_sys)

        argv = [
            "/bin/sh",
            "-c",
            os.path.join(bundle_path, "bin/tuxmath"),
            "--homedir %s" % os.path.join(bundle_path, "tux_homedir("),
            "--fullscreen"
        ]

        if hasattr(self._vte, 'fork_command_full'):
            self._vte.fork_command_full(
                Vte.PtyFlags.DEFAULT,
                os.environ['HOME'],
                argv,
                [],
                GLib.SpawnFlags.DO_NOT_REAP_CHILD,
                None,
                None)
        else:
            self._vte.spawn_sync(
                Vte.PtyFlags.DEFAULT,
                os.environ['HOME'],
                argv,
                [],
                GLib.SpawnFlags.DO_NOT_REAP_CHILD,
                None,
                None)
示例#34
0
 def _sample_loader(self):
     # Convert from thumbnail path to sample path
     basename = os.path.basename(self._selected_sample)[:-4]
     file_path = os.path.join(activity.get_bundle_path(),
                              'samples', basename + '.json')
     self.get_window().set_cursor(Gdk.Cursor(Gdk.CursorType.LEFT_PTR))
     self.__load_game(file_path)
示例#35
0
文件: smilies.py 项目: quozl/speak
def init():
    if _catalog:
        return

    svg_dir = os.path.join(get_bundle_path(), 'icons', 'smilies')

    for index, (name, hint, codes) in enumerate(THEME):
        archivo = os.path.join(svg_dir, '%s.svg' % (name))
        if name[0:7] == 'unicode':
            # Create the icon from unicode character on the fly
            pl = GdkPixbuf.PixbufLoader.new_with_type('svg')
            pl.write(_generate_svg(codes[0]))
            pl.close()
            pixbuf = pl.get_pixbuf()
            if not os.path.exists(archivo):
                try:
                    fd = open(archivo, 'w')
                    fd.write(_generate_svg(codes[0]))
                    fd.close()
                except IOError:
                    pass
        else:
            pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
                archivo, SMILIES_SIZE, SMILIES_SIZE)
        for i in codes:
            _catalog[i] = pixbuf
            THEME[index] = (archivo, hint, codes)
示例#36
0
 def __init__(self, handle):
     # fork pygame before we initialize the activity.
     import os
     import pygame
     import sys
     pygame.init()
     windowid = pygame.display.get_wm_info()['wmwindow']
     self.child_pid = os.fork()
     if self.child_pid == 0:
         bp = activity.get_bundle_path()
         library_path = os.path.join(bp, 'library')
         pippy_app_path = os.path.join(bp, '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)
     from gi.repository import GObject
     from gi.repository import Gtk
     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()
示例#37
0
    def __init__(self,
                 box,
                 imagen,
                 x,
                 y,
                 ancho=50,
                 alto=30,
                 direccion=DIR_ABAJO,
                 font_name=DEFAULT_FONT):

        self.globe_type = "IMAGE"
        self.box = box
        self.radio = 30
        self.ancho = ancho
        self.alto = alto
        self.image_name = imagen

        self.selec = False

        self.x = x
        self.y = y
        self.direccion = direccion
        self.punto = [0, 0]  # fake, but needed for persistence

        appdir = os.path.join(activity.get_bundle_path())
        self.icon_buffer = _IconBuffer()
        self.icon_buffer.file_name = os.path.join(appdir, imagen)
        self.icon_buffer.stroke_color = '#000000'
        self.texto = None
示例#38
0
 def _load_ball_cb(self, widget, event, ball):
     if ball == 'custom':
         chooser(self, 'Image', self._new_ball_from_journal)
     else:
         self._bounce_window.ball.new_ball(os.path.join(
             activity.get_bundle_path(), 'images', ball + '.svg'))
         self._bounce_window.set_background(BGDICT[BALLDICT[ball][1]][1])
     self._current_ball = ball
 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()
     return samples
示例#40
0
    def _reset_ball(self):
        ''' If we switch back from sector mode, we need to restore the ball '''
        if self._bounce_window.mode != 'sectors':
            return

        if self._current_ball == 'custom':  # TODO: Reload custom ball
            self._current_ball = 'soccerball'
        self._bounce_window.ball.new_ball(os.path.join(
            activity.get_bundle_path(), 'images', self._current_ball + '.svg'))
    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.max_participants = 4  # sharing
        self._playing = True

        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

        self._current_ball = 'soccerball'

        self._toolbar_was_expanded = False

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

        Gdk.Screen.get_default().connect('size-changed', self._configure_cb)

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

        if self.shared_activity:
            # We're joining
            if not self.get_shared():
                xocolors = XoColor(profile.get_color().to_string())
                share_icon = Icon(icon_name='zoom-neighborhood',
                                  xo_color=xocolors)
                self._joined_alert = NotifyAlert()
                self._joined_alert.props.icon = share_icon
                self._joined_alert.props.title = _('Please wait')
                self._joined_alert.props.msg = _('Starting connection...')
                self._joined_alert.connect('response', self._alert_cancel_cb)
                self.add_alert(self._joined_alert)

                self._label.set_label(_('Wait for the sharer to start.'))

                # Wait for joined signal
                self.connect("joined", self._joined_cb)

        self._setup_sharing()
示例#42
0
 def _scan_for_samples(self):
     samples = sorted(
         glob.glob(
             os.path.join(
                 activity.get_bundle_path(),
                 'samples',
                 'thumbnails',
                 '*.png')))
     return samples
    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.max_participants = 4  # sharing
        self._playing = True

        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

        self._current_ball = 'soccerball'

        self._toolbar_was_expanded = False

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

        Gdk.Screen.get_default().connect('size-changed', self._configure_cb)

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

        if self.shared_activity:
            # We're joining
            if not self.get_shared():
                xocolors = XoColor(profile.get_color().to_string())
                share_icon = Icon(icon_name='zoom-neighborhood',
                                  xo_color=xocolors)
                self._joined_alert = NotifyAlert()
                self._joined_alert.props.icon = share_icon
                self._joined_alert.props.title = _('Please wait')
                self._joined_alert.props.msg = _('Starting connection...')
                self._joined_alert.connect('response', self._alert_cancel_cb)
                self.add_alert(self._joined_alert)

                self._label.set_label(_('Wait for the sharer to start.'))

                # Wait for joined signal
                self.connect("joined", self._joined_cb)

        self._setup_sharing()
示例#44
0
 def _scan_for_samples(self):
     samples = sorted(
         glob.glob(
             os.path.join(
                 activity.get_bundle_path(),
                 'samples',
                 'thumbnails',
                 '*.png')))
     return samples
示例#45
0
    def play_sound(self, event):
        if _HAS_SOUND:
            SOUNDS_PATH = os.path.join(get_bundle_path(), 'sounds')
            SOUNDS = {'said_nick': os.path.join(SOUNDS_PATH, 'alert.wav'),
                      'login': os.path.join(SOUNDS_PATH, 'login.wav'),
                      'logout': os.path.join(SOUNDS_PATH, 'logout.wav')}

            self.element.set_state(Gst.State.NULL)
            self.element.set_property('uri', 'file://%s' % SOUNDS[event])
            self.element.set_state(Gst.State.PLAYING)
示例#46
0
 def new(self, widget):
     print 'New slideshow'
     # no effect if slideshow is already 'new', e.g. when ShowNTell is opened
     # directly not by read_file
     # this needs to be changed to show slideshow with html title slide
     self.activity.read_file(
         path(
             activity.get_bundle_path()) /
         'resources' /
         'new.cpxo')
示例#47
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
示例#48
0
def _create_activity_icon(metadata):
    if metadata is not None and metadata.get('icon-color'):
        color = XoColor(metadata['icon-color'])
    else:
        color = profile.get_color()

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

    return icon
示例#49
0
def _create_activity_icon(metadata):
    if metadata.get('icon-color', ''):
        color = XoColor(metadata['icon-color'])
    else:
        color = XoColor()

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

    return icon
示例#50
0
def image_from_svg_file(filename):
    path = os.path.join(activity.get_bundle_path(), 'icons', filename)
    fd = open(path)
    svg = fd.read()
    fd.close()
    pl = GdkPixbuf.PixbufLoader.new_with_type('svg')
    pl.write(svg)
    pl.close()
    pixbuf = pl.get_pixbuf()
    image = Gtk.Image()
    image.set_from_pixbuf(pixbuf)
    return image
示例#51
0
    def __init__(self, title, message, button_callback):
        Gtk.EventBox.__init__(self)

        self.modify_bg(Gtk.StateType.NORMAL, style.COLOR_WHITE.get_gdk_color())

        alignment = Gtk.Alignment.new(0.5, 0.5, 0.1, 0.1)
        self.add(alignment)
        alignment.show()

        box = Gtk.VBox()
        alignment.add(box)
        box.show()

        # Get the icon of this activity through the bundle path.
        bundle_path = activity.get_bundle_path()
        activity_bundle = ActivityBundle(bundle_path)
        icon = Icon(
            pixel_size=style.LARGE_ICON_SIZE,
            file=activity_bundle.get_icon(),
            stroke_color=style.COLOR_BUTTON_GREY.get_svg(),
            fill_color=style.COLOR_TRANSPARENT.get_svg(),
        )

        box.pack_start(icon, expand=True, fill=False, padding=0)
        icon.show()

        color = style.COLOR_BUTTON_GREY.get_html()

        label = Gtk.Label()
        label.set_markup('<span weight="bold" color="%s">%s</span>' % (color, GLib.markup_escape_text(title)))
        box.pack_start(label, expand=True, fill=False, padding=0)
        label.show()

        label = Gtk.Label()
        label.set_markup('<span color="%s">%s</span>' % (color, GLib.markup_escape_text(message)))
        box.pack_start(label, expand=True, fill=False, padding=0)
        label.show()

        button_box = Gtk.HButtonBox()
        button_box.set_layout(Gtk.ButtonBoxStyle.CENTER)
        box.pack_start(button_box, False, True, 0)
        button_box.show()

        button = Gtk.Button(label=_("Try again"))
        button.connect("clicked", button_callback)
        button.props.image = Icon(
            icon_name="entry-refresh",
            pixel_size=style.SMALL_ICON_SIZE,
            stroke_color=style.COLOR_WHITE.get_svg(),
            fill_color=style.COLOR_TRANSPARENT.get_svg(),
        )
        button_box.pack_start(button, expand=True, fill=False, padding=0)
        button.show()
示例#52
0
 def load_JSshell(self):
     browser = self.current_browser
     page = os.path.join(activity.get_bundle_path(),
                         "data/Interactive_Javascript_Shell2.html")
     new_browser = self.add_tab(next_to_current=True)
     new_browser.load_uri('file://' + page)
     new_browser.grab_focus()
     #self.set_label('With')
     #self._label = Gtk.Label(label=_('Wither'))
     
     self._label.set_text(_('Untit'))
     self._title = _('Untit')
示例#53
0
 def connectVNC(self, button):
     self._vte.grab_focus()
     # check if x11vnc is installed
     cmd = '/usr/bin/x11vnc'
     if os.path.isfile(cmd) and os.access(cmd, os.X_OK):
         logging.error('Using x11vnc installed in the system')
     else:
         # check platform
         if platform.machine().startswith('arm'):
             path = os.path.join(activity.get_bundle_path(), 'bin/arm')
         else:
             if platform.architecture()[0] == '64bit':
                 path = os.path.join(activity.get_bundle_path(),
                                     'bin/x86-64')
             else:
                 path = os.path.join(activity.get_bundle_path(), 'bin/x86')
         self._vte.feed_child(
             "export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:%s/lib\n" % path, -1)
         cmd = os.path.join(path, 'x11vnc') + "\n"
         logging.error('Using %s', cmd)
     self._vte.feed_child(cmd, -1)
示例#54
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 sugar3.activity.activity import get_bundle_path
    bundle = ActivityBundle(get_bundle_path())
    icon = Icon(file=bundle.get_icon(), xo_color=color)

    return icon