587dbb
From 9645cbffa8ba1a08b73fdae50b31125d11aa5684 Mon Sep 17 00:00:00 2001
587dbb
From: Bastien Nocera <hadess@hadess.net>
587dbb
Date: Mon, 9 Aug 2021 23:19:17 +0200
587dbb
Subject: [PATCH 1/4] gio: Add portal version of GPowerProfileMonitor
587dbb
587dbb
---
587dbb
 docs/reference/gio/meson.build   |   1 +
587dbb
 gio/giomodule.c                  |   2 +
587dbb
 gio/gpowerprofilemonitorportal.c | 182 +++++++++++++++++++++++++++++++
587dbb
 gio/gpowerprofilemonitorportal.h |  31 ++++++
587dbb
 gio/meson.build                  |   1 +
587dbb
 5 files changed, 217 insertions(+)
587dbb
 create mode 100644 gio/gpowerprofilemonitorportal.c
587dbb
 create mode 100644 gio/gpowerprofilemonitorportal.h
587dbb
587dbb
diff --git a/docs/reference/gio/meson.build b/docs/reference/gio/meson.build
587dbb
index fbabd25ca..9aaafeed5 100644
587dbb
--- a/docs/reference/gio/meson.build
587dbb
+++ b/docs/reference/gio/meson.build
587dbb
@@ -66,6 +66,7 @@ if get_option('gtk_doc')
587dbb
     'gpollfilemonitor.h',
587dbb
     'gportalsupport.h',
587dbb
     'gpowerprofilemonitordbus.h',
587dbb
+    'gpowerprofilemonitorportal.h',
587dbb
     'gproxyresolverportal.h',
587dbb
     'gregistrysettingsbackend.h',
587dbb
     'gresourcefile.h',
587dbb
diff --git a/gio/giomodule.c b/gio/giomodule.c
587dbb
index dfd895717..d34037a45 100644
587dbb
--- a/gio/giomodule.c
587dbb
+++ b/gio/giomodule.c
587dbb
@@ -50,6 +50,7 @@
587dbb
 #include "gmemorymonitordbus.h"
587dbb
 #include "gpowerprofilemonitor.h"
587dbb
 #include "gpowerprofilemonitordbus.h"
587dbb
+#include "gpowerprofilemonitorportal.h"
587dbb
 #ifdef G_OS_WIN32
587dbb
 #include "gregistrysettingsbackend.h"
587dbb
 #include "giowin32-priv.h"
587dbb
@@ -1305,6 +1306,7 @@ _g_io_modules_ensure_loaded (void)
587dbb
       g_type_ensure (g_memory_monitor_dbus_get_type ());
587dbb
       g_type_ensure (g_memory_monitor_portal_get_type ());
587dbb
       g_type_ensure (g_network_monitor_portal_get_type ());
587dbb
+      g_type_ensure (g_power_profile_monitor_portal_get_type ());
587dbb
       g_type_ensure (g_proxy_resolver_portal_get_type ());
587dbb
 #endif
587dbb
 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
587dbb
diff --git a/gio/gpowerprofilemonitorportal.c b/gio/gpowerprofilemonitorportal.c
587dbb
new file mode 100644
587dbb
index 000000000..bb1b4fd15
587dbb
--- /dev/null
587dbb
+++ b/gio/gpowerprofilemonitorportal.c
587dbb
@@ -0,0 +1,182 @@
587dbb
+/* GIO - GLib Input, Output and Streaming Library
587dbb
+ *
587dbb
+ * Copyright 2021 Red Hat, Inc.
587dbb
+ *
587dbb
+ * This library is free software; you can redistribute it and/or
587dbb
+ * modify it under the terms of the GNU Lesser General Public
587dbb
+ * License as published by the Free Software Foundation; either
587dbb
+ * version 2.1 of the License, or (at your option) any later version.
587dbb
+ *
587dbb
+ * This library is distributed in the hope that it will be useful,
587dbb
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
587dbb
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
587dbb
+ * Lesser General Public License for more details.
587dbb
+ *
587dbb
+ * You should have received a copy of the GNU Lesser General
587dbb
+ * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
587dbb
+ */
587dbb
+
587dbb
+#include "config.h"
587dbb
+
587dbb
+#include "gpowerprofilemonitor.h"
587dbb
+#include "gpowerprofilemonitorportal.h"
587dbb
+#include "gdbuserror.h"
587dbb
+#include "gdbusproxy.h"
587dbb
+#include "ginitable.h"
587dbb
+#include "gioerror.h"
587dbb
+#include "giomodule-priv.h"
587dbb
+#include "gportalsupport.h"
587dbb
+
587dbb
+#define G_POWER_PROFILE_MONITOR_PORTAL_GET_INITABLE_IFACE(o) (G_TYPE_INSTANCE_GET_INTERFACE ((o), G_TYPE_INITABLE, GInitable))
587dbb
+
587dbb
+static void g_power_profile_monitor_portal_iface_init (GPowerProfileMonitorInterface *iface);
587dbb
+static void g_power_profile_monitor_portal_initable_iface_init (GInitableIface *iface);
587dbb
+
587dbb
+typedef enum
587dbb
+{
587dbb
+  PROP_POWER_SAVER_ENABLED = 1,
587dbb
+} GPowerProfileMonitorPortalProperty;
587dbb
+
587dbb
+struct _GPowerProfileMonitorPortal
587dbb
+{
587dbb
+  GObject parent_instance;
587dbb
+
587dbb
+  GDBusProxy *proxy;
587dbb
+  gulong signal_id;
587dbb
+  gboolean power_saver_enabled;
587dbb
+};
587dbb
+
587dbb
+G_DEFINE_TYPE_WITH_CODE (GPowerProfileMonitorPortal, g_power_profile_monitor_portal, G_TYPE_OBJECT,
587dbb
+                         G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
587dbb
+                                                g_power_profile_monitor_portal_initable_iface_init)
587dbb
+                         G_IMPLEMENT_INTERFACE (G_TYPE_POWER_PROFILE_MONITOR,
587dbb
+                                                g_power_profile_monitor_portal_iface_init)
587dbb
+                         _g_io_modules_ensure_extension_points_registered ();
587dbb
+                         g_io_extension_point_implement (G_POWER_PROFILE_MONITOR_EXTENSION_POINT_NAME,
587dbb
+                                                         g_define_type_id,
587dbb
+                                                         "portal",
587dbb
+                                                         40))
587dbb
+
587dbb
+static void
587dbb
+g_power_profile_monitor_portal_init (GPowerProfileMonitorPortal *portal)
587dbb
+{
587dbb
+}
587dbb
+
587dbb
+static void
587dbb
+proxy_properties_changed (GDBusProxy *proxy,
587dbb
+                          GVariant   *changed_properties,
587dbb
+                          GStrv       invalidated_properties,
587dbb
+                          gpointer    user_data)
587dbb
+{
587dbb
+  GPowerProfileMonitorPortal *ppm = user_data;
587dbb
+  gboolean power_saver_enabled;
587dbb
+
587dbb
+  if (!g_variant_lookup (changed_properties, "power-saver-enabled", "b", &power_saver_enabled))
587dbb
+    return;
587dbb
+
587dbb
+  if (power_saver_enabled == ppm->power_saver_enabled)
587dbb
+    return;
587dbb
+
587dbb
+  ppm->power_saver_enabled = power_saver_enabled;
587dbb
+  g_object_notify (G_OBJECT (ppm), "power-saver-enabled");
587dbb
+}
587dbb
+
587dbb
+static void
587dbb
+g_power_profile_monitor_portal_get_property (GObject    *object,
587dbb
+                                             guint       prop_id,
587dbb
+                                             GValue     *value,
587dbb
+                                             GParamSpec *pspec)
587dbb
+{
587dbb
+  GPowerProfileMonitorPortal *ppm = G_POWER_PROFILE_MONITOR_PORTAL (object);
587dbb
+
587dbb
+  switch ((GPowerProfileMonitorPortalProperty) prop_id)
587dbb
+    {
587dbb
+    case PROP_POWER_SAVER_ENABLED:
587dbb
+      g_value_set_boolean (value, ppm->power_saver_enabled);
587dbb
+      break;
587dbb
+
587dbb
+    default:
587dbb
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
587dbb
+    }
587dbb
+}
587dbb
+
587dbb
+static gboolean
587dbb
+g_power_profile_monitor_portal_initable_init (GInitable     *initable,
587dbb
+                                              GCancellable  *cancellable,
587dbb
+                                              GError       **error)
587dbb
+{
587dbb
+  GPowerProfileMonitorPortal *ppm = G_POWER_PROFILE_MONITOR_PORTAL (initable);
587dbb
+  GDBusProxy *proxy;
587dbb
+  gchar *name_owner;
587dbb
+
587dbb
+  if (!glib_should_use_portal ())
587dbb
+    {
587dbb
+      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, "Not using portals");
587dbb
+      return FALSE;
587dbb
+    }
587dbb
+
587dbb
+  proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SESSION,
587dbb
+                                         G_DBUS_PROXY_FLAGS_NONE,
587dbb
+                                         NULL,
587dbb
+                                         "org.freedesktop.portal.Desktop",
587dbb
+                                         "/org/freedesktop/portal/desktop",
587dbb
+                                         "org.freedesktop.portal.PowerProfileMonitor",
587dbb
+                                         cancellable,
587dbb
+                                         error);
587dbb
+  if (!proxy)
587dbb
+    return FALSE;
587dbb
+
587dbb
+  name_owner = g_dbus_proxy_get_name_owner (proxy);
587dbb
+
587dbb
+  if (name_owner == NULL)
587dbb
+    {
587dbb
+      g_object_unref (proxy);
587dbb
+      g_set_error (error,
587dbb
+                   G_DBUS_ERROR,
587dbb
+                   G_DBUS_ERROR_NAME_HAS_NO_OWNER,
587dbb
+                   "Desktop portal not found");
587dbb
+      return FALSE;
587dbb
+    }
587dbb
+
587dbb
+  g_free (name_owner);
587dbb
+
587dbb
+  ppm->signal_id = g_signal_connect (proxy, "g-properties-changed",
587dbb
+                                     G_CALLBACK (proxy_properties_changed), ppm);
587dbb
+
587dbb
+  ppm->proxy = g_steal_pointer (&proxy);
587dbb
+
587dbb
+  return TRUE;
587dbb
+}
587dbb
+
587dbb
+static void
587dbb
+g_power_profile_monitor_portal_finalize (GObject *object)
587dbb
+{
587dbb
+  GPowerProfileMonitorPortal *ppm = G_POWER_PROFILE_MONITOR_PORTAL (object);
587dbb
+
587dbb
+  g_clear_signal_handler (&ppm->signal_id, ppm->proxy);
587dbb
+  g_clear_object (&ppm->proxy);
587dbb
+
587dbb
+  G_OBJECT_CLASS (g_power_profile_monitor_portal_parent_class)->finalize (object);
587dbb
+}
587dbb
+
587dbb
+static void
587dbb
+g_power_profile_monitor_portal_class_init (GPowerProfileMonitorPortalClass *nl_class)
587dbb
+{
587dbb
+  GObjectClass *gobject_class = G_OBJECT_CLASS (nl_class);
587dbb
+
587dbb
+  gobject_class->get_property = g_power_profile_monitor_portal_get_property;
587dbb
+  gobject_class->finalize  = g_power_profile_monitor_portal_finalize;
587dbb
+
587dbb
+  g_object_class_override_property (gobject_class, PROP_POWER_SAVER_ENABLED, "power-saver-enabled");
587dbb
+}
587dbb
+
587dbb
+static void
587dbb
+g_power_profile_monitor_portal_iface_init (GPowerProfileMonitorInterface *monitor_iface)
587dbb
+{
587dbb
+}
587dbb
+
587dbb
+static void
587dbb
+g_power_profile_monitor_portal_initable_iface_init (GInitableIface *iface)
587dbb
+{
587dbb
+  iface->init = g_power_profile_monitor_portal_initable_init;
587dbb
+}
587dbb
diff --git a/gio/gpowerprofilemonitorportal.h b/gio/gpowerprofilemonitorportal.h
587dbb
new file mode 100644
587dbb
index 000000000..b91a14610
587dbb
--- /dev/null
587dbb
+++ b/gio/gpowerprofilemonitorportal.h
587dbb
@@ -0,0 +1,31 @@
587dbb
+/* GIO - GLib Input, Output and Streaming Library
587dbb
+ *
587dbb
+ * Copyright 2021 Red Hat, Inc.
587dbb
+ *
587dbb
+ * This library is free software; you can redistribute it and/or
587dbb
+ * modify it under the terms of the GNU Lesser General Public
587dbb
+ * License as published by the Free Software Foundation; either
587dbb
+ * version 2.1 of the License, or (at your option) any later version.
587dbb
+ *
587dbb
+ * This library is distributed in the hope that it will be useful,
587dbb
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
587dbb
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
587dbb
+ * Lesser General Public License for more details.
587dbb
+ *
587dbb
+ * You should have received a copy of the GNU Lesser General
587dbb
+ * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
587dbb
+ */
587dbb
+
587dbb
+#ifndef __G_POWER_PROFILE_MONITOR_PORTAL_H__
587dbb
+#define __G_POWER_PROFILE_MONITOR_PORTAL_H__
587dbb
+
587dbb
+#include <glib-object.h>
587dbb
+
587dbb
+G_BEGIN_DECLS
587dbb
+
587dbb
+#define G_TYPE_POWER_PROFILE_MONITOR_PORTAL         (g_power_profile_monitor_portal_get_type ())
587dbb
+G_DECLARE_FINAL_TYPE (GPowerProfileMonitorPortal, g_power_profile_monitor_portal, G, POWER_PROFILE_MONITOR_PORTAL, GObject)
587dbb
+
587dbb
+G_END_DECLS
587dbb
+
587dbb
+#endif /* __G_POWER_PROFILE_MONITOR_PORTAL_H__ */
587dbb
diff --git a/gio/meson.build b/gio/meson.build
587dbb
index d5838ed8a..ac3373f2b 100644
587dbb
--- a/gio/meson.build
587dbb
+++ b/gio/meson.build
587dbb
@@ -383,6 +383,7 @@ if host_system != 'windows'
587dbb
     'gopenuriportal.c',
587dbb
     'gmemorymonitorportal.c',
587dbb
     'gnetworkmonitorportal.c',
587dbb
+    'gpowerprofilemonitorportal.c',
587dbb
     'gproxyresolverportal.c',
587dbb
     'gtrashportal.c',
587dbb
     'gportalsupport.c',
587dbb
-- 
587dbb
GitLab
587dbb
587dbb
587dbb
From 18eb29897d80bf662d58bd11a89617ddd7ebfeed Mon Sep 17 00:00:00 2001
587dbb
From: Bastien Nocera <hadess@hadess.net>
587dbb
Date: Tue, 10 Aug 2021 10:58:53 +0200
587dbb
Subject: [PATCH 2/4] gio: Add GPowerProfileMonitor tests
587dbb
587dbb
Tests both the portal and direct D-Bus variants.
587dbb
---
587dbb
 gio/tests/meson.build                        |  14 ++-
587dbb
 gio/tests/power-profile-monitor-dbus.py.in   | 107 ++++++++++++++++
587dbb
 gio/tests/power-profile-monitor-portal.py.in | 126 +++++++++++++++++++
587dbb
 3 files changed, 241 insertions(+), 6 deletions(-)
587dbb
 create mode 100755 gio/tests/power-profile-monitor-dbus.py.in
587dbb
 create mode 100755 gio/tests/power-profile-monitor-portal.py.in
587dbb
587dbb
diff --git a/gio/tests/meson.build b/gio/tests/meson.build
587dbb
index fc2055101..5dbfb8e60 100644
587dbb
--- a/gio/tests/meson.build
587dbb
+++ b/gio/tests/meson.build
587dbb
@@ -541,27 +541,29 @@ if installed_tests_enabled
587dbb
   install_subdir('static-link', install_dir : installed_tests_execdir)
587dbb
   install_data('static-link.py', install_dir : installed_tests_execdir)
587dbb
 
587dbb
-  memory_monitor_tests = [
587dbb
+  monitor_tests = [
587dbb
     'memory-monitor-dbus',
587dbb
     'memory-monitor-portal',
587dbb
+    'power-profile-monitor-dbus',
587dbb
+    'power-profile-monitor-portal'
587dbb
   ]
587dbb
 
587dbb
-  foreach memory_monitor_test : memory_monitor_tests
587dbb
+  foreach monitor_test : monitor_tests
587dbb
     cdata = configuration_data()
587dbb
     cdata.set('installed_tests_dir', installed_tests_execdir)
587dbb
-    cdata.set('program', memory_monitor_test + '.py')
587dbb
+    cdata.set('program', monitor_test + '.py')
587dbb
     cdata.set('env', '')
587dbb
     configure_file(
587dbb
       input: installed_tests_template_tap,
587dbb
-      output: memory_monitor_test + '.test',
587dbb
+      output: monitor_test + '.test',
587dbb
       install_dir: installed_tests_metadir,
587dbb
       configuration: cdata
587dbb
     )
587dbb
     cdata = configuration_data()
587dbb
     cdata.set('libexecdir', join_paths(glib_prefix, get_option('libexecdir')))
587dbb
     configure_file(
587dbb
-      input: memory_monitor_test + '.py.in',
587dbb
-      output: memory_monitor_test + '.py',
587dbb
+      input: monitor_test + '.py.in',
587dbb
+      output: monitor_test + '.py',
587dbb
       install_dir : installed_tests_execdir,
587dbb
       configuration: cdata,
587dbb
     )
587dbb
diff --git a/gio/tests/power-profile-monitor-dbus.py.in b/gio/tests/power-profile-monitor-dbus.py.in
587dbb
new file mode 100755
587dbb
index 000000000..06e594f4a
587dbb
--- /dev/null
587dbb
+++ b/gio/tests/power-profile-monitor-dbus.py.in
587dbb
@@ -0,0 +1,107 @@
587dbb
+#!/usr/bin/python3
587dbb
+
587dbb
+# This program is free software; you can redistribute it and/or modify it under
587dbb
+# the terms of the GNU Lesser General Public License as published by the Free
587dbb
+# Software Foundation; either version 3 of the License, or (at your option) any
587dbb
+# later version.  See http://www.gnu.org/copyleft/lgpl.html for the full text
587dbb
+# of the license.
587dbb
+
587dbb
+__author__ = 'Bastien Nocera'
587dbb
+__email__ = 'hadess@hadess.net'
587dbb
+__copyright__ = '(c) 2019, 2021 Red Hat Inc.'
587dbb
+__license__ = 'LGPL 3+'
587dbb
+
587dbb
+import unittest
587dbb
+import sys
587dbb
+import subprocess
587dbb
+import fcntl
587dbb
+import os
587dbb
+import time
587dbb
+
587dbb
+import taptestrunner
587dbb
+
587dbb
+try:
587dbb
+    # Do all non-standard imports here so we can skip the tests if any
587dbb
+    # needed packages are not available.
587dbb
+    import dbus
587dbb
+    import dbus.mainloop.glib
587dbb
+    import dbusmock
587dbb
+    from gi.repository import GLib
587dbb
+    from gi.repository import Gio
587dbb
+
587dbb
+    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
587dbb
+
587dbb
+    class TestPowerProfileMonitor(dbusmock.DBusTestCase):
587dbb
+        '''Test GPowerProfileMonitorDBus'''
587dbb
+
587dbb
+        @classmethod
587dbb
+        def setUpClass(klass):
587dbb
+            klass.start_system_bus()
587dbb
+            klass.dbus_con = klass.get_dbus(True)
587dbb
+
587dbb
+        def setUp(self):
587dbb
+            try:
587dbb
+                Gio.PowerProfileMonitor
587dbb
+            except AttributeError:
587dbb
+                raise unittest.SkipTest('Power Profile Monitor not in '
587dbb
+                                        'introspection data. Requires '
587dbb
+                                        'GObject-Introspection ≥ 1.63.2') # FIXME version
587dbb
+            try:
587dbb
+                (self.p_mock, self.obj_ppd) = self.spawn_server_template(
587dbb
+                    'power_profiles_daemon', {}, stdout=subprocess.PIPE)
587dbb
+            except ModuleNotFoundError:
587dbb
+                raise unittest.SkipTest("power-profiles-daemon dbusmock template not "
587dbb
+                                        "found. Requires dbusmock > 0.23.1.") # FIXME version
587dbb
+            # set log to nonblocking
587dbb
+            flags = fcntl.fcntl(self.p_mock.stdout, fcntl.F_GETFL)
587dbb
+            fcntl.fcntl(self.p_mock.stdout, fcntl.F_SETFL, flags | os.O_NONBLOCK)
587dbb
+            self.power_saver_enabled = False
587dbb
+            self.dbus_props = dbus.Interface(self.obj_ppd, dbus.PROPERTIES_IFACE)
587dbb
+            self.power_profile_monitor = Gio.PowerProfileMonitor.dup_default()
587dbb
+            self.power_profile_monitor.connect("notify::power-saver-enabled", self.power_saver_enabled_cb)
587dbb
+            self.mainloop = GLib.MainLoop()
587dbb
+            self.main_context = self.mainloop.get_context()
587dbb
+
587dbb
+        def tearDown(self):
587dbb
+            self.p_mock.terminate()
587dbb
+            self.p_mock.wait()
587dbb
+
587dbb
+        def assertEventually(self, condition, message=None, timeout=50):
587dbb
+            '''Assert that condition function eventually returns True.
587dbb
+
587dbb
+            Timeout is in deciseconds, defaulting to 50 (5 seconds). message is
587dbb
+            printed on failure.
587dbb
+            '''
587dbb
+            while timeout >= 0:
587dbb
+                context = GLib.MainContext.default()
587dbb
+                while context.iteration(False):
587dbb
+                    pass
587dbb
+                if condition():
587dbb
+                    break
587dbb
+                timeout -= 1
587dbb
+                time.sleep(0.1)
587dbb
+            else:
587dbb
+                self.fail(message or 'timed out waiting for ' + str(condition))
587dbb
+
587dbb
+        def power_saver_enabled_cb(self, spec, data):
587dbb
+            self.power_saver_enabled = self.power_profile_monitor.get_power_saver_enabled()
587dbb
+            self.main_context.wakeup()
587dbb
+
587dbb
+        def test_power_profile_power_saver_enabled(self):
587dbb
+            '''power-saver-enabled property'''
587dbb
+
587dbb
+            self.assertEqual(self.power_profile_monitor.get_power_saver_enabled(), False)
587dbb
+            self.dbus_props.Set('net.hadess.PowerProfiles', 'ActiveProfile', dbus.String('power-saver', variant_level=1))
587dbb
+            self.assertEventually(lambda: self.power_saver_enabled == True, "power-saver didn't become enabled", 10)
587dbb
+
587dbb
+            self.dbus_props.Set('net.hadess.PowerProfiles', 'ActiveProfile', dbus.String('balanced', variant_level=1))
587dbb
+            self.assertEventually(lambda: self.power_saver_enabled == False, "power-saver didn't become disabled", 10)
587dbb
+
587dbb
+except ImportError as e:
587dbb
+    @unittest.skip("Cannot import %s" % e.name)
587dbb
+    class TestPowerProfileMonitor(unittest.TestCase):
587dbb
+        def test_power_profile_power_saver_enabled(self):
587dbb
+            pass
587dbb
+
587dbb
+if __name__ == '__main__':
587dbb
+    unittest.main(testRunner=taptestrunner.TAPTestRunner())
587dbb
diff --git a/gio/tests/power-profile-monitor-portal.py.in b/gio/tests/power-profile-monitor-portal.py.in
587dbb
new file mode 100755
587dbb
index 000000000..960a62232
587dbb
--- /dev/null
587dbb
+++ b/gio/tests/power-profile-monitor-portal.py.in
587dbb
@@ -0,0 +1,126 @@
587dbb
+#!/usr/bin/python3
587dbb
+
587dbb
+# This program is free software; you can redistribute it and/or modify it under
587dbb
+# the terms of the GNU Lesser General Public License as published by the Free
587dbb
+# Software Foundation; either version 3 of the License, or (at your option) any
587dbb
+# later version.  See http://www.gnu.org/copyleft/lgpl.html for the full text
587dbb
+# of the license.
587dbb
+
587dbb
+__author__ = 'Bastien Nocera'
587dbb
+__email__ = 'hadess@hadess.net'
587dbb
+__copyright__ = '(c) 2021 Red Hat Inc.'
587dbb
+__license__ = 'LGPL 3+'
587dbb
+
587dbb
+import unittest
587dbb
+import sys
587dbb
+import subprocess
587dbb
+import fcntl
587dbb
+import os
587dbb
+import time
587dbb
+
587dbb
+import taptestrunner
587dbb
+
587dbb
+try:
587dbb
+    # Do all non-standard imports here so we can skip the tests if any
587dbb
+    # needed packages are not available.
587dbb
+    import dbus
587dbb
+    import dbus.mainloop.glib
587dbb
+    import dbusmock
587dbb
+    from gi.repository import GLib
587dbb
+    from gi.repository import Gio
587dbb
+
587dbb
+    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
587dbb
+
587dbb
+    # XDG_DESKTOP_PORTAL_PATH = os.path.expanduser("~/.cache/jhbuild/build/xdg-desktop-portal/xdg-desktop-portal")
587dbb
+    XDG_DESKTOP_PORTAL_PATH = "@libexecdir@/xdg-desktop-portal"
587dbb
+
587dbb
+    class TestPowerProfileMonitorPortal(dbusmock.DBusTestCase):
587dbb
+        '''Test GPowerProfileMonitorPortal'''
587dbb
+
587dbb
+        @classmethod
587dbb
+        def setUpClass(klass):
587dbb
+            klass.start_system_bus()
587dbb
+            klass.dbus_con = klass.get_dbus(True)
587dbb
+            # Start session bus so that xdg-desktop-portal can run on it
587dbb
+            klass.start_session_bus()
587dbb
+
587dbb
+        def setUp(self):
587dbb
+            try:
587dbb
+                Gio.PowerProfileMonitor
587dbb
+            except AttributeError:
587dbb
+                raise unittest.SkipTest('Power Profile Monitor not in '
587dbb
+                                        'introspection data. Requires '
587dbb
+                                        'GObject-Introspection > 1.69.0')
587dbb
+            try:
587dbb
+                (self.p_mock, self.obj_ppd) = self.spawn_server_template(
587dbb
+                    'power_profiles_daemon', {}, stdout=subprocess.PIPE)
587dbb
+            except ModuleNotFoundError:
587dbb
+                raise unittest.SkipTest("power-profiles-daemon dbusmock template not "
587dbb
+                                        "found. Requires dbusmock > 0.23.1.")
587dbb
+            # set log to nonblocking
587dbb
+            flags = fcntl.fcntl(self.p_mock.stdout, fcntl.F_GETFL)
587dbb
+            fcntl.fcntl(self.p_mock.stdout, fcntl.F_SETFL, flags | os.O_NONBLOCK)
587dbb
+            self.power_saver_enabled = False
587dbb
+            self.dbus_props = dbus.Interface(self.obj_ppd, dbus.PROPERTIES_IFACE)
587dbb
+            try:
587dbb
+                self.xdp = subprocess.Popen([XDG_DESKTOP_PORTAL_PATH])
587dbb
+            except FileNotFoundError:
587dbb
+                raise unittest.SkipTest("xdg-desktop-portal not available")
587dbb
+
587dbb
+            try:
587dbb
+                self.wait_for_bus_object('org.freedesktop.portal.Desktop',
587dbb
+                                        '/org/freedesktop/portal/desktop')
587dbb
+            except:
587dbb
+                raise
587dbb
+            # subprocess.Popen(['gdbus', 'monitor', '--session', '--dest', 'org.freedesktop.portal.Desktop'])
587dbb
+
587dbb
+            os.environ['GTK_USE_PORTAL'] = "1"
587dbb
+            self.power_profile_monitor = Gio.PowerProfileMonitor.dup_default()
587dbb
+            assert("GPowerProfileMonitorPortal" in str(self.power_profile_monitor))
587dbb
+            self.power_profile_monitor.connect("notify::power-saver-enabled", self.power_saver_enabled_cb)
587dbb
+            self.mainloop = GLib.MainLoop()
587dbb
+            self.main_context = self.mainloop.get_context()
587dbb
+
587dbb
+        def tearDown(self):
587dbb
+            self.p_mock.terminate()
587dbb
+            self.p_mock.wait()
587dbb
+
587dbb
+        def assertEventually(self, condition, message=None, timeout=50):
587dbb
+            '''Assert that condition function eventually returns True.
587dbb
+
587dbb
+            Timeout is in deciseconds, defaulting to 50 (5 seconds). message is
587dbb
+            printed on failure.
587dbb
+            '''
587dbb
+            while timeout >= 0:
587dbb
+                context = GLib.MainContext.default()
587dbb
+                while context.iteration(False):
587dbb
+                    pass
587dbb
+                if condition():
587dbb
+                    break
587dbb
+                timeout -= 1
587dbb
+                time.sleep(0.1)
587dbb
+            else:
587dbb
+                self.fail(message or 'timed out waiting for ' + str(condition))
587dbb
+
587dbb
+        def power_saver_enabled_cb(self, spec, data):
587dbb
+            self.power_saver_enabled = self.power_profile_monitor.get_power_saver_enabled()
587dbb
+            self.main_context.wakeup()
587dbb
+
587dbb
+        def test_power_profile_power_saver_enabled_portal(self):
587dbb
+            '''power-saver-enabled property'''
587dbb
+
587dbb
+            self.assertEqual(self.power_profile_monitor.get_power_saver_enabled(), False)
587dbb
+            self.dbus_props.Set('net.hadess.PowerProfiles', 'ActiveProfile', dbus.String('power-saver', variant_level=1))
587dbb
+            self.assertEventually(lambda: self.power_saver_enabled == True, "power-saver didn't become enabled", 10)
587dbb
+
587dbb
+            self.dbus_props.Set('net.hadess.PowerProfiles', 'ActiveProfile', dbus.String('balanced', variant_level=1))
587dbb
+            self.assertEventually(lambda: self.power_saver_enabled == False, "power-saver didn't become disabled", 10)
587dbb
+
587dbb
+except ImportError as e:
587dbb
+    @unittest.skip("Cannot import %s" % e.name)
587dbb
+    class TestPowerProfileMonitorPortal(unittest.TestCase):
587dbb
+        def test_power_profile_power_saver_enabled_portal(self):
587dbb
+            pass
587dbb
+
587dbb
+if __name__ == '__main__':
587dbb
+    unittest.main(testRunner=taptestrunner.TAPTestRunner())
587dbb
-- 
587dbb
GitLab
587dbb
587dbb
587dbb
From 66acea8418eb3d8e46bb6f93dc0c3f13a1f7822b Mon Sep 17 00:00:00 2001
587dbb
From: Bastien Nocera <hadess@hadess.net>
587dbb
Date: Wed, 11 Aug 2021 15:37:40 +0200
587dbb
Subject: [PATCH 3/4] gio: Remove left-over debug statement from memory monitor
587dbb
 portal test
587dbb
587dbb
---
587dbb
 gio/tests/memory-monitor-portal.py.in | 1 -
587dbb
 1 file changed, 1 deletion(-)
587dbb
587dbb
diff --git a/gio/tests/memory-monitor-portal.py.in b/gio/tests/memory-monitor-portal.py.in
587dbb
index cb4a960eb..f5fd2283f 100755
587dbb
--- a/gio/tests/memory-monitor-portal.py.in
587dbb
+++ b/gio/tests/memory-monitor-portal.py.in
587dbb
@@ -31,7 +31,6 @@ try:
587dbb
 
587dbb
     dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
587dbb
 
587dbb
-    # XDG_DESKTOP_PORTAL_PATH = os.path.expanduser("~/.cache/jhbuild/build/xdg-desktop-portal/xdg-desktop-portal")
587dbb
     XDG_DESKTOP_PORTAL_PATH = "@libexecdir@/xdg-desktop-portal"
587dbb
 
587dbb
     class TestLowMemoryMonitorPortal(dbusmock.DBusTestCase):
587dbb
-- 
587dbb
GitLab
587dbb
587dbb
587dbb
From 2e9842cafc73a7fb94cfde7937e125e1a91f35f8 Mon Sep 17 00:00:00 2001
587dbb
From: Bastien Nocera <hadess@hadess.net>
587dbb
Date: Wed, 11 Aug 2021 15:38:12 +0200
587dbb
Subject: [PATCH 4/4] gio: Simplify memory monitor tests by using
587dbb
 assertEventually() helper
587dbb
587dbb
assertEventually is a helper used in a number of projects that use
587dbb
dbusmock.
587dbb
587dbb
See https://github.com/martinpitt/python-dbusmock/issues/82
587dbb
---
587dbb
 gio/tests/memory-monitor-dbus.py.in   | 31 ++++++++++++++++-----------
587dbb
 gio/tests/memory-monitor-portal.py.in | 31 ++++++++++++++++-----------
587dbb
 2 files changed, 38 insertions(+), 24 deletions(-)
587dbb
587dbb
diff --git a/gio/tests/memory-monitor-dbus.py.in b/gio/tests/memory-monitor-dbus.py.in
587dbb
index 7823e7309..e8ac28faf 100755
587dbb
--- a/gio/tests/memory-monitor-dbus.py.in
587dbb
+++ b/gio/tests/memory-monitor-dbus.py.in
587dbb
@@ -66,6 +66,23 @@ try:
587dbb
             self.p_mock.terminate()
587dbb
             self.p_mock.wait()
587dbb
 
587dbb
+        def assertEventually(self, condition, message=None, timeout=50):
587dbb
+            '''Assert that condition function eventually returns True.
587dbb
+
587dbb
+            Timeout is in deciseconds, defaulting to 50 (5 seconds). message is
587dbb
+            printed on failure.
587dbb
+            '''
587dbb
+            while timeout >= 0:
587dbb
+                context = GLib.MainContext.default()
587dbb
+                while context.iteration(False):
587dbb
+                    pass
587dbb
+                if condition():
587dbb
+                    break
587dbb
+                timeout -= 1
587dbb
+                time.sleep(0.1)
587dbb
+            else:
587dbb
+                self.fail(message or 'timed out waiting for ' + str(condition))
587dbb
+
587dbb
         def memory_warning_cb(self, monitor, level):
587dbb
             self.last_warning = level
587dbb
             self.main_context.wakeup()
587dbb
@@ -82,21 +99,11 @@ try:
587dbb
 
587dbb
             self.dbusmock.EmitWarning(100)
587dbb
             # Wait 2 seconds or until warning
587dbb
-            timeout = 2
587dbb
-            while timeout > 0 and self.last_warning != 100:
587dbb
-                time.sleep(0.5)
587dbb
-                timeout -= 0.5
587dbb
-                self.main_context.iteration(False)
587dbb
-            self.assertEqual(self.last_warning, 100)
587dbb
+            self.assertEventually(self.last_warning == 100, "'100' low-memory warning not received", 20)
587dbb
 
587dbb
             self.dbusmock.EmitWarning(255)
587dbb
             # Wait 2 seconds or until warning
587dbb
-            timeout = 2
587dbb
-            while timeout > 0 and self.last_warning != 255:
587dbb
-                time.sleep(0.5)
587dbb
-                timeout -= 0.5
587dbb
-                self.main_context.iteration(False)
587dbb
-            self.assertEqual(self.last_warning, 255)
587dbb
+            self.assertEventually(self.last_warning == 255, "'255' low-memory warning not received", 20)
587dbb
 
587dbb
 except ImportError as e:
587dbb
     @unittest.skip("Cannot import %s" % e.name)
587dbb
diff --git a/gio/tests/memory-monitor-portal.py.in b/gio/tests/memory-monitor-portal.py.in
587dbb
index f5fd2283f..36d5094d3 100755
587dbb
--- a/gio/tests/memory-monitor-portal.py.in
587dbb
+++ b/gio/tests/memory-monitor-portal.py.in
587dbb
@@ -84,6 +84,23 @@ try:
587dbb
             self.p_mock.terminate()
587dbb
             self.p_mock.wait()
587dbb
 
587dbb
+        def assertEventually(self, condition, message=None, timeout=50):
587dbb
+            '''Assert that condition function eventually returns True.
587dbb
+
587dbb
+            Timeout is in deciseconds, defaulting to 50 (5 seconds). message is
587dbb
+            printed on failure.
587dbb
+            '''
587dbb
+            while timeout >= 0:
587dbb
+                context = GLib.MainContext.default()
587dbb
+                while context.iteration(False):
587dbb
+                    pass
587dbb
+                if condition():
587dbb
+                    break
587dbb
+                timeout -= 1
587dbb
+                time.sleep(0.1)
587dbb
+            else:
587dbb
+                self.fail(message or 'timed out waiting for ' + str(condition))
587dbb
+
587dbb
         def portal_memory_warning_cb(self, monitor, level):
587dbb
             self.last_warning = level
587dbb
             self.main_context.wakeup()
587dbb
@@ -100,21 +117,11 @@ try:
587dbb
 
587dbb
             self.dbusmock.EmitWarning(100)
587dbb
             # Wait 2 seconds or until warning
587dbb
-            timeout = 2
587dbb
-            while timeout > 0 and self.last_warning != 100:
587dbb
-                time.sleep(0.5)
587dbb
-                timeout -= 0.5
587dbb
-                self.main_context.iteration(False)
587dbb
-            self.assertEqual(self.last_warning, 100)
587dbb
+            self.assertEventually(self.last_warning == 100, "'100' low-memory warning not received", 20)
587dbb
 
587dbb
             self.dbusmock.EmitWarning(255)
587dbb
             # Wait 2 seconds or until warning
587dbb
-            timeout = 2
587dbb
-            while timeout > 0 and self.last_warning != 255:
587dbb
-                time.sleep(0.5)
587dbb
-                timeout -= 0.5
587dbb
-                self.main_context.iteration(False)
587dbb
-            self.assertEqual(self.last_warning, 255)
587dbb
+            self.assertEventually(self.last_warning == 255, "'255' low-memory warning not received", 20)
587dbb
 
587dbb
 except ImportError as e:
587dbb
     @unittest.skip("Cannot import %s" % e.name)
587dbb
-- 
587dbb
GitLab
587dbb