Пример #1
0
    def journal_open_image(self):
        self.object_chooser_active = True
        if hasattr(mime, 'GENERIC_TYPE_IMAGE'):
            chooser = ObjectChooser(_('Choose image'),
                                    what_filter=mime.GENERIC_TYPE_IMAGE)
        else:
            chooser = ObjectChooser(_('Choose image'))

        try:
            result = chooser.run()
            if result == gtk.RESPONSE_ACCEPT and chooser.get_selected_object():
                jobject = chooser.get_selected_object()
            else:
                return False

            if jobject and jobject.file_path:
                logging.debug("journal_open_image: fname=%s" %
                              jobject.file_path)
                try:
                    self.orig_pic = gtk.gdk.pixbuf_new_from_file(
                        jobject.file_path)
                    self.filename = os.path.join(
                        'images', os.path.basename(jobject.file_path))
                except Exception, e:
                    logging.error("journal_open_image: %s" % e)
                    return False
            else:
Пример #2
0
    def add_image (self, *args):#widget=None, response=None, *args):
        """ Use to trigger and process the My Own Image selector. """

        if hasattr(mime, 'GENERIC_TYPE_IMAGE'):
            chooser = ObjectChooser(_('Choose image'), self._parent,
                                    gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                                    what_filter=mime.GENERIC_TYPE_IMAGE)
        else:
            chooser = ObjectChooser(_('Choose image'), self._parent,
                                    gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT)

        try:
            result = chooser.run()
            if result == gtk.RESPONSE_ACCEPT:
                jobject = chooser.get_selected_object()
                if jobject and jobject.file_path:
                    if self.load_image(str(jobject.file_path), True):
                        pass
                    else:
                        err = gtk.MessageDialog(self._parent, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK,
                                                _("Not a valid image file"))
                        err.run()
                        err.destroy()
                        return
        finally:
            chooser.destroy()
            del chooser
Пример #3
0
    def __do_clicked_image(self, control, event, obj, property):
        if hasattr(mime, "GENERIC_TYPE_IMAGE"):
            filter = {"what_filter": mime.GENERIC_TYPE_IMAGE}
        else:
            filter = {}

        # Courtesy of Write.activity - toolbar.py
        chooser = ObjectChooser(
            title=_("Choose image"),
            parent=Globals.JokeMachineActivity,  # ._parent,
            flags=gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
            **filter
        )
        try:
            result = chooser.run()
            if result == gtk.RESPONSE_ACCEPT:
                logging.debug("ObjectChooser: %r" % chooser.get_selected_object())
                journal_object = chooser.get_selected_object()
                if hasattr(obj, "image_blob") and journal_object and journal_object.file_path:
                    logging.debug("Getting journal object: %r, %s", journal_object, journal_object.file_path)
                    # Set the image now
                    raw = _load_image(journal_object.file_path)
                    obj.image = str(journal_object.metadata["title"])
                    obj.image_blob = raw
                    # refresh the image
                    image_file = StringIO.StringIO(obj.image_blob)
                    surface = cairo.ImageSurface.create_from_png(image_file)
                    control.props.image = surface
        finally:
            # chooser.hide()
            chooser.destroy()
            del chooser
Пример #4
0
 def _load_game(self, button):
     chooser = ObjectChooser(_('Choose memorize game'),
             parent=self.activity,
             flags=gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT)
     jobject = ''
     try:
         result = chooser.run()
         if result == gtk.RESPONSE_ACCEPT:
             logging.debug('ObjectChooser: %r', 
                           chooser.get_selected_object())
             jobject = chooser.get_selected_object()
             if not jobject or  not jobject.file_path:
                 return
     finally:
         chooser.destroy()
         del chooser
         
     if jobject and jobject.file_path:   
         title = jobject.metadata['title']
         if jobject.metadata.has_key('icon-color'):
             color = jobject.metadata['icon-color']
         else:
             color = profile.get_color().to_string()
         self.emit('game_changed', jobject.file_path, 4,
                   'file', title, color)
          
         if self.jobject != None:
             self.jobject.destroy()
         self.jobject = jobject
Пример #5
0
    def __do_clicked_image(self, control, event, obj, property):
        if hasattr(mime, 'GENERIC_TYPE_IMAGE'):
            filter = {'what_filter': mime.GENERIC_TYPE_IMAGE}
        else:
            filter = {}

        # Courtesy of Write.activity - toolbar.py
        chooser = ObjectChooser(
            title=_('Choose image'),
            parent=Globals.JokeMachineActivity,  #._parent,
            flags=gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
            **filter)
        try:
            result = chooser.run()
            if result == gtk.RESPONSE_ACCEPT:
                logging.debug('ObjectChooser: %r' %
                              chooser.get_selected_object())
                journal_object = chooser.get_selected_object()
                if hasattr(obj, 'image_blob'
                           ) and journal_object and journal_object.file_path:
                    logging.debug('Getting journal object: %r, %s',
                                  journal_object, journal_object.file_path)
                    # Set the image now
                    raw = _load_image(journal_object.file_path)
                    obj.image = str(journal_object.metadata['title'])
                    obj.image_blob = raw
                    # refresh the image
                    image_file = StringIO.StringIO(obj.image_blob)
                    surface = cairo.ImageSurface.create_from_png(image_file)
                    control.props.image = surface
        finally:
            #chooser.hide()
            chooser.destroy()
            del chooser
    def add_image(self, *args):  #widget=None, response=None, *args):
        """ Use to trigger and process the My Own Image selector. """

        if hasattr(mime, 'GENERIC_TYPE_IMAGE'):
            filter = {'what_filter': mime.GENERIC_TYPE_IMAGE}
        else:
            filter = {}

        chooser = ObjectChooser(
            _('Choose image'),
            self.parentp,  #self._parent,
            gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
            **filter)
        try:
            result = chooser.run()
            if result == gtk.RESPONSE_ACCEPT:
                jobject = chooser.get_selected_object()
                if jobject and jobject.file_path:
                    if self.load_image(str(jobject.file_path), True):
                        pass
                    else:
                        err = gtk.MessageDialog(self._parent, gtk.DIALOG_MODAL,
                                                gtk.MESSAGE_ERROR,
                                                gtk.BUTTONS_OK,
                                                _("Not a valid image file"))
                        err.run()
                        err.destroy()
                        return
        finally:
            chooser.destroy()
            del chooser
Пример #7
0
    def _object_chooser(self, mime_type, type_name):
        chooser = ObjectChooser()
        matches_mime_type = False

        response = chooser.run()
        if response == gtk.RESPONSE_ACCEPT:
            jobject = chooser.get_selected_object()
            metadata = jobject.metadata
            file_path = jobject.file_path

            if metadata['mime_type'] == mime_type:
                matches_mime_type = True

            else:
                alert = Alert()

                alert.props.title = _('Invalid object')
                alert.props.msg = \
                       _('The selected object must be a %s file' % (type_name))

                ok_icon = Icon(icon_name='dialog-ok')
                alert.add_button(gtk.RESPONSE_OK, _('Ok'), ok_icon)
                ok_icon.show()

                alert.connect('response', lambda a, r: self.remove_alert(a))

                self.add_alert(alert)

                alert.show()

        return matches_mime_type, file_path, metadata['title']
Пример #8
0
    def __do_clicked_choose_sound(self, control, event, obj, property):
        if hasattr(mime, 'GENERIC_TYPE_AUDIO'):
            filter = {'what_filter': mime.GENERIC_TYPE_AUDIO}
        else:
            filter = {}

        logging.debug('choosing sound file')
        chooser = ObjectChooser(
            title=_('Choose Sound'),
            parent=Globals.JokeMachineActivity,  #._parent,
            flags=gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
            **filter)
        try:
            result = chooser.run()
            if result == gtk.RESPONSE_ACCEPT:
                logging.debug('ObjectChooser: %r' %
                              chooser.get_selected_object())
                journal_object = chooser.get_selected_object()
                if hasattr(obj, 'sound_blob'
                           ) and journal_object and journal_object.file_path:
                    logging.debug('Getting journal object: %r, %s, %s',
                                  journal_object, journal_object.file_path,
                                  journal_object.metadata['title'])
                    # Set the sound now
                    f = open(journal_object.file_path, 'r')
                    raw = f.read()
                    f.close()
                    obj.sound = str(journal_object.metadata['title'])
                    obj.sound_blob = raw
                    control.props.text = obj.sound
        finally:
            #chooser.hide()
            chooser.destroy()
            del chooser
Пример #9
0
    def _object_chooser(self, mime_type, type_name):
        chooser = ObjectChooser()
        matches_mime_type = False

        response = chooser.run()
        if response == gtk.RESPONSE_ACCEPT:
            jobject = chooser.get_selected_object()
            metadata = jobject.metadata
            file_path = jobject.file_path

            if metadata['mime_type'] == mime_type:
                matches_mime_type = True

            else:
                alert = Alert()

                alert.props.title = _('Invalid object')
                alert.props.msg = \
                       _('The selected object must be a %s file' % (type_name))

                ok_icon = Icon(icon_name='dialog-ok')
                alert.add_button(gtk.RESPONSE_OK, _('Ok'), ok_icon)
                ok_icon.show()

                alert.connect('response', lambda a, r: self.remove_alert(a))

                self.add_alert(alert)

                alert.show()

        return matches_mime_type, file_path, metadata['title']
Пример #10
0
 def _set_img(self, widget, win):
     win.destroy()
     chooser = ObjectChooser()
     res = chooser.run()
     if res == gtk.RESPONSE_CANCEL:
         chooser.destroy()
     else:
         chooser.destroy()
         image = gtk.Image()
         ch = chooser.get_selected_object()
         self.user.disconnect(self.conectado)
         path = ch.file_path
         self.conectado = self.user.connect('clicked', self.open, path)
         pix = gtk.gdk.pixbuf_new_from_file_at_size(path, 200, 200)
         image.set_from_pixbuf(pix)
         for x in list(self.user):
             self.user.remove(x)
         self.user.add(image)
         ###
         d = utils.model.get_value(utils.iter_sel, 0)
         echo = False
         a = 0
         while not echo:
             if d == NAMES[a]:
                 utils.current = a
                 echo = True
             a += 1
         AVATARS.__setitem__(utils.current, path)
         ##
         self.show_all()
Пример #11
0
    def show(self):
        chooser = ObjectChooser(parent=self._parent)
        try:
            result = chooser.run()
            if result == gtk.RESPONSE_ACCEPT:
                logging.debug('FilePicker.show: %r' % 
                              chooser.get_selected_object())
                jobject = chooser.get_selected_object()
                if jobject and jobject.file_path:
                    ext = os.path.splitext(jobject.file_path)[1]
                    f, new_temp = tempfile.mkstemp(ext)
                    del f

                    global _temp_files_to_clean
                    _temp_files_to_clean.append(new_temp)
                    shutil.copy(jobject.file_path, new_temp)

                    self._file = new_temp
        finally:
            chooser.destroy()
            del chooser

        if self._file:
            return interfaces.nsIFilePicker.returnOK
        else:
            return interfaces.nsIFilePicker.returnCancel
Пример #12
0
 def __send_cb(self, button):
     chooser = ObjectChooser()
     try:
         result = chooser.run()
         if result == gtk.RESPONSE_ACCEPT:
             jobject = chooser.get_selected_object()
             if jobject and jobject.file_path:
                 logging.debug('##### %s' % jobject.file_path)
     finally:
         chooser.destroy()
         del chooser        
Пример #13
0
    def _select_hw_from_journal(self, widget):
        '''Abre un selector de objetos del diario'''
        chooser = ObjectChooser()
        response = chooser.run()

        if response == gtk.RESPONSE_ACCEPT:
            jobject = chooser.get_selected_object()
            self._hw_path = str(jobject.get_file_path())
            self._notebook.set_current_page(-1)
            self._send.set_sensitive(True)
            self._hw_title.set_text(jobject.get_metadata()["title"])
            self._hw_mimetype = mime.get_for_file(self._hw_path)
Пример #14
0
 def _new_picture(self, widget):
     try:
         chooser = ObjectChooser(parent=self)
     except:
         chooser = None
     f = None
     if chooser is not None:
         result = chooser.run()
         if result == gtk.RESPONSE_ACCEPT:
             dsobject = chooser.get_selected_object()
             f = dsobject.file_path
     if f is not None:
         self._image = pygame.image.load(f)
         self.actividad.set_background(self._image)
Пример #15
0
 def choose(self, widget):
   chooser = ObjectChooser(parent=self, what_filter=mime.GENERIC_TYPE_AUDIO)
   result = chooser.run()
   index = self.boxd.child_get_property(widget, "position")
   if result == gtk.RESPONSE_ACCEPT:
     self.jobjects[index] = chooser.get_selected_object()
     self.paths[index] = str(self.jobjects[index].get_file_path())
     self.buts[index].modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(0, 0x8800, 0))
     self.buts[index].modify_bg(gtk.STATE_PRELIGHT, gtk.gdk.Color(0, 0x8800, 0))
   else:
     self.paths[index] = "0"
     self.jobjects[index] = None
     self.buts[index].modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(0x6600, 0, 0))
     self.buts[index].modify_bg(gtk.STATE_PRELIGHT, gtk.gdk.Color(0x6600, 0, 0))
Пример #16
0
    def insertImage(self, widget, activity):
        self._activity = activity
        chooser = ObjectChooser('Choose image', self._activity,
                                gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT)
        try:
            result = chooser.run()
            if result == gtk.RESPONSE_ACCEPT:
                jobject = chooser.get_selected_object()
                if jobject and jobject.file_path:
                    self._activity.toUploadChosen(jobject.file_path)

        finally:
            chooser.destroy()
            del chooser
Пример #17
0
 def _image_cb(self, button):
     chooser = ObjectChooser(
         _('Choose image'), self._parent,
         gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT)
     try:
         result = chooser.run()
         if result == gtk.RESPONSE_ACCEPT:
             logging.debug('ObjectChooser: %r' %
                           chooser.get_selected_object())
             jobject = chooser.get_selected_object()
             if jobject and jobject.file_path:
                 self._abiword_canvas.insert_image(jobject.file_path, True)
     finally:
         chooser.destroy()
         del chooser
Пример #18
0
    def _show_picker_cb(self, duumy1):

        chooser = ObjectChooser(parent=self,
                                what_filter=mime.GENERIC_TYPE_AUDIO)
        try:
            result = chooser.run()
            if result == gtk.RESPONSE_ACCEPT:
                jobject = chooser.get_selected_object()
                if jobject and jobject.file_path:
                    #print jobject.file_path
                    self.obj = jobject.file_path
                    subprocess.call(['/usr/bin/killall', 'mpg123'])
                    self.read_file(str(jobject.file_path))
        finally:
            chooser.destroy()
            del chooser
Пример #19
0
def chooser(parent_window, filter, action):
    """ Choose an object from the datastore and take some action """
    chooser = None
    try:
        chooser = ObjectChooser(parent=parent_window, what_filter=filter)
    except TypeError:
        chooser = ObjectChooser(None, parent_window,
            gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT)
    if chooser is not None:
        try:
            result = chooser.run()
            if result == gtk.RESPONSE_ACCEPT:
                dsobject = chooser.get_selected_object()
                action(dsobject)
                dsobject.destroy()
        finally:
            chooser.destroy()
            del chooser
Пример #20
0
def open_from_journal(button, filechooser, activity=None):
        if filechooser:
                chooser = ObjectChooser(parent=filechooser,
                                        what_filter=mime.GENERIC_TYPE_TEXT)
        else:
                chooser = ObjectChooser(parent=activity,
                                        what_filter=mime.GENERIC_TYPE_TEXT)
        result = chooser.run()
        chooser.destroy()
        if result == gtk.RESPONSE_ACCEPT:
                jobject = chooser.get_selected_object()
                path = str(jobject.get_file_path())
        else:
                path = None
        if filechooser:
                filechooser.path = path
                filechooser.response(OPEN_FROM_JOURNAL)
        else:
                activity.open_file(None, from_journal=path)
Пример #21
0
 def _load_game(self, button):
     chooser = ObjectChooser(_('Choose memorize game'),
             parent=self.activity,
             flags=gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT)
     jobject = ''
     try:
         result = chooser.run()
         if result == gtk.RESPONSE_ACCEPT:
             logging.debug('ObjectChooser: %r' % chooser.get_selected_object())
             jobject = chooser.get_selected_object()
             if not jobject or  not jobject.file_path:
                 return
     finally:
         chooser.destroy()
         del chooser
         
     if jobject and jobject.file_path:    
         self.emit('create_load_game', jobject.file_path)
         self._save_button.set_sensitive(False)
Пример #22
0
    def requestAddFile(self, widget, data=None):
        _logger.info('Requesting to add file')

        chooser = ObjectChooser()
        if chooser.run() == gtk.RESPONSE_ACCEPT:
            # get object and build file
            jobject = chooser.get_selected_object()

            self.show_throbber(True, _("Packaging Object"))
            try:
                file_obj = self.activity.build_file(jobject)
            except InShareException:
                self._alert(_("Object Not Added"), _("Object already shared"))
                self.show_throbber(False)
                return

            # No problems continue
            self.show_throbber(False)

            # Add To UI
            self._addFileToUIList(file_obj.id, file_obj)

            # Register File with activity share list
            self.activity._registerShareFile(file_obj.id, file_obj)

            # Upload to server?
            if data and data.has_key('upload'):
                self.show_throbber(True, _("Uploading Object to server"))

                def send():
                    try:
                        self.activity.send_file_to_server(
                            file_obj.id, file_obj)
                    except FileUploadFailure:
                        self._alert(_("Failed to upload object"))
                        self._remFileFromUIList(file_obj.id)
                        self.activity.delete_file(file_obj.id)
                    self.show_throbber(False)

                threading.Thread(target=send).start()

        chooser.destroy()
        del chooser
Пример #23
0
def chooser(parent_window, filter, action):
    """ Choose an object from the datastore and take some action """
    from sugar.graphics.objectchooser import ObjectChooser

    _chooser = None
    try:
        _chooser = ObjectChooser(parent=parent_window, what_filter=filter)
    except TypeError:
        _chooser = ObjectChooser(None, parent_window, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT)
    if _chooser is not None:
        try:
            result = _chooser.run()
            if result == gtk.RESPONSE_ACCEPT:
                dsobject = _chooser.get_selected_object()
                action(dsobject)
                dsobject.destroy()
        finally:
            _chooser.destroy()
            del _chooser
Пример #24
0
def open_from_journal(button, filechooser, activity=None):
    if filechooser:
        chooser = ObjectChooser(parent=filechooser,
                                what_filter=mime.GENERIC_TYPE_TEXT)
    else:
        chooser = ObjectChooser(parent=activity,
                                what_filter=mime.GENERIC_TYPE_TEXT)
    result = chooser.run()
    chooser.destroy()
    if result == gtk.RESPONSE_ACCEPT:
        jobject = chooser.get_selected_object()
        path = str(jobject.get_file_path())
    else:
        path = None
    if filechooser:
        filechooser.path = path
        filechooser.response(OPEN_FROM_JOURNAL)
    else:
        activity.open_file(None, from_journal=path)
Пример #25
0
 def loadButtonClicked(self, button):
     chooser = ObjectChooser(
         'Pick a level', self,
         gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT)
     try:
         result = chooser.run()
         if result == gtk.RESPONSE_ACCEPT:
             jobject = chooser.get_selected_object()
             if jobject and jobject.file_path:
                 event = olpcgames.eventwrap.Event(
                     type=pygame.USEREVENT,
                     code=olpcgames.FILE_READ_REQUEST,
                     filename=jobject.file_path,
                     metadata=jobject.metadata,
                 )
                 olpcgames.eventwrap.post(event)
                 event.block()
     finally:
         chooser.destroy()
         del chooser
Пример #26
0
    def requestAddFile(self, widget, data=None):
        _logger.info('Requesting to add file')

        chooser = ObjectChooser(parent=self.activity)
        if chooser.run() == gtk.RESPONSE_ACCEPT:
            # get object and build file
            jobject = chooser.get_selected_object()

            self.show_throbber(True, _("Packaging Object") )
            try:
                file_obj = self.activity.build_file( jobject )
            except InShareException:
                self._alert(_("Object Not Added"), _("Object already shared"))
                self.show_throbber( False )
                return

            # No problems continue
            self.show_throbber( False )

            # Add To UI
            self._addFileToUIList( file_obj.id, file_obj )

            # Register File with activity share list
            self.activity._registerShareFile( file_obj.id, file_obj )

            # Upload to server?
            if data and data.has_key('upload'):
                self.show_throbber(True, _("Uploading Object to server"))
                def send():
                    try:
                        self.activity.send_file_to_server( file_obj.id, file_obj )
                    except FileUploadFailure:
                        self._alert( _("Failed to upload object") )
                        self._remFileFromUIList( file_obj.id )
                        self.activity.delete_file( file_obj.id )
                    self.show_throbber( False )
                threading.Thread(target=send).start()

        chooser.destroy()
        del chooser
Пример #27
0
def pick(cb=None, default=None, parent=None, what=None):
    """
    Opens object chooser.
    
    Method returns:

        * cb(jobject), if object was choosen and cb is not None
        * jobject, if object was choosen and cb is None
        * default, otherwise

    NOTE: 'what' makes sense only for sugar >= 0.84
    """
    what = what and {'what_filter': what} or {}
    chooser = ObjectChooser(parent=parent, **what)

    logging.error(chooser)

    jobject = None
    out = None

    try:
        if chooser.run() == gtk.RESPONSE_ACCEPT:
            jobject = chooser.get_selected_object()
            logging.debug('ObjectChooser: %r' % jobject)

            if jobject and jobject.file_path:
                if cb:
                    out = cb(jobject)
                else:
                    out = jobject
    finally:
        if jobject and id(jobject) != id(out):
            jobject.destroy()
        chooser.destroy()
        del chooser

    if out:
        return out
    else:
        return default
Пример #28
0
    def _load_button_cb(self, widget):

        chooser = ObjectChooser(parent=self)
        result = chooser.run()
        if result == gtk.RESPONSE_ACCEPT:
            try:
                jobject = chooser.get_selected_object()
                _file_path = str(jobject.get_file_path())
                self.read_file(_file_path)
                alerta = NotifyAlert(10)
                alerta.props.title = _('Good!')
                alerta.props.msg = _('Book loaded')
                alerta.connect('response', lambda w, i: self.remove_alert(w))
                self.add_alert(alerta)
            except IOError:
                alerta = NotifyAlert(10)
                alerta.props.title = 'Error'
                alerta.props.msg = _('Error in load book')
                alerta.connect('response', lambda w, i: self.remove_alert(w))
                self.add_alert(alerta)
        else:
            return
    def open_diario(self, widget):  # Abrir un zip desde el diario.
        chooser = ObjectChooser()
        resultado = chooser.run()
        if resultado == gtk.RESPONSE_ACCEPT:
            Archivo_s = chooser.get_selected_object()
            Archivo = Archivo_s.get_file_path()
            try:
                print Archivo
                utils.Archivo_d = Archivo
                utils.decompress(Archivo, Hboxx, '/tmp/Compress/Work', 'Abrir',
                                 True)

            except IOError:
                Mensaje = _("""Oh..Parece que no selecciono un archivo zip""")
                info = gtk.MessageDialog(type=gtk.MESSAGE_WARNING,
                                         buttons=gtk.BUTTONS_OK,
                                         message_format=Mensaje)
                a = info.run()
                if a == gtk.RESPONSE_OK:
                    info.destroy()
                    self.set_model(self.construir_lista())
                    Uri.set_text(os.getcwd())
Пример #30
0
def pick(cb=None, default=None, parent=None, what=None):
    """
    Opens object chooser.

    Method returns:

        * cb(jobject), if object was choosen and cb is not None
        * jobject, if object was choosen and cb is None
        * default, otherwise

    NOTE: 'what' makes sense only for sugar >= 0.84
    """
    what = what and {'what_filter': what} or {}
    chooser = ObjectChooser(parent=parent, **what)

    jobject = None
    out = None

    try:
        if chooser.run() == gtk.RESPONSE_ACCEPT:
            jobject = chooser.get_selected_object()
            logging.debug('ObjectChooser: %r' % jobject)

            if jobject and jobject.file_path:
                if cb:
                    out = cb(jobject)
                else:
                    out = jobject
    finally:
        if jobject and id(jobject) != id(out):
            jobject.destroy()
        chooser.destroy()
        del chooser

    if out:
        return out
    else:
        return default
Пример #31
0
    def load_image_from_journal(self):
        chooser = None
        name = None
        jobject = None
        try:
            chooser = ObjectChooser(parent=self, what_filter=None)
        except TypeError:
            chooser = ObjectChooser(
                None, self, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT)
        if chooser is not None:
            try:
                result = chooser.run()
                if result == gtk.RESPONSE_ACCEPT:
                    jobject = chooser.get_selected_object()
                    if jobject and jobject.file_path:
                        name = jobject.metadata['title']
                        #mime_type = jobject.metadata['mime_type']
                        #_logger.debug('result of choose: %s (%s)' % \(name, str(mime_type)))
            finally:
                chooser.destroy()
                del chooser

        return jobject
Пример #32
0
def chooser_dialog(parent_window, filter, action):
    ''' Choose an object from the datastore and take some action '''
    from sugar.graphics.objectchooser import ObjectChooser

    chooser = None
    dsobject = None
    cleanup_needed = False
    try:
        chooser = ObjectChooser(parent=parent_window, what_filter=filter)
    except TypeError:  # Old-syle Sugar chooser
        chooser = ObjectChooser(
            None, parent_window,
            gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT)
        cleanup_needed = True

    if chooser is not None:
        result = chooser.run()
        if result == gtk.RESPONSE_ACCEPT:
            dsobject = chooser.get_selected_object()
        if cleanup_needed:
            chooser.destroy()
            del chooser
    gobject.idle_add(action, dsobject)
Пример #33
0
def chooser_dialog(parent_window, filter, action):
    ''' Choose an object from the datastore and take some action '''
    from sugar.graphics.objectchooser import ObjectChooser

    chooser = None
    dsobject = None
    cleanup_needed = False
    try:
        chooser = ObjectChooser(parent=parent_window, what_filter=filter)
    except TypeError:  # Old-syle Sugar chooser
        chooser = ObjectChooser(
            None,
            parent_window,
            gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT)
        cleanup_needed = True

    if chooser is not None:
        result = chooser.run()
        if result == gtk.RESPONSE_ACCEPT:
            dsobject = chooser.get_selected_object()
        if cleanup_needed:
            chooser.destroy()
            del chooser
    gobject.idle_add(action, dsobject)
Пример #34
0
    def __do_clicked_choose_sound(self, control, event, obj, property):
        if hasattr(mime, "GENERIC_TYPE_AUDIO"):
            filter = {"what_filter": mime.GENERIC_TYPE_AUDIO}
        else:
            filter = {}

        logging.debug("choosing sound file")
        chooser = ObjectChooser(
            title=_("Choose Sound"),
            parent=Globals.JokeMachineActivity,  # ._parent,
            flags=gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
            **filter
        )
        try:
            result = chooser.run()
            if result == gtk.RESPONSE_ACCEPT:
                logging.debug("ObjectChooser: %r" % chooser.get_selected_object())
                journal_object = chooser.get_selected_object()
                if hasattr(obj, "sound_blob") and journal_object and journal_object.file_path:
                    logging.debug(
                        "Getting journal object: %r, %s, %s",
                        journal_object,
                        journal_object.file_path,
                        journal_object.metadata["title"],
                    )
                    # Set the sound now
                    f = open(journal_object.file_path, "r")
                    raw = f.read()
                    f.close()
                    obj.sound = str(journal_object.metadata["title"])
                    obj.sound_blob = raw
                    control.props.text = obj.sound
        finally:
            # chooser.hide()
            chooser.destroy()
            del chooser
Пример #35
0
	def journal_open_image (self):
		self.object_chooser_active = True
		if hasattr(mime, 'GENERIC_TYPE_IMAGE'):
			chooser = ObjectChooser(_('Choose image'),
					what_filter=mime.GENERIC_TYPE_IMAGE)
		else:
			chooser = ObjectChooser(_('Choose image'))

		try:
			result = chooser.run()
			if result == gtk.RESPONSE_ACCEPT and chooser.get_selected_object():
				jobject = chooser.get_selected_object()
			else:
				return False

			if jobject and jobject.file_path:
				logging.debug("journal_open_image: fname=%s" % jobject.file_path)
				try:
					self.orig_pic = gtk.gdk.pixbuf_new_from_file (jobject.file_path)
					self.filename = os.path.join('images', os.path.basename(jobject.file_path))
				except Exception, e:
					logging.error("journal_open_image: %s" % e)
					return False
			else:
Пример #36
0
    def _dom_title_cb(self, view, gParamSpec):
        """
		Use the document.title notify::title property change signal to call
		Python from JavaScript, as suggested here:
		http://code.google.com/p/pywebkitgtk/wiki/HowDoI
		"""
        title = self._webview.get_main_frame().get_title()
        #logging.debug("_dom_title_cb: %s" % (title,))
        if title is None:
            self._title_req_ids.clear()
        else:
            if title.startswith("ShockTherapySugarRequest:"):
                parts = title.split(":", 2)
                if len(parts) != 3:
                    raise ValueError(title)
                callback = parts[1]
                path = parts[2]
                req_id = int(callback[len("shockTherapySugarRequest"):])
                if req_id in self._title_req_ids:
                    # suppress event with duplicate req_id
                    pass
                else:
                    self._title_req_ids.add(req_id)

                    if path.startswith("file:///ShockTherapy."):
                        command = path[len("file:///ShockTherapy."):]
                        status = 200
                        content = b''
                        if command.startswith("viewChanged:"):
                            uri = unquote(command[len("viewChanged:"):])
                            self._uri_cb(uri)

                    elif path.startswith("file:///ShockTherapyConfig."):
                        command = path[len("file:///ShockTherapyConfig."):]
                        status = 200
                        content = b''
                        if command == "load":
                            content = self.metadata.get("options")
                            if content is None:
                                content = b"{}"
                            else:
                                content = content.decode(encoding="utf_8",
                                                         errors="replace")
                        elif command.startswith("persist:"):
                            self.metadata['options'] = unquote(
                                command[len("persist:"):])
                        elif command.startswith("export:"):
                            options = unquote(command[len("export:"):])
                            self.metadata['options'] = options
                            options.encode(encoding='utf_8', errors='replace')
                            dsobject = self._save_dsobject(
                                "ShockTherapyOptions.json", options)
                            self._saved_dsobject_alert(dsobject)
                        elif command == "import":
                            chooser = ObjectChooser(
                                parent=self,
                                what_filter=mime.GENERIC_TYPE_TEXT)
                            result = chooser.run()
                            if result == gtk.RESPONSE_ACCEPT:
                                f = open(
                                    chooser.get_selected_object().
                                    get_file_path(), 'rb')
                                try:
                                    options = f.read()
                                finally:
                                    f.close()
                                options = options.decode(encoding='utf_8',
                                                         errors='replace')
                                self.metadata['options'] = options
                                self._webview.reload()

                    else:
                        path = path[len(self._base_uri):]
                        path = os.path.join(self._http_dir, path)
                        path = os.path.normpath(path)
                        if not (path.startswith(self._http_dir)):
                            # don't allow traversal above _http_dir via ../
                            status = 404
                            content = ""
                        else:
                            f = None
                            try:
                                f = open(path, 'rb')
                                content = f.read()
                            except IOError:
                                status = 404
                                content = ""
                            else:
                                status = 200
                            finally:
                                if f is not None:
                                    f.close()

                    #logging.debug(
                    #	"ShockTherapySugarRequest: %s status: %s content: %s" %
                    #	(path, status, content))
                    self._webview.execute_script(
                        "%s(%s, \"%s\")" %
                        (callback, status, base64.b64encode(content)))