Exemplo n.º 1
0
def _create_new_object(type_name, pnode):
    att = {}
    obj = None
    
    print 'new:', type_name
    isAction = gobject.type_is_a(type_name, 'GtkAction')
    isActionGroup = gobject.type_is_a(type_name, 'GtkActionGroup')
    isMenuItem = gobject.type_is_a(type_name, 'GtkMenuItem')
    isToolItem = gobject.type_is_a(type_name, 'GtkToolItem')

    if isAction or isActionGroup:
        att = _conly_properties(pnode, type_name) 
        
    elif isMenuItem or isToolItem:
        _id = node = pnode.parentNode.getAttribute('action')
        if not _id == '':
            dic = _top_node(pnode).loader.dic
            act = dic[int(_id)]
            
            if isMenuItem:
                obj = act.create_menu_item()
            elif isToolItem:
                obj = act.create_tool_item()
            
            obj.set_data('shakya:action', act)
    
    if not obj:  
        obj = gobject.new(type_name, **att)
        if gobject.type_is_a(obj, gtk.Widget):
            obj.hide()
    
    return obj
Exemplo n.º 2
0
 def _object_to_xml(self, obj, parent_node=None):
     doc = self._doc
     
     # create the object node
     node = doc.createElement('object')
     node.setAttribute('class', gobject.type_name(obj))
     node.setAttribute('id', '%d'%id(obj))
     if isinstance(obj, gtk.MenuItem) or isinstance(obj, gtk.ToolItem):
         act = obj.get_data('shakya:action')
         if act:
             node.setAttribute('action', '%d' % id(act))
     
     # write the object properties
     prop_node = doc.createElement('properties')
     self._write_properties(prop_node, obj)
     node.appendChild(prop_node) 
     
     # write the widget child-properties        
     if gobject.type_is_a(obj, 'GtkWidget'):
         parent = obj.get_parent()
         if parent and gobject.type_is_a(parent, 'GtkContainer'):
             childprop_node = doc.createElement('child-properties')
             self._write_child_properties(childprop_node, obj)
             node.appendChild(childprop_node) 
     
     # write container widget children     
     if isinstance(obj, gtk.Container):
         act = None
         
         if isinstance(obj, gtk.MenuItem) or isinstance(obj, gtk.ToolItem):
             act = obj.get_data('shakya:action')
         
         if not act:
             children_node = doc.createElement('children')
             for child in self._filter_children(obj.get_children()):
                 child_node = self._object_to_xml(child, children_node)
             node.appendChild(children_node)
     
     # write menuitem submenus        
     if isinstance(obj, gtk.MenuItem):
         submenu_node = doc.createElement('submenu')
         submenu = obj.get_submenu()
         if submenu:
             menu_node = self._object_to_xml(submenu, submenu_node)
         node.appendChild(submenu_node)
     
     # link child node with parent
     if parent_node:
         parent_node.appendChild(node)
     
     return node
Exemplo n.º 3
0
    def _object_to_xml(self, obj, parent_node=None):
        doc = self._doc

        # create the object node
        node = doc.createElement('object')
        node.setAttribute('class', gobject.type_name(obj))
        node.setAttribute('id', '%d' % id(obj))
        if isinstance(obj, gtk.MenuItem) or isinstance(obj, gtk.ToolItem):
            act = obj.get_data('shakya:action')
            if act:
                node.setAttribute('action', '%d' % id(act))

        # write the object properties
        prop_node = doc.createElement('properties')
        self._write_properties(prop_node, obj)
        node.appendChild(prop_node)

        # write the widget child-properties
        if gobject.type_is_a(obj, 'GtkWidget'):
            parent = obj.get_parent()
            if parent and gobject.type_is_a(parent, 'GtkContainer'):
                childprop_node = doc.createElement('child-properties')
                self._write_child_properties(childprop_node, obj)
                node.appendChild(childprop_node)

        # write container widget children
        if isinstance(obj, gtk.Container):
            act = None

            if isinstance(obj, gtk.MenuItem) or isinstance(obj, gtk.ToolItem):
                act = obj.get_data('shakya:action')

            if not act:
                children_node = doc.createElement('children')
                for child in self._filter_children(obj.get_children()):
                    child_node = self._object_to_xml(child, children_node)
                node.appendChild(children_node)

        # write menuitem submenus
        if isinstance(obj, gtk.MenuItem):
            submenu_node = doc.createElement('submenu')
            submenu = obj.get_submenu()
            if submenu:
                menu_node = self._object_to_xml(submenu, submenu_node)
            node.appendChild(submenu_node)

        # link child node with parent
        if parent_node:
            parent_node.appendChild(node)

        return node
Exemplo n.º 4
0
    def _get_base_type(self, value_type):
        if gobject.type_is_a(value_type, gobject.TYPE_OBJECT):
            base_type = gobject.TYPE_OBJECT
        elif gobject.type_is_a(value_type, gobject.TYPE_ENUM):
            base_type = gobject.TYPE_ENUM
        elif gobject.type_is_a(value_type, gobject.TYPE_FLAGS):
            base_type = gobject.TYPE_FLAGS
        elif gobject.type_is_a(value_type, gobject.TYPE_BOXED):
            base_type = gobject.TYPE_BOXED
        else:
            base_type = value_type

        base = self._bases.get(base_type)
        if not base:
            raise PropertyError("Can't find base type for %r" % base_type)
        return base
Exemplo n.º 5
0
    def _update_paste_action(self, selection, clipboard_item):
        """
        Update the paste action.

        @param selection: the selected widgets
        @type selection: list
        @param clipboard_item: the selected item on the clipboard
        @type clipboard_item: L{gazpacho.clipboard.ClipboardItem}
        """
        sensitive = False
        if clipboard_item:
            # We can always paste a toplevel
            if clipboard_item.is_toplevel:
                sensitive = True

            # columns can be pasted in tree views
            elif (len(selection) == 1
                  and isinstance(selection[0], gtk.TreeView)
                  and gobject.type_is_a(clipboard_item.type,
                                        gtk.TreeViewColumn)):
                sensitive = True

            # otherwise we need a placeholder
            elif (len(selection) == 1
                  and isinstance(selection[0], Placeholder)):
                sensitive = True

        bar_manager.set_action_prop('Paste', sensitive=sensitive)
Exemplo n.º 6
0
    def get_type(self, x):
        for t in ("GParamFloat", "GParamDouble"):
            if gobject.type_is_a(x, gobject.type_from_name(t)):
                return "float"
        for t in ("GParamInt", "GParamInt64", "GParamUInt", "GParamUInt64", "GParamLong", "GParamULong"):
            if gobject.type_is_a(x, gobject.type_from_name(t)):
                return "integer"
        for t in ("GParamString", "GParamChar", "GParamUChar"):
            if gobject.type_is_a(x, gobject.type_from_name(t)):
                return "string"
        if gobject.type_is_a(x, gobject.type_from_name("GParamEnum")):
            return "enum"
        if gobject.type_is_a(x, gobject.type_from_name("GParamBoolean")):
            return "boolean"

        return "unknown"
Exemplo n.º 7
0
 def do_get_accounts(self, list, types):
     store = False
     transport = False
     if types == tinymail.ACCOUNT_STORE_STORE_ACCOUNTS:
         store = True
     elif types == tinymail.ACCOUNT_STORE_TRANSPORT_ACCOUNTS:
         transport = True
     else:
         store = True
         transport = True
     for account in self.__accounts:
         if gobject.type_is_a(account.__gtype__,
                              tinymail.StoreAccount) and store:
             list.append(account)
         elif gobject.type_is_a(account._gtype__,
                                tinymail.TransportAccount) and transport:
             list.append(account)
Exemplo n.º 8
0
    def _add_type(self, prop_name, prop_type, pspec=None):
        if pspec:
            if gobject.type_is_a(pspec.value_type, gobject.TYPE_ENUM):
                prop_type.enum_class = pspec.enum_class
            elif gobject.type_is_a(pspec.value_type, gobject.TYPE_FLAGS):
                prop_type.flags_class = pspec.flags_class

            prop_type.label = pspec.nick
            prop_type.type = pspec.value_type
        else:
            if not prop_type.label:
                prop_type.label = prop_name.capitalize()

        if prop_name in self._types:
            msg = "There is already a property called %s registered"
            raise TypeError(msg % prop_name)

        self._types[prop_name] = prop_type
Exemplo n.º 9
0
    def _setup_widget(self, widget_name, widget):
        if not IProxyWidget.providedBy(widget):
            raise ProxyError("The widget %s (%r), in view %s is not "
                             "a kiwi widget and cannot be added to a proxy"
                             % (widget_name, widget,
                                self._view.__class__.__name__))

        data_type = _get_widget_data_type(widget)
        if data_type is None:
            raise ProxyError("The kiwi widget %s (%r) in view %s should "
                             "have a data type set" % (
                                 widget_name, widget, self._view.__class__.__name__))

        attribute = widget.get_property('model-attribute')
        if not attribute:
            attribute = widget_name
            widget.set_property('model-attribute', widget_name)

        # Do a isinstance here instead of in the callback,
        # as an optimization, it'll never change in runtime anyway
        connection_id = widget.connect(
            'content-changed',
            self._on_widget__content_changed,
            attribute,
            IValidatableProxyWidget.providedBy(widget))
        widget.set_data('content-changed-id', connection_id)

        if IValidatableProxyWidget.providedBy(widget):
            connection_id = widget.connect(
                'notify::visible',
                self._on_widget__notify)
            widget.set_data('notify-visible-id', connection_id)

            connection_id = widget.connect(
                'notify::sensitive',
                self._on_widget__notify)
            widget.set_data('notify-sensitive-id', connection_id)

            connection_id = widget.connect(
                'validation-changed',
                self._on_widget__validation_changed,
                attribute)
            widget.set_data('validation-changed-id', connection_id)

        model_attributes = self._model_attributes
        # save this widget in our map
        if (attribute in model_attributes and
            # RadioButtons are allowed several times
            not gobject.type_is_a(widget, 'GtkRadioButton')):
            old_widget = model_attributes[attribute]
            raise KeyError("The widget %s (%r) in view %s is already in "
                           "the proxy, defined by widget %s (%r)" % (
                               widget_name, widget, self._view.__class__.__name__,
                               old_widget.name, old_widget))

        model_attributes[attribute] = widget
        self._reset_widget(attribute, widget)
Exemplo n.º 10
0
    def _setup_widget(self, widget_name, widget):
        if not IProxyWidget.providedBy(widget):
            raise ProxyError("The widget %s (%r), in view %s is not "
                             "a kiwi widget and cannot be added to a proxy"
                             % (widget_name, widget,
                                self._view.__class__.__name__))

        data_type = _get_widget_data_type(widget)
        if data_type is None:
            raise ProxyError("The kiwi widget %s (%r) in view %s should "
                             "have a data type set" % (
                                 widget_name, widget, self._view.__class__.__name__))

        attribute = widget.get_property('model-attribute')
        if not attribute:
            attribute = widget_name
            widget.set_property('model-attribute', widget_name)

        # Do a isinstance here instead of in the callback,
        # as an optimization, it'll never change in runtime anyway
        connection_id = widget.connect(
            'content-changed',
            self._on_widget__content_changed,
            attribute,
            IValidatableProxyWidget.providedBy(widget))
        widget.set_data('content-changed-id', connection_id)

        if IValidatableProxyWidget.providedBy(widget):
            connection_id = widget.connect(
                'notify::visible',
                self._on_widget__notify)
            widget.set_data('notify-visible-id', connection_id)

            connection_id = widget.connect(
                'notify::sensitive',
                self._on_widget__notify)
            widget.set_data('notify-sensitive-id', connection_id)

            connection_id = widget.connect(
                'validation-changed',
                self._on_widget__validation_changed,
                attribute)
            widget.set_data('validation-changed-id', connection_id)

        model_attributes = self._model_attributes
        # save this widget in our map
        if (attribute in model_attributes and
            # RadioButtons are allowed several times
            not gobject.type_is_a(widget, 'GtkRadioButton')):
            old_widget = model_attributes[attribute]
            raise KeyError("The widget %s (%r) in view %s is already in "
                           "the proxy, defined by widget %s (%r)" % (
                               widget_name, widget, self._view.__class__.__name__,
                               old_widget.name, old_widget))

        model_attributes[attribute] = widget
        self._reset_widget(attribute, widget)
Exemplo n.º 11
0
def load_ui(filename):
    print 'Loading: %s...' % filename    
    loader = UILoader()
    obj = loader.load(filename)
    print obj    
    if gobject.type_is_a(obj, 'GtkWindow'):
        w, h = obj.get_default_size()
        obj.resize(w, h)
    
    return obj
Exemplo n.º 12
0
    def _create_editor_property(self, property_class):
        if property_class.editor != PropertyCustomEditor:
            return EditorPropertySpecial(property_class, self._app)

        # Special case GObject subclasses
        if gobject.type_is_a(property_class.type, gobject.GObject):
            return EditorPropertyObject(property_class, self._app)

        if property_map.has_key(property_class.base_type):
            return property_map[property_class.base_type](property_class,
                                                          self._app)
Exemplo n.º 13
0
def get_pixbuf(name, fail_gracefully=0, width=0, height=0):

    if not name:
        assert fail_gracefully
        return None

    if width > 0 and height > 0:
        key = "%s %d %d" % (name, width, height)
    else:
        key = name

    # If this isn't a string, maybe it is a GdkPixbuf.  If so, just
    # pass it through.  Otherwise something is very wrong, so we
    # assert.
    # FIXME: How do I check this type w/o the "try"?
    if type(name) != type(""):
        try:
            if gobject.type_is_a(name.__gtype__,
                                 gtk.gdk.Pixbuf.__gtype__):
                return name
        except:
            print "Unknown type passed to get_pixbuf"
            assert 0
        

    if pixbuf_cache.has_key(key):
        return pixbuf_cache[key]

    pixbuf = None
    
    if width > 0 and height > 0:

        original = get_pixbuf(name)
        pixbuf = original.scale_simple(width, height, gtk.gdk.INTERP_BILINEAR)

    else:

        for dir in pixbuf_path:
            filename = os.path.join(dir, name + ".png")
            if os.path.isfile(filename):
                pixbuf = gtk.gdk.pixbuf_new_from_file(filename)
                if not pixbuf:
                    print "Couldn't load pixbuf from '%s'" % filename
                    assert 0

    if pixbuf:
        pixbuf_cache[key] = pixbuf
        return pixbuf

    if not fail_gracefully:
        print "Couldn't find pixbuf '%s'" % name
        assert 0

    return None
Exemplo n.º 14
0
 def get_enum(p):
     vals = []
     if not gobject.type_is_a(p.value_type, gobject.TYPE_ENUM):
         raise errors.ComponentSetupError(p.name + ': unexpected property type.')
     else:
         for item in p.enum_class.__enum_values__.items():
             vals.append({
                 'value': item[0],
                 'name': item[1].value_name,
                 'nick': item[1].value_nick
             })
     return vals
Exemplo n.º 15
0
def get_pixbuf(name, fail_gracefully=0, width=0, height=0):

    if not name:
        assert fail_gracefully
        return None

    if width > 0 and height > 0:
        key = "%s %d %d" % (name, width, height)
    else:
        key = name

    # If this isn't a string, maybe it is a GdkPixbuf.  If so, just
    # pass it through.  Otherwise something is very wrong, so we
    # assert.
    # FIXME: How do I check this type w/o the "try"?
    if type(name) != type(""):
        try:
            if gobject.type_is_a(name.__gtype__, gtk.gdk.Pixbuf.__gtype__):
                return name
        except:
            print "Unknown type passed to get_pixbuf"
            assert 0

    if pixbuf_cache.has_key(key):
        return pixbuf_cache[key]

    pixbuf = None

    if width > 0 and height > 0:

        original = get_pixbuf(name)
        pixbuf = original.scale_simple(width, height, gtk.gdk.INTERP_BILINEAR)

    else:

        for dir in pixbuf_path:
            filename = os.path.join(dir, name + ".png")
            if os.path.isfile(filename):
                pixbuf = gtk.gdk.pixbuf_new_from_file(filename)
                if not pixbuf:
                    print "Couldn't load pixbuf from '%s'" % filename
                    assert 0

    if pixbuf:
        pixbuf_cache[key] = pixbuf
        return pixbuf

    if not fail_gracefully:
        print "Couldn't find pixbuf '%s'" % name
        assert 0

    return None
Exemplo n.º 16
0
def valuefromstringsimpletypes(gtype, string):
    if gtype in (gobject.TYPE_CHAR, gobject.TYPE_UCHAR):
        value = string[0]
    elif gtype == gobject.TYPE_BOOLEAN:
        value = str2bool(string)
    elif gtype in (gobject.TYPE_INT, gobject.TYPE_UINT):
        value = int(string)
    elif gtype in (gobject.TYPE_LONG, gobject.TYPE_ULONG):
        value = long(string)
    elif gtype in (gobject.TYPE_FLOAT, gobject.TYPE_DOUBLE):
        value = float(string)
    elif gtype == gobject.TYPE_STRING:
        value = string
    elif gobject.type_is_a(gtype, gobject.TYPE_PYOBJECT):
        value = string
    elif gobject.type_is_a(gtype, gobject.GBoxed):
        print 'TODO: boxed'
        value = None
    else:
        raise TypeError("type %r is unknown" % gtype)

    return value
Exemplo n.º 17
0
    def testConstruct(self):
        objs = [("kiwi+ui+widgets+list+List", "w1"),
                ("kiwi+ui+widgets+combobox+ComboBox", "w3"),
                ("kiwi+ui+widgets+combobox+ComboBoxEntry", "w5")
                ]

        if HAVE_2_8:
            objs.extend([("ObjectList", "w2"),
                         ("ProxyComboBox", "w4"),
                         ("ProxyComboBoxEntry", "w6")
                         ])
        s = ''

        for obj, name in objs:
            s += '<widget class="%s" id="%s"/>\n' % (obj, name)
        ob = disabledeprecationcall(ObjectBuilder, buffer=glade(s))
        for obj, name in objs:
            widget = ob.get_widget(name)
            self.failUnless(isinstance(widget, gtk.Widget))
            gtype = gobject.type_from_name(obj)
            self.failUnless(gobject.type_is_a(gtype, gtk.Widget))
            self.failUnless(gobject.type_is_a(gtype, widget))
Exemplo n.º 18
0
def _build_object(node, parent=None):
    pnode = _get_first_child(node, 'properties')
    cpnode = _get_first_child(node, 'child-properties')
    cnode = _get_first_child(node, 'children')
    #print pnode, cpnode, cnode    

    _id = int(node.getAttribute('id'))
    type_name = str(node.getAttribute('class'))    
    obj = _create_new_object(type_name, pnode); print obj
    _add_child(parent, obj)

    # store a reference on the dictionary
    dic = _top_node(node).loader.dic
    dic[_id] = obj

    # setup the properties
    for prop in _properties(pnode):
        _set_property(obj, prop)

    # setup the child-properties
    if parent and gobject.type_is_a(parent, 'GtkContainer'):
        for prop in _properties(cpnode):
            _set_child_property(parent, obj, prop)

    # recursively create children
    if gobject.type_is_a(obj, 'GtkContainer'):
        for child in _children(cnode):
            _build_object(child, obj)
    
    # create submenus
    if gobject.type_is_a(obj, 'GtkMenuItem'):
        submenu = _get_first_child(node, 'submenu')
        #print '*** menuitem', submenu
        if submenu:
            child = _get_first_child(submenu, 'object')
            if child:
                _build_object(child, obj)
    
    return obj
Exemplo n.º 19
0
    def get_builder_toplevel(self, builder):
        """Get the toplevel widget from a gtk.Builder file.

        The main view implementation first searches for the widget named as
        self.toplevel_name (which defaults to "main". If this is missing, or not
        a gtk.Window, the first toplevel window found in the gtk.Builder is
        used.
        """
        toplevel = builder.get_object(self.toplevel_name)
        if not gobject.type_is_a(toplevel, gtk.Window):
            toplevel = None
        if toplevel is None:
            toplevel = get_first_builder_window(builder)
        return toplevel
Exemplo n.º 20
0
def fetch(obj):
    """
    Fetch properties info of an object. This is used in the Property Browser
    to get all the editable properties of that object.
    """
    
    result = []
    
    properties = list(gobject.list_properties(obj))
    for klass, infos in _infos.iteritems():
        if gobject.type_is_a(obj, klass):
            for info in infos:
                info.property = _get_property(info.name, properties)
                result.append(info)
    
    return result
Exemplo n.º 21
0
def fetch(obj):
    """
    Fetch properties info of an object. This is used in the Property Browser
    to get all the editable properties of that object.
    """

    result = []

    properties = list(gobject.list_properties(obj))
    for klass, infos in _infos.iteritems():
        if gobject.type_is_a(obj, klass):
            for info in infos:
                info.property = _get_property(info.name, properties)
                result.append(info)

    return result
Exemplo n.º 22
0
    def _apply_delayed_properties(self):
        for inst, prop in self._delayed_properties:
            if '.' in prop.name:
                parts = prop.name.split('.')
                start = parts[0]
                for part in parts[:-1]:
                    inst = getattr(inst.props, part)
                prop_name = parts[-1]
            else:
                prop_name = prop.name
            pspec = getattr(inst.__class__.props, prop_name)
            if GObject.type_is_a(pspec.value_type, GObject.TYPE_OBJECT):
                value = self._objects[prop.value]
            else:
                value = self._parse_property(pspec, prop)

            inst.set_property(prop_name, value)
Exemplo n.º 23
0
    def load(self, widget):
        self._start_load(widget)
        current = self.property.get()

        self.model.clear()
        for pwidget in self.project.get_widgets():
            if isinstance(pwidget, gtk.Window):
                continue

            if not gobject.type_is_a(pwidget, self.property_type):
                continue

            iter = self.model.append((pwidget.name, pwidget))
            if pwidget == current:
                self.input.set_active_iter(iter)

        self._finish_load()
Exemplo n.º 24
0
def ListDeviceProbe(element, probe_name):
    element_name = element.get_factory().get_property("name")
    dev_info_list = []

    if hasattr(element.props, "device"):
        default_device = element.__class__.props.device.default_value
        if gobject.type_is_a(element, gst.interfaces.PropertyProbe):
            element.probe_property_name("device")
            devices = element.probe_get_values_name("device")

            if (default_device != None) and (default_device not in devices):
                dev_info_list.append((default_device, ""))

            if probe_name and hasattr(element.props, "device-name"):
                for dev in devices:
                    element.set_property("device", dev)

                    # certain elements like pulsesrc won't load the device-name until STATE_PLAYING
                    state_change_type = element.set_state(gst.STATE_PLAYING)
                    if state_change_type == gst.STATE_CHANGE_ASYNC:
                        new_state = None
                        while new_state != gst.STATE_PLAYING and new_state != gst.STATE_READY:
                            gtk.main_iteration()
                            state_change_type, new_state, pending = element.get_state(
                                0)
                            time.sleep(0.01)
                    name = element.get_property("device-name")
                    element.set_state(gst.STATE_NULL)

                    dev_info_list.append((dev, name))
            else:
                for dev in devices:
                    dev_info_list.append((dev, ""))
        else:
            dev_info_list.append((default_device, ""))
    else:
        Globals.debug("Cannot list devices: property probe not supported on",
                      element_name)

    # Sort the devices by device ID (ensures that monitor devices are after canonical devices)
    dev_info_list.sort()

    return dev_info_list
Exemplo n.º 25
0
    def _valuefromstring(self, obj_id, pspec, string):
        # This is almost a 1:1 copy of glade_xml_set_value_from_string from
        # libglade.
        prop_type = pspec.value_type

        if (prop_type in (gobject.TYPE_INT, gobject.TYPE_UINT)
            and gobject.type_name(pspec) == 'GParamUnichar'):
            value = unicode(string and string[0] or "")
            return value

        try:
            value = valuefromstringsimpletypes(prop_type, string)
        except TypeError:
            pass # it's ok if we fail so far, we'll try other types
        else:
            return value

        if gobject.type_is_a(prop_type, gobject.TYPE_ENUM):
            value = enumfromstring(string, pspec)
        elif gobject.type_is_a(prop_type, gobject.TYPE_FLAGS):
            value = flagsfromstring(string, pspec)
        elif gobject.type_is_a(prop_type, gobject.GObject):
            if gobject.type_is_a(prop_type, gtk.Adjustment):
                value = gtk.Adjustment(0, 0, 100, 1, 10, 10)
                (value.value, value.lower, value.upper,
                 value.step_increment, value.page_increment,
                 value.page_size) = map(float, string.split(' '))
            elif gobject.type_is_a(prop_type, gdk.Pixbuf):
                filename = self._build.find_resource(string)
                value = None
                if filename:
                    # XXX: Handle GError exceptions.
                    value = gdk.pixbuf_new_from_file(filename);
            elif (gobject.type_is_a(gobject.GObject, prop_type) or
                  gobject.type_is_a(prop_type, gobject.GObject)):
                value = self._build.get_widget(string)
                if value is None:
                    self._build.add_delayed_property(obj_id, pspec, string)
            else:
                value = None
        else:
            raise AssertionError("type %r is unknown" % prop_type)

        return value
Exemplo n.º 26
0
def ListDeviceProbe(element, probe_name):
    element_name = element.get_factory().get_property("name")
    dev_info_list = []

    if hasattr(element.props, "device"):
        default_device = element.__class__.props.device.default_value
        if gobject.type_is_a(element, gst.interfaces.PropertyProbe):
            element.probe_property_name("device")
            devices = element.probe_get_values_name("device")

            if (default_device != None) and (default_device not in devices):
                dev_info_list.append((default_device, ""))

            if probe_name and hasattr(element.props, "device-name"):
                for dev in devices:
                    element.set_property("device", dev)

                    # certain elements like pulsesrc won't load the device-name until STATE_PLAYING
                    state_change_type = element.set_state(gst.STATE_PLAYING)
                    if state_change_type == gst.STATE_CHANGE_ASYNC:
                        new_state = None
                        while new_state != gst.STATE_PLAYING and new_state != gst.STATE_READY:
                            gtk.main_iteration()
                            state_change_type, new_state, pending = element.get_state(0)
                            time.sleep(0.01)
                    name = element.get_property("device-name")
                    element.set_state(gst.STATE_NULL)

                    dev_info_list.append((dev, name))
            else:
                for dev in devices:
                    dev_info_list.append((dev, ""))
        else:
            dev_info_list.append((default_device, ""))
    else:
        Globals.debug("Cannot list devices: property probe not supported on", element_name)

        # Sort the devices by device ID (ensures that monitor devices are after canonical devices)
    dev_info_list.sort()

    return dev_info_list
Exemplo n.º 27
0
    def __init__(self, gadget):
        self._initial = None

        cls = type(self)
        assert cls.name != None
        assert cls.owner_name != None
        assert cls.owner_type != gobject.TYPE_INVALID

        self.gadget = gadget
        self._project = gadget.project
        gobj = gadget.widget

        # Assert that the owner is of correct type
        if self.child:
            test_object = gobj.get_parent()
        else:
            test_object = gobj
        if not gobject.type_is_a(test_object, self.owner_type):
            raise TypeError("Expected an object of type %s, got %r" % (
                gobject.type_name(self.owner_type), test_object))

        self.load()
Exemplo n.º 28
0
def load_gadget_from_widget(widget, project):
    """  This function creates a gadget from a widget.
    It recursively creates any children of the original widget.
    This method is mainly used when loading a .glade file with
    gazpacho.loader

    Also makes sure the name of the widget is unique in the project
    parameter and if not, change it for a valid one.

    @return: a new gadget
    @rtype: Gadget
    """

    # widget may not have a name if it is an intermediate internal children
    # For example, the label of a button does not have a name
    if widget.name is None:
        # this is not an important widget but maybe its children are
        if isinstance(widget, gtk.Container):
            for child in get_all_children(widget):
                load_gadget_from_widget(child, project)
        return

    type_name = gobject.type_name(widget)
    adaptor = widget_registry.get_by_name(type_name)
    if adaptor is None:
        print 'Warning: could not get the class from widget: %s' % widget
        return

    gadget = adaptor.load(project.context, widget)
    if not isinstance(gadget, Gadget):
        raise TypeError("WidgetAdaptor.load should always return a Gadget"
                        " not %s" % gadget)
    if not gobject.type_is_a(gadget.widget, adaptor.type):
        raise TypeError("%s is not of the type %s"
                        % (gadget.widget, adaptor.type))
    return gadget
Exemplo n.º 29
0
    def add_action_widget(self, child, response_id):
        if not gobject.type_is_a(child, gtk.Widget):
            print 'Not a Widget' #FIXME:
            return

        print '#TODO: add response data'
        print child

        if type(child) is gtk.Button:
            signal_id = gobject.signal_lookup('clicked', type(child))
        else:
            signal_id = gobject.signal_lookup('activate', type(child))
            
        if signal_id:
            print 'TODO: check if this is correct.'
            signal = gobject.signal_name(signal_id)
            child.connect(signal, MessageArea.__action_widget_activated, self) #FIXME:
        else:
            print "Only 'activatable' widgets can be packed into the action area of a MessageArea"

        if response_id != gtk.RESPONSE_HELP:
            self.action_area.pack_start(child, False, False, 0)
        else:
            self.action_area.pack_end(child, False, False, 0)
Exemplo n.º 30
0
def gproperty(name,
              ptype,
              default=None,
              nick='',
              blurb='',
              flags=gobject.PARAM_READWRITE,
              **kwargs):
    """
    Add a GObject property to the current object.
    @param name:   name of property
    @type name:    string
    @param ptype:   type of property
    @type ptype:    type
    @param default:  default value
    @param nick:     short description
    @param blurb:    long description
    @param flags:    parameter flags, a combination of:
      - PARAM_READABLE
      - PARAM_READWRITE
      - PARAM_WRITABLE
      - PARAM_CONSTRUCT
      - PARAM_CONSTRUCT_ONLY
      - PARAM_LAX_VALIDATION
    Optional, only for int, float, long types:
    @note: minimum: minimum allowed value
    @note: maximum: maximum allowed value
    """

    # General type checking
    if default is None:
        default = _DEFAULT_VALUES.get(ptype)
    elif not isinstance(default, ptype):
        raise TypeError("default must be of type %s, not %r" %
                        (ptype, default))
    if not isinstance(nick, str):
        raise TypeError('nick for property %s must be a string, not %r' %
                        (name, nick))
    nick = nick or name
    if not isinstance(blurb, str):
        raise TypeError('blurb for property %s must be a string, not %r' %
                        (name, blurb))

    # Specific type checking
    if ptype == int or ptype == float or ptype == long:
        default = (kwargs.get('minimum', ptype(0)),
                   kwargs.get('maximum', _MAX_VALUES[ptype]), default)
    elif ptype == bool:
        if (default is not True and default is not False):
            raise TypeError("default must be True or False, not %r" %
                            (default))
        default = default,
    elif gobject.type_is_a(ptype, gobject.GEnum):
        if default is None:
            raise TypeError("enum properties needs a default value")
        elif not isinstance(default, ptype):
            raise TypeError("enum value %s must be an instance of %r" %
                            (default, ptype))
        default = default,
    elif ptype == str:
        default = default,
    elif ptype == object:
        if default is not None:
            raise TypeError("object types does not have default values")
        default = ()
    else:
        raise NotImplementedError("type %r" % ptype)

    if flags < 0 or flags > 32:
        raise TypeError("invalid flag value: %r" % (flags, ))

    frame = sys._getframe(1)
    try:
        locals = frame.f_locals
        dict = locals.setdefault('__gproperties__', {})
    finally:
        del frame

    dict[name] = (ptype, nick, blurb) + default + (flags, )
Exemplo n.º 31
0
 def append_widget_to_model(self, widget, parent_iter, model):
     iter = model.append(parent_iter, _widget_data(widget))
     if gobject.type_is_a(widget, 'GtkContainer'):
         for child in widget.get_children():
             self.append_widget_to_model(child, iter,  model)
Exemplo n.º 32
0
def gproperty(name, ptype, default=None, nick="", blurb="", flags=gobject.PARAM_READWRITE, **kwargs):
    """Add a GObject property to the current object.

    :param name:   name of property
    :param ptype:   type of property
    :param default:  default value
    :param nick:     short description
    :param blurb:    long description
    :param flags:    parameter flags, a combination of:
      - PARAM_READABLE
      - PARAM_READWRITE
      - PARAM_WRITABLE
      - PARAM_CONSTRUCT
      - PARAM_CONSTRUCT_ONLY
      - PARAM_LAX_VALIDATION

    Optional, only for int, float, long types:

    :param minimum: minimum allowed value
    :param: maximum: maximum allowed value
    """

    # General type checking
    if default is None:
        default = _DEFAULT_VALUES.get(ptype)
    elif not isinstance(default, ptype):
        raise TypeError("default must be of type %s, not %r" % (ptype, default))
    if not isinstance(nick, str):
        raise TypeError("nick for property %s must be a string, not %r" % (name, nick))
    nick = nick or name
    if not isinstance(blurb, str):
        raise TypeError("blurb for property %s must be a string, not %r" % (name, blurb))

    # Specific type checking
    if ptype == int or ptype == float or ptype == long:
        default = (kwargs.get("minimum", ptype(0)), kwargs.get("maximum", _MAX_VALUES[ptype]), default)
    elif ptype == bool:
        if default is not True and default is not False:
            raise TypeError("default must be True or False, not %r" % (default))
        default = (default,)
    elif gobject.type_is_a(ptype, gobject.GEnum):
        if default is None:
            raise TypeError("enum properties needs a default value")
        elif not isinstance(default, ptype):

            raise TypeError("enum value %s must be an instance of %r" % (default, ptype))
        default = (default,)
    elif ptype == str:
        default = (default,)
    elif ptype == object:
        if default is not None:
            raise TypeError("object types does not have default values")
        default = ()
    else:
        raise NotImplementedError("type %r" % ptype)

    if flags < 0 or flags > 32:
        raise TypeError("invalid flag value: %r" % (flags,))

    frame = sys._getframe(1)
    try:
        locals = frame.f_locals
        dict = locals.setdefault("__gproperties__", {})
    finally:
        del frame

    dict[name] = (ptype, nick, blurb) + default + (flags,)
Exemplo n.º 33
0
 def find_cancel_btn(btn, _self):
     if btn and gobject.type_is_a(
             btn, gtk.Button) and btn.get_label() == gtk.STOCK_CANCEL:
         _self.cancel_btn = btn
Exemplo n.º 34
0
def test_ui_main_delegate_bad_toplevel():
    d = _Delegate6()
    assert gobject.type_is_a(d._toplevel, gtk.Window)
Exemplo n.º 35
0
def _get_pspec_args(self):
    if gobject.type_is_a(self.type, gobject.GEnum):
        return (self.type, self.nick, self.blurb, self.default, self.flags)
    else:
        return parent_get_pspec_args(self)
Exemplo n.º 36
0
def _get_pspec_args(self):
    if gobject.type_is_a(self.type, gobject.GEnum):
        return (self.type, self.nick, self.blurb, self.default, self.flags)
    else:
        return parent_get_pspec_args(self)
Exemplo n.º 37
0
 def append_widget_to_model(self, widget, parent_iter, model):
     iter = model.append(parent_iter, _widget_data(widget))
     if gobject.type_is_a(widget, 'GtkContainer'):
         for child in widget.get_children():
             self.append_widget_to_model(child, iter, model)
Exemplo n.º 38
0
 def find_hbox(w, _self):
     if w and gobject.type_is_a(w, gtk.HBox):
         w.forall(find_cancel_btn, _self)
Exemplo n.º 39
0
    def __init__(self, element=None):
        gtk.Window.__init__(self)
        
        if element:
            title = element.props.name + " - Parameters"
            self.set_title(title)
            self.element = element
            
        self.set_position(gtk.WIN_POS_MOUSE)
        self.set_default_size(380, 500)

        self.connect("delete-event", self.onDelete)
        
        self.vbox = gtk.VBox()
        self.vbox.set_border_width(15)
        self.scrollwin = gtk.ScrolledWindow()
        self.scrollwin.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        self.scrollwin.add_with_viewport(self.vbox)
        self.add(self.scrollwin)
        
        #TODO: make this prettier
        self.vbox.pack_start(gtk.Label('Set Element Parameters'), expand=False,
                                        padding=10)
        
        proplist = gobject.list_properties(self.element)
        self.table = gtk.Table(len(proplist), 2)
        self.table.props.row_spacing = 5
        self.table.props.column_spacing = 5
        self.vbox.pack_start(self.table, expand=False, padding=10)
        
        count = 0
        for property in proplist:
            label = gtk.Label(property.name)
            label.set_alignment(1,0.5)
            self.table.attach(label, 0, 1, count, count+1)
            
            #non readable params
            if not(property.flags & gobject.PARAM_READABLE):
                rlabel = gtk.Label("-parameter not readable-")
                self.table.attach(plabel, 1, 2, count, count+1)

            # just display non-writable param values
            elif not(property.flags & gobject.PARAM_WRITABLE):
                wvalue = self.element.get_property(property.name)
                if wvalue:
                    wlabel = gtk.Label(wvalue)
                    self.table.attach(wlabel, 1, 2, count, count+1)

            #TODO: tooltips using property.blurb
            
            elif hasattr(property, "minimum") and hasattr(property, "maximum"):
                #guess that it's numeric - we can use an HScale
                value = self.element.get_property(property.name)
                adj = gtk.Adjustment(value, property.minimum, property.maximum)
                
                adj.connect("value_changed", self.onValueChanged, property)
                hscale = gtk.HScale(adj)
                hscale.set_value_pos(gtk.POS_RIGHT)
                
                #check for ints and change digits
                if not((property.value_type == gobject.TYPE_FLOAT) or
                        (property.value_type == gobject.TYPE_DOUBLE)):
                    hscale.set_digits(0)
                    
                self.table.attach(hscale, 1, 2, count, count+1)
                #TODO: add numeric entry box
                
            elif gobject.type_is_a(property.value_type, gobject.TYPE_BOOLEAN):
                #booleans get a toggle button
                #TODO: change this to a tick box or pixmap button
                tstate = self.element.get_property(property.name)
                if tstate:
                    button = gtk.ToggleButton("On")
                else:
                    button = gtk.ToggleButton("Off")
                button.set_active(tstate)
                button.set_size_request(40,30)
                button.connect("toggled", self.onToggled, property)
                self.table.attach(button, 1, 2, count, count+1)

            elif hasattr(property, "enum_class"):
                #for enumerated types, use a combobox
                choices = _getChoices(property)
                enum = self.element.get_property(property.name)
                
                combo = gtk.ComboBox(choices)
                cell = gtk.CellRendererText()
                combo.pack_start(cell, True)
                combo.add_attribute(cell, 'text', 0)
                combo.set_active(enum)

                combo.connect("changed", self.onComboBoxChanged, property)
                self.table.attach(combo, 1, 2, count, count+1)

            elif gobject.type_is_a(property.value_type, gobject.TYPE_STRING):
                #strings get a gtk.Entry widget
                entry = gtk.Entry()
                text = self.element.get_property(property.name)
                # ignore empty strings
                if text:
                    entry.set_text(text)
                
                entry.connect("changed", self.onEntryChanged, property)
                self.table.attach(entry, 1, 2, count, count+1)

            count += 1