summaryrefslogtreecommitdiffstats
path: root/src/tdepowersave.cpp
blob: d214a3b7da1b98af2baeee2a1f86706fba91287e (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
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
 /**************************************************************************
 *   Copyright (C) 2004 by  Thomas Renninger                               *
 *                            <trenn@suse.de> and                          *
 *            2004-2007 by  Danny Kukawka                                  *
 *                            <dkukawka@suse.de>, <danny.kukawka@web.de>   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of version 2 of the GNU General Public License     *
 *   as published by the Free Software Foundation.                         *
 *                                                                         *
 *   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 Street, Fifth Floor, Boston, MA 02110-1301, USA.          *
 ***************************************************************************/

// KDE headers:
#include <tdeaboutapplication.h>
#include <tdeapplication.h>
#include <kaudioplayer.h>
#include <tdeconfig.h>
#include <kiconloader.h>
#include <tdemessagebox.h>
#include <knotifyclient.h>
#include <knotifydialog.h>
#include <kpassivepopup.h>
#include <tdepopupmenu.h>
#include <kglobalaccel.h>

// other TQt headers:
#include <tqcursor.h>
#include <tqevent.h>
#include <tqfile.h>
#include <tqimage.h>
#include <tqpixmap.h>
#include <tqtimer.h>
#include <tqtooltip.h>

// own headers:
#include "tdepowersave.h"
#include "infodialog.h"

/*!
*  \file 	tdepowersave.cpp
*  \brief 	This file contains the main functionality of the tdepowersave-applet.*/

/*!
 * This is the default constructor of the class tdepowersave.
 */
tdepowersave::tdepowersave( bool force_acpi_check, bool trace_func ) : KSystemTray(0, "tdepowersave"),
								   DCOPObject("tdepowersaveIface") {
	trace = trace_func;
	kdDebugFuncIn(trace);

	display = new screen();
	settings = new Settings();
	autoSuspend = new autosuspend(display);
	autoDimm = new autodimm(display);
	hwinfo = new HardwareInfo();
	suspend = hwinfo->getSuspendSupport();

	yast2 = NULL;

	resume_result = 0;

	config = TDEGlobal::config();
	config->setGroup("General");
	if(!config->readBoolEntry("AlreadyStarted", false) || force_acpi_check){
		config->writeEntry("AlreadyStarted", true);
		// check whether APM, ACPI, PMU, CPUFreq or Suspend2Disk/ram supported, otherwise end up
		// and don't start tdepowersave ever again until force_acpi_check == true.
		if (!hwinfo->hasACPI() && !hwinfo->hasAPM() && !hwinfo->hasPMU() &&
		    !hwinfo->supportCPUFreq() && !suspend.suspend2disk && !suspend.suspend2ram){
			config->writeEntry("Autostart", false);
			config->sync();
			kdError() << "This machine does not support ACPI, APM, PMU, CPUFreq, Suspend2Disk nor "
			          << "Suspend2RAM. Please close tdepowersave now." << endl;
			exit(-1);
		}
	}

	// default init
	if (hwinfo->getAcAdapter()) {
		settings->load_scheme_settings( settings->ac_scheme);
	} else {
		settings->load_scheme_settings( settings->battery_scheme);
	}
	// set the battery warning levels
	hwinfo->setPrimaryBatteriesWarningLevel(settings->batteryWarningLevel,
						settings->batteryLowLevel,
						settings->batteryCriticalLevel);

	// connect to signals for changes
	connect(hwinfo, TQT_SIGNAL(generalDataChanged()), this, TQT_SLOT(update()));
	connect(hwinfo, TQT_SIGNAL(primaryBatteryChanged()), this, TQT_SLOT(update()));
	connect(hwinfo, TQT_SIGNAL(ACStatus(bool)), this, TQT_SLOT(handleACStatusChange (bool)));
	connect(hwinfo, TQT_SIGNAL(resumed(int)), this, TQT_SLOT(forwardResumeSignal(int)));

	// connect to error messages
	connect(autoSuspend, TQT_SIGNAL(displayErrorMsg(TQString)), this, TQT_SLOT(showErrorMessage(TQString)));

	// connect to events
	connect(hwinfo, TQT_SIGNAL(lidclosetStatus(bool)), this, TQT_SLOT(handleLidEvent(bool)));
	connect(hwinfo, TQT_SIGNAL(powerButtonPressed()), this, TQT_SLOT (handlePowerButtonEvent()));
	connect(hwinfo, TQT_SIGNAL(sleepButtonPressed()), this, TQT_SLOT (handleSleepButtonEvent()));
	connect(hwinfo, TQT_SIGNAL(s2diskButtonPressed()), this, TQT_SLOT (handleS2DiskButtonEvent()));
	connect(hwinfo, TQT_SIGNAL(batteryWARNState(int,int)), this, TQT_SLOT(notifyBatteryStatusChange (int,int)));
	connect(hwinfo, TQT_SIGNAL(desktopSessionIsActive(bool)), this, TQT_SLOT (handleSessionState(bool)));
	connect(autoSuspend, TQT_SIGNAL(inactivityTimeExpired()), this, TQT_SLOT(do_autosuspendWarn()));
	connect(autoDimm, TQT_SIGNAL(inactivityTimeExpired()), this, TQT_SLOT(do_downDimm()));
	connect(autoDimm, TQT_SIGNAL(UserIsActiveAgain()), this, TQT_SLOT(do_upDimm()));

	// connect to hotkeys
	m_globalAccel = new TDEGlobalAccel( TQT_TQOBJECT(this) );
	m_globalAccel->insert( "Power button", i18n( "Execute configured power button action"), TQString(),
			TDEShortcut(TQString("XF86PowerOff")), TDEShortcut(TQString("XF86PowerOff")), TQT_TQOBJECT(this), TQT_SLOT( handlePowerButtonEvent() ) );
	m_globalAccel->insert( "Sleep button", i18n( "Sleep configured power button action"), TQString(),
			TDEShortcut(TQString("XF86Sleep")), TDEShortcut(TQString("XF86Sleep")), TQT_TQOBJECT(this), TQT_SLOT( handleSleepButtonEvent() ) );
	m_globalAccel->insert( "Hibernate button", i18n( "Hibernate configured power button action"), TQString(),
			TDEShortcut(TQString("XF86Suspend")), TDEShortcut(TQString("XF86Suspend")), TQT_TQOBJECT(this), TQT_SLOT( handleS2DiskButtonEvent() ) );
	m_globalAccel->readSettings();
	m_globalAccel->updateConnections();

	config->sync();

	config_dialog_shown = false;
	suspend_dialog_shown = false;
	detailedIsShown = false;
	icon_set_colored = false;
	icon_BG_is_colored = false;

 	calledSuspend = -1;
	countWhiteIconPixel = 0;

	pixmap_name = "NONE";
        suspendType = "NULL";

	BAT_WARN_ICON_Timer = new TQTimer(this);
	connect(BAT_WARN_ICON_Timer, TQT_SIGNAL(timeout()), this, TQT_SLOT(do_setIconBG()));

	AUTODIMM_Timer = new TQTimer(this);

	initMenu();
	update();
	updateCPUFreqMenu();
	setSchemeSettings();

	kdDebugFuncOut(trace);
}


/*! This is the default destructor of class tdepowersave. */
tdepowersave::~tdepowersave(){
	kdDebugFuncIn(trace);

	delete hwinfo;
	delete display;
	delete settings;
	delete autoSuspend;
#ifdef ENABLE_YAST_ENTRY
	delete yast2;
#endif
}

/*!
 * use this function to initalise the main kicker menu
 */
void tdepowersave::initMenu() {
	kdDebugFuncIn(trace);

	CONFIGURE_ID = this->contextMenu()->insertItem(SmallIcon("configure", TQIconSet::Automatic),
								  i18n("Configure TDEPowersave..."),
								  this, TQT_SLOT(showConfigureDialog()));
	CONFIGURE_EVENTS_ID = this->contextMenu()->insertItem(SmallIcon("knotify", TQIconSet::Automatic),
							      i18n("Configure Notifications..."),
							      this, TQT_SLOT(showConfigureNotificationsDialog()));
#ifdef ENABLE_YAST_ENTRY
	YAST_MODULE_MENU_ID = this->contextMenu()->insertItem(SmallIcon("yast", TQIconSet::Automatic),
							      i18n("Start YaST2 Power Management Module..."),
							      this, TQT_SLOT(do_config()));
#endif

	SLEEP_SEPARATOR_MENU_ID = this->contextMenu()->insertSeparator();
	SUSPEND2DISK_MENU_ID = this->contextMenu()->insertItem( SmallIconSet("suspend_to_disk",
								TQIconSet::Automatic),
								i18n("Hibernate"), this,
								TQT_SLOT(do_suspend2disk()));
	SUSPEND2RAM_MENU_ID = this->contextMenu()->insertItem( SmallIconSet("suspend_to_ram",
							       TQIconSet::Automatic),
							       i18n("Sleep"), this,
							       TQT_SLOT(do_suspend2ram()));
	FREEZE_MENU_ID = this->contextMenu()->insertItem( SmallIconSet("suspend_to_ram", TQIconSet::Automatic),
							   i18n("Freeze"), this, TQT_SLOT(do_freeze()));
	STANDBY_MENU_ID = this->contextMenu()->insertItem( SmallIconSet("stand_by", TQIconSet::Automatic),
							   i18n("Standby"), this, TQT_SLOT(do_standby()));

	speed_menu = new TQPopupMenu(this, i18n("Set CPU Frequency Policy").ascii());
	speed_menu->insertItem(i18n("Performance"), PERFORMANCE);
	speed_menu->insertItem(i18n("Dynamic"), DYNAMIC);
	speed_menu->insertItem(i18n("Powersave"), POWERSAVE);

	CPUFREQ_SEPARATOR_MENU_ID = contextMenu()->insertSeparator();

	CPUFREQ_MENU_ID = contextMenu()->insertItem(i18n("Set CPU Frequency Policy"), speed_menu);
	connect(speed_menu, TQT_SIGNAL(activated(int)), this, TQT_SLOT(do_setSpeedPolicy(int)));
	connect(hwinfo, TQT_SIGNAL(currentCPUFreqPolicyChanged()), this, TQT_SLOT(updateCPUFreqMenu()));


	SCHEME_SEPARATOR_MENU_ID = contextMenu()->insertSeparator();

	scheme_menu = new TQPopupMenu(this, i18n("Set Active Scheme").ascii());
	SCHEME_MENU_ID = contextMenu()->insertItem(i18n("Set Active Scheme"), scheme_menu);
	connect(scheme_menu, TQT_SIGNAL(activated(int)), this, TQT_SLOT(do_setActiveScheme(int)));

	// menu entry for the autosuspend disable checkbox, disabled by default, only
	// displayed if autosuspend for the current scheme is activated
	AUTOSUSPEND_SEPARATOR_MENU_ID = contextMenu()->insertSeparator();
	AUTOSUSPEND_MENU_ID = this->contextMenu()->insertItem( i18n("Disable Actions on Inactivity"),
							       this,TQT_SLOT(do_setAutosuspend()));
	this->contextMenu()->setItemVisible(AUTOSUSPEND_SEPARATOR_MENU_ID, false);
	this->contextMenu()->setItemVisible(AUTOSUSPEND_MENU_ID, false);

	HELP_SEPARATOR_MENU_ID = contextMenu()->insertSeparator();

	help_menu = new TQPopupMenu(this, i18n("&Help").ascii());

	help_menu->insertItem( SmallIcon("help", TQIconSet::Automatic), i18n("&TDEPowersave Handbook"),
			       this, TQT_SLOT(slotHelp()));
	help_menu->insertSeparator();
	help_menu->insertItem( i18n("&Report a bug ..."), this, TQT_SLOT(slotReportBug()));
	help_menu->insertItem( SmallIcon("tdepowersave", TQIconSet::Automatic),
			       i18n("&About TDEPowersave"), this, TQT_SLOT(slotAbout()));

	HELP_MENU = contextMenu()->insertItem(SmallIcon("help", TQIconSet::Automatic),
							i18n("&Help"), help_menu);

	connect(this, TQT_SIGNAL(quitSelected()), this, TQT_SLOT(_quit()));

	kdDebugFuncOut(trace);
}

void tdepowersave::resizeEvent ( TQResizeEvent * )
{
	// Honor Free Desktop specifications that allow for arbitrary system tray icon sizes
	loadIcon(true);
	drawIcon();
}

/*!
 * This funtion load and manipulate the icons for the kickerapplet-section.
 * The redraw interval depends on \ref icon_set_colored and \ref BAT_icon_BG_intervall.
 */
void tdepowersave::redrawPixmap(){
	kdDebugFuncIn(trace);

	// if colored icon_background: normal redraw intervall is set off.
	// Icon (only) redrawed every BAT_icon_BG_intervall
	if (icon_set_colored) {
		if (icon_state_changed) {
			loadIcon();
			drawIcon();
		}
	}
	else {
		loadIcon();
		drawIcon();
	}

	kdDebugFuncOut(trace);
}

/*!
 * Starts the configure dialog of tdepowersave.
 */
void tdepowersave::showConfigureDialog() {
	kdDebugFuncIn(trace);

	if(!config_dialog_shown) {
		if (settings->schemes.count() > 0){
			configDlg = new ConfigureDialog(config, hwinfo, settings);
 			configDlg->show();
			config_dialog_shown = true;
			connect(configDlg, TQT_SIGNAL(destroyed()), this, TQT_SLOT(observeConfigDlg()));
			connect(configDlg, TQT_SIGNAL(openHelp()), this, TQT_SLOT(slotHelp()));
			connect(configDlg, TQT_SIGNAL(openKNotify()), this, TQT_SLOT(showConfigureNotificationsDialog()));
		}
		else {
			KPassivePopup::message(i18n("WARNING"), i18n("Cannot find any schemes."),
					       SmallIcon("messagebox_warning", 20), this,
					       i18n("Warning").ascii(), 15000);
		}
	} else {
		configDlg->setWindowState((configDlg->windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
		configDlg->setActiveWindow();
	}

	kdDebugFuncOut(trace);
}

/*!
 * Starts the notification configure dialog of tdepowersave.
 */
void tdepowersave::showConfigureNotificationsDialog() {
	kdDebugFuncIn(trace);

	KNotifyDialog::configure(this);

	kdDebugFuncOut(trace);
}

/*!
 * Load the icons (from filesystem) for the kicker applet to \ref pixmap .
 * To reduce the systemload the icons are only reloaded if \ref pixmap_name
 * is changed.
 */
void tdepowersave::loadIcon(bool forceReload){
	kdDebugFuncIn(trace);

	TQString pixmap_name_tmp = "NONE";

	BatteryCollection *primary = hwinfo->getPrimaryBatteries();

	if ( !hwinfo->isOnline() ) {
		pixmap_name_tmp = TQString("ERROR");
	}
	else if (hwinfo->getAcAdapter() || primary->getBatteryState() == BAT_NONE) {
		icon_set_colored = false;

		if (primary->getBatteryState() == BAT_NONE || (primary->getRemainingPercent() < 0 ||
		    primary->getRemainingPercent() >= 99))
			pixmap_name_tmp = TQString("laptoppower");
		else
			pixmap_name_tmp = TQString("laptopcharge");
	}
	else {
		switch(primary->getBatteryState()) {
			case BAT_CRIT:
			case BAT_LOW:
				if (icon_BG_is_colored) pixmap_name_tmp = TQString("laptopbattery");
				else pixmap_name_tmp = TQString("laptopbatteryRED");
				icon_BG_is_colored = !icon_BG_is_colored;
				icon_set_colored = true;
				break;
			case BAT_WARN:
				if (icon_BG_is_colored) pixmap_name_tmp = TQString("laptopbattery");
				else pixmap_name_tmp = TQString("laptopbatteryORANGE");
				icon_BG_is_colored = !icon_BG_is_colored;
				icon_set_colored = true;
				break;
			default:
				// if battery is discharging and not in warning, low or critical state
				pixmap_name_tmp = TQString("laptopbattery");
				icon_set_colored = false;
				icon_BG_is_colored = false;
		}

		if (icon_set_colored){
			icon_state_changed = false;
			BAT_WARN_ICON_Timer->start(BAT_icon_BG_intervall, true);
		}
	}

	// reload icon only if new icon selected
	if ((pixmap_name_tmp != pixmap_name) || (forceReload)) {
		pixmap_name = pixmap_name_tmp;
		if (pixmap_name.startsWith("ERROR")) {
			pixmap = SmallIcon("laptoppower", isShown() ? width() : 22, TDEIcon::DisabledState);
		}
		else {
			pixmap = SmallIcon(pixmap_name, isShown() ? width() : 22);
		}
	}

	kdDebugFuncOut(trace);
}


/*!
 * This function draw the battery-capacity (colored field) to the icon.
 * Here also counted the white pixel in the icon-files. Since the icons are
 * the same and white pixel only in the rectangle of the icon, the white pixel
 * stored in \ref countWhiteIconPixel only one time.
 */
void tdepowersave::drawIcon(){
	kdDebugFuncIn(trace);

	BatteryCollection *primary = hwinfo->getPrimaryBatteries();

	TQImage image = pixmap.convertToImage();
	int w = image.width();
	int h = image.height();
	int x, y;
	countWhiteIconPixel = 0;

	if((pixmap_name.contains("laptopbattery") || pixmap_name.contains("charge")) &&
	    countWhiteIconPixel == 0) {
		for (x = 0; x < w; x++)
			for (y = 0; y < h; y++)
				if(TQColor(image.pixel(x, y)) == TQt::white) countWhiteIconPixel++;
	}

	int c = (countWhiteIconPixel * primary->getRemainingPercent()) / 100;

	if (c > 0) {
		uint ui;
		TQRgb Rgb_set;

		if (hwinfo->getAcAdapter()) {
			Rgb_set = tqRgb(0x00, 0xff, 0x00); //green
		}
		else {
			switch(primary->getBatteryState()) {
				case BAT_CRIT:
				case BAT_LOW:
					Rgb_set = tqRgb(0xff, 0x00, 0x00);//red
					break;
				case BAT_WARN:
					Rgb_set = tqRgb(0xff, 0x55, 0x00); //orange
					break;
				default:
					Rgb_set = tqRgb(0x00, 0xff, 0x00); //green
			}
		}
		if (image.depth() <= 8) {
			ui = image.numColors();
			image.setNumColors(ui + 1);
			image.setColor(ui, Rgb_set);
		}
		ui = 0xff000000 | Rgb_set;

		for (y = h - 1; y >= 0; y--) {
			for (x = 0; x < w ; x++) {
				if(TQColor(image.pixel(x, y)) == TQt::white) {
					image.setPixel(x, y, ui);
					c--;
					if (c <= 0) goto quit;
				}
			}
		}
	}
quit:
	if (isShown()) {
		image = image.smoothScale(width(), height());
	}
	fullIcon.convertFromImage(image);
	setPixmap(fullIcon);

	kdDebugFuncOut(trace);
}

/*!
* By this function we fill and update the Tooltip for the icon in the kicker applet.
* The content of the tooltip alway updated, if something change.
* \todo Check if the tooltip also updated if mouse \b is over the icon, if not we maybe
*	should implement this.\n If it is possible we should update the tooltip permanently
*	while the mouse cursor is over the widget
*/
void tdepowersave::updateTooltip(){
	kdDebugFuncIn(trace);

	BatteryCollection *primary = hwinfo->getPrimaryBatteries();
	int percent = primary->getRemainingPercent();
	int minutes = primary->getRemainingMinutes();
	int charging_state = primary->getChargingState();

	TQString tmp, num3;
	num3.setNum(minutes % 60);
	num3 = num3.rightJustify(2, '0');

	if ( !hwinfo->isOnline() ){
		tmp = i18n("No information about battery and AC status available");
	}
	else if (hwinfo->getAcAdapter()) {
		if (percent == 100) tmp = i18n("Plugged in -- fully charged");
		// assume that no battery is there
		else {
			if ((percent < 0 && minutes < 0) || primary->getBatteryState() == BAT_NONE) {
				tmp = i18n("Plugged in");
			}
			else if (minutes > 0){
				if (charging_state == CHARGING)
					tmp = i18n("Plugged in -- %1% charged (%2:%3 h until full "
						   "charged)").arg(percent).arg(minutes / 60).arg(num3);
				else
					tmp = i18n("Plugged in -- %1% charged (%2:%3 remaining hours)")
						   .arg(percent).arg(minutes / 60).arg(num3);
			}
			else if (charging_state == CHARGING && hwinfo->hasAPM()) {
				tmp = i18n("Plugged in -- %1% charged").arg(percent);
			}
			else{
				if (percent == -1) tmp = i18n("Plugged in -- no battery");
				else tmp = i18n("Plugged in -- %1% charged").arg(percent);
			}
		}
	} else{
		if (minutes >= 0){
			tmp = i18n("Running on batteries -- %1% charged (%2:%3 hours remaining)")
				   .arg(percent).arg(minutes / 60).arg(num3);
		}
		else {
			tmp = i18n("Running on batteries -- %1% charged").arg(percent);
		}
	}
	// add string whether battery is charging, but only if < 100% to avoid
	// stupid tooltip message on machines which always with 100% and on AC
	// are charging, as e.g. Sony Vaio FS vgn-fs115b
	if (charging_state == CHARGING && percent < 100)
		tmp += i18n(" -- battery is charging");

	TQToolTip::add(this, tmp);

	kdDebugFuncOut(trace);
}

/*!
 * \b TQT_SLOT to starts the Yast2-power-management module. This called by the menuentry
 * with ID \ref YAST_MODULE_MENU_ID, named "Start YaST2 Power Management Module".
 * It create a new TDEProcess and execute "/sbin/yast2 power-management" with tdesu.
 */
void tdepowersave::do_config(){
	kdDebugFuncIn(trace);

	#ifdef ENABLE_YAST_ENTRY
	delete yast2;

	yast2 = new TDEProcess;
	*yast2 << "tdesu" << "--nonewdcop" << "/sbin/yast2" << "power-management";

	connect(yast2, TQT_SIGNAL(processExited(TDEProcess *)),
	         TQT_SLOT(slotConfigProcessExited(TDEProcess *)));
	if(!yast2->start(TDEProcess::NotifyOnExit))
	{
		delete yast2;
		yast2 = NULL;
	}

	kdDebugFuncOut(trace);
	#else
	kdDebugFuncOut(trace);
	return;
	#endif
}

/*!
 * \b TQT_SLOT to open the tdepowersave help
 */
void tdepowersave::slotHelp()
{
    kapp->invokeHelp( "", "tdepowersave" );
}

/*!
 * \b TQT_SLOT to open the tdepowersave About dialog
 */
void tdepowersave::slotAbout()
{
 	TDEAboutApplication a( this );
        a.exec();
}

/*!
 * \b TQT_SLOT to open the website to report bugs
 */
void tdepowersave::slotReportBug()
{
#ifdef DISTRO_IS_SUSE
 #ifdef DISTRO_IS_SLES_SLED
	kapp->invokeBrowser("https://bugzilla.novell.com/");
 #else
	kapp->invokeBrowser("http://en.opensuse.org/Submitting_Bug_Reports");
 #endif
#else
 #ifdef DISTRO_IS_ALTLINUX
	kapp->invokeBrowser("http://bugzilla.altlinux.org/");
 #else
  #ifdef DISTRO_IS_UBUNTU
	kapp->invokeBrowser("https://launchpad.net/distros/ubuntu/+bugs");
  #else
   #ifdef DISTRO_IS_PARDUS
	kapp->invokeBrowser("http://bugs.pardus.org.tr/");
   #else
	kapp->invokeBrowser("http://sourceforge.net/tracker/?group_id=124576&atid=700009");
   #endif
  #endif
 #endif
#endif
}

/*!
 * \b TQT_SLOT to set the icon background on/off if battery is in critical, low or warning-state. Within
 * this function we set \ref icon_state_changed to true and call \ref redrawPixmap() to redraw the
 * kickerapplet icon and create a icon with blinking background. \n \n
 * The slot called by the TQTimer \ref BAT_WARN_ICON_Timer . The interval of the timer is defined
 * trough \ref BAT_icon_BG_intervall and starts here: \ref loadIcon() .
 */
void tdepowersave::do_setIconBG(){
	kdDebugFuncIn(trace);

	if (icon_set_colored) icon_state_changed = true;
	redrawPixmap();

	kdDebugFuncOut(trace);
}
/*!
 * \b TQT_SLOT to enable/disable the autosuspend.
 */
void tdepowersave::do_setAutosuspend(){
	kdDebugFuncIn(trace);

	if(!contextMenu()->isItemChecked(AUTOSUSPEND_MENU_ID)) {
		autoSuspend->stop();
		contextMenu()->setItemChecked(AUTOSUSPEND_MENU_ID, true);
	}
        else {
		if(settings->autoSuspend) {
			contextMenu()->setItemChecked(AUTOSUSPEND_MENU_ID, false);
			setAutoSuspend(false);
		}
		else {
			contextMenu()->setItemVisible(AUTOSUSPEND_MENU_ID, false);
			contextMenu()->setItemChecked(AUTOSUSPEND_MENU_ID, false);
			contextMenu()->setItemVisible(AUTOSUSPEND_SEPARATOR_MENU_ID, false);
		}
        }

	kdDebugFuncOut(trace);
}

/*!
 * \b TQT_SLOT which called if the \ref configDlg is destroyed. We set within this SLOT
 * \ref config_dialog_shown to false.
 * TODO: check if we maybe should force here the current default scheme depending on the AC/battery state
 */
void tdepowersave::observeConfigDlg(){
	kdDebugFuncIn(trace);

	// reload general settings
	settings->load_general_settings();
	// set the battery warning levels - all other general settings don't need to
	// get set, since we check the settings only on events.
	hwinfo->setPrimaryBatteriesWarningLevel(settings->batteryWarningLevel,
						settings->batteryLowLevel,
						settings->batteryCriticalLevel);

	// reload the maybe changed scheme settings
	settings->load_scheme_settings( settings->currentScheme );
	// set the scheme
	setSchemeSettings();

	config_dialog_shown=false;

	kdDebugFuncOut(trace);
}

/*!
 * \b TQT_SLOT which called from \ref do_config() if the 'tdesu yast2' TDEProcess exited.
 * This function control the return value and display if needed a errormessage on failure.
 */
void tdepowersave::slotConfigProcessExited(TDEProcess *proc){
	kdDebugFuncIn(trace);

	#ifdef ENABLE_YAST_ENTRY
	if (proc->normalExit()){
		if (proc->exitStatus() != 0 && proc->exitStatus() != 16){
			KPassivePopup::message( i18n("WARNING"),
						i18n("Could not start YaST Power Management Module. "
						     "Check if it is installed."),
						SmallIcon("messagebox_warning", 20), this,
						i18n("Warning"), 15000);
		}
	}
	else{
		KPassivePopup::message( i18n("WARNING"),
					i18n("Could not start YaST Power Management Module. "
					     "Check if it is installed."),
					SmallIcon("messagebox_warning", 20), this, i18n("Warning"), 15000);
	}

	kdDebugFuncOut(trace);
	#else
	kdDebugFuncOut(trace);
	return;
	#endif
}

/*!
 * \b TQT_SLOT to send the command for "suspend to disk" to TDE hardware library.
 * If there is a error while "suspend to disk" the user get e messagebox.
 * This function need a power management backend in TDE hardware library for "suspend to disk".
 * \return boolean with the result of the operation
 * \retval true if successful
 * \retval false if command not supported or if powersaved not running
 */
bool tdepowersave::do_suspend2disk(){
	kdDebugFuncIn(trace);

	if (suspend.suspend2disk) {
		if (suspend.suspend2disk_allowed || suspend.suspend2disk_allowed == -1) {
			calledSuspend = SUSPEND2DISK;
			if (!handleMounts(true)) {
				kdWarning() << "Could not umount ..." << endl;
				calledSuspend = -1;
				kdDebugFuncOut(trace);
				return false;
			}

			if(settings->lockOnSuspend) {
				display->lockScreen( settings->lockmethod );
			}

			autoSuspend->stop();
			autoDimm->stop();
			notifySuspend(calledSuspend);
			bool ret = hwinfo->suspend(SUSPEND2DISK);

			if (ret) {
				kdDebugFuncOut(trace);
				return true;
			} else {
				KPassivePopup::message( i18n("WARNING"),i18n("Hibernation failed"),
							SmallIcon("messagebox_warning", 20), this,
							i18n("Warning").ascii(), 15000);
				kdDebugFuncOut(trace);
				return false;
			}
		} else {
			KPassivePopup::message( i18n("WARNING"),
						i18n("Hibernation disabled by administrator."),
						SmallIcon("messagebox_warning", 20),
						this, i18n("Warning").ascii(), 15000);
			this->contextMenu()->setItemEnabled(SUSPEND2DISK_MENU_ID, false);
			kdDebugFuncOut(trace);
			return false;
		}
	} else {
		kdWarning() << "This machine does not provide hibernation state" << endl;
		kdDebugFuncOut(trace);
		return false;
	}
}

/*!
 * \b TQT_SLOT to send the command for "suspend to RAM" to the TDE hardware library.
 * If there is a error while "suspend to RAM" the user get a messagebox.
 * This function need a power management backend in TDE hardware library for "suspend to RAM".
 * \return boolean with the result of the operation
 * \retval true if successful
 * \retval false if command not supported or if powersaved not running
 */
bool tdepowersave::do_suspend2ram(){
	kdDebugFuncIn(trace);

	if (suspend.suspend2ram) {
		if (suspend.suspend2ram_allowed || suspend.suspend2ram_allowed == -1) {
			calledSuspend = SUSPEND2RAM;
			if (!handleMounts(true)) {
				kdWarning() << "Could not umount ..." << endl;
				calledSuspend = -1;
				kdDebugFuncOut(trace);
				return false;
			}

			if(settings->lockOnSuspend) {
				display->lockScreen( settings->lockmethod );
			}

			autoSuspend->stop();
			autoDimm->stop();
			notifySuspend(calledSuspend);
			bool ret = hwinfo->suspend(SUSPEND2RAM);

			if (ret) {
				kdDebugFuncOut(trace);
				return true;
			} else {
				KPassivePopup::message( i18n("WARNING"),i18n("Sleep mode failed"),
							SmallIcon("messagebox_warning", 20), this,
							i18n("Warning").ascii(), 15000);
				kdDebugFuncOut(trace);
				return false;
			}
		} else {
			KPassivePopup::message( i18n("WARNING"),
						i18n("Sleep mode disabled by administrator."),
						SmallIcon("messagebox_warning", 20), this,
						i18n("Warning").ascii(), 15000);
			this->contextMenu()->setItemEnabled(SUSPEND2RAM_MENU_ID, false);
			kdDebugFuncOut(trace);
			return false;
		}
	} else {
		kdWarning() << "This machine does not provide Sleep state" << endl;
		kdDebugFuncOut(trace);
		return false;
	}
}

/*!
 * \b TQT_SLOT to send the command for "freeze" to the TDE hardware library.
 * If there is a error while "freeze" the user get e messagebox.
 * This function need a power management backend in TDE hardware library for "freeze".
 * \return boolean with the result of the operation
 * \retval true if successful
 * \retval false if command not supported or if powersaved not running
 */
bool tdepowersave::do_freeze(){
	kdDebugFuncIn(trace);

	if (suspend.freeze) {
		if (suspend.freeze_allowed || suspend.freeze_allowed == -1) {
			calledSuspend = FREEZE;
			if (!handleMounts(true)) {
				kdWarning() << "Could not umount ..." << endl;
				calledSuspend = -1;
				kdDebugFuncOut(trace);
				return false;
			}

			if(settings->lockOnSuspend) {
				display->lockScreen( settings->lockmethod );
			}

			autoSuspend->stop();
			autoDimm->stop();
			notifySuspend(calledSuspend);
			bool ret = hwinfo->suspend(FREEZE);

			if (ret) {
				kdDebugFuncOut(trace);
				return true;
			} else {
				KPassivePopup::message( i18n("WARNING"),i18n("Freeze failed"),
							SmallIcon("messagebox_warning", 20), this,
							i18n("Warning").ascii(), 15000);
				kdDebugFuncOut(trace);
				return false;
			}
		} else {
			KPassivePopup::message( i18n("WARNING"),i18n("Freeze disabled by administrator."),
						SmallIcon("messagebox_warning", 20), this,
						i18n("Warning").ascii(), 15000);
			this->contextMenu()->setItemEnabled(FREEZE_MENU_ID, false);
			kdDebugFuncOut(trace);
			return false;
		}
	} else {
		kdWarning() << "This machine does not provide freeze suspend state" << endl;
		kdDebugFuncOut(trace);
		return false;
	}
}

/*!
 * \b TQT_SLOT to send the command for "stand-by" to the TDE hardware library.
 * If there is a error while "stand-by" the user get e messagebox.
 * This function need a power management backend in TDE hardware library for "stand-by".
 * \return boolean with the result of the operation
 * \retval true if successful
 * \retval false if command not supported or if powersaved not running
 */
bool tdepowersave::do_standby(){
	kdDebugFuncIn(trace);

	if (suspend.standby) {
		if (suspend.standby_allowed || suspend.standby_allowed == -1) {
			calledSuspend = STANDBY;
			if (!handleMounts(true)) {
				kdWarning() << "Could not umount ..." << endl;
				calledSuspend = -1;
				kdDebugFuncOut(trace);
				return false;
			}

			if(settings->lockOnSuspend) {
				display->lockScreen( settings->lockmethod );
			}

			autoSuspend->stop();
			autoDimm->stop();
			notifySuspend(calledSuspend);
			bool ret = hwinfo->suspend(STANDBY);

			if (ret) {
				kdDebugFuncOut(trace);
				return true;
			} else {
				KPassivePopup::message( i18n("WARNING"),i18n("Standby failed"),
							SmallIcon("messagebox_warning", 20), this,
							i18n("Warning").ascii(), 15000);
				kdDebugFuncOut(trace);
				return false;
			}
		} else {
			KPassivePopup::message( i18n("WARNING"),i18n("Standby disabled by administrator."),
						SmallIcon("messagebox_warning", 20), this,
						i18n("Warning").ascii(), 15000);
			this->contextMenu()->setItemEnabled(STANDBY_MENU_ID, false);
			kdDebugFuncOut(trace);
			return false;
		}
	} else {
		kdWarning() << "This machine does not provide standby suspend state" << endl;
		kdDebugFuncOut(trace);
		return false;
	}
}

/*!
 * \b TQT_SLOT to send check if we should display the warning dialog and display
 * the dialog if needed or call directly autosuspend after the signal
 * \ref autosuspend::inactivityTimeExpired was recieved.
 */
void tdepowersave::do_autosuspendWarn() {
	kdDebugFuncIn(trace);

	// Verify that the desired suspend action is allowed before displaying the dialog
	SuspendStates suspend = hwinfo->getSuspendSupport();
	bool allowed = false;
	if(settings->autoInactiveAction == "Hibernate") {
		if ( suspend.suspend2disk && (suspend.suspend2disk_allowed || suspend.suspend2disk_allowed == -1)) {
			allowed = true;
		}
	}
	else if (settings->autoInactiveAction == "Sleep") {
		if( suspend.suspend2ram && (suspend.suspend2ram_allowed || suspend.suspend2ram_allowed == -1)) {
			allowed = true;
		}
	}
	else if (settings->autoInactiveAction == "Freeze") {
		if ( suspend.freeze && (suspend.freeze_allowed || suspend.freeze_allowed == -1)) {
			allowed = true;
		}
	}
	else if (settings->autoInactiveAction == "Standby") {
		if ( suspend.standby && (suspend.standby_allowed || suspend.standby_allowed == -1)) {
			allowed = true;
		}
	}

	if (allowed) {
		if (settings->autoSuspendCountdown && (settings->autoSuspendCountdownTimeout > 0)) {
			// we have to display the warn dialog
			if(!contextMenu()->isItemChecked(AUTOSUSPEND_MENU_ID)) {
				TQString message;

				countdown = new countDownDialog(settings->autoSuspendCountdownTimeout);

				if(settings->autoInactiveAction == "Hibernate") {
					countdown->setPixmap("suspend2disk");
				} else if (settings->autoInactiveAction == "Sleep") {
					countdown->setPixmap("suspend2ram");
				} else if (settings->autoInactiveAction == "Freeze") {
					countdown->setPixmap("suspend2ram");
				} else if (settings->autoInactiveAction == "Standby") {
					countdown->setPixmap("standby");
				} else {
					countdown->setPixmap("tdepowersave");
				}

				// TODO: rework this after translation round for openSUSE 10.3 !
				message = i18n("Inactivity detected.") + " " +
					i18n("To stop the %1 press the 'Cancel' button before the countdown "
					"expires.").arg(i18n("Autosuspend")) + "\n\n" +
					i18n("The computer autosuspend in: ");

				countdown->setMessageText(message);

				connect(countdown, TQT_SIGNAL(dialogClosed(bool)), this, TQT_SLOT(do_autosuspend(bool)));
				countdown->showDialog();
			}
		}
		else {
			// call directly autosuspend
			do_autosuspend(false);
		}
	}

	kdDebugFuncOut(trace);
}

/*!
 * \b TQT_SLOT to send the related suspend command for autosuspend
 * \param  cancel boolean with info if the autosuspend should get canceled
 * \return boolean with the result of the operation
 * \retval true if successful
 * \retval false if command not supported or on any other error
 * \todo	add check if the requested command is supported before send and
 *		add message for this case to tell that maybe changed config!
 */
bool tdepowersave::do_autosuspend(bool cancel) {
	kdDebugFuncIn(trace);

	// TODO: check if this is really needed, it get called also on the suspend methodes
	autoSuspend->stop();

	if (!cancel) {
		if(!settings->disableNotifications) {
			KNotifyClient::event( this->winId(), "autosuspend_event",
					i18n("System is going into suspend mode now"));
		}

		if(settings->autoSuspend && !contextMenu()->isItemChecked(AUTOSUSPEND_MENU_ID)) {
			if(settings->autoInactiveAction == "Hibernate") {
				return do_suspend2disk();
			} else if (settings->autoInactiveAction == "Sleep") {
				return do_suspend2ram();
			} else if (settings->autoInactiveAction == "Freeze") {
				return do_freeze();
			} else if (settings->autoInactiveAction == "Standby") {
				return do_standby();
			} else {
				return false;
			}
		} else {
			return false;
		}
	} else {
		kdDebug() << "The autosuspend was canceled (via the cancel dialog), start again." << endl;
		setAutoSuspend(false);
		return false;
	}
}

/*!
 * \b TQT_SLOT to dimm the display down to the configured level if the signal
 * \ref autodimm::inactivityTimeExpired was recieved.
 * \param
 * \return boolean with the result of the operation
 * \retval true 	if successful
 * \retval false 	else
 */
void tdepowersave::do_downDimm() {
	kdDebugFuncIn(trace);

	if (hwinfo->supportBrightness()) {
		if (!AUTODIMM_Timer->isActive()) {
			int dimmToLevel = (int)((float)hwinfo->getMaxBrightnessLevel()*((float)settings->autoDimmTo/100.0));

			// check if we really need to dimm down
			if (dimmToLevel < hwinfo->getCurrentBrightnessLevel()) {
				int steps = hwinfo->getCurrentBrightnessLevel() - dimmToLevel;
				int timePerStep = (1500 / steps);

				autoDimmDown = true;

				AUTODIMM_Timer = new TQTimer(this);
				connect(AUTODIMM_Timer, TQT_SIGNAL(timeout()), this, TQT_SLOT(do_dimm()));
				AUTODIMM_Timer->start(timePerStep, false);
			} else {
				kdWarning() << "Don't dimm down, current level is already lower than requested Level" << endl;
			}
		} else {
			// wait until the timer is stopped, try later!
			TQTimer::singleShot(1500, this, TQT_SLOT(do_downDimm()));
		}
	}

	kdDebugFuncOut(trace);
}

/*!
 * \b TQT_SLOT to dimm the display up to the configured level if the signal
 * \ref autodimm::UserIsActiveAgain was recieved.
 * \param
 * \return boolean with the result of the operation
 * \retval true 	if successful
 * \retval false 	else
 */
void tdepowersave::do_upDimm() {
	kdDebugFuncIn(trace);

	//NOTE we go back to the value of the scheme and not the last on, to reduce trouble with the scheme

	if (hwinfo->supportBrightness()) {
		if (!AUTODIMM_Timer->isActive()) {
			int dimmToLevel = (int)((float)hwinfo->getMaxBrightnessLevel()*((float)settings->brightnessValue/100.0));

			// check if we really need to dimm up
			if (dimmToLevel > hwinfo->getCurrentBrightnessLevel()) {
				int steps = dimmToLevel - hwinfo->getCurrentBrightnessLevel();
				int timePerStep = (750 / steps);

				autoDimmDown = false;

				AUTODIMM_Timer = new TQTimer(this);
				connect(AUTODIMM_Timer, TQT_SIGNAL(timeout()), this, TQT_SLOT(do_dimm()));
				AUTODIMM_Timer->start(timePerStep, false);

				// start autodimm again
				setAutoDimm(false);
			} else {
				kdWarning() << "Don't dimm up, current level is already above requested Level" << endl;
			}
		} else {
			// wait until the timer is stopped, try later!
			TQTimer::singleShot(750, this, TQT_SLOT(do_downDimm()));
		}
	}

	kdDebugFuncOut(trace);
}


/*!
 * \b TQT_SLOT to dimm the display down
 * \return boolean with the result of the operation
 * \retval true 	if successful
 * \retval false 	else
 */
void tdepowersave::do_dimm() {
	kdDebugFuncIn(trace);

	int current = hwinfo->getCurrentBrightnessLevel();

	if (autoDimmDown) {
		// dimm the display down
		if (current > 0 &&
		    current > ((int)((float)hwinfo->getMaxBrightnessLevel()*((float)settings->autoDimmTo/100.0))-1)) {
			hwinfo->setBrightness((current -1) , -1);
		} else {
			AUTODIMM_Timer->stop();

			// start checking if the user get active again
			// NOTE: we start this here because the X-Server detect brightness changes as
			// 	 User activity --> FUCKING STUPID PIECE OF SHIT
			autoDimm->startCheckForActivity();
		}
	} else {
		// dimm the display up
		if (current < ((int)((float)hwinfo->getMaxBrightnessLevel()*((float)settings->brightnessValue/100.0))-1)) {
			hwinfo->setBrightness((current +1) , -1);
		} else {
			AUTODIMM_Timer->stop();
		}
	}

	kdDebugFuncOut(trace);
}

/*!
 * Function handle umount/remount external storage media before/after
 * suspend.
 * \param suspend 	boolean with info if the machine go into suspend or not
 * \return 		result of the operation
 * \retval true		if all was successful
 * \retval false	if not
 */
bool tdepowersave::handleMounts( bool suspend ) {
	if (trace) kdDebug() << funcinfo << "IN: " << "called suspend: " << suspend << endl;

	bool _ret = false;
	TQString _errormsg;

	if (settings->unmountExternalOnSuspend) {
		TQString _method;
		DCOPRef dcop_ref = DCOPRef( "kded", "mediamanager" );

		if (suspend) {
			_method = "unmountAllSuspend()";
		} else {
			_method = "remountAllResume()";
		}
		DCOPReply reply = dcop_ref.call(_method.latin1());
		if ( reply.isValid() ) {
			reply.get(_errormsg);
			if (_errormsg.isEmpty()) {
				kdDebugFuncOut(trace);
				return true;
			} else {
				kdError() << "ERROR while umount/remount partitions: " << _errormsg << endl;
			}
		} else {
			kdWarning() << "Could not umount external storage partitions." << endl;
		}

	} else {
		kdDebugFuncOut(trace);
		return true;
	}

	// this is only needed for suspend case and an error ...
	// on resume a simple error msg should be enough
	if (!_ret && suspend) {
		// handle error case
		TQString _msg;
		TQString _e_msg;
		TQString _suspend;

		if (!_errormsg.isEmpty()) {
			_e_msg = _errormsg;
		} else {
			_e_msg = i18n("Could not call DCOP interface to umount external media.");
		}

		// ugly: need qt-tags because mediamanager can return html formated strings !!!
		_msg = 	"<qt>" +
			i18n("Could not umount external media before suspend/standby. \n "
			    "(Reason: %1)\n \n Would you like to continue suspend/standby "
			    "anyway? \n(Warning: Continue suspend can cause data loss!)").arg(_e_msg) +
			"</qt>";

		_suspend = getSuspendString(calledSuspend);

		int answer = KMessageBox::questionYesNo( 0, _msg,
							 i18n("Error while prepare %1").arg(_suspend),
							 i18n("Suspend anyway"), i18n("Cancel suspend"),
							 "ignoreMountOnSuspend");

		if (answer == KMessageBox::Yes) {
			_ret = true;
		}
	}

	kdDebugFuncOut(trace);
	return _ret;
}

/*!
 * Handle the event for the power button and call the related action.
 */
void tdepowersave::handlePowerButtonEvent( ) {
	kdDebugFuncIn(trace);

	/* Only go to suspend on button event if we already resumed successful.
	   This should solve problems if we get may a event for the powerbutton
	   if there machine was waked up via power button. */
	if (calledSuspend == -1) {
		handleActionCall(settings->powerButtonAction, settings->powerButtonActionValue);
	}

	kdDebugFuncOut(trace);
}

/*!
 * Handle the event for the suspend2ram/sleep button and call the related action.
 */
void tdepowersave::handleSleepButtonEvent() {
	kdDebugFuncIn(trace);

	// Only go to suspend on button event if we already resumed successful.
	if (calledSuspend == -1) {
		handleActionCall(settings->sleepButtonAction, -1);
	}

	kdDebugFuncOut(trace);
}

/*!
 * Handle the event for the suspend2disk (hibernater) button and call the related action.
 */
void tdepowersave::handleS2DiskButtonEvent() {
	kdDebugFuncIn(trace);

	// Only go to suspend on button event if we already resumed successful.
	if (calledSuspend == -1) {
		handleActionCall(settings->s2diskButtonAction, -1);
	}

	kdDebugFuncOut(trace);
}

/*!
 * \b TQT_SLOT to handle the lidclose event. If the screen get locked
 * depends on the user specific settings.
 * \param closed 	boolean with info if the lid is closed or not
 */
void tdepowersave::handleLidEvent( bool closed ){
	if (trace) kdDebug() << funcinfo << "IN: " << "Lid closed? " << closed << endl;

	if (closed) {
		// get new general settings! This could maybe removed if we
		// could be shure, that the settings are actuall
		settings->load_general_settings();

		// handle screen lock
		if (settings->lidcloseAction < 0) {
			if(settings->lockOnLidClose) {
				if(!display->lockScreen( settings->lockmethod )) {
					KPassivePopup::message( i18n("WARNING"),
								i18n("Could not lock the screen. There may "
								     "be a problem with the selected \nlock "
								     "method or something else."),
								SmallIcon("messagebox_warning", 20), this,
								i18n("Warning").ascii(), 10000);

				}
			}
			if(settings->forceDpmsOffOnLidClose) {
				display->forceDPMSOff();
			}
		} else {
			// handle lock action
			if (hwinfo->currentSessionIsActive()) {
				handleActionCall(settings->lidcloseAction, settings->lidcloseActionValue);
			} else {
				kdWarning() << "Session is not active, don't react on lidclose "
					    << "event with a action call (like e.g. Suspend)!" << endl;
			}
		}

		if(!settings->disableNotifications)
			KNotifyClient::event( this->winId(), "lid_closed_event", i18n("The Lid was closed."));
	} else {
		if(settings->forceDpmsOffOnLidClose) {
			// reset the scheme settings to avoid problems related to call xset on lidclose
			setSchemeSettings();
		}

		if (settings->lockOnLidClose) {
			activateLoginScreen();
		}

		if(!settings->disableNotifications)
			KNotifyClient::event( this->winId(), "lid_opened_event", i18n("The Lid was opened."));
	}

	kdDebugFuncOut(trace);
}

/*!
 * \b TQT_SLOT to show the login dialog if the desktop was locked before the suspend.
 */
void tdepowersave::activateLoginScreen(){
	kdDebugFuncIn(trace);

        // get new general settings! This could maybe removed if we
	// could be shure, that the settings are actuall
	settings->load_general_settings();

	if(settings->timeToFakeKeyAfterLock >= 0) {
		TQTimer::singleShot(settings->timeToFakeKeyAfterLock, display, TQT_SLOT(fakeShiftKeyEvent()));
	}

	kdDebugFuncOut(trace);
}

/*!
 * \b TQT_SLOT to set the current suspend type for later use.
 */
void tdepowersave::setSuspendType( TQString suspendtype){
	kdDebugFuncIn(trace);

	suspendType = suspendtype;

	kdDebugFuncOut(trace);
}

/*!
 * \b TQT_SLOT which called if tdepowersave is exited by the user. In this case the user
 * is asked through a yes/no box if "tdepowersave start automatically on log in" and the
 * result is written to the KDE configfile.
 */
void tdepowersave::_quit (){
	kdDebugFuncIn(trace);

	// set the KDE-Settings back to user default
	if(getenv("TDE_FULL_SESSION")) {
		// first try to call the KDE method via DCOP to reset, if not fall back
		if (!display->resetKDEScreensaver()) {
			settings->load_kde();
			// reset to KDE screensaver settings
			display->blankOnlyScreen(false);
			if(!settings->kde->enabled) display->setScreenSaver(false);
			else display->setScreenSaver(true);

			if(!settings->kde->displayEnergySaving) display->setDPMS(false);
			else display->setDPMS(true);

			display->has_DPMS = display->setDPMSTimeouts( settings->kde->displayStandby,
								      settings->kde->displaySuspend,
								      settings->kde->displayPowerOff);
		}
	}

	// set, if this is a GNOME session, XScreensaver settings back to user default
	TQString session = getenv("DESKTOP_SESSION");
	if(session.startsWith("gnome")) {
		display->resetXScreensaver();
	}

	if(!settings->autostartNeverAsk) {
		TQString tmp1 = i18n ("Start tdepowersave automatically when you log in?");
		int tmp2 = KMessageBox::questionYesNo ( 0, tmp1, i18n("Question"),
							i18n("Start Automatically"), i18n("Do Not Start"));
		config->setGroup("General");
		config->writeEntry ("Autostart", tmp2 == KMessageBox::Yes);
		config->sync ();
	}

	kdDebugFuncOut(trace);
}

/*!
 * \b TQT_SLOT called if the user select a 'CPU Frequency Policy' from the menu ( \ref CPUFREQ_MENU_ID ).
 */
void tdepowersave::do_setSpeedPolicy(int menu_id){
	if (trace) kdDebug() << funcinfo << "IN: " << "menu_id/set policy to: " << menu_id << endl;

	if(!hwinfo->setCPUFreq((cpufreq_type)menu_id, settings->cpuFreqDynamicPerformance)) {
		KPassivePopup::message(i18n("WARNING"),
				 i18n("CPU Freq Policy %1 could not be set.").arg(speed_menu->text(menu_id)),
				 SmallIcon("messagebox_warning", 20), this, i18n("Warning").ascii(), 10000);
	} else {
		hwinfo->checkCurrentCPUFreqPolicy();
		update();
	}

	kdDebugFuncOut(trace);
}

/*!
 * \b TQT_SLOT called if the user select a scheme from the menu. If there is any errormessage
 * while try to set the selected scheme, the user get a messagebox with info.
 */
void tdepowersave::do_setActiveScheme( int i ){
	if (trace) kdDebug() << funcinfo << "IN: " << "set scheme to: " << i << endl;

	if(!settings->schemes[i].isEmpty() && (settings->schemes[i] != settings->currentScheme)) {
		for (int x = 0; x < (int) scheme_menu->count(); x++){
			if (x == i)
				scheme_menu->setItemChecked(x, true);
			else
				scheme_menu->setItemChecked(x, false);
		}
		settings->load_scheme_settings( settings->schemes[i]);
		setSchemeSettings();
		notifySchemeSwitch();
 	} else if (!settings->schemes[i]){
		KPassivePopup::message( i18n("WARNING"),
					i18n("Scheme %1 could not be activated.").arg(scheme_menu->text(i)),
					SmallIcon("messagebox_warning", 20), this, i18n("Warning").ascii(), 5000);
	}

	kdDebugFuncOut(trace);
}

/*!
 * This function is invoked if something has to be updated. This including also menu entries.
 * If the battery is in warning state (and powersave set pdaemon->send_battery_state_change_message)
 * the function pop-up a messagebox.
 */
void tdepowersave::update(){
	kdDebugFuncIn(trace);

	int redraw_pixmap = 0;
	TQString justMins;

	/* need to redraw pixmap in toolbar */
	if (hwinfo->update_info_ac_changed){
		redraw_pixmap = 1;
	}
	if (!hwinfo->isOnline()){
		this->contextMenu()->setItemVisible(SUSPEND2DISK_MENU_ID, false);
		this->contextMenu()->setItemVisible(SUSPEND2RAM_MENU_ID, false);
		this->contextMenu()->setItemVisible(FREEZE_MENU_ID, false);
		this->contextMenu()->setItemVisible(STANDBY_MENU_ID, false);
		this->contextMenu()->setItemVisible(SLEEP_SEPARATOR_MENU_ID, false);
		this->contextMenu()->setItemVisible(SCHEME_SEPARATOR_MENU_ID, false);
		this->contextMenu()->setItemVisible(SCHEME_MENU_ID, false);
		this->contextMenu()->setItemVisible(HELP_SEPARATOR_MENU_ID, false);
		this->contextMenu()->setItemVisible(CONFIGURE_ID, false);
		this->contextMenu()->setItemVisible(CONFIGURE_EVENTS_ID, false);
		if (!pixmap_name.startsWith("ERROR")) {
			// dirty !!! but this work for the moment
			hwinfo->update_info_cpufreq_policy_changed = true;
			suspend = hwinfo->getSuspendSupport();
			redraw_pixmap = 1;
		}
	}
	else{
		if (pixmap_name.startsWith("ERROR")) {
			redraw_pixmap = 1;
			hwinfo->update_info_cpufreq_policy_changed = true;
			suspend = hwinfo->getSuspendSupport();
		}
		this->contextMenu()->setItemVisible(SUSPEND2DISK_MENU_ID, true);
		this->contextMenu()->setItemVisible(SUSPEND2RAM_MENU_ID, true);
		this->contextMenu()->setItemVisible(FREEZE_MENU_ID, true);
		this->contextMenu()->setItemVisible(STANDBY_MENU_ID, true);
		this->contextMenu()->setItemVisible(SLEEP_SEPARATOR_MENU_ID, true);
		this->contextMenu()->setItemVisible(SCHEME_SEPARATOR_MENU_ID, true);
		this->contextMenu()->setItemVisible(SCHEME_MENU_ID, true);
		this->contextMenu()->setItemVisible(HELP_SEPARATOR_MENU_ID, true);
		this->contextMenu()->setItemVisible(CONFIGURE_ID, true);
		this->contextMenu()->setItemVisible(CONFIGURE_EVENTS_ID, true);

		if (suspend.suspend2disk && (suspend.suspend2disk_allowed ||
		    suspend.suspend2disk_allowed == -1)) {
			this->contextMenu()->setItemEnabled(SUSPEND2DISK_MENU_ID, true);
		} else {
			if (!suspend.suspend2disk)
				this->contextMenu()->setItemVisible(SUSPEND2DISK_MENU_ID, false);
			else
				this->contextMenu()->setItemEnabled(SUSPEND2DISK_MENU_ID, false);
		}

		if (suspend.suspend2ram && (suspend.suspend2ram_allowed ||
		    suspend.suspend2ram_allowed == -1)) {
			this->contextMenu()->setItemEnabled(SUSPEND2RAM_MENU_ID, true);
		} else {
			if (!suspend.suspend2ram)
				this->contextMenu()->setItemVisible(SUSPEND2RAM_MENU_ID, false);
			else
				this->contextMenu()->setItemEnabled(SUSPEND2RAM_MENU_ID, false);
		}

		if (suspend.freeze && (suspend.freeze_allowed || suspend.freeze_allowed == -1)) {
			this->contextMenu()->setItemEnabled(FREEZE_MENU_ID, true);
		} else {
			if (!suspend.freeze)
				this->contextMenu()->setItemVisible(FREEZE_MENU_ID, false);
			else
				this->contextMenu()->setItemEnabled(FREEZE_MENU_ID, false);
		}

		if (suspend.standby && (suspend.standby_allowed || suspend.standby_allowed == -1)) {
			this->contextMenu()->setItemEnabled(STANDBY_MENU_ID, true);
		} else {
			if (!suspend.standby)
				this->contextMenu()->setItemVisible(STANDBY_MENU_ID, false);
			else
				this->contextMenu()->setItemEnabled(STANDBY_MENU_ID, false);
		}
	}

	if (hwinfo->update_info_cpufreq_policy_changed == true){
		updateCPUFreqMenu();
	}

	BatteryCollection *primary = hwinfo->getPrimaryBatteries();

	if (hwinfo->update_info_primBattery_changed == true){
		justMins.setNum(primary->getRemainingMinutes() % 60);
		justMins = justMins.rightJustify(2, '0');

		redraw_pixmap = 1;
		hwinfo->update_info_primBattery_changed = false;
	}

	updateSchemeMenu();

	if (redraw_pixmap){
		redrawPixmap();
	}

	kdDebugFuncOut(trace);
}

/*!
 * This function is involved if the CPUFreqMenu must be updated.
 */
void tdepowersave::updateCPUFreqMenu(){
	kdDebugFuncIn(trace);

	if (hwinfo->supportCPUFreq() && hwinfo->isOnline() && hwinfo->isCpuFreqAllowed()) {
		/* set CPU frequency menu entries *********/
		/* speed menu has id 3 in context menu */
		contextMenu()->setItemVisible(CPUFREQ_MENU_ID, true);
		contextMenu()->setItemEnabled(CPUFREQ_MENU_ID, true);
		contextMenu()->setItemVisible(CPUFREQ_SEPARATOR_MENU_ID, true);

		switch (hwinfo->getCurrentCPUFreqPolicy()){
			case PERFORMANCE:
				speed_menu->setItemChecked(PERFORMANCE, true);
				speed_menu->setItemChecked(DYNAMIC, false);
				speed_menu->setItemChecked(POWERSAVE, false);
				break;
			case DYNAMIC:
				speed_menu->setItemChecked(PERFORMANCE, false);
				speed_menu->setItemChecked(DYNAMIC, true);
				speed_menu->setItemChecked(POWERSAVE, false);
				break;
			case POWERSAVE:
				speed_menu->setItemChecked(PERFORMANCE, false);
				speed_menu->setItemChecked(DYNAMIC, false);
				speed_menu->setItemChecked(POWERSAVE, true);
				break;
		}
	} else {
		/* there never were policies */
		if (!speed_menu) {
			return ;
		} else if (hwinfo->supportCPUFreq() && (hwinfo->isCpuFreqAllowed() != 1)) {
			contextMenu()->setItemEnabled(CPUFREQ_MENU_ID, false);
			contextMenu()->setItemVisible(CPUFREQ_SEPARATOR_MENU_ID, true);
		} else{
			/* there were CPU freq policies, but they are not accessible any more */
			/* delete speed_menu */
			contextMenu()->setItemVisible(CPUFREQ_MENU_ID, false);
                        contextMenu()->setItemVisible(CPUFREQ_SEPARATOR_MENU_ID, false);
		}
	}

	hwinfo->update_info_cpufreq_policy_changed = false;

	kdDebugFuncOut(trace);
}

/*!
 * The function used to update the scheme menu. A update is needed if
 * if there is maybe new schemes or if the current scheme changed or switched
 * By this way also set the settings for screensaver and other parameter
 * related to the selected scheme.
 */
void tdepowersave::updateSchemeMenu(){
	kdDebugFuncIn(trace);

	if (settings->schemes.count() == 0 || !hwinfo->isOnline()){
		/* there never were schemes */
		if (!scheme_menu)
			return ;
		else{
			/* there were schemes, but they are not accessible any more */
			/* delete scheme_menu */
			scheme_menu->clear();
			contextMenu()->setItemVisible(SCHEME_MENU_ID, false);
			contextMenu()->setItemVisible(SCHEME_SEPARATOR_MENU_ID, false);
			return ;
		}
	}

	/* redraw all scheme entries ... */
	scheme_menu->clear();
	// clear the list of real scheme names
	org_schemenames.clear();

	org_schemenames = settings->schemes;

	int x = 0;
	for ( TQStringList::iterator it = org_schemenames.begin(); it != org_schemenames.end(); ++it ) {

		TQString _t = *it;

		if ( *it == settings->ac_scheme ){
			scheme_menu->insertItem( SmallIcon("scheme_power", TQIconSet::Automatic),
						 i18n( ((TQString)*it).ascii() ), x, x);
		}
		else{
			if ( *it == settings->battery_scheme ){
				scheme_menu->insertItem(SmallIcon("scheme_powersave", TQIconSet::Automatic),
							i18n( (*it).ascii() ), x, x);
			}
			else{
				if ((TQString)*it == "Acoustic"){
					scheme_menu->insertItem(SmallIcon("scheme_acoustic",
								TQIconSet::Automatic),
								i18n("Acoustic"), x, x);
				}
				else if ((TQString)*it == "Presentation"){
					scheme_menu->insertItem(SmallIcon("scheme_presentation",
								TQIconSet::Automatic),
								i18n("Presentation"), x, x);

				}
				else if((TQString)*it == "AdvancedPowersave") {
					scheme_menu->insertItem(SmallIcon("scheme_advanced_powersave",
								TQIconSet::Automatic),
								i18n( "Advanced Powersave" ), x, x);
				}
				else {
					scheme_menu->insertItem(i18n( (*it).ascii() ), x, x);
				}
			}
		}

		if ( *it == settings->currentScheme ) {
			scheme_menu->setItemChecked(x, true);
		}
		++x;
	}

	if (x == 0 && scheme_menu){
		// this should not happen, scheme_list should have been NULL before
		// now we'd have an empty menu ...
	}
	else{
		contextMenu()->setItemVisible(SCHEME_MENU_ID, true);
		contextMenu()->setItemVisible(SCHEME_SEPARATOR_MENU_ID, true);
	}

	kdDebugFuncOut(trace);
}


/*!
 * Reimplemented eventhandler for mouse enterEvent. This is called if the mouse cursor
 * enters the widget. In this case if the user move the mouse cursor over the tdepowersave
 * trayicon. \n \n
 * We use this event to update the Tooltip with all needed information. The time beetween
 * the event and the automatically popup of the TQToolTip should be long enought to collect
 * the needed values and add a updated Tooltip.
 */
void tdepowersave::enterEvent( TQEvent */*qee*/ ){

	updateTooltip();

}

/*!
 * Event handler for mouse wheel events.  If the system supports changing display
 * brightness and changing brightness is enabled in the current scheme settings,
 * this will raise the brightness by one level for wheel up events and lower the
 * brightness by one level for wheel down events.
 */
void tdepowersave::wheelEvent (TQWheelEvent *qwe)
{
	kdDebugFuncIn(trace);

	if (!hwinfo->supportBrightness() && settings->brightness)
		return;

	if (qwe->orientation () == Qt::Vertical) {
		if (qwe->delta() > 0) {
			do_brightnessUp(5);
		} else {
			do_brightnessDown(5);
		}
	}

	kdDebugFuncOut(trace);
}

/*!
 * Reimplemented eventhandler for mousePressEvents which is involved if the user click
 * on the icon on the kickerapplet. This was written to guarantee that a click with the
 * right and the left mousebutton activate the menu. In the future this can also used
 * to popup maybe a other menu.
 */
void tdepowersave::mousePressEvent(TQMouseEvent *qme){
	kdDebugFuncIn(trace);

	KSystemTray::mousePressEvent(qme);
	if (hwinfo->isOnline()) {
		if (qme->button() == Qt::RightButton){
			// TODO check if  maybe some rechecks needed
			this->contextMenu()->exec(TQCursor::pos());
		} else if (qme->button() == Qt::LeftButton) {
			showDetailedDialog();
		}
	}

	kdDebugFuncOut(trace);
}

/*!
 * \b TQT_SLOT called if the detaileddialog is closed. With this we prevent open
 * the dialog twice, use this function to reset the used variables.
 */
void tdepowersave::closedetaileddialog() {
	detailedIsShown = false;
}

/*!
 * \b TQT_SLOT used to display messeges in tdepowersave. This function
 * block all messeges which we have in tdepowersave!
 */
void tdepowersave::showErrorMessage( TQString msg ){
	kdDebugFuncIn(trace);

	if(settings->psMsgAsPassivePopup) {
		KPassivePopup::message("tdepowersave", msg, SmallIcon("messagebox_warning", 20),
				       this, i18n("Warning").ascii(), 10000);
	} else {
		kapp->updateUserTimestamp();
		// KMessageBox::error( 0, msg);
		KMessageBox::queuedMessageBox(0, KMessageBox::Error, msg);
        }

	kdDebugFuncOut(trace);
}


/*!
 * Use this function to set the SchemeSettings. This function currently set the
 * e.g. the screensaver and dpms settings. Don't forget to call this function if
 * a scheme is changed or if the settings changed.
 */
void tdepowersave::setSchemeSettings(){
	kdDebugFuncIn(trace);

	// --> check if there is a scheme set, if not, use defaults
	if ( settings->currentScheme.isEmpty()) {
		if (hwinfo->getAcAdapter()) {
			settings->load_scheme_settings( settings->ac_scheme);
		} else {
			settings->load_scheme_settings( settings->battery_scheme);
		}
	}

	// --> set autosuspend settings
	if(settings->autoSuspend) {
		setAutoSuspend(false);
	}
	else {
		this->contextMenu()->setItemVisible(AUTOSUSPEND_MENU_ID, false);
		this->contextMenu()->setItemChecked(AUTOSUSPEND_MENU_ID, false);
		this->contextMenu()->setItemVisible(AUTOSUSPEND_SEPARATOR_MENU_ID, false);
		autoSuspend->stop();
	}

	// --> set autodimm settings
	if (settings->autoDimm) {
		setAutoDimm(true);
	} else {
		autoDimm->stop();
	}

	// --> set screensaver
	if(settings->specSsSettings){
		if(settings->disableSs) display->setScreenSaver(false);
		else {
			display->setScreenSaver(true);
			if(settings->blankSs) display->blankOnlyScreen(true);
			else {
				display->blankOnlyScreen(false);
			}
		}

	} // TODO: check if this really work !!!
	else if(getenv("TDE_FULL_SESSION")) {
		// try to reset the complete screensaver settings. Ff this fail, use own methodes
		if (!display->resetKDEScreensaver()) {
			settings->load_kde();
			// Always disable blankOnly screensaver setting (default). KDE does
			// not provide a GUI to configure it and most likely we are the
			// only ones messing with it
			display->blankOnlyScreen(false);

			// reset to global screensaver settings
			if(!settings->kde->enabled) display->setScreenSaver(false);
			else {
				display->setScreenSaver(true);
				// What should we do with settings->kde->lock ?
				// Maybe nothing ?!
			}
		}
	} else if ((getenv("DESKTOP_SESSION") != NULL) && !strcmp(getenv("DESKTOP_SESSION"), "gnome")) {
		// use this to set XScreensaver back to default settings this should
		// also cover the DPMS settings for GNOME/XScreensaver
		display->resetXScreensaver();
	}

	// --> set DPMS settings
	if(settings->specPMSettings){
		// set the new DPMS settings
		if(settings->disableDPMS) {
			display->setDPMS(false);
		}
		else {
			display->setDPMS(true);
			display->has_DPMS = display->setDPMSTimeouts( settings->standbyAfter,
								      settings->suspendAfter,
								      settings->powerOffAfter);
		}
	}
	else  if(getenv("TDE_FULL_SESSION")){
		// try to reset the KDE screensaver/DPMS settings (if there are also
		// no special screensaver settings) otherwise fall back and set values from files
		if (!settings->specSsSettings && !display->resetKDEScreensaver()) {
			settings->load_kde();
			// reset to global screensaver settings
			if(!settings->kde->displayEnergySaving) {
				display->setDPMS(false);
			}
			else {
				display->setDPMS(true);
				display->has_DPMS = display->setDPMSTimeouts( settings->kde->displayStandby,
									      settings->kde->displaySuspend,
									      settings->kde->displayPowerOff);
			}
		}
	}

	// --> set brightness settings
	if(settings->brightness && hwinfo->supportBrightness()) {
		// set to given values
		hwinfo->setBrightness (-1, settings->brightnessValue);
	}

	// --> set CPU Freq settings
	if(hwinfo->supportCPUFreq() && hwinfo->isCpuFreqAllowed()) {
		hwinfo->setCPUFreq( settings->cpuFreqPolicy, settings->cpuFreqDynamicPerformance);
	}

	kdDebugFuncOut(trace);
}

/*!
 * \b TQT_SLOT which called to set and start the autosuspend monitoring.
 * \param resumed boolean value which represent information if machine
 *		  currently back from suspend/standby
 */
void tdepowersave::setAutoSuspend( bool resumed ){
	if (trace) kdDebug() << funcinfo << "IN: " << "resumed? " << resumed << endl;

	// Verify that the desired suspend action is allowed before enabling autosuspend
	SuspendStates suspend = hwinfo->getSuspendSupport();
	bool allowed = false;
	if(settings->autoInactiveAction == "Hibernate") {
		if ( suspend.suspend2disk && (suspend.suspend2disk_allowed || suspend.suspend2disk_allowed == -1)) {
			allowed = true;
		}
	}
	else if (settings->autoInactiveAction == "Sleep") {
		if( suspend.suspend2ram && (suspend.suspend2ram_allowed || suspend.suspend2ram_allowed == -1)) {
			allowed = true;
		}
	}
	else if (settings->autoInactiveAction == "Freeze") {
		if ( suspend.freeze && (suspend.freeze_allowed || suspend.freeze_allowed == -1)) {
			allowed = true;
		}
	}
	else if (settings->autoInactiveAction == "Standby") {
		if ( suspend.standby && (suspend.standby_allowed || suspend.standby_allowed == -1)) {
			allowed = true;
		}
	}
	if (!allowed) {
		settings->autoSuspend = false;
	}

	if(settings->autoInactiveActionAfter > 0 && settings->autoSuspend) {
		int autoInactiveActionAfter = 0;

		if( settings->autoInactiveAction.startsWith("_NONE_")) {
			autoSuspend->stop();
			return;
		}
		if (resumed) {
			autoSuspend->stop();
			delete autoSuspend;
			autoSuspend = new autosuspend(display);
			connect(autoSuspend, TQT_SIGNAL(inactivityTimeExpired()), this, TQT_SLOT(do_autosuspendWarn()));
		}

		if (settings->autoSuspendCountdown && (settings->autoSuspendCountdownTimeout > 0)) {
			autoInactiveActionAfter = ((settings->autoInactiveActionAfter * 60) -
						    settings->autoSuspendCountdownTimeout);
		} else {
			autoInactiveActionAfter = settings->autoInactiveActionAfter * 60;
		}

		if(settings->autoInactiveSBlistEnabled) {
			autoSuspend->start( autoInactiveActionAfter, settings->autoInactiveSBlist );
		}
		else {
			autoSuspend->start( autoInactiveActionAfter, settings->autoInactiveGBlist );
		}
		this->contextMenu()->setItemVisible(AUTOSUSPEND_SEPARATOR_MENU_ID, true);
		this->contextMenu()->setItemVisible(AUTOSUSPEND_MENU_ID, true);
	}
	else {
		// if autosuspend is not NULL: stop autosuspend
		if (autoSuspend) {
			autoSuspend->stop();
		}

		this->contextMenu()->setItemVisible(AUTOSUSPEND_MENU_ID, false);
		this->contextMenu()->setItemVisible(AUTOSUSPEND_SEPARATOR_MENU_ID, false);
	}

	kdDebugFuncOut(trace);
}

/*!
 * \b TQT_SLOT which called to set and start the autodimm monitoring.
 * \param resumed boolean value which represent information if machine
 *		  currently back from suspend/standby
 */
void tdepowersave::setAutoDimm( bool resumed ){
	if (trace) kdDebug() << funcinfo << "IN: " << "resumed? " << resumed << endl;

	if(settings->autoDimmAfter > 0 && settings->autoDimm) {
		if(settings->autoDimmTo < 0) {
			autoDimm->stop();
			kdWarning() << "Not allowed or set level for dimm" << endl;
		} else {
			if (resumed) {
				// setup again
				autoDimm->stop();
				delete autoDimm;
				autoDimm = new autodimm(display);
				connect(autoDimm, TQT_SIGNAL(inactivityTimeExpired()), this, TQT_SLOT(do_downDimm()));
				connect(autoDimm, TQT_SIGNAL(UserIsActiveAgain()), this, TQT_SLOT(do_upDimm()));
			}

			if (settings->autoDimmSBlistEnabled) {
				autoDimm->start(settings->autoDimmAfter * 60, settings->autoDimmSBlist);
			} else {
				autoDimm->start(settings->autoDimmAfter * 60, settings->autoDimmGBlist);
			}
		}
	} else {
		if (autoDimm)
			autoDimm->stop();
	}

	kdDebugFuncOut(trace);
}

// -------- start KNotify functions ------------- //

/*!
 * \b TQT_SLOT called if a battery warning state reached and related signal recieved.
 * Here we emit the related KNotify event, if not disabled.
 * \param type  integer with  the type of the battery
 * \param state integer represent the reached battery state
 */
void tdepowersave::notifyBatteryStatusChange ( int type, int state ) {
	if (trace) kdDebug() << funcinfo << "IN: " << "type: " << type << "state: " << state << endl;


	if (type == BAT_PRIMARY) {
		BatteryCollection *primary = hwinfo->getPrimaryBatteries();
		int min = primary->getRemainingMinutes();

		if (primary->getChargingState() == CHARGING) {
			kdDebug() << "tdepowersave::notifyBatteryStatusChange: Battery is charging, ignore event" << endl;
			return;
		}
		if (hwinfo->getAcAdapter()) {
			// the machine is on AC, no need to inform about battery state,
			// this is maybe only a race condition with not directly actuall
			// charge state
			kdDebug() << "tdepowersave::notifyBatteryStatusChange: Machine is on AC, ignore event" << endl;
			kdDebugFuncOut(trace);
			return;
		}

		switch (state) {
		case BAT_WARN:
			if (!settings->disableNotifications)
				KNotifyClient::event(this->winId(), "battery_warning_event",
						     i18n("Battery state changed to WARNING -- remaining time: "
						     "%1 hours and %2 minutes.").arg(min/60).arg(min%60));
			// set/call related actions
			handleActionCall(settings->batteryWarningLevelAction,
					 settings->batteryWarningLevelActionValue);
			break;
		case BAT_LOW:
			if (!settings->disableNotifications)
				KNotifyClient::event(this->winId(), "battery_low_event",
				i18n("Battery state changed to LOW -- remaining time: "
						     "%1 hours and %2 minutes.").arg(min/60).arg(min%60));
			// set/call related actions
			handleActionCall(settings->batteryLowLevelAction,
					 settings->batteryLowLevelActionValue);
			break;
		case BAT_CRIT:
			// handle carefully:
			if (settings->batteryCriticalLevelAction == GO_SHUTDOWN) {
				if (!settings->disableNotifications)
					KNotifyClient::event(this->winId(), "battery_critical_event",
							     i18n("Battery state changed to CRITICAL -- "
								  "remaining time: %1 hours and %2 minutes.\n"
								  "Shut down your system or plug in the power "
								  "cable immediately. Otherwise the machine\n"
								  "will go shutdown in 30 seconds")
								.arg(min/ 60).arg(min%60));

				TQTimer::singleShot(30000, this, TQT_SLOT(handleCriticalBatteryActionCall()));
			} else {
				if (!settings->disableNotifications)
					KNotifyClient::event(this->winId(), "battery_critical_event",
							     i18n("Battery state changed to CRITICAL -- "
								  "remaining time: %1 hours and %2 minutes.\n"
								  "Shut down your system or plug in the power "
								  "cable immediately.")
								.arg(min/ 60).arg(min%60));

				handleActionCall(settings->batteryCriticalLevelAction,
						 settings->batteryCriticalLevelActionValue);
			}
			break;
		default:
			break;
		}
	} else {
		// TODO: add some code later for the other batteries
	}

	kdDebugFuncOut(trace);
}


/*!
 * Function to call the action for battery critical event. This is ugly, but
 * because of TQTimer::singleShot() can't take param ...
 * NOTE: Use this only for SHUTDOWN atm
 */
void tdepowersave::handleCriticalBatteryActionCall () {
	kdDebugFuncIn(trace);

	handleActionCall(GO_SHUTDOWN, settings->batteryCriticalLevelActionValue, true, true);

	kdDebugFuncOut(trace);
}

/*!
 * Function to set a special action for a battery warning level.
 * \param action 	integer with the type of the action from \ref action
 * \param value 	integer value of the action as e.g. a brightness level
 * \param checkAC	bool if there should be a check for AC state befor call the action
 */
void tdepowersave::handleActionCall ( action action, int value , bool checkAC, bool batWarnCall ) {
	if (trace) kdDebug() << funcinfo << "IN: " << "action: " << action << "value: " << value
						   << "checkAC: " << checkAC << endl;

	if (hwinfo->currentSessionIsActive()) {
		switch (action) {
			case GO_SHUTDOWN:
				// confirm that we really need/want to shutdown
				if ((checkAC && !hwinfo->getAcAdapter()) || !checkAC ) {
					DCOPRef shutdown = DCOPRef( "ksmserver", "ksmserver" );
					shutdown.send("logout", 0, 2, 2);
				}
				break;
			case LOGOUT_DIALOG:
				{
					// Do not display the logout dialog if the screen saver/lock system is active
					bool saving = true;
					TQString _method;
					DCOPRef dcop_ref = DCOPRef( "kdesktop", "KScreensaverIface" );
					_method = "isBlanked()";
					DCOPReply reply = dcop_ref.call(_method.latin1());
					if ( reply.isValid() ) {
						if (!reply.get(saving)) {
							saving = false;
						}
					}

					if (!saving) {
						DCOPRef shutdown = DCOPRef( "ksmserver", "ksmserver" );
						shutdown.send("logout", 1, 2, 2);
					}
				}
				break;
			case GO_SUSPEND2RAM:
				TQTimer::singleShot(100, this, TQT_SLOT(do_suspend2ram()));
				break;
			case GO_SUSPEND2DISK:
				TQTimer::singleShot(100, this, TQT_SLOT(do_suspend2disk()));
				break;
			case GO_FREEZE:
				TQTimer::singleShot(100, this, TQT_SLOT(do_freeze()));
				break;
			case BRIGHTNESS:
				hwinfo->setBrightness( -1, value );
				break;
			case CPUFREQ_POWERSAVE:
				hwinfo->setCPUFreq( POWERSAVE );
				break;
			case CPUFREQ_DYNAMIC:
				hwinfo->setCPUFreq( DYNAMIC, settings->cpuFreqDynamicPerformance );
				break;
			case CPUFREQ_PERFORMANCE:
				hwinfo->setCPUFreq( PERFORMANCE );
				break;
			case SWITCH_SCHEME: // not supported atm
			case UNKNOWN_ACTION:
			case NONE:
			default:
				kdError() << "Could not set the requested Action: " << action << endl;
				break;
		}
	} else if (batWarnCall) {
		// FIXME
		// Is there a way to check if is active power manager on currently active session?
		if (true) {
			switch (action) {
				case GO_SHUTDOWN:
					// to be sure if we really need the shutdown
					if ((checkAC && !hwinfo->getAcAdapter()) || !checkAC ) {
						DCOPRef shutdown = DCOPRef( "ksmserver", "ksmserver" );
						shutdown.send("logout", 0, 2, 2);
					}
					break;
				default:
					kdError() << "Could not call requested action, inactive session: " << action << endl;
					break;
			}
		}
	} else {
		kdError() << "Could not set the requested action, session is inactiv: " << action << endl;
	}
	kdDebugFuncOut(trace);
}

/*!
 * \b TQT_SLOT called if ac stated changed. Here we emit the related KNotify event.
 * and switch to the AC/battery scheme depending on the state of AC
 * \param acstate boolean represent the state of AC (true == AC plugged in ...)
 */
void tdepowersave::handleACStatusChange ( bool acstate , bool notifyEvent ) {
	if (trace) kdDebug() << funcinfo << "IN: " << "acstate: " << acstate << "notifyEvent: " << notifyEvent << endl;

	int index;

	if (hwinfo->currentSessionIsActive()) {

		// emit notify event
		if(notifyEvent && !settings->disableNotifications) {
			if (acstate) {
				KNotifyClient::event(this->winId(), "plug_event", i18n("AC adapter plugged in"));
			} else {
				KNotifyClient::event(this->winId(), "unplug_event", i18n("AC adapter unplugged"));
			}
		}

		// handle switch to AC/battery default scheme
		if (acstate) {
			index = settings->schemes.findIndex(settings->ac_scheme);
		} else {
			index = settings->schemes.findIndex(settings->battery_scheme);
		}

		if (index != -1)
			do_setActiveScheme(index);

		// update applet
		update();
	}

	kdDebugFuncOut(trace);
}

/*!
 * \b TQT_SLOT called if scheme switched. Here we emit the related KNotify events
 * if they are not disabled.
 */
void tdepowersave::notifySchemeSwitch() {
	kdDebugFuncIn(trace);

	if(!settings->disableNotifications) {
		TQString _scheme = settings->currentScheme;
		TQString eventType;

		if( _scheme != "Performance" && _scheme != "Powersave" && _scheme != "Acoustic" &&
		    _scheme != "Presentation" && _scheme != "AdvancedPowersave" )
			eventType = "scheme_Unknown";
		else
			eventType = "scheme_" + _scheme;

		KNotifyClient::event( this->winId(), eventType,
				      i18n("Switched to scheme: %1").arg(i18n(_scheme.ascii())).ascii());
	}

	kdDebugFuncOut(trace);
}

/*!
 * \b TQT_SLOT called if the machine suspend. Here we emit the related KNotify events
 * if they are not disabled.
 */
void tdepowersave::notifySuspend( int suspendType ) {
	kdDebugFuncIn(trace);

	if(!settings->disableNotifications) {
		switch (suspendType) {
			case SUSPEND2DISK:
				KNotifyClient::event( this->winId(), "suspend2disk_event",
						      i18n("System is going into %1 now.").
						      arg(i18n("hibernation")));
				break;
			case SUSPEND2RAM:
				KNotifyClient::event( this->winId(), "suspend2ram_event",
						      i18n("System is going into %1 now.").
						      arg(i18n("sleep")));
				break;
			case FREEZE:
				KNotifyClient::event( this->winId(), "freeze_event",
						      i18n("System is going into %1 now.").
						      arg(i18n("freeze")));
				break;
			case STANDBY:
				KNotifyClient::event( this->winId(), "standby_event",
						      i18n("System is going into %1 now.").
						      arg(i18n("standby")));
				break;
			default:
				break;
		}
	}

	kdDebugFuncOut(trace);
}

/*!
 * \b TQT_SLOT called to independent handleResumeSignal() from event loop and
 * to avoid problems with the QT3 D-Bus bindings
 */
void tdepowersave::forwardResumeSignal( int result ) {
	if (trace) kdDebug() << funcinfo << "IN: " << "result: " << result << endl;

	resume_result = result;

	TQTimer::singleShot(100, this, TQT_SLOT(handleResumeSignal()));

	kdDebugFuncOut(trace);
}

/*!
 * \b TQT_SLOT called if the machine suspend. Here we emit the related KNotify events
 * if they are not disabled.
 */
void tdepowersave::handleResumeSignal() {
	kdDebugFuncIn(trace);

	// fake key to show the login dialog if we locked the screen
	if(settings->lockOnSuspend) {
		activateLoginScreen();
	}

	// reset autosuspend and autodimm
	setAutoSuspend(true);
	setAutoDimm(true);

	// reset the CPU Freq Policy ... for more see https://bugzilla.novell.com/show_bug.cgi?id=223164
	if(hwinfo->supportCPUFreq() && hwinfo->isCpuFreqAllowed()) {
		hwinfo->setCPUFreq( settings->cpuFreqPolicy, settings->cpuFreqDynamicPerformance );
	}

	if(!settings->disableNotifications) {
		switch (calledSuspend) {
			case SUSPEND2DISK:
				KNotifyClient::event( this->winId(), "resume_from_suspend2disk_event",
						      i18n("System is resumed from %1.").arg(
						      i18n("hibernation")));
				break;
			case SUSPEND2RAM:
				KNotifyClient::event( this->winId(), "resume_from_suspend2ram_event",
					      	      i18n("System is resumed from %1.").arg(
						      i18n("sleep")));
				break;
			case FREEZE:
				KNotifyClient::event( this->winId(), "resume_from_freeze_event",
						      i18n("System is resumed from %1.").arg(
						      i18n("freeze")));
				break;
			case STANDBY:
				KNotifyClient::event( this->winId(), "resume_from_standby_event",
						      i18n("System is resumed from %1.").arg(
						      i18n("standby")));
				break;
			default:
				kdError() << "called suspend type unknown" << endl;
				break;

		}
	}

	// handle result of the resume/suspend
	// 1 is a valid return code; don't error out when it is received!
	if ((resume_result == 0) || (resume_result == 1) || (resume_result == INT_MAX)) {
		if ( resume_result == INT_MAX )
			kdWarning() << "Unknown if we successful resumed, look like a D-Bus timeout since "
				    << "elapsed time between suspend and resume is higher than 6 hours" << endl;

		// successful resumed ... remount only in this case
		if (!handleMounts(false)) {
			KPassivePopup::message( i18n("WARNING"),
						i18n("Could not remount (all) external storage"
						" media."), SmallIcon("messagebox_warning", 20),
						this, i18n("Warning").ascii(), 15000);
		}
	} else {
		kdError() << "Unknown error while suspend. Errorcode: " << resume_result << endl;
		TQString msg;

		msg = i18n("An unknown error occurred while %1. The errorcode is: '%2'").
			arg(getSuspendString(calledSuspend)).arg(resume_result);

#if defined(DISTRO_IS_SUSE) || defined(DISTRO_IS_SLES_SLED) || defined(DISTRO_IS_PARDUS)
		// okay we know this system use pm-utils and log is under /var/log/pm-suspend.log
		msg += "\n" + i18n("Do you want to have a look at the log file?");
		int answer = KMessageBox::questionYesNo(0, msg, i18n("Error while %1").
							arg(getSuspendString(calledSuspend)));
		if (answer == KMessageBox::Yes) {
 #if defined(DISTRO_IS_SLES_SLED)
			switch (calledSuspend) {
				case SUSPEND2DISK:
					logview = new LogViewer ("/var/log/suspend2disk.log");
					logview->show();
					break;
				case SUSPEND2RAM:
					logview = new LogViewer ("/var/log/suspend2ram.log");
					logview->show();
					break;
				case FREEZE:
					logview = new LogViewer ("/var/log/freeze.log");
					logview->show();
					break;
				case STANDBY:
					logview = new LogViewer ("/var/log/standby.log");
					logview->show();
					break;
				default:
					break;
			}
 #else
			logview = new LogViewer ("/var/log/pm-suspend.log");
			logview->show();
 #endif
		}
#else
		KMessageBox::error(0, msg, i18n("Error while %1").arg(getSuspendString(calledSuspend)));
#endif
	}
	// set back ... suspend is handled
	calledSuspend = -1;
	resume_result = 0;

	kdDebugFuncOut(trace);
}

/*!
 * \b TQT_SLOT called if the state of the current session change
 * \param state boolean represent the state of the session
 * TODO: fix scheme handling
 * TODO: fix critical battery situations (see the todo file in the source)
 */
void tdepowersave::handleSessionState (bool state) {
	kdDebugFuncIn(trace);

	if (state) {
		// session is active again
		if (settings->autoSuspend) disableAutosuspend(false);
		if (settings->autoDimm) setAutoDimm(false);
		/* handle may missed/not set AC status changes while the
		   session was inactive and set them to the default schemes ?! */
		handleACStatusChange(hwinfo->getAcAdapter(), false);

	} else {
		// session is now inactive
		if (settings->autoSuspend) disableAutosuspend(true);
		if (settings->autoDimm) autoDimm->stop();
	}

	kdDebugFuncOut(trace);
}

// -------- end KNotify functions ------------- //
// ------------ helper functions -------------- //

/*!
 * Helper function to get a i18n name for a suspend type.
 * \param type	Integer value with the suspend type
 * \return 	TQString with the translated name or NULL if it fail
 */
TQString tdepowersave::getSuspendString (int type) {
	kdDebugFuncIn(trace);

	switch (type) {
		case SUSPEND2DISK:
			return i18n("Hibernate");
			break;
		case SUSPEND2RAM:
			return i18n("Sleep");
			break;
		case FREEZE:
			return i18n("Freeze");
			break;
		case STANDBY:
			return i18n("Standby");
			break;
		default:
			return TQString();
	}

	kdDebugFuncOut(trace);
}

// --------- end helper functions ------------- //
// ------------ DCOP functions ---------------- //

/*!
 * DCOP Interface funtion to lock the screen with the userdefined methode.
 * \return boolean with the result of locking the screen
 * \retval true if locking the screen was successful
 * \retval false if locking the screen failed or the user don't wan't to lock
 */
bool tdepowersave::lockScreen(){
	kdDebugFuncIn(trace);

	settings->load_general_settings();

	return display->lockScreen( settings->lockmethod );

	kdDebugFuncOut(trace);
}

/*!
 * DCOP Interface funtion to return the name of the current powersave scheme.
 * \return TQString with the name of the current scheme
 */
TQString tdepowersave::currentScheme (){
	kdDebugFuncIn(trace);

	if(hwinfo->isOnline()) {
		return settings->currentScheme;
	} else {
		return "ERROR: D-Bus not running";
	}

	kdDebugFuncOut(trace);
}

/*!
 * DCOP Interface funtion to return the name of the current cpuFreqPolicy.
 * \return TQString with the name of the current cpuFreqPolicy
 */
TQString tdepowersave::currentCPUFreqPolicy() {
	kdDebugFuncIn(trace);

	if(hwinfo->isOnline()) {
		TQString _cpuFreq = "";
		switch (hwinfo->getCurrentCPUFreqPolicy()){
			case PERFORMANCE:
				_cpuFreq = "PERFORMANCE";
				break;
			case DYNAMIC:
				_cpuFreq = "DYNAMIC";
				break;
			case POWERSAVE:
				_cpuFreq = "POWERSAVE";
				break;
			default:
				_cpuFreq = "UNKNOWN";
				break;
		}
		return _cpuFreq;
	} else {
		return "ERROR: DBus not running";
	}

	kdDebugFuncOut(trace);
}

/*!
 * DCOP Interface funtion to send a list with the allowed
 * CPU Frequency states.
 * \return TQStringList with the supported CPUFreq states
 */
TQStringList tdepowersave::listCPUFreqPolicies() {
	kdDebugFuncIn(trace);

	TQStringList ret_list;
	if (hwinfo->isCpuFreqAllowed()) {
		ret_list.append("PERFORMANCE");
		ret_list.append("DYNAMIC");
		ret_list.append("POWERSAVE");
	}
	else {
		ret_list.append("NOT SUPPORTED");
	}

	kdDebugFuncOut(trace);
	return ret_list;
}

/*!
 * DCOP Interface funtion to set the current CPUFreq policy
 * \param policy TQString with the policy to set, only values from
 * 		 list_CPUFreqPolicies are allowed (except "NOT SUPPORTED")
 * \return boolean with the result of set the requested CPUFreq policy
 * \retval true if successful set
 * \retval false if not supported or any other failure
 */
bool tdepowersave::do_setCPUFreqPolicy( TQString policy ) {
	if (trace) kdDebug() << funcinfo << "IN: " << "policy: " << policy << endl;


	bool ret = true;
	/*
	if (hwinfo->isCpuFreqAllowed() && hwinfo->isOnline()) {
		if (policy == "PERFORMANCE") {
			hwinfo->setCPUFreq(PERFORMANCE);
		} else if (policy == "DYNAMIC") {
			hwinfo->setCPUFreq(DYNAMIC, settings->cpuFreqDynamicPerformance);
		} else if (policy == "POWERSAVE") {
			hwinfo->setCPUFreq(POWERSAVE);
		} else {
			kdDebugFuncOut(trace);
			ret = false;
		}
	} else {
		ret = false;
	}
	*/
	kdDebugFuncOut(trace);
	return ret;
}

/*!
 * DCOP Interface funtion to send a list with the supported and enabled
 * sleeping states.
 * \return TQStringList with the supported spleeping states
 */
TQStringList tdepowersave::allowed_sleepingStates(){
	kdDebugFuncIn(trace);

	TQStringList sleepList;
	if(hwinfo->isOnline()) {
		if (suspend.suspend2disk && (suspend.suspend2disk_allowed ||
		    suspend.suspend2disk_allowed == -1)){
			sleepList.append("suspendToDisk");
		}
		if (suspend.suspend2ram && (suspend.suspend2ram_allowed ||
		    suspend.suspend2ram_allowed == -1)){
			sleepList.append("suspendToRAM");
		}
		if (suspend.freeze && (suspend.freeze_allowed || suspend.freeze_allowed == -1)){
			sleepList.append("freeze");
		}
		if (suspend.standby && (suspend.standby_allowed || suspend.standby_allowed == -1)){
			sleepList.append("standBy");
		}
		if(sleepList.isEmpty()){
			sleepList.append("NO_SLEEPING_STATES_SUPPORTED");
		}
	}
	else {
		sleepList.append("ERROR: D-Bus not running");
	}

	kdDebugFuncOut(trace);
	return sleepList;
}

/*!
 * DCOP Interface funtion to send a list with the all schemes.
 * \return TQStringList with all schemes
 */
TQStringList tdepowersave::listSchemes(){
	kdDebugFuncIn(trace);

	TQStringList _schemeList;
	if(hwinfo->isOnline()) {
		if (settings->schemes.count() > 0){
			_schemeList = settings->schemes;
		}
	}
	else {
		_schemeList.append("ERROR: D-Bus not running");
	}

	kdDebugFuncOut(trace);
	return _schemeList;
}


/*!
 * DCOP Interface funtion to set the current scheme.
 * \return boolean with the result of set the requested scheme
 * \retval false if failed (e.g. scheme is not in the list)
 * \retval true if scheme found and set
 * \param _scheme TQString with the scheme to set, scheme should be
 *		  named as list from list_schemes()
 */
bool tdepowersave::do_setScheme( TQString /*_scheme*/ ) {
	kdDebugFuncIn(trace);

/*	int index;
	index = settings->schemes.findIndex(_scheme);

	if (index != -1) {
		do_setActiveScheme(index);
		kdDebugFuncOut(trace);
		return true;
	}
	else {
		kdDebugFuncOut(trace);
		return false;
	}
*/
	kdDebugFuncOut(trace);
	return false;
}

/*!
 * DCOP Interface funtion to send the suspend to disk command to powersave.
 * \return boolean with the result of calling do_suspend2disk()
 * \retval true if successful
 * \retval false if not supported or powersaved not running
 */
bool tdepowersave::do_suspendToDisk(){
	kdDebugFuncIn(trace);
	kdDebugFuncOut(trace);
	return do_suspend2disk();
}

/*!
 * DCOP Interface funtion to send the suspend to disk command to powersave.
 * \return boolean with the result of calling do_suspend2ram()
 * \retval true if successful
 * \retval false if not supported or powersaved not running
 */
bool tdepowersave::do_suspendToRAM(){
	kdDebugFuncIn(trace);
	kdDebugFuncOut(trace);
	return do_suspend2ram();
}

/*!
 * DCOP Interface funtion to send the freeze command to powersave.
 * \return boolean with the result of calling do_freeze()
 * \retval true if successful
 * \retval false if not supported or powersaved not running
 */
bool tdepowersave::do_suspendFreeze(){
	kdDebugFuncIn(trace);
	kdDebugFuncOut(trace);
	return do_freeze();
}

/*!
 * DCOP Interface funtion to send the standby command to powersave.
 * \return boolean with the result of calling do_standby()
 * \retval true if successful
 * \retval false if not supported or powersaved not running
 */
bool tdepowersave::do_standBy(){
	kdDebugFuncIn(trace);
	kdDebugFuncOut(trace);
	return do_standby();
}

//! dcop function to set the brightness up
bool tdepowersave::do_brightnessUp(int percentageStep) {
	kdDebugFuncIn(trace);

	bool retval = false;

	if(hwinfo->isOnline()) {
		retval = hwinfo->setBrightnessUp(percentageStep);
	}

	kdDebugFuncOut(trace);
	return retval;
}

//! dcop function to set the brightness down
bool tdepowersave::do_brightnessDown(int percentageStep) {
	kdDebugFuncIn(trace);

	bool retval = false;

	if(hwinfo->isOnline()) {
		retval = hwinfo->setBrightnessDown(percentageStep);
	}

	kdDebugFuncOut(trace);
	return retval;
}


/*!
 * DCOP Interface funtion to stop/start the Autosuspend
 * \param disable boolean which tell if the autosuspend should be stopped (true)
 *		   or started (false).
 */
void tdepowersave::disableAutosuspend( bool disable ){
	kdDebugFuncIn(trace);

	if(settings->autoSuspend && settings->autoInactiveActionAfter > 0) {
		if (disable) {
			if ( !contextMenu()->isItemChecked(AUTOSUSPEND_MENU_ID)) {
				autoSuspend->stop();
				contextMenu()->setItemChecked(AUTOSUSPEND_MENU_ID, true);
			}
		}
		else {
			contextMenu()->setItemChecked(AUTOSUSPEND_MENU_ID, false);
			setAutoSuspend(true);
		}
	}

	kdDebugFuncOut(trace);
}

/*!
 * DCOP Interface funtion to open/close the detailed dialog.
 */
void tdepowersave::showDetailedDialog( ){
	kdDebugFuncIn(trace);

	if (detailedIsShown) {
		detailedDlg->close();
		delete(detailedDlg);
		closedetaileddialog();
		return;
	}

	detailedDlg = new detaileddialog(hwinfo, &fullIcon, settings);

	if (detailedDlg) {
		detailedDlg->show();
		detailedIsShown = true;
	}

	connect(detailedDlg, TQT_SIGNAL(destroyed()), this, TQT_SLOT(closedetaileddialog()));

	kdDebugFuncOut(trace);
}

/*!
 * DCOP Interface funtion to open the configure dialog.
 * \return boolean with the result of open the dialog
 * \retval false if failed (e.g. D-Bus or HAL is not running)
 * \retval true if correct opend
 */
bool tdepowersave::openConfigureDialog (){
	kdDebugFuncIn(trace);

	if(hwinfo->isOnline()) {
		showConfigureDialog();
		kdDebugFuncOut(trace);
		return config_dialog_shown;
	} else {
		kdDebugFuncOut(trace);
		return false;
	}
}

/*!
 * DCOP Interface funtion to find out if the current
 * scheme manages DPMS
 * \return boolean
 * \retval false if current scheme does not overwrite DPMS
 * \retval true if current scheme does
 */
bool tdepowersave::currentSchemeManagesDPMS () {
	kdDebugFuncIn(trace);

	return settings->specPMSettings;

	kdDebugFuncOut(trace);
}


//! dcop funtion to get the current brightness level
int tdepowersave::brightnessGet() {
	kdDebugFuncIn(trace);

	int retval = -1;

	if (hwinfo->supportBrightness()) {
		retval = (int)(((float)hwinfo->getCurrentBrightnessLevel() / (float)hwinfo->getMaxBrightnessLevel()-1) * 100.0);
	}

	kdDebugFuncOut(trace);

	return retval;
}

#include "tdepowersave.moc"