summaryrefslogtreecommitdiff
path: root/src/dkp-daemon.c
blob: b4452e266fa5c85ba78b8c497f3d11b17c7f41fc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*-
 *
 * Copyright (C) 2008 David Zeuthen <davidz@redhat.com>
 * Copyright (C) 2008 Richard Hughes <richard@hughsie.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#ifdef HAVE_CONFIG_H
#  include "config.h"
#endif

#include <string.h>
#include <stdlib.h>

#include <glib.h>
#include <glib/gi18n-lib.h>
#include <glib-object.h>
#include <dbus/dbus-glib.h>
#include <dbus/dbus-glib-lowlevel.h>

#include "egg-debug.h"

#include "dkp-polkit.h"
#include "dkp-device-list.h"
#include "dkp-device.h"
#include "dkp-backend.h"
#include "dkp-daemon.h"

#include "dkp-daemon-glue.h"
#include "dkp-marshal.h"

enum
{
	PROP_0,
	PROP_DAEMON_VERSION,
	PROP_CAN_SUSPEND,
	PROP_CAN_HIBERNATE,
	PROP_ON_BATTERY,
	PROP_ON_LOW_BATTERY,
	PROP_LID_IS_CLOSED,
	PROP_LID_IS_PRESENT,
	PROP_LAST
};

enum
{
	SIGNAL_DEVICE_ADDED,
	SIGNAL_DEVICE_REMOVED,
	SIGNAL_DEVICE_CHANGED,
	SIGNAL_CHANGED,
	SIGNAL_LAST,
};

static guint signals[SIGNAL_LAST] = { 0 };

struct DkpDaemonPrivate
{
	DBusGConnection		*connection;
	DBusGProxy		*proxy;
	DkpPolkit		*polkit;
	DkpBackend		*backend;
	DkpDeviceList		*power_devices;
	gboolean		 on_battery;
	gboolean		 on_low_battery;
	gboolean		 lid_is_closed;
	gboolean		 lid_is_present;
	gboolean		 kernel_can_suspend;
	gboolean		 kernel_can_hibernate;
	gboolean		 kernel_has_swap_space;
	gboolean		 during_coldplug;
};

static void	dkp_daemon_finalize		(GObject	*object);
static gboolean	dkp_daemon_get_on_battery_local	(DkpDaemon	*daemon);
static gboolean	dkp_daemon_get_on_low_battery_local (DkpDaemon	*daemon);
static gboolean	dkp_daemon_get_on_ac_local 	(DkpDaemon	*daemon);

G_DEFINE_TYPE (DkpDaemon, dkp_daemon, G_TYPE_OBJECT)

#define DKP_DAEMON_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), DKP_TYPE_DAEMON, DkpDaemonPrivate))

/* if using more memory compared to usable swap, disable hibernate */
#define DKP_DAEMON_SWAP_WATERLINE 			80.0f /* % */

/* refresh all the devices after this much time when on-battery has changed */
#define DKP_DAEMON_ON_BATTERY_REFRESH_DEVICES_DELAY	3 /* seconds */

/**
 * dkp_daemon_check_sleep_states:
 **/
static gboolean
dkp_daemon_check_sleep_states (DkpDaemon *daemon)
{
	gchar *contents = NULL;
	GError *error = NULL;
	gboolean ret;
	const gchar *filename = "/sys/power/state";

	/* see what kernel can do */
	ret = g_file_get_contents (filename, &contents, NULL, &error);
	if (!ret) {
		egg_warning ("failed to open %s: %s", filename, error->message);
		g_error_free (error);
		goto out;
	}

	/* does the kernel advertise this */
	daemon->priv->kernel_can_suspend = (g_strstr_len (contents, -1, "mem") != NULL);
	daemon->priv->kernel_can_hibernate = (g_strstr_len (contents, -1, "disk") != NULL);
out:
	g_free (contents);
	return ret;
}

/**
 * dkp_daemon_check_swap:
 **/
static gfloat
dkp_daemon_check_swap (DkpDaemon *daemon)
{
	gchar *contents = NULL;
	gchar **lines = NULL;
	GError *error = NULL;
	gchar **tokens;
	gboolean ret;
	guint active = 0;
	guint swap_free = 0;
	guint len;
	guint i;
	gfloat percentage = 0.0f;
	const gchar *filename = "/proc/meminfo";

	/* get memory data */
	ret = g_file_get_contents (filename, &contents, NULL, &error);
	if (!ret) {
		egg_warning ("failed to open %s: %s", filename, error->message);
		g_error_free (error);
		goto out;
	}

	/* process each line */
	lines = g_strsplit (contents, "\n", -1);
	for (i=1; lines[i] != NULL; i++) {
		tokens = g_strsplit_set (lines[i], ": ", -1);
		len = g_strv_length (tokens);
		if (len > 3) {
			if (g_strcmp0 (tokens[0], "SwapFree") == 0)
				swap_free = atoi (tokens[len-2]);
			else if (g_strcmp0 (tokens[0], "Active") == 0)
				active = atoi (tokens[len-2]);
		}
		g_strfreev (tokens);
	}

	/* work out how close to the line we are */
	if (swap_free > 0 && active > 0)
		percentage = (active * 100) / swap_free;
	egg_debug ("total swap available %i kb, active memory %i kb (%.1f%%)", swap_free, active, percentage);
out:
	g_free (contents);
	g_strfreev (lines);
	return percentage;
}

/**
 * dkp_daemon_get_on_battery_local:
 *
 * As soon as _any_ battery goes discharging, this is true
 **/
static gboolean
dkp_daemon_get_on_battery_local (DkpDaemon *daemon)
{
	guint i;
	gboolean ret;
	gboolean result = FALSE;
	gboolean on_battery;
	DkpDevice *device;
	GPtrArray *array;

	/* ask each device */
	array = dkp_device_list_get_array (daemon->priv->power_devices);
	for (i=0; i<array->len; i++) {
		device = (DkpDevice *) g_ptr_array_index (array, i);
		ret = dkp_device_get_on_battery (device, &on_battery);
		if (ret && on_battery) {
			result = TRUE;
			break;
		}
	}
	g_ptr_array_unref (array);
	return result;
}

/**
 * dkp_daemon_get_number_devices_of_type:
 **/
guint
dkp_daemon_get_number_devices_of_type (DkpDaemon *daemon, DkpDeviceType type)
{
	guint i;
	DkpDevice *device;
	GPtrArray *array;
	DkpDeviceType type_tmp;
	guint count = 0;

	/* ask each device */
	array = dkp_device_list_get_array (daemon->priv->power_devices);
	for (i=0; i<array->len; i++) {
		device = (DkpDevice *) g_ptr_array_index (array, i);
		g_object_get (device,
			      "type", &type_tmp,
			      NULL);
		if (type == type_tmp)
			count++;
	}
	g_ptr_array_unref (array);
	return count;
}

/**
 * dkp_daemon_get_on_low_battery_local:
 *
 * As soon as _all_ batteries are low, this is true
 **/
static gboolean
dkp_daemon_get_on_low_battery_local (DkpDaemon *daemon)
{
	guint i;
	gboolean ret;
	gboolean result = TRUE;
	gboolean on_low_battery;
	DkpDevice *device;
	GPtrArray *array;

	/* ask each device */
	array = dkp_device_list_get_array (daemon->priv->power_devices);
	for (i=0; i<array->len; i++) {
		device = (DkpDevice *) g_ptr_array_index (array, i);
		ret = dkp_device_get_low_battery (device, &on_low_battery);
		if (ret && !on_low_battery) {
			result = FALSE;
			break;
		}
	}
	g_ptr_array_unref (array);
	return result;
}

/**
 * dkp_daemon_get_on_ac_local:
 *
 * As soon as _any_ ac supply goes online, this is true
 **/
static gboolean
dkp_daemon_get_on_ac_local (DkpDaemon *daemon)
{
	guint i;
	gboolean ret;
	gboolean result = FALSE;
	gboolean online;
	DkpDevice *device;
	GPtrArray *array;

	/* ask each device */
	array = dkp_device_list_get_array (daemon->priv->power_devices);
	for (i=0; i<array->len; i++) {
		device = (DkpDevice *) g_ptr_array_index (array, i);
		ret = dkp_device_get_online (device, &online);
		if (ret && online) {
			result = TRUE;
			break;
		}
	}
	g_ptr_array_unref (array);
	return result;
}

/**
 * dkp_daemon_set_pmutils_powersave:
 *
 * Uses pm-utils to run scripts in power.d
 **/
static gboolean
dkp_daemon_set_pmutils_powersave (DkpDaemon *daemon, gboolean powersave)
{
	gboolean ret;
	gchar *command;
	GError *error = NULL;

	/* run script from pm-utils */
	command = g_strdup_printf ("/usr/sbin/pm-powersave %s", powersave ? "true" : "false");
	egg_debug ("excuting command: %s", command);
	ret = g_spawn_command_line_async (command, &error);
	if (!ret) {
		egg_warning ("failed to run script: %s", error->message);
		g_error_free (error);
		goto out;
	}
out:
	g_free (command);
	return ret;
}

/**
 * dkp_daemon_refresh_battery_devices:
 **/
static gboolean
dkp_daemon_refresh_battery_devices (DkpDaemon *daemon)
{
	guint i;
	GPtrArray *array;
	DkpDevice *device;
	DkpDeviceType type;

	/* refresh all devices in array */
	array = dkp_device_list_get_array (daemon->priv->power_devices);
	for (i=0; i<array->len; i++) {
		device = (DkpDevice *) g_ptr_array_index (array, i);
		/* only refresh battery devices */
		g_object_get (device,
			      "type", &type,
			      NULL);
		if (type == DKP_DEVICE_TYPE_BATTERY)
			dkp_device_refresh_internal (device);
	}
	g_ptr_array_unref (array);

	return TRUE;
}

/**
 * dkp_daemon_enumerate_devices:
 **/
gboolean
dkp_daemon_enumerate_devices (DkpDaemon *daemon, DBusGMethodInvocation *context)
{
	guint i;
	GPtrArray *array;
	GPtrArray *object_paths;
	DkpDevice *device;

	/* build a pointer array of the object paths */
	object_paths = g_ptr_array_new ();
	array = dkp_device_list_get_array (daemon->priv->power_devices);
	for (i=0; i<array->len; i++) {
		device = (DkpDevice *) g_ptr_array_index (array, i);
		g_ptr_array_add (object_paths, g_strdup (dkp_device_get_object_path (device)));
	}
	g_ptr_array_unref (array);

	/* return it on the bus */
	dbus_g_method_return (context, object_paths);

	/* free */
	g_ptr_array_foreach (object_paths, (GFunc) g_free, NULL);
	g_ptr_array_free (object_paths, TRUE);
	return TRUE;
}

/**
 * dkp_daemon_suspend:
 **/
gboolean
dkp_daemon_suspend (DkpDaemon *daemon, DBusGMethodInvocation *context)
{
	gboolean ret;
	GError *error;
	GError *error_local = NULL;
	PolkitSubject *subject = NULL;
	gchar *stdout = NULL;
	gchar *stderr = NULL;

	/* no kernel support */
	if (!daemon->priv->kernel_can_suspend) {
		error = g_error_new (DKP_DAEMON_ERROR,
				     DKP_DAEMON_ERROR_GENERAL,
				     "No kernel support");
		g_error_free (error_local);
		dbus_g_method_return_error (context, error);
		goto out;
	}

	subject = dkp_polkit_get_subject (daemon->priv->polkit, context);
	if (subject == NULL)
		goto out;

	if (!dkp_polkit_check_auth (daemon->priv->polkit, subject, "org.freedesktop.devicekit.power.suspend", context))
		goto out;

	ret = g_spawn_command_line_sync ("/usr/sbin/pm-suspend", &stdout, &stderr, NULL, &error_local);
	if (!ret) {
		error = g_error_new (DKP_DAEMON_ERROR,
				     DKP_DAEMON_ERROR_GENERAL,
				     "Failed to spawn: %s, stdout:%s, stderr:%s", error_local->message, stdout, stderr);
		g_error_free (error_local);
		dbus_g_method_return_error (context, error);
		goto out;
	}
	dbus_g_method_return (context, NULL);
out:
	g_free (stdout);
	g_free (stderr);
	if (subject != NULL)
		g_object_unref (subject);
	return TRUE;
}

/**
 * dkp_daemon_hibernate:
 **/
gboolean
dkp_daemon_hibernate (DkpDaemon *daemon, DBusGMethodInvocation *context)
{
	gboolean ret;
	GError *error;
	GError *error_local = NULL;
	PolkitSubject *subject = NULL;
	gchar *stdout = NULL;
	gchar *stderr = NULL;

	/* no kernel support */
	if (!daemon->priv->kernel_can_hibernate) {
		error = g_error_new (DKP_DAEMON_ERROR,
				     DKP_DAEMON_ERROR_GENERAL,
				     "No kernel support");
		g_error_free (error_local);
		dbus_g_method_return_error (context, error);
		goto out;
	}

	/* enough swap? */
	if (!daemon->priv->kernel_has_swap_space) {
		error = g_error_new (DKP_DAEMON_ERROR,
				     DKP_DAEMON_ERROR_GENERAL,
				     "Not enough swap space");
		g_error_free (error_local);
		dbus_g_method_return_error (context, error);
		goto out;
	}

	subject = dkp_polkit_get_subject (daemon->priv->polkit, context);
	if (subject == NULL)
		goto out;

	if (!dkp_polkit_check_auth (daemon->priv->polkit, subject, "org.freedesktop.devicekit.power.hibernate", context))
		goto out;

	ret = g_spawn_command_line_sync ("/usr/sbin/pm-hibernate", &stdout, &stderr, NULL, &error_local);
	if (!ret) {
		error = g_error_new (DKP_DAEMON_ERROR,
				     DKP_DAEMON_ERROR_GENERAL,
				     "Failed to spawn: %s, stdout:%s, stderr:%s", error_local->message, stdout, stderr);
		g_error_free (error_local);
		dbus_g_method_return_error (context, error);
		goto out;
	}
	dbus_g_method_return (context, NULL);
out:
	g_free (stdout);
	g_free (stderr);
	if (subject != NULL)
		g_object_unref (subject);
	return TRUE;
}

/**
 * dkp_daemon_register_power_daemon:
 **/
static gboolean
dkp_daemon_register_power_daemon (DkpDaemon *daemon)
{
	DBusConnection *connection;
	DBusError dbus_error;
	GError *error = NULL;

	daemon->priv->connection = dbus_g_bus_get (DBUS_BUS_SYSTEM, &error);
	if (daemon->priv->connection == NULL) {
		if (error != NULL) {
			g_critical ("error getting system bus: %s", error->message);
			g_error_free (error);
		}
		goto error;
	}
	connection = dbus_g_connection_get_connection (daemon->priv->connection);

	dbus_g_connection_register_g_object (daemon->priv->connection,
					     "/org/freedesktop/DeviceKit/Power",
					     G_OBJECT (daemon));

	daemon->priv->proxy = dbus_g_proxy_new_for_name (daemon->priv->connection,
						      DBUS_SERVICE_DBUS,
						      DBUS_PATH_DBUS,
						      DBUS_INTERFACE_DBUS);
	dbus_error_init (&dbus_error);
	if (dbus_error_is_set (&dbus_error)) {
		egg_warning ("Cannot add match rule: %s: %s", dbus_error.name, dbus_error.message);
		dbus_error_free (&dbus_error);
		goto error;
	}

	return TRUE;
error:
	return FALSE;
}

/**
 * dkp_daemon_startup:
 **/
gboolean
dkp_daemon_startup (DkpDaemon *daemon)
{
	gboolean ret;
	gboolean on_battery;
	gboolean on_low_battery;

	/* register on bus */
	ret = dkp_daemon_register_power_daemon (daemon);
	if (!ret) {
		egg_warning ("failed to register");
		goto out;
	}

	/* stop signals and callbacks */
	egg_debug ("daemon now coldplug");
	g_object_freeze_notify (G_OBJECT(daemon));
	daemon->priv->during_coldplug = TRUE;

	/* coldplug backend backend */
	ret = dkp_backend_coldplug (daemon->priv->backend, daemon);
	if (!ret) {
		egg_warning ("failed to coldplug backend");
		goto out;
	}

	/* get battery state */
	on_battery = (dkp_daemon_get_on_battery_local (daemon) &&
		      !dkp_daemon_get_on_ac_local (daemon));
	on_low_battery = dkp_daemon_get_on_low_battery_local (daemon);
	g_object_set (daemon,
		      "on-battery", on_battery,
		      "on-low-battery", on_low_battery,
		      NULL);

	/* start signals and callbacks */
	g_object_thaw_notify (G_OBJECT(daemon));
	daemon->priv->during_coldplug = FALSE;
	egg_debug ("daemon now not coldplug");

	/* set pm-utils power policy */
	dkp_daemon_set_pmutils_powersave (daemon, daemon->priv->on_battery);
out:
	return ret;
}

/**
 * dkp_daemon_refresh_battery_devices_cb:
 **/
static gboolean
dkp_daemon_refresh_battery_devices_cb (DkpDaemon *daemon)
{
	egg_debug ("doing the delayed refresh");
	dkp_daemon_refresh_battery_devices (daemon);
	return FALSE;
}

/**
 * dkp_daemon_get_device_list:
 **/
DkpDeviceList *
dkp_daemon_get_device_list (DkpDaemon *daemon)
{
	return g_object_ref (daemon->priv->power_devices);
}

/**
 * dkp_daemon_device_added_cb:
 **/
static void
dkp_daemon_device_added_cb (DkpBackend *backend, GObject *native, DkpDevice *device, DkpDaemon *daemon)
{
	const gchar *object_path;

	g_return_if_fail (DKP_IS_DAEMON (daemon));
	g_return_if_fail (DKP_IS_DEVICE (device));
	g_return_if_fail (G_IS_OBJECT (native));

	/* add to device list */
	dkp_device_list_insert (daemon->priv->power_devices, native, G_OBJECT (device));

	/* emit */
	if (!daemon->priv->during_coldplug) {
		object_path = dkp_device_get_object_path (device);
		egg_debug ("emitting added: %s (during coldplug %i)", object_path, daemon->priv->during_coldplug);

		/* don't crash the session */
		if (object_path == NULL) {
			egg_warning ("INTERNAL STATE CORRUPT: not sending NULL, native:%p, device:%p", native, device);
			return;
		}
		g_signal_emit (daemon, signals[SIGNAL_DEVICE_ADDED], 0, object_path);
	}
}

/**
 * dkp_daemon_device_changed_cb:
 **/
static void
dkp_daemon_device_changed_cb (DkpBackend *backend, GObject *native, DkpDevice *device, DkpDaemon *daemon)
{
	const gchar *object_path;
	DkpDeviceType type;
	gboolean ret;

	g_return_if_fail (DKP_IS_DAEMON (daemon));
	g_return_if_fail (DKP_IS_DEVICE (device));
	g_return_if_fail (G_IS_OBJECT (native));

	/* refresh battery devices when AC state changes */
	g_object_get (device,
		      "type", &type,
		      NULL);
	if (type == DKP_DEVICE_TYPE_LINE_POWER) {
		/* refresh now, and again in a little while */
		dkp_daemon_refresh_battery_devices (daemon);
		g_timeout_add_seconds (DKP_DAEMON_ON_BATTERY_REFRESH_DEVICES_DELAY,
				       (GSourceFunc) dkp_daemon_refresh_battery_devices_cb, daemon);
	}

	/* second, check if the on_battery and on_low_battery state has changed */
	ret = (dkp_daemon_get_on_battery_local (daemon) && !dkp_daemon_get_on_ac_local (daemon));
	if (ret != daemon->priv->on_battery) {
		g_object_set (daemon, "on-battery", ret, NULL);

		/* set pm-utils power policy */
		dkp_daemon_set_pmutils_powersave (daemon, ret);
	}
	ret = dkp_daemon_get_on_low_battery_local (daemon);
	if (ret != daemon->priv->on_low_battery) {
		g_object_set (daemon, "on-low-battery", ret, NULL);
	}

	/* emit */
	if (!daemon->priv->during_coldplug) {
		object_path = dkp_device_get_object_path (device);
		egg_debug ("emitting device-changed: %s", object_path);

		/* don't crash the session */
		if (object_path == NULL) {
			egg_warning ("INTERNAL STATE CORRUPT: not sending NULL, native:%p, device:%p", native, device);
			return;
		}
		g_signal_emit (daemon, signals[SIGNAL_DEVICE_CHANGED], 0, object_path);
	}
}

/**
 * dkp_daemon_device_removed_cb:
 **/
static void
dkp_daemon_device_removed_cb (DkpBackend *backend, GObject *native, DkpDevice *device, DkpDaemon *daemon)
{
	const gchar *object_path;

	g_return_if_fail (DKP_IS_DAEMON (daemon));
	g_return_if_fail (DKP_IS_DEVICE (device));
	g_return_if_fail (G_IS_OBJECT (native));

	/* remove from list */
	dkp_device_list_remove (daemon->priv->power_devices, G_OBJECT(device));

	/* emit */
	if (!daemon->priv->during_coldplug) {
		object_path = dkp_device_get_object_path (device);
		egg_debug ("emitting device-removed: %s", object_path);

		/* don't crash the session */
		if (object_path == NULL) {
			egg_warning ("INTERNAL STATE CORRUPT: not sending NULL, native:%p, device:%p", native, device);
			return;
		}
		g_signal_emit (daemon, signals[SIGNAL_DEVICE_REMOVED], 0, object_path);
	}

	/* finalise the object */
	g_object_unref (device);
}

/**
 * dkp_daemon_properties_changed_cb:
 **/
static void
dkp_daemon_properties_changed_cb (GObject *object, GParamSpec *pspec, DkpDaemon *daemon)
{
	g_return_if_fail (DKP_IS_DAEMON (daemon));

	/* emit */
	if (!daemon->priv->during_coldplug) {
		egg_debug ("emitting changed");
		g_signal_emit (daemon, signals[SIGNAL_CHANGED], 0);
	}
}

/**
 * dkp_daemon_init:
 **/
static void
dkp_daemon_init (DkpDaemon *daemon)
{
	gfloat waterline;

	daemon->priv = DKP_DAEMON_GET_PRIVATE (daemon);
	daemon->priv->polkit = dkp_polkit_new ();
	daemon->priv->lid_is_present = FALSE;
	daemon->priv->lid_is_closed = FALSE;
	daemon->priv->kernel_can_suspend = FALSE;
	daemon->priv->kernel_can_hibernate = FALSE;
	daemon->priv->kernel_has_swap_space = FALSE;
	daemon->priv->power_devices = dkp_device_list_new ();
	daemon->priv->on_battery = FALSE;
	daemon->priv->on_low_battery = FALSE;
	daemon->priv->during_coldplug = FALSE;

	daemon->priv->backend = dkp_backend_new ();
	g_signal_connect (daemon->priv->backend, "device-added",
			  G_CALLBACK (dkp_daemon_device_added_cb), daemon);
	g_signal_connect (daemon->priv->backend, "device-changed",
			  G_CALLBACK (dkp_daemon_device_changed_cb), daemon);
	g_signal_connect (daemon->priv->backend, "device-removed",
			  G_CALLBACK (dkp_daemon_device_removed_cb), daemon);

	/* watch when these properties change */
	g_signal_connect (daemon, "notify::lid-is-present",
			  G_CALLBACK (dkp_daemon_properties_changed_cb), daemon);
	g_signal_connect (daemon, "notify::lid-is-closed",
			  G_CALLBACK (dkp_daemon_properties_changed_cb), daemon);
	g_signal_connect (daemon, "notify::on-battery",
			  G_CALLBACK (dkp_daemon_properties_changed_cb), daemon);
	g_signal_connect (daemon, "notify::on-low-battery",
			  G_CALLBACK (dkp_daemon_properties_changed_cb), daemon);

	/* check if we have support */
	dkp_daemon_check_sleep_states (daemon);

	/* do we have enough swap? */
	if (daemon->priv->kernel_can_hibernate) {
		waterline = dkp_daemon_check_swap (daemon);
		if (waterline < DKP_DAEMON_SWAP_WATERLINE)
			daemon->priv->kernel_has_swap_space = TRUE;
		else
			egg_debug ("not enough swap to enable hibernate");
	}
}

/**
 * dkp_daemon_error_quark:
 **/
GQuark
dkp_daemon_error_quark (void)
{
	static GQuark ret = 0;
	if (ret == 0)
		ret = g_quark_from_static_string ("dkp_daemon_error");
	return ret;
}

#define ENUM_ENTRY(NAME, DESC) { NAME, "" #NAME "", DESC }
/**
 * dkp_daemon_error_get_type:
 **/
GType
dkp_daemon_error_get_type (void)
{
	static GType etype = 0;

	if (etype == 0) {
		static const GEnumValue values[] = {
			ENUM_ENTRY (DKP_DAEMON_ERROR_GENERAL, "GeneralError"),
			ENUM_ENTRY (DKP_DAEMON_ERROR_NOT_SUPPORTED, "NotSupported"),
			ENUM_ENTRY (DKP_DAEMON_ERROR_NO_SUCH_DEVICE, "NoSuchDevice"),
			{ 0, 0, 0 }
		};
		g_assert (DKP_DAEMON_NUM_ERRORS == G_N_ELEMENTS (values) - 1);
		etype = g_enum_register_static ("DkpDaemonError", values);
	}
	return etype;
}

/**
 * dkp_daemon_get_property:
 **/
static void
dkp_daemon_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec)
{
	DkpDaemon *daemon;
	daemon = DKP_DAEMON (object);
	switch (prop_id) {
	case PROP_DAEMON_VERSION:
		g_value_set_string (value, PACKAGE_VERSION);
		break;
	case PROP_CAN_SUSPEND:
		g_value_set_boolean (value, daemon->priv->kernel_can_suspend);
		break;
	case PROP_CAN_HIBERNATE:
		g_value_set_boolean (value, (daemon->priv->kernel_can_hibernate && daemon->priv->kernel_has_swap_space));
		break;
	case PROP_ON_BATTERY:
		g_value_set_boolean (value, daemon->priv->on_battery);
		break;
	case PROP_ON_LOW_BATTERY:
		g_value_set_boolean (value, daemon->priv->on_battery && daemon->priv->on_low_battery);
		break;
	case PROP_LID_IS_CLOSED:
		g_value_set_boolean (value, daemon->priv->lid_is_closed);
		break;
	case PROP_LID_IS_PRESENT:
		g_value_set_boolean (value, daemon->priv->lid_is_present);
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
		break;
	}
}

/**
 * dkp_daemon_set_property:
 **/
static void
dkp_daemon_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec)
{
	DkpDaemon *daemon = DKP_DAEMON (object);
	switch (prop_id) {
	case PROP_LID_IS_CLOSED:
		daemon->priv->lid_is_closed = g_value_get_boolean (value);
		egg_debug ("now lid_is_closed = %s", daemon->priv->lid_is_closed ? "yes" : "no");
		break;
	case PROP_LID_IS_PRESENT:
		daemon->priv->lid_is_present = g_value_get_boolean (value);
		egg_debug ("now lid_is_present = %s", daemon->priv->lid_is_present ? "yes" : "no");
		break;
	case PROP_ON_BATTERY:
		daemon->priv->on_battery = g_value_get_boolean (value);
		egg_debug ("now on_battery = %s", daemon->priv->on_battery ? "yes" : "no");
		break;
	case PROP_ON_LOW_BATTERY:
		daemon->priv->on_low_battery = g_value_get_boolean (value);
		egg_debug ("now on_low_battery = %s", daemon->priv->on_low_battery ? "yes" : "no");
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
		break;
	}
}

/**
 * dkp_daemon_class_init:
 **/
static void
dkp_daemon_class_init (DkpDaemonClass *klass)
{
	GObjectClass *object_class = G_OBJECT_CLASS (klass);
	object_class->finalize = dkp_daemon_finalize;
	object_class->get_property = dkp_daemon_get_property;
	object_class->set_property = dkp_daemon_set_property;

	g_type_class_add_private (klass, sizeof (DkpDaemonPrivate));

	signals[SIGNAL_DEVICE_ADDED] =
		g_signal_new ("device-added",
			      G_OBJECT_CLASS_TYPE (klass),
			      G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
			      0, NULL, NULL,
			      g_cclosure_marshal_VOID__STRING,
			      G_TYPE_NONE, 1, G_TYPE_STRING);

	signals[SIGNAL_DEVICE_REMOVED] =
		g_signal_new ("device-removed",
			      G_OBJECT_CLASS_TYPE (klass),
			      G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
			      0, NULL, NULL,
			      g_cclosure_marshal_VOID__STRING,
			      G_TYPE_NONE, 1, G_TYPE_STRING);

	signals[SIGNAL_DEVICE_CHANGED] =
		g_signal_new ("device-changed",
			      G_OBJECT_CLASS_TYPE (klass),
			      G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
			      0, NULL, NULL,
			      g_cclosure_marshal_VOID__STRING,
			      G_TYPE_NONE, 1, G_TYPE_STRING);

	signals[SIGNAL_CHANGED] =
		g_signal_new ("changed",
			      G_OBJECT_CLASS_TYPE (klass),
			      G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
			      0, NULL, NULL,
			      g_cclosure_marshal_VOID__BOOLEAN,
			      G_TYPE_NONE, 0);


	g_object_class_install_property (object_class,
					 PROP_DAEMON_VERSION,
					 g_param_spec_string ("daemon-version",
							      "Daemon Version",
							      "The version of the running daemon",
							      NULL,
							      G_PARAM_READABLE));

	g_object_class_install_property (object_class,
					 PROP_LID_IS_PRESENT,
					 g_param_spec_boolean ("lid-is-present",
							       "Is a laptop",
							       "If this computer is probably a laptop",
							       FALSE,
							       G_PARAM_READWRITE));

	g_object_class_install_property (object_class,
					 PROP_CAN_SUSPEND,
					 g_param_spec_boolean ("can-suspend",
							       "Can Suspend",
							       "Whether the system can suspend",
							       FALSE,
							       G_PARAM_READABLE));

	g_object_class_install_property (object_class,
					 PROP_CAN_HIBERNATE,
					 g_param_spec_boolean ("can-hibernate",
							       "Can Hibernate",
							       "Whether the system can hibernate",
							       FALSE,
							       G_PARAM_READABLE));

	g_object_class_install_property (object_class,
					 PROP_ON_BATTERY,
					 g_param_spec_boolean ("on-battery",
							       "On Battery",
							       "Whether the system is running on battery",
							       FALSE,
							       G_PARAM_READWRITE));

	g_object_class_install_property (object_class,
					 PROP_ON_LOW_BATTERY,
					 g_param_spec_boolean ("on-low-battery",
							       "On Low Battery",
							       "Whether the system is running on battery and if the battery is critically low",
							       FALSE,
							       G_PARAM_READWRITE));

	g_object_class_install_property (object_class,
					 PROP_LID_IS_CLOSED,
					 g_param_spec_boolean ("lid-is-closed",
							       "Laptop lid is closed",
							       "If the laptop lid is closed",
							       FALSE,
							       G_PARAM_READWRITE));

	dbus_g_object_type_install_info (DKP_TYPE_DAEMON, &dbus_glib_dkp_daemon_object_info);

	dbus_g_error_domain_register (DKP_DAEMON_ERROR, NULL, DKP_DAEMON_TYPE_ERROR);
}

/**
 * dkp_daemon_finalize:
 **/
static void
dkp_daemon_finalize (GObject *object)
{
	DkpDaemon *daemon;

	g_return_if_fail (object != NULL);
	g_return_if_fail (DKP_IS_DAEMON (object));

	daemon = DKP_DAEMON (object);

	g_return_if_fail (daemon->priv != NULL);

	if (daemon->priv->proxy != NULL)
		g_object_unref (daemon->priv->proxy);
	if (daemon->priv->connection != NULL)
		dbus_g_connection_unref (daemon->priv->connection);
	g_object_unref (daemon->priv->power_devices);
	g_object_unref (daemon->priv->polkit);
	g_object_unref (daemon->priv->backend);

	G_OBJECT_CLASS (dkp_daemon_parent_class)->finalize (object);
}

/**
 * dkp_daemon_new:
 **/
DkpDaemon *
dkp_daemon_new (void)
{
	DkpDaemon *daemon;
	daemon = DKP_DAEMON (g_object_new (DKP_TYPE_DAEMON, NULL));
	return daemon;
}

/***************************************************************************
 ***                          MAKE CHECK TESTS                           ***
 ***************************************************************************/
#ifdef EGG_TEST
#include "egg-test.h"

void
dkp_daemon_test (gpointer user_data)
{
	EggTest *test = (EggTest *) user_data;
	DkpDaemon *daemon;

	if (!egg_test_start (test, "DkpDaemon"))
		return;

	/************************************************************/
	egg_test_title (test, "get instance");
	daemon = dkp_daemon_new ();
	egg_test_assert (test, daemon != NULL);

	/* unref */
	g_object_unref (daemon);

	egg_test_end (test);
}
#endif