def test_float_inf_nan(self): nan = float('nan') for type_ in [GObject.TYPE_FLOAT, GObject.TYPE_DOUBLE]: for x in [float('inf'), float('-inf'), nan]: value = GObject.Value(type_, x) # assertEqual() is False for (nan, nan) if x is nan: self.assertEqual(str(value.get_value()), 'nan') else: self.assertEqual(value.get_value(), x)
def test_value_int32(self): v = GObject.Value() v.init(GObject.TYPE_INT) v.set_int(2**31 - 1) v.set_int(-2**31) v.set_int(42.50) self.assertEqual(v.get_int(), 42) self.assertRaises(TypeError, v.set_int, "a") self.assertRaises(tests.GIOverflowError, v.set_int, 2**31) self.assertRaises(tests.GIOverflowError, v.set_int, -(2**31 + 1))
def add_user_row(self, userdata): username = userdata.username status = userdata.status country = userdata.country or "" # country can be None, ensure string is used status_icon = get_status_icon(status) or get_status_icon(0) flag_icon = get_flag_icon_name(country) # Request user's IP address, so we can get the country and ignore messages by IP self.frame.np.queue.append(slskmessages.GetPeerAddress(username)) h_speed = "" avgspeed = userdata.avgspeed if avgspeed > 0: h_speed = human_speed(avgspeed) files = userdata.files h_files = humanize(files) weight = Pango.Weight.NORMAL underline = Pango.Underline.NONE if self.room in self.frame.np.chatrooms.private_rooms: if username == self.frame.np.chatrooms.private_rooms[ self.room]["owner"]: weight = Pango.Weight.BOLD underline = Pango.Underline.SINGLE elif username in self.frame.np.chatrooms.private_rooms[ self.room]["operators"]: weight = Pango.Weight.BOLD underline = Pango.Underline.NONE iterator = self.usersmodel.insert_with_valuesv( -1, self.column_numbers, [ status_icon, flag_icon, username, h_speed, h_files, status, GObject.Value(GObject.TYPE_UINT, avgspeed), GObject.Value(GObject.TYPE_UINT, files), country, weight, underline ]) self.users[username] = iterator
def test_value_char(self): v = GObject.Value() v.init(GObject.TYPE_CHAR) v.set_char(97) self.assertEqual(v.get_char(), 97) self.assertRaises(TypeError, v.set_char, u"a") self.assertRaises(TypeError, v.set_char, "ab") self.assertRaises(tests.GIOverflowError, v.set_char, 9999) v.set_char(103.5) self.assertEqual(v.get_char(), 103)
def add_to_list(self, user): if user in self.user_iterators: return empty_int = 0 empty_str = "" self.user_iterators[user] = self.usersmodel.insert_with_valuesv( -1, self.column_numbers, [ GObject.Value(GObject.TYPE_OBJECT, self.frame.get_status_image(0)), GObject.Value(GObject.TYPE_OBJECT, None), user, empty_str, empty_str, False, False, False, _("Never seen"), empty_str, empty_int, empty_int, empty_int, empty_int, empty_str ] ) self.save_user_list() # Request user status, speed and number of shared files self.frame.np.watch_user(user, force_update=True) # Request user's IP address, so we can get the country self.frame.np.queue.append(slskmessages.GetPeerAddress(user)) for widget in self.buddies_combo_entries: widget.append_text(user) if config.sections["words"]["buddies"]: self.frame.update_completions()
def __init__(self, ntree, types): full_types = [] for col_type in (COL_TYPES + tuple(types)): full_types.extend([col_type] * ntree) super().__init__(*full_types) self._none_of_cols = { col_num: GObject.Value(col_type, None) for col_num, col_type in enumerate(full_types) } self.ntree = ntree self._setup_default_styles()
def as_scenario_action(self): st = Gst.Structure.new_empty("set-child-property") st['element-name'] = self.track_element.get_name() st['property'] = self.property_name value = self.new_value if isinstance(self.new_value, (GObject.GEnum, GObject.GFlags)): value = int(self.new_value) _, _, pspec = self.track_element.lookup_child(self.property_name) st['value'] = GObject.Value(pspec.value_type, value) return st
def create_labels_structure(labels: List[str]) -> Gst.Structure: arr = GObject.ValueArray.new(len(labels)) gvalue = GObject.Value() gvalue.init(GObject.TYPE_STRING) for label in labels: gvalue.set_string(label) arr.append(gvalue) labels_struct = Gst.Structure.new_empty("labels_struct") labels_struct.set_array("labels", arr) return labels_struct
def set_labels(self, labels: List[str]): warn("set_labels method is deprecated and will be removed in future") arr = GObject.ValueArray.new(len(labels)) gvalue = GObject.Value() gvalue.init(GObject.TYPE_STRING) for label in labels: gvalue.set_string(label) arr.append(gvalue) self.__structure.set_array("labels", arr) return self
def __set_shadow_type(self): # This is a hack needed to use the shadow type of a statusbar statusbar = Gtk.Statusbar() context = statusbar.get_style_context() # I guess this counts as "documentation"? # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=636620 shadow_type = GObject.Value() shadow_type.init(Gtk.ShadowType) context.get_style_property('shadow-type', shadow_type) self._frame.set_shadow_type(shadow_type.get_enum())
def test_value_float(self): v = GObject.Value() v.init(GObject.TYPE_FLOAT) v.set_float(42.50) self.assertEqual(v.get_float(), 42.50) v.set_float(42) self.assertEqual(v.get_float(), 42) self.assertRaises(TypeError, v.set_float, "a") self.assertRaises(TypeError, v.set_float, []) self.assertRaises(tests.GIOverflowError, v.set_float, 10**39) self.assertRaises(tests.GIOverflowError, v.set_float, -10**39)
def test_value_gtype_convert(self): v = GObject.Value() v.init(GObject.TYPE_GTYPE) v.set_gtype(str) self.assertEqual(v.get_gtype(), GObject.TYPE_STRING) v.set_gtype(int) self.assertEqual(v.get_gtype(), GObject.TYPE_INT) v.set_gtype(float) self.assertEqual(v.get_gtype(), GObject.TYPE_DOUBLE) v.set_gtype(bool) self.assertEqual(v.get_gtype(), GObject.TYPE_BOOLEAN)
def test_value_boolean(self): v = GObject.Value() v.init(GObject.TYPE_BOOLEAN) v.set_boolean(True) self.assertEqual(v.get_boolean(), True) v.set_boolean(False) self.assertEqual(v.get_boolean(), False) v.set_boolean([]) self.assertEqual(v.get_boolean(), False) v.set_boolean([1]) self.assertEqual(v.get_boolean(), True)
def get_user_status(self, msg): status = msg.status if status < 0: # User doesn't exist, nothing to do return user = msg.user iterator = self.user_iterators.get(user) if iterator is None: return if status == int(self.usersmodel.get_value(iterator, 10)): return notify = self.usersmodel.get_value(iterator, 6) if notify: if status == 1: status_text = _("User %s is away") elif status == 2: status_text = _("User %s is online") else: status_text = _("User %s is offline") log.add(status_text, user) self.frame.notifications.new_text_notification(status_text % user) img = self.frame.get_status_image(status) self.usersmodel.set_value(iterator, 0, GObject.Value(GObject.TYPE_OBJECT, img)) self.usersmodel.set_value(iterator, 10, GObject.Value(GObject.TYPE_INT64, status)) if status: # online self.set_last_seen(user, online=True) elif not self.usersmodel.get_value(iterator, 8): # disconnected self.set_last_seen(user)
def set_user_country(self, user, country): iterator = self.user_iterators.get(user) if iterator is None: return self.usersmodel.set_value( iterator, 1, GObject.Value(GObject.TYPE_OBJECT, self.frame.get_flag_image(country))) self.usersmodel.set_value(iterator, 14, "flag_" + country)
def test_value_long(self): v = GObject.Value() v.init(GObject.TYPE_LONG) v.set_long(GObject.G_MAXLONG) v.set_long(GObject.G_MINLONG) v.set_long(42.50) self.assertEqual(v.get_long(), 42) self.assertRaises(TypeError, v.set_long, "a") self.assertRaises(tests.GIOverflowError, v.set_long, GObject.G_MAXLONG + 1) self.assertRaises(tests.GIOverflowError, v.set_long, GObject.G_MINLONG - 1)
def prepare_network_ssid(self, value): if value == "": ssid_str = "<no ssid>" else: ssid_str = value try: ssid = self.value_cache['ssid'][ssid_str] except KeyError: ssid = GObject.Value(GObject.TYPE_STRING, ssid_str) self.value_cache['ssid'][ssid_str] = ssid return ssid
def test_value_invalid_type(): v = GObject.Value() assert v.g_type == GObject.TYPE_INVALID assert isinstance(GObject.TYPE_INVALID, GObject.GType) with pytest.raises(ValueError, match="Invalid GType"): v.init(GObject.TYPE_INVALID) with pytest.raises(TypeError, match="GObject.Value needs to be initialized first"): v.set_value(None) assert v.get_value() is None
def test_value_variant(): v = GObject.Value(GObject.TYPE_VARIANT) assert v.get_value() is None variant = GLib.Variant('i', 42) v.set_value(variant) assert v.get_value() == variant v.set_value(None) assert v.get_value() is None with pytest.raises(TypeError): v.set_value(object())
def get_user_stats(self, msg): iterator = self.recommendation_users.get(msg.user) if iterator is None: return h_speed = "" avgspeed = msg.avgspeed if avgspeed > 0: h_speed = human_speed(avgspeed) files = msg.files h_files = humanize(msg.files) self.recommendation_users_model.set_value(iterator, 2, h_speed) self.recommendation_users_model.set_value(iterator, 3, h_files) self.recommendation_users_model.set_value( iterator, 5, GObject.Value(GObject.TYPE_UINT, avgspeed)) self.recommendation_users_model.set_value( iterator, 6, GObject.Value(GObject.TYPE_UINT, files))
def test_value_gtype(): class TestObject(GObject.GObject): pass v = GObject.Value(GObject.TYPE_GTYPE) assert v.get_value() == GObject.TYPE_INVALID v.set_value(TestObject.__gtype__) assert v.get_value() == TestObject.__gtype__ v.set_value(TestObject) assert v.get_value() == TestObject.__gtype__ with pytest.raises(TypeError): v.set_value(None)
def _set_property_switch(self, property_name: str, switch_name: str, value: bool): try: value = bool(value) log.debug(f'Set property switch {property_name}:{switch_name} to {value} on device {self}') result = self.source.set_tcam_property(f'{property_name} {switch_name}', GObject.Value(type(value), value)) if not result: log.warning(f'Failed to set property switch {property_name}:{switch_name} ' f'to {value} on device {self}.') except Exception as error: log.warning(f'Error setting property switch {property_name}:{switch_name} to {value} on device {self}// {error}') raise
def set_dark_color(self, r, g, b, a): """ Overrides background color, inverts icon colors and darkens some borders """ # Override background self.background = self.dark_color = (r, g, b, a) self.set_bg_color(*self.background) # Recolor existing widgets self.text_color = (1, 1, 1, 1) col = Gdk.RGBA(*self.text_color) for key in self.value_widgets: for w in self.value_widgets[key]: if isinstance(w, Gtk.Image): if (Gtk.get_major_version(), Gtk.get_minor_version()) <= (3, 10): # Mint.... v1 = GObject.Value(int, 0) v2 = GObject.Value(int, 0) self.grid.child_get_property(w, "left-attach", v1) self.grid.child_get_property(w, "top-attach", v2) la, ta = v1.get_int(), v2.get_int() else: la = self.grid.child_get_property(w, "left-attach") ta = self.grid.child_get_property(w, "top-attach") vis = not w.get_no_show_all() wIcon = self._prepare_icon(self.icons[key]) w.get_parent().remove(w) self.grid.attach(wIcon, la, ta, 1, 1) if not vis: wIcon.set_no_show_all(True) wIcon.set_visible(False) wValue, trash, wTitle = self.value_widgets[key] self.value_widgets[key] = (wValue, wIcon, wTitle) else: w.override_color(Gtk.StateFlags.NORMAL, col) # Recolor borders self.recolor() # Recolor header self.set_title(self.str_title)
def _drag_data_get(raw_widget, raw_path, raw_selection_data): ''' Static function that gets inserted as the drag_data_get vfunction, instead of using the vfunction implementation provided by pygobject This function exists so that we can modify the raw selection data explicitly, which allows the high-level DnD API to work. ''' # It turns out that GValue is really useful for converting raw pointers # to/from python objects. We use it + ctypes to xform the values # Grab the python wrapper for the widget instance gv = GObject.Value(cls) g_value_set_object(hash(gv), raw_widget) widget = gv.get_object() # Convert the path to a python object via GValue v1 = GObject.Value(Gtk.TreePath) g_value_set_static_boxed(ctypes.c_void_p(hash(v1)), raw_path) path = v1.get_boxed() # Convert the selection data too v2 = GObject.Value(Gtk.SelectionData) g_value_set_static_boxed(ctypes.c_void_p(hash(v2)), raw_selection_data) selection_data = v2.get_boxed() # Call the original virtual function with the converted arguments retval = widget.do_drag_data_get(path, selection_data) # At this point, selection_data has the information, but it's still just # a copy. Copy the data back to the original selection data data = selection_data.get_data() gtk_selection_data_set( raw_selection_data, gtk_selection_data_get_data_type(hash(selection_data)), selection_data.get_format(), data, len(data)) return retval
def set_right_sidebar_width(self, width): """Sets the width of the right sidebar toolstack """ if self._rstack.is_empty(): return width = max(width, 100) handle_size = GObject.Value() handle_size.init(int) self._rpaned.style_get_property("handle-size", handle_size) position = self._rpaned.get_allocated_width() position -= width position -= handle_size.get_int() self._rpaned.set_position(position)
def test_value_uint64(): v = GObject.Value(GObject.TYPE_UINT64) assert v.get_value() == 0 v.set_value(0) assert v.get_value() == 0 v.set_value(GLib.MAXUINT64) assert v.get_value() == GLib.MAXUINT64 with pytest.raises(OverflowError): v.set_value(GLib.MAXUINT64 + 1) with pytest.raises(OverflowError): v.set_value(-1)
def _widgetScale(self): # First, check if the GDK_SCALE environment variable is already set. If so, # leave it alone. if "GDK_SCALE" in os.environ: log.debug("GDK_SCALE already set to %s, not scaling", os.environ["GDK_SCALE"]) return # Next, check if a scaling factor is already being applied via XSETTINGS, # such as by gnome-settings-daemon display = Gdk.Display.get_default() screen = display.get_default_screen() val = GObject.Value() val.init(GObject.TYPE_INT) if screen.get_setting("gdk-window-scaling-factor", val): log.debug("Window scale set to %s by XSETTINGS, not scaling", val.get_int()) return # Get the primary monitor dimensions in pixels and mm from Gdk primary_monitor = display.get_primary_monitor() # It can be None if no primary monitor is configured by the user. if not primary_monitor: return monitor_geometry = primary_monitor.get_geometry() monitor_scale = primary_monitor.get_scale_factor() monitor_width_mm = primary_monitor.get_width_mm() monitor_height_mm = primary_monitor.get_height_mm() # Sometimes gdk returns 0 for physical widths and heights if monitor_height_mm == 0 or monitor_width_mm == 0: return # Check if this monitor is high DPI, using heuristics from gnome-settings-dpi. # If the monitor has a height >= 1200 pixels and a resolution > 192 dpi in both # x and y directions, apply a scaling factor of 2 so that anaconda isn't all tiny monitor_width_px = monitor_geometry.width * monitor_scale monitor_height_px = monitor_geometry.height * monitor_scale monitor_dpi_x = monitor_width_px / (monitor_width_mm / 25.4) monitor_dpi_y = monitor_height_px / (monitor_height_mm / 25.4) log.debug("Detected primary monitor: %dx%d %ddpix %ddpiy", monitor_width_px, monitor_height_px, monitor_dpi_x, monitor_dpi_y) if monitor_height_px >= 1200 and monitor_dpi_x > 192 and monitor_dpi_y > 192: display.set_window_scale(2) # Export the scale so that Gtk programs launched by anaconda are also scaled util.setenv("GDK_SCALE", "2")
def set_user_flag(self, user, country): if user not in self.users: return if self.usersmodel.get_value(self.users[user], 8) == country: # Country didn't change, no need to update return self.usersmodel.set_value( self.users[user], 1, GObject.Value(GObject.TYPE_OBJECT, self.frame.get_flag_image(country))) self.usersmodel.set_value(self.users[user], 8, country)
def bench_gvalue(n): times = [] b = Gtk.Button() for i in xrange(n): t = time.time() value = GObject.Value() value.init(GObject.TYPE_INT) value.set_int(42) value.get_int() value.unset() value = GObject.Value() value.init(GObject.TYPE_STRING) value.set_string("foobar") value.get_string() value.unset() value = GObject.Value() value.init(GObject.TYPE_OBJECT) value.set_object(b) value.get_object() value.unset() t = time.time() - t times.append(t) return times
def get_user_stats(self, msg): user = msg.user iterator = self.user_iterators.get(user) if iterator is None: return h_speed = "" avgspeed = msg.avgspeed if avgspeed > 0: h_speed = human_speed(avgspeed) files = msg.files h_files = humanize(files) self.usersmodel.set_value(iterator, 3, h_speed) self.usersmodel.set_value(iterator, 4, h_files) self.usersmodel.set_value(iterator, 11, GObject.Value(GObject.TYPE_UINT64, avgspeed)) self.usersmodel.set_value(iterator, 12, GObject.Value(GObject.TYPE_UINT64, files))