def _set_properties_defaults(self): """Set default value as given in __gproperties___.""" [ self._data.update({p.name: p.default_value}) for p in gobject.list_properties(self) ] [ self.set_property(p.name, p.default_value) for p in gobject.list_properties(self) ]
def list_properties(gtype, parent=True): """ Return a list of all properties for GType gtype, excluding properties in parent classes """ pspecs = gobject.list_properties(gtype) if parent: return pspecs parent = gobject.type_parent(gtype) parent_pspecs = gobject.list_properties(parent) return [pspec for pspec in pspecs if pspec not in parent_pspecs]
def _elem2str(self, element): desc = "" factory = element.get_factory() if factory: name = factory.get_name() else: name = element.__class__.__name__ desc += name if desc == "capsfilter": caps = str(element.get_property("caps")) if caps == "ANY": return "capsfilter" return "'%s'" % caps.replace("; ", ";") compProps = self._hiddenCompProps.get(name, set()) hiddenProps = self._hiddenProperties | compProps for p in gobject.list_properties(element): if (p.name in hiddenProps): continue if p.name == "location": desc += " location=$FILE_PATH" continue defVal = p.default_value currVal = element.get_property(p.name) if currVal != defVal: #For enums if hasattr(currVal, "value_name"): currVal = currVal.value_name try: float(currVal) except: currVal = "'%s'" % currVal desc += " %s=%s" % (p.name, currVal) return desc
def recurse(node): global removed_properties for child in node.childNodes: if child.nodeType != child.ELEMENT_NODE: recurse(child) continue class_ = child.getAttribute('class') if class_: type_ = builder.get_type_from_name(class_) object = gobject.new(type_) for property in gobject.list_properties(type_): try: default = object.get_property(property.name) except TypeError, te: default = None for child_node in child.childNodes: if getattr(child_node, 'tagName', None) == 'property' \ and child_node.getAttribute('name') == property.name: if check_default(default, get_text(child_node.childNodes)): removed_properties += 1 child.removeChild(child_node) child_node.unlink() recurse(child)
def __init__(self, options={}): base.Base.__init__(self, options) gst.Bin.__init__(self, self.options['name']) aux = pipestr.replace('gc-videotest-preview', 'sink-' + self.options['name']) # Usable by the Drawing Area bin = gst.parse_bin_from_description(aux, False) # replace identity self.add(bin) self.get_by_name('gc-videotest-sink').set_property('location', path.join(self.options['path'], self.options['file'])) #self.get_by_name('gc-videotest-filter').set_property('caps', gst.Caps(self.options['caps'])) #fr = re.findall("framerate *= *[0-9]+/[0-9]+", self.options['caps']) #if fr: # newcaps = 'video/x-raw-yuv,' + fr[0] #self.get_by_name('gc-videotest-vrate').set_property('caps', gst.Caps(newcaps)) source = self.get_by_name('gc-videotest-src') source.set_property('pattern', int(self.options['pattern'])) coloured = False for properties in gobject.list_properties(source): if properties.name == 'foreground-color': coloured = True if self.options["color1"] and coloured: source.set_property('foreground-color', int(self.options['color1']))
def OnSingleEffectPresetSave(self, widget): """ Grab the effect properties and send it to the presets code to be saved. Parameters: widget -- reserved for GTK callbacks, don't use it explicitly. """ # grab the label from the combo label = self.presetscombo.get_active_text() if label == "": return effectdict = {} effect = self.instrument.effects[self.effectpos] effectelement = effect.get_factory().get_name() proplist = gobject.list_properties(effect) # for each property in proplist, add it to the effectdict dictionary for property in proplist: effectdict[property.name] = effect.get_property(property.name) # save the preset self.presets.SaveSingleEffect(label, effectdict, effectelement, "LADSPA")
def OnEffectChainPresetSave(self, button): """ Grabs the effects chain and sends it to the presets code to be saved. Parameters: button -- reserved for GTK callbacks, don't use it explicitly. """ # grab the label from the combo label = self.comboPresets.get_active_text() if label == "": return self.effectlist = [] for effect in self.instrument.effects: effectdict = {} effectsettings = {} proplist = gobject.list_properties(effect) for property in proplist: effectsettings[property.name] = effect.get_property(property.name) effectdict["effectelement"] = effect.get_factory().get_name() effectdict["effecttype"] = "LADSPA" effectdict["settings"] = effectsettings self.effectlist.append(effectdict) self.presets.SaveEffectChain(label, self.effectlist, self.instrument.instrType)
def testProperties(self): for pspec in gobject.list_properties(Test): self.assertEqual(pspec.name, 'str-prop') self.assertEqual(pspec.nick, 'Nick', pspec.nick) self.assertEqual(pspec.default_value, 'Default', pspec.default_value) self.assertEqual(pspec.blurb, 'Blurb', pspec.blurb)
def getEffectConfigurationUI(self, effect): """ Permit to get a configuration GUI for the effect @param effect: The effect for which whe want the configuration UI @type effect: C{gst.Element} """ if effect not in self.cache_dict: #Here we should handle special effects configuration UI effect_set_ui = GstElementSettingsWidget() effect_set_ui.setElement(effect, ignore=PROPS_TO_IGNORE, default_btn=True, use_element_props=True) nb_rows = effect_set_ui.get_children()[0].get_property('n-rows') effect_configuration_ui = gtk.ScrolledWindow() effect_configuration_ui.add_with_viewport(effect_set_ui) effect_configuration_ui.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self.cache_dict[effect] = effect_configuration_ui self._connectAllWidgetCbs(effect_set_ui, effect) self._postConfiguration(effect, effect_set_ui) effect_set_ui = self._getUiToSetEffect(effect) self._current_effect_setting_ui = effect_set_ui element = self._current_effect_setting_ui.element for prop in gobject.list_properties(element): if prop.flags & gobject.PARAM_READABLE: self._current_element_values[prop.name] = element.get_property(prop.name) return self.cache_dict[effect]
def read_props(self, obj): self.ide.storeProps.clear() try: props = gobject.list_properties( type(obj) ) except: props = [] for prop in props: pname = prop.name ptipo = prop.value_type.name pdefault = str( prop.default_value ) pdesc = prop.blurb if ptipo == 'gint' or ptipo == 'guint': img = get_image_by_name( 'prop_int' ) elif ptipo == 'gboolean': img = get_image_by_name( 'prop_bool' ) elif ptipo == 'gchararray': img = get_image_by_name( 'prop_string' ) elif ptipo == 'gfloat': img = get_image_by_name( 'prop_float' ) elif ptipo == 'GdkColor': img = get_image_by_name( 'prop_color' ) else: img = get_image_by_name( 'prop_default' ) self.ide.storeProps.append( [img, pname, ptipo, pdefault, pdesc] )
def _addWidgets(self, properties): props = [ x for x in gobject.list_properties(self.element) if not x.name in self.ignore ] if not props: self.pack_start(gtk.Label(_("No properties..."))) self.show_all() return table = gtk.Table(rows=len(props), columns=2) table.set_row_spacings(5) table.set_col_spacings(5) table.set_border_width(5) y = 0 for prop in props: label = gtk.Label(prop.nick) label.set_alignment(0.0, 0.5) widget = make_property_widget(self.element, prop, properties.get(prop.name)) table.attach(label, 0, 1, y, y + 1, xoptions=gtk.FILL, yoptions=gtk.FILL) table.attach(widget, 1, 2, y, y + 1, yoptions=gtk.FILL) self.properties[prop] = widget y += 1 self.pack_start(table) self.show_all()
def OnEffectChainPresetSave(self, button): """ Grabs the effects chain and sends it to the presets code to be saved. Parameters: button -- reserved for GTK callbacks, don't use it explicitly. """ # grab the label from the combo label = self.comboPresets.get_active_text() if label == "": return self.effectlist = [] for effect in self.instrument.effects: effectdict = {} effectsettings = {} proplist = gobject.list_properties(effect) for property in proplist: effectsettings[property.name] = effect.get_property( property.name) effectdict["effectelement"] = effect.get_factory().get_name() effectdict["effecttype"] = "LADSPA" effectdict["settings"] = effectsettings self.effectlist.append(effectdict) self.presets.SaveEffectChain(label, self.effectlist, self.instrument.instrType)
def getEffectConfigurationUI(self, effect): """ Permit to get a configuration GUI for the effect @param effect: The effect for which whe want the configuration UI @type effect: C{gst.Element} """ if effect not in self.cache_dict: #Here we should handle special effects configuration UI effect_set_ui = GstElementSettingsWidget() effect_set_ui.setElement(effect, ignore=PROPS_TO_IGNORE, default_btn=True, use_element_props=True) nb_rows = effect_set_ui.get_children()[0].get_property('n-rows') effect_configuration_ui = gtk.ScrolledWindow() effect_configuration_ui.add_with_viewport(effect_set_ui) effect_configuration_ui.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self.cache_dict[effect] = effect_configuration_ui self._connectAllWidgetCbs(effect_set_ui, effect) self._postConfiguration(effect, effect_set_ui) effect_set_ui = self._getUiToSetEffect(effect) self._current_effect_setting_ui = effect_set_ui element = self._current_effect_setting_ui.element for prop in gobject.list_properties(element): if prop.flags & gobject.PARAM_READABLE: self._current_element_values[prop.name] = element.get_property( prop.name) return self.cache_dict[effect]
def __init__(self, options={}): base.Base.__init__(self, options) gst.Bin.__init__(self, self.options['name']) aux = pipestr.replace('gc-videotest-preview', 'sink-' + self.options['name']) # Usable by the Drawing Area bin = gst.parse_bin_from_description(aux, False) # replace identity self.add(bin) self.get_by_name('gc-videotest-sink').set_property( 'location', path.join(self.options['path'], self.options['file'])) #self.get_by_name('gc-videotest-filter').set_property('caps', gst.Caps(self.options['caps'])) #fr = re.findall("framerate *= *[0-9]+/[0-9]+", self.options['caps']) #if fr: # newcaps = 'video/x-raw-yuv,' + fr[0] #self.get_by_name('gc-videotest-vrate').set_property('caps', gst.Caps(newcaps)) source = self.get_by_name('gc-videotest-src') source.set_property('pattern', int(self.options['pattern'])) coloured = False for properties in gobject.list_properties(source): if properties.name == 'foreground-color': coloured = True if self.options["color1"] and coloured: source.set_property('foreground-color', int(self.options['color1']))
def get_default_prop_widget(self, prop_info, prop_storage, data): encoder_prop = gobject.list_properties(gst.element_factory_make(data["plugin"])) for x in encoder_prop: if x.name == prop_info["property"]: # if (gobject.type_is_a(x.default_value, gobject.TYPE_FLOAT)): prop_type = self.get_type(x) if prop_type == "float": hbox = gtk.HBox() hbox.pack_start(gtk.Label(prop_info["title"])) spin = gtk.SpinButton() spin.set_range(x.minimum, x.maximum) spread = x.maximum - x.minimum spin.set_increments(spread / 20, spread / 5) spin.set_digits(2) spin.set_value(x.default_value) spin.connect("value-changed", self.spin_change, prop_storage, x.name) hbox.pack_start(spin) return hbox elif prop_type == "integer": hbox = gtk.HBox() hbox.pack_start(gtk.Label(prop_info["title"])) spin = gtk.SpinButton() spin.set_range(x.minimum, x.maximum) spread = x.maximum - x.minimum spin.set_increments(1, spread // 5 + 1) spin.set_digits(0) spin.set_value(x.default_value) spin.connect("value-changed", self.spin_change, prop_storage, x.name) hbox.pack_start(spin) return hbox return gtk.Button("aaa")
def __init__(self): super(XfConSettings, self).__init__() if (XfConSettings.__instance__): raise RuntimeError("Settings already instantiated") XfConSettings.__instance__ = self if (self.__properties__ == {}): for prop in gobject.list_properties(XfConSettings): self.__properties__[prop.name] = prop.default_value
def addEffectElement(self, gst_element): properties = {} for prop in gobject.list_properties(gst_element): gst_element.connect('notify::' + prop.name, self._propertyChangedCb, gst_element) if prop.flags & gobject.PARAM_READABLE: properties[prop.name] = gst_element.get_property(prop.name) self._tracked_effects[gst_element] = properties
def get_default_handler(klass, name): properties = gobject.list_properties(klass) for property in properties: if property.name == name: property_type = gobject.type_name(property) break return _default_handlers[property_type]
def copy(self, other): """Copy all properties from 'other' into self""" self.name = other.name self.set_title(other.get_property('title')) for pspec in gobject.list_properties(gtk.TreeViewColumn): if pspec.flags & gobject.PARAM_WRITABLE != 0: value = other.get_property(pspec.name) self.set_property(pspec.name, value)
def _write_properties(self, owner_node, owner): doc = self._doc # TODO: we need a smart property fetcher here properties = gobject.list_properties(owner) for prop in self._filter_properties(properties): node = self._property_to_xml(owner, prop, 'normal') owner_node.appendChild(node)
def get_props (obj, inlist): propvals = {} for pspec in gobject.list_properties (obj): if pspec.name in inlist: val = obj.get_property (pspec.name) if val and type (val) == str: val = val.strip () if val: s = pspec.name.replace ('-', ' ').title ().replace (' ', '') propvals[s] = val return propvals
def _addWidgets(self, properties, default_btn, use_element_props): props = [prop for prop in gobject.list_properties(self.element) if not prop.name in self.ignore] if not props: table = gtk.Table(rows=1, columns=1) widget = gtk.Label(_("No properties...")) table.attach(widget, 0, 1, 0, 1, yoptions=gtk.FILL) self.pack_start(table) self.show_all() return if default_btn: table = gtk.Table(rows=len(props), columns=3) else: table = gtk.Table(rows=len(props), columns=2) table.set_row_spacings(SPACING) table.set_col_spacings(SPACING) table.set_border_width(SPACING) y = 0 for prop in props: if not prop.flags & gobject.PARAM_WRITABLE\ or not prop.flags & gobject.PARAM_READABLE: continue if use_element_props: prop_value = self.element.get_property(prop.name) else: prop_value = properties.get(prop.name) widget = make_property_widget(self.element, prop, prop_value) if isinstance(widget, dynamic.ToggleWidget): widget.set_label(prop.nick) table.attach(widget, 0, 2, y, y + 1, yoptions=gtk.FILL) else: label = gtk.Label(prop.nick + ":") label.set_alignment(0.0, 0.5) table.attach(label, 0, 1, y, y + 1, xoptions=gtk.FILL, yoptions=gtk.FILL) table.attach(widget, 1, 2, y, y + 1, yoptions=gtk.FILL) if hasattr(prop, 'description'): # TODO: check that widget.set_tooltip_text(prop.description) self.properties[prop] = widget if default_btn: button = self._getResetToDefaultValueButton(prop, widget) table.attach(button, 2, 3, y, y + 1, xoptions=gtk.FILL, yoptions=gtk.FILL) self.buttons[button] = widget self.element.connect('notify::' + prop.name, self._propertyChangedCb, widget) y += 1 self.pack_start(table) self.show_all()
def display_props(self, source, event): desc = "Item description:\n" elt = self.gstelt import gobject props = gobject.list_properties(elt) for prop in props: name = prop.name if name != "last-buffer": value = elt.get_property(name) desc += "%s=%s\n" %(name, str(value)) self.launch_event("item_description", desc)
def undo(self): element = self.track_object.getElement() props = gobject.list_properties(element) self.effect_props = [(prop.name, element.get_property(prop.name)) for prop in props if prop.flags & gobject.PARAM_WRITABLE and prop.name not in PROPS_TO_IGNORE] gnl_props = gobject.list_properties(self.track_object.gnl_object) gnl_obj = self.track_object.gnl_object self.gnl_obj_props = [(prop.name, gnl_obj.get_property(prop.name)) for prop in gnl_props if prop.flags & gobject.PARAM_WRITABLE] self.timeline_object.removeTrackObject(self.track_object) self.track_object.track.removeTrackObject(self.track_object) self._props_changed =\ self._properties_watcher.getPropChangedFromTrackObj(self.track_object) del self.track_object self.track_object = None self._undone()
def copy(self): other = TrackObject.copy(self) if self.track is not None: element = self.getElement() new_element = other.getElement() for prop in gobject.list_properties(element): value = element.get_property(prop.name) if value != prop.default_value: new_element.set_property(prop.name, value) return other
def element_factory_has_property(element_factory, property_name): """ Check if the given element factory has the given property. @rtype: boolean """ # FIXME: find a better way than instantiating one e = gst.element_factory_make(element_factory) for pspec in gobject.list_properties(e): if pspec.name == property_name: return True return False
def _saveEffectProperties(self, track_object, effect_element): effect_properties = Element("gst-element-properties") effect = track_object.getElement() properties = gobject.list_properties(effect) for prop in properties: if prop.flags & gobject.PARAM_READABLE: type_name = str(gobject.type_name(prop.value_type.fundamental)) #FIXME we just take the int equivalent to the GEnum, how should it be handled? if type_name == "GEnum": value = str(effect.get_property(prop.name).__int__()) else: value = str(effect.get_property(prop.name)) effect_properties.attrib[prop.name] = '(' + type_name + ')' + value effect_element.append(effect_properties)
def _saveEffectProperties(self, track_object, effect_element): effect_properties = Element("gst-element-properties") effect = track_object.getElement() properties = gobject.list_properties(effect) for prop in properties: if prop.flags & gobject.PARAM_READABLE: type_name = str(gobject.type_name(prop.value_type.fundamental)) #FIXME we just take the int equivalent to the GEnum, how should it be handled? if type_name == "GEnum": value = str(effect.get_property(prop.name).__int__()) else: value = str(effect.get_property(prop.name)) effect_properties.attrib[ prop.name] = '(' + type_name + ')' + value effect_element.append(effect_properties)
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
def enterElement(self, branch, previous, element, next): prefix = "| " * (len(branch) - 1) if len(next) > 0: prefix += "|" else: prefix += "\\" properties = "" for p in gobject.list_properties(element): defVal = p.default_value currVal = element.get_property(p.name) if currVal != defVal: #For enums if hasattr(currVal, "value_name"): currVal = currVal.value_name properties += " %s=%s" % (p.name, currVal) self._write(prefix, self._getFactoryName(element), properties) return True
def gobject_set_property(object, property, value): """ Set the given property to the given value on the given object. @type object: L{gobject.GObject} @type property: string @param value: value to set property to """ for pspec in gobject.list_properties(object): if pspec.name == property: break else: raise errors.PropertyError( "Property '%s' in element '%s' does not exist" % ( property, object.get_property('name'))) if pspec.value_type in (gobject.TYPE_INT, gobject.TYPE_UINT, gobject.TYPE_INT64, gobject.TYPE_UINT64): try: value = int(value) except ValueError: msg = "Invalid value given for property '%s' in element '%s'" % ( property, object.get_property('name')) raise errors.PropertyError(msg) elif pspec.value_type == gobject.TYPE_BOOLEAN: if value == 'False': value = False elif value == 'True': value = True else: value = bool(value) elif pspec.value_type in (gobject.TYPE_DOUBLE, gobject.TYPE_FLOAT): value = float(value) elif pspec.value_type == gobject.TYPE_STRING: value = str(value) # FIXME: this is superevil ! we really need to find a better way # of checking if this property is a param enum # also, we only allow int for now elif repr(pspec.__gtype__).startswith("<GType GParamEnum"): value = int(value) else: raise errors.PropertyError('Unknown property type: %s' % pspec.value_type) object.set_property(property, value)
def gobject_set_property(object, property, value): """ Set the given property to the given value on the given object. @type object: L{gobject.GObject} @type property: string @param value: value to set property to """ for pspec in gobject.list_properties(object): if pspec.name == property: break else: raise errors.PropertyError( "Property '%s' in element '%s' does not exist" % (property, object.get_property('name'))) if pspec.value_type in (gobject.TYPE_INT, gobject.TYPE_UINT, gobject.TYPE_INT64, gobject.TYPE_UINT64): try: value = int(value) except ValueError: msg = "Invalid value given for property '%s' in element '%s'" % ( property, object.get_property('name')) raise errors.PropertyError(msg) elif pspec.value_type == gobject.TYPE_BOOLEAN: if value == 'False': value = False elif value == 'True': value = True else: value = bool(value) elif pspec.value_type in (gobject.TYPE_DOUBLE, gobject.TYPE_FLOAT): value = float(value) elif pspec.value_type == gobject.TYPE_STRING: value = str(value) # FIXME: this is superevil ! we really need to find a better way # of checking if this property is a param enum # also, we only allow int for now elif repr(pspec.__gtype__).startswith("<GType GParamEnum"): value = int(value) else: raise errors.PropertyError('Unknown property type: %s' % pspec.value_type) object.set_property(property, value)
def StoreToXML(self, doc, parent, graveyard=False): """ Converts this Instrument into an XML representation suitable for saving to a file. Parameters: doc -- the XML document object the Instrument will be saved to. parent -- the parent node that the serialized Instrument should be added to. graveyard -- True if this Instrument is on the graveyard stack, and should be serialized as a dead Instrument. """ if graveyard: ins = doc.createElement("DeadInstrument") else: ins = doc.createElement("Instrument") parent.appendChild(ins) ins.setAttribute("id", str(self.id)) items = [ "name", "isArmed", "isMuted", "isSolo", "input", "output", "volume", "isSelected", "isVisible", "inTrack", "instrType", "pan" ] params = doc.createElement("Parameters") ins.appendChild(params) Utils.StoreParametersToXML(self, doc, params, items) for effect in self.effects: globaleffect = doc.createElement("GlobalEffect") globaleffect.setAttribute("element", effect.get_factory().get_name()) ins.appendChild(globaleffect) propsdict = {} for prop in gobject.list_properties(effect): if prop.flags & gobject.PARAM_WRITABLE: propsdict[prop.name] = effect.get_property(prop.name) Utils.StoreDictionaryToXML(doc, globaleffect, propsdict) for ev in self.events: ev.StoreToXML(doc, ins) for ev in self.graveyard: ev.StoreToXML(doc, ins, graveyard=True)
def _print_all_properties(self): """Printing of all properties. Useful to creates the table _properties""" import gobject print "Properties ====================================" ct = evolution.ebook.EContact() obt = [] for prop in gobject.list_properties(ct): obt.append(str(prop.value_type).split()[1]) print " '{0}': ('{1}', '{2}'),".format(prop.name, obt[-1], prop.name.title().replace('-', ' ')) obs = list(set(obt)) obs.sort() print print "Object types ==================================" print obs print
def _list_properties(self, type_name): "List all properties for type_name, and use a simple cache" pspecs = self._pspec_cache.get(type_name, []) if pspecs: return pspecs try: if self.child: pspecs = gtk.container_class_list_child_properties(type_name) else: pspecs = gobject.list_properties(type_name) except TypeError: raise PropertyError("Unknown GType name: %s" % type_name) pspecs = list(pspecs) self._pspec_cache[type_name] = pspecs return pspecs
def __init__(self, name, bases, namespace): def _update_bases(bases, props, signals): for base in bases: props.update(getattr(base, '__gproperties__', {})) signals.update(getattr(base, '__gsignals__', {})) _update_bases(base.__bases__, props, signals) for base in bases: if issubclass(base, gobject.GObject): # This will be fun. # Merge in properties and signals from all bases, this # is not the default behavior of PyGTK, but we need it props = namespace.setdefault('__gproperties__', {}) signals = namespace.setdefault('__gsignals__', {}) _update_bases(bases, props, signals) break # Workaround brokenness in PyGObject meta/type registration props = namespace.get('__gproperties__', {}) signals = namespace.get('__gsignals__', {}) if hasattr(self, '__gtype__'): self.__gproperties__ = props self.__gsignals__ = signals gtype = self.__gtype__ # Delete signals and properties which are already # present in the list signal_names = gobject.signal_list_names(gtype) for signal in signals.copy(): if signal in signal_names : del signals[signal] prop_names = [prop.name for prop in gobject.list_properties(gtype)] for prop in props.copy(): if prop in prop_names: del props[prop] if HAVE_2_6 and issubclass(self, gobject.GObject): gobject.type_register(self) _GObjectClassInittableMetaType.__init__(self, name, bases, namespace) # The metaclass forgets to remove properties and signals self.__gproperties__ = {} self.__gsignals__ = {}
def __init__(self, name, bases, namespace): def _update_bases(bases, props, signals): for base in bases: props.update(getattr(base, '__gproperties__', {})) signals.update(getattr(base, '__gsignals__', {})) _update_bases(base.__bases__, props, signals) for base in bases: if issubclass(base, gobject.GObject): # This will be fun. # Merge in properties and signals from all bases, this # is not the default behavior of PyGTK, but we need it props = namespace.setdefault('__gproperties__', {}) signals = namespace.setdefault('__gsignals__', {}) _update_bases(bases, props, signals) break # Workaround brokenness in PyGObject meta/type registration props = namespace.get('__gproperties__', {}) signals = namespace.get('__gsignals__', {}) if hasattr(self, '__gtype__'): self.__gproperties__ = props self.__gsignals__ = signals gtype = self.__gtype__ # Delete signals and properties which are already # present in the list signal_names = gobject.signal_list_names(gtype) for signal in signals.copy(): if signal in signal_names: del signals[signal] prop_names = [prop.name for prop in gobject.list_properties(gtype)] for prop in props.copy(): if prop in prop_names: del props[prop] if HAVE_2_6 and issubclass(self, gobject.GObject): gobject.type_register(self) _GObjectClassInittableMetaType.__init__(self, name, bases, namespace) # The metaclass forgets to remove properties and signals self.__gproperties__ = {} self.__gsignals__ = {}
def StoreToXML(self, doc, parent, graveyard=False): """ Converts this Instrument into an XML representation suitable for saving to a file. Parameters: doc -- the XML document object the Instrument will be saved to. parent -- the parent node that the serialized Instrument should be added to. graveyard -- True if this Instrument is on the graveyard stack, and should be serialized as a dead Instrument. """ if graveyard: ins = doc.createElement("DeadInstrument") else: ins = doc.createElement("Instrument") parent.appendChild(ins) ins.setAttribute("id", str(self.id)) items = ["name", "isArmed", "isMuted", "isSolo", "input", "output", "volume", "isSelected", "isVisible", "inTrack", "instrType", "pan"] params = doc.createElement("Parameters") ins.appendChild(params) Utils.StoreParametersToXML(self, doc, params, items) for effect in self.effects: globaleffect = doc.createElement("GlobalEffect") globaleffect.setAttribute("element", effect.get_factory().get_name()) ins.appendChild(globaleffect) propsdict = {} for prop in gobject.list_properties(effect): if prop.flags & gobject.PARAM_WRITABLE: propsdict[prop.name] = effect.get_property(prop.name) Utils.StoreDictionaryToXML(doc, globaleffect, propsdict) for ev in self.events: ev.StoreToXML(doc, ins) for ev in self.graveyard: ev.StoreToXML(doc, ins, graveyard=True)
def __init__(self): fw.Widget.__init__(self) model = gtk.ListStore(str, str) for i in gobject.list_properties(self._widget): model.append([ i.name, gobject.type_name(i) + ': ' + gobject.type_name(i.value_type) ]) cell = gtk.CellRendererText() cell2 = gtk.CellRendererText() column = gtk.TreeViewColumn('Name') column2 = gtk.TreeViewColumn('Type') column.pack_start(cell, True) column2.pack_start(cell2, True) column.add_attribute(cell, 'text', 0) column2.add_attribute(cell2, 'text', 1) listview = self._widgets['treeView'] listview.set_model(model) listview.append_column(column) listview.append_column(column2)
def get_controllable_properties(element): """ Returns a list of controllable properties for the given element (and child if it's a container). The list is made of tuples containing: * The GstObject * The GParamspec """ log.debug("utils", "element %r, %d", element, isinstance(element, gst.Bin)) res = [] if isinstance(element, gst.Bin): for child in element.elements(): res.extend(get_controllable_properties(child)) else: for prop in gobject.list_properties(element): if prop.flags & gst.PARAM_CONTROLLABLE: log.debug("utils", "adding property %r", prop) res.append((element, prop)) return res
def _addWidgets(self, properties): props = [x for x in gobject.list_properties(self.element) if not x.name in self.ignore] if not props: self.pack_start(gtk.Label("No properties...")) self.show_all() return table = gtk.Table(rows=len(props), columns=2) table.set_row_spacings(5) table.set_col_spacings(5) table.set_border_width(5) y = 0 for prop in props: label = gtk.Label(prop.nick) label.set_alignment(0.0, 0.5) widget = make_property_widget(self.element, prop, properties.get(prop.name)) table.attach(label, 0, 1, y, y+1, xoptions=gtk.FILL, yoptions=gtk.FILL) table.attach(widget, 1, 2, y, y+1, yoptions=gtk.FILL) self.properties[prop] = widget y += 1 self.pack_start(table) self.show_all()
def OnEffectSettings(self, button=None): """ Show a dialog filled with settings sliders for a specific effect Parameters: button -- reserved for GTK callbacks, don't use it explicitly. """ # TODO: Make this modal or as part of the effects window selection = self.listActiveEffects.get_selection().get_selected() # return if there is no active selection if not selection[1]: return # grab references to the effect position in the table and the # effect element itself self.effectpos = self.modelActiveEffects[selection[1]].path[0] self.effectelement = self.instrument.effects[self.effectpos] # this variable is used to slash the values for the different sliders self.sliderdict = {} # Threshold value to determine if a property is buggy self.propertyThreshold = 1000000 # Min/Max value assigned to buggy properties self.fixValue = 15.0 # set the index of the current edited effect - used to reference the # effect elsewhere self.settWin = gtk.glade.XML(Globals.GLADE_PATH, "EffectSettingsDialog") settsignals = { "on_presetsCombo_changed": self.OnSingleEffectPresetChanged, "on_savePresetButton_clicked": self.OnSingleEffectPresetSave, "on_deletePresetButton_clicked": self.OnSingleEffectPresetDelete, "on_closeButton_clicked": self.OnSingleEffectSettingsClose } self.settWin.signal_autoconnect(settsignals) # create references to glade items self.settingswindow = self.settWin.get_widget("EffectSettingsDialog") self.settingsvbox = self.settWin.get_widget("EffectSettingsVBox") self.effectLabel = self.settWin.get_widget("effectLabel") self.effectImage = self.settWin.get_widget("effectImage") self.settingstable = self.settWin.get_widget("settingsTable") self.presetscombo = self.settWin.get_widget("presetsCombo") self.settingsHeaderCairoImage = CairoDialogHeaderImage( _("Effect Settings")) self.settingsHeaderCairoImage.set_size_request(450, 60) self.settingsvbox.pack_start(self.settingsHeaderCairoImage, expand=False, fill=True) self.settingsHeaderCairoImage.show() # set the window icon and parent (for correct modal mode) self.settingswindow.set_icon(self.windowIcon) self.settingswindow.set_transient_for(self.window) # grab a list of properties from the effect proplist = gobject.list_properties( self.instrument.effects[self.effectpos]) # set the effect name and icon self.effectLabel.set_label("<b>%s</b>" % self.modelActiveEffects[selection[1]][2]) self.effectImage.set_from_pixbuf( self.modelActiveEffects[selection[1]][0]) # resize the settingstable to accomodate the number of settings sliders required self.settingstable.resize(len(proplist), 2) count = 0 # iterate through the properties list, determine its value type # and show it where needed for property in proplist: # non readable params if not (property.flags & gobject.PARAM_READABLE): # create and attach a property name label to the settings table label = gtk.Label(property.name) label.set_alignment(1, 0.5) self.settingstable.attach(label, 0, 1, count, count + 1, xoptions=gtk.FILL) rlabel = gtk.Label(_("-parameter not readable-")) self.settingstable.attach(rlabel, 1, 2, count, count + 1) # just display non-writable param values elif not (property.flags & gobject.PARAM_WRITABLE): # create and attach a property name label to the settings table label = gtk.Label(property.name) label.set_alignment(1, 0.5) self.settingstable.attach(label, 0, 1, count, count + 1, xoptions=gtk.FILL) wvalue = self.effectelement.get_property(property.name) if wvalue != None: wlabel = gtk.Label(wvalue) self.settingstable.attach(wlabel, 1, 2, count, count + 1, xoptions=gtk.FILL) elif hasattr(property, "minimum") and hasattr(property, "maximum"): # create and attach a property name label to the settings table label = gtk.Label(property.name) label.set_alignment(1, 0.5) self.settingstable.attach(label, 0, 1, count, count + 1, xoptions=gtk.FILL) # assume that it's numeric so we can use an HScale value = self.effectelement.get_property(property.name) # use these values for the slider range minValue = property.minimum maxValue = property.maximum # fix the ridiculously big min/max range values if needed if property.minimum < -self.propertyThreshold: minValue = -self.fixValue if property.maximum > self.propertyThreshold: maxValue = self.fixValue adj = gtk.Adjustment(value, minValue, maxValue) adj.connect("value_changed", self.SetSingleEffectSetting, property.name, property) self.sliderdict[property.name] = hscale = gtk.HScale(adj) hscale.set_value_pos(gtk.POS_RIGHT) # add step increment for mouse-wheel scrolling - proportional # to range in view. Must be at least the smallest interval # possible (determined by get_digits()) or scroll doesn't happen adj.step_increment = (maxValue - minValue) / 100.0 adj.step_increment = max(adj.step_increment, 1.0 / (10**hscale.get_digits())) # 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) # add the slider to the settings table (with tooltips) self.sliderdict[property.name].set_tooltip_text(property.blurb) self.settingstable.attach(self.sliderdict[property.name], 1, 2, count, count + 1, gtk.FILL | gtk.EXPAND) count += 1 # set up presets self.elementfactory = self.effectelement.get_factory().get_name() self.model = gtk.ListStore(str) self.presetscombo.set_model(self.model) self._LoadEffectPresets() # show the settings window self.settingstable.show() self.settingswindow.show_all()
def _addWidgets(self, properties, default_btn, use_element_props): props = [ prop for prop in gobject.list_properties(self.element) if not prop.name in self.ignore ] if not props: table = gtk.Table(rows=1, columns=1) widget = gtk.Label(_("No properties...")) table.attach(widget, 0, 1, 0, 1, yoptions=gtk.FILL) self.pack_start(table) self.show_all() return if default_btn: table = gtk.Table(rows=len(props), columns=3) else: table = gtk.Table(rows=len(props), columns=2) table.set_row_spacings(5) table.set_col_spacings(5) table.set_border_width(5) y = 0 for prop in props: if not prop.flags & gobject.PARAM_WRITABLE\ or not prop.flags & gobject.PARAM_READABLE: continue label = gtk.Label(prop.nick + ":") label.set_alignment(0.0, 0.5) table.attach(label, 0, 1, y, y + 1, xoptions=gtk.FILL, yoptions=gtk.FILL) if use_element_props: prop_value = self.element.get_property(prop.name) else: prop_value = properties.get(prop.name) widget = make_property_widget(self.element, prop, prop_value) if hasattr(prop, 'description'): #TODO: check that widget.set_tooltip_text(prop.description) table.attach(widget, 1, 2, y, y + 1, yoptions=gtk.FILL) self.properties[prop] = widget if default_btn: button = self._getResetToDefaultValueButton(prop, widget) table.attach(button, 2, 3, y, y + 1, xoptions=gtk.FILL, yoptions=gtk.FILL) self.buttons[button] = widget self.element.connect('notify::' + prop.name, self._propertyChangedCb, widget) y += 1 self.pack_start(table) self.show_all()
def parse_annotate_params(self, element, params, duration=0): # valid params: # text= ; # halign=<left|center|right> # valign=<top|bottom|baseline> # size=X%; (as percent of total image) # color=color; ('black', 'white', 'orange','0x556633') # font=font; # fontstyle=fontstle (space separated list of varient, weight, stretch, or gravity; # vertical=<0|1> (display text vertically) # justification=<0-left|1-right|2-center> props = dict(text = "Fill me in", shaded_background=False, duration=0, # 0 means the duration of the entire slide start=0, # start time to turn on the annotation ) # first initialize props based on config dictionary (global defaults) for key in [ "annotate_size", "annotate_font", "annotate_color", "annotate_halign", "annotate_valign", "annotate_vertical", "annotate_justification", "annotate_fontstyle" ]: props[key.replace("annotate_","")] = self.config[key] params = map(str.strip, params.strip().split(";")) for param in params: if param: key,val = param.split("=",1) props[key] = val if props.has_key("size"): if props["size"].endswith("%"): props["size"] = round(self.config["height"] * eval(props["size"].replace("%","")) / 10.)/10. else: props["size"] = eval(props["size"]) font = "%s %s %gpx" % (props["font"], props["fontstyle"], props["size"],) props["text"] = props["text"].replace("\\n", "\n") def set_prop(element, prop, value): try: element.set_property(prop, value) except TypeError: log.warn("Annotation: Cannot set property %s to %s because gstreamer-plugins-base is too old. Update to enable this feature." % (prop, value)) set_prop(element, "text", props["text"]) set_prop(element, "shaded-background", int(props["shaded_background"])) set_prop(element, "halignment", props["halign"]) set_prop(element, "valignment", props["valign"]) set_prop(element, "color", Element.get_color(props["color"])) try: ctlr = gst.Controller(element, "silent", "xpos", "ypos", "color") except RuntimeError: log.warn("Annotation: Your gstreamer-plugins-base library is too old to support dynamic annotation such as xpos2, ypos2, start, duration. Update your gstreamer library to enable this feature.") ctlr = None if props.has_key("xpos") or props.has_key("ypos"): supported_props = [x.name for x in gobject.list_properties(element)] if "xpos" not in supported_props: log.warn("Annotation: you selected xpos and ypos in your annimation, but your version of gstreamer-plugins-base does not support it.") else: set_prop(element, "xpos", float(props.get("xpos", 0.5))) set_prop(element, "ypos", float(props.get("ypos", 0.5))) set_prop(element, "halignment", "position") set_prop(element, "valignment", "position") def create_pos_controller(cont, prop, start, stop, dur): if not(cont): return cont.set_interpolation_mode(prop, gst.INTERPOLATE_LINEAR) cont.set(prop, 0, start) cont.set(prop, dur, stop) if props.has_key("xpos2"): create_pos_controller(ctlr, "xpos", element.props.xpos, float(props["xpos2"]), duration) if props.has_key("ypos2"): create_pos_controller(ctlr, "ypos", element.props.ypos, float(props["ypos2"]), duration) set_prop(element, "vertical-render", int(props["vertical"])) set_prop(element, "font-desc", font) set_prop(element, "auto-resize", False) set_prop(element, "line-alignment", props["justification"]) if (props["duration"] or props["start"]) and ctlr: dur = int(round(float(props["duration"]) * gst.SECOND)) start = int(round(float(props["start"]) * gst.SECOND)) ctlr.set_interpolation_mode("silent", gst.INTERPOLATE_NONE) if start > 0: ctlr.set("silent", 0, 1) ctlr.set("silent", start, 0) else: ctlr.set("silent", 0, 0) if dur > 0: ctlr.set("silent", start+dur, 1) # save off a reference to the controller so that it does not pop # off the the stack and dissapear. self.controllers.append(ctlr)
def do_set_property(self, pspec, value): print ' do_set_property called for %s=%r' % (pspec.name, value) if pspec.name == 'foo': self.foo = value else: raise AttributeError, 'unknown property %s' % pspec.name def do_get_property(self, pspec): print ' do_get_property called for %s' % pspec.name if pspec.name == 'foo': return self.foo elif pspec.name == 'boolprop': return 1 else: raise AttributeError, 'unknown property %s' % pspec.name gobject.type_register(MyObject) print "MyObject properties: ", gobject.list_properties(MyObject) obj = MyObject() val = obj.get_property('foo') print "obj.get_property('foo') == ", val obj.set_property('foo', 'spam') print "obj.set_property('foo', 'spam')" val = obj.get_property('foo') print "obj.get_property('foo') == ", val val = obj.get_property('boolprop') print "obj.get_property('boolprop') == ", val