summaryrefslogtreecommitdiffstats
path: root/content/browser/power_save_blocker_linux.cc
blob: e24665022235ff0be01d5ae89c1c9722a968d5d0 (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
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/power_save_blocker.h"

#include <X11/Xlib.h>
#include <X11/extensions/dpms.h>
// Xlib #defines Status, but we can't have that for some of our headers.
#ifdef Status
#undef Status
#endif

#include "base/basictypes.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/environment.h"
#include "base/file_path.h"
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/singleton.h"
#include "base/message_loop_proxy.h"
#if defined(TOOLKIT_GTK)
#include "base/message_pump_gtk.h"
#else
#include "base/message_pump_aurax11.h"
#endif
#include "base/nix/xdg_util.h"
#include "content/public/browser/browser_thread.h"
#include "dbus/bus.h"
#include "dbus/message.h"
#include "dbus/object_path.h"
#include "dbus/object_proxy.h"

using content::BrowserThread;

namespace {

// This class is used to inhibit Power Management on Linux systems using D-Bus
// interfaces. Mainly, there are two interfaces that make this possible.
// org.freedesktop.PowerManagement[.Inhibit] is considered to be the
// desktop-agnostic solution. However, it is only used by KDE4 and XFCE.
//
// org.gnome.SessionManager is the Power Management interface available on GNOME
// desktops. Given that there is no generic solution to this problem, this class
// delegates the task of calling specific D-Bus APIs, to a
// DBusPowerSaveBlock::Delegate object.
//
// This class is a Singleton and the delegate will be instantiated internally,
// when the singleton instance is created, based on the desktop environment in
// which the application is running. When the class is instantiated, if it runs
// under a supported desktop environment it creates the Bus object and the
// delegate. Otherwise, no object is created and the ApplyBlock method will not
// do anything.
class DBusPowerSaveBlocker {
 public:
  // String passed to D-Bus APIs as the reason for which
  // the power management features are temporarily disabled.
  static const char kPowerSaveReason[];

  // This delegate interface represents a concrete implementation for a specific
  // D-Bus interface. It is responsible for obtaining specific object proxies,
  // making D-Bus method calls and handling D-Bus responses.
  //
  // When a new DBusPowerBlocker is created, only a specific implementation of
  // the delegate is instantiated. See the DBusPowerSaveBlocker constructor for
  // more details. This is ref_counted to make sure that the callbacks stay
  // alive even after the DBusPowerSaveBlocker object is deleted.
  class Delegate : public base::RefCountedThreadSafe<Delegate> {
   public:
    Delegate() {}
    virtual void ApplyBlock(PowerSaveBlocker::PowerSaveBlockerType type) = 0;

   protected:
    virtual ~Delegate() {}

   private:
    friend class base::RefCountedThreadSafe<Delegate>;

    DISALLOW_COPY_AND_ASSIGN(Delegate);
  };

  // Returns a pointer to the sole instance of this class
  static DBusPowerSaveBlocker* GetInstance();

  // Forwards a power save block request to the concrete implementation of the
  // Delegate interface. If |delegate_| is NULL, the application runs under an
  // unsupported desktop environment. In this case, the method does nothing.
  void ApplyBlock(PowerSaveBlocker::PowerSaveBlockerType type) {
    if (delegate_)
      delegate_->ApplyBlock(type);
  }

  // Getter for the Bus object. Used by the Delegates to obtain object proxies.
  scoped_refptr<dbus::Bus> bus() const { return bus_; }

 private:
  DBusPowerSaveBlocker();
  virtual ~DBusPowerSaveBlocker();

  // If DPMS is not enabled, then we don't want to try to disable power saving,
  // since on some desktop environments that may enable DPMS with very poor
  // default settings (e.g. turning off the display after only 1 second).
  static bool DPMSEnabled();

  // The D-Bus connection.
  scoped_refptr<dbus::Bus> bus_;

  // Concrete implementation of the Delegate interface.
  scoped_refptr<Delegate> delegate_;

  friend struct DefaultSingletonTraits<DBusPowerSaveBlocker>;

  DISALLOW_COPY_AND_ASSIGN(DBusPowerSaveBlocker);
};

// Delegate implementation for KDE4. It uses the
// org.freedesktop.PowerManagement interface. It works on XFCE4, too.
class KDEPowerSaveBlocker : public DBusPowerSaveBlocker::Delegate {
 public:
  KDEPowerSaveBlocker()
      : inhibit_cookie_(0),
        pending_inhibit_call_(false),
        postponed_uninhibit_call_(false) {
  }

  virtual void ApplyBlock(
      PowerSaveBlocker::PowerSaveBlockerType type) OVERRIDE {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    DCHECK(pending_inhibit_call_ || !postponed_uninhibit_call_);

    // If we have a pending inhibit call, we add a postponed uninhibit
    // request, such that it will be canceled as soon as the response arrives.
    // If we have an active inhibit request and receive a new one,
    // we ignore it since the 'freedesktop' interface has only one Inhibit level
    // and we cannot differentiate between SystemSleep and DisplaySleep,
    // so there's no need to make additional D-Bus method calls.
    if (type == PowerSaveBlocker::kPowerSaveBlockPreventNone) {
      if (pending_inhibit_call_ && postponed_uninhibit_call_) {
        return;
      } else if (pending_inhibit_call_ && !postponed_uninhibit_call_) {
        postponed_uninhibit_call_ = true;
        return;
      } else if (!pending_inhibit_call_ && inhibit_cookie_ == 0) {
        return;
      }
    } else if ((pending_inhibit_call_ && !postponed_uninhibit_call_) ||
                inhibit_cookie_ > 0) {
        return;
    }

    scoped_refptr<dbus::ObjectProxy> object_proxy =
        DBusPowerSaveBlocker::GetInstance()->bus()->GetObjectProxy(
            "org.freedesktop.PowerManagement",
            dbus::ObjectPath("/org/freedesktop/PowerManagement/Inhibit"));
    dbus::MethodCall method_call("org.freedesktop.PowerManagement.Inhibit",
                                 "Inhibit");
    dbus::MessageWriter message_writer(&method_call);
    base::Callback<void(dbus::Response*)> bus_callback;

    switch (type) {
      case PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep:
      case PowerSaveBlocker::kPowerSaveBlockPreventSystemSleep:
        // The org.freedesktop.PowerManagement.Inhibit interface offers only one
        // Inhibit() method, that temporarily disables all power management
        // features. We cannot differentiate and disable individual features,
        // like display sleep or system sleep.
        // The first argument of the Inhibit method is the application name.
        // The second argument of the Inhibit method is a string containing
        // the reason of the power save block request.
        // The method returns a cookie (an int), which we must pass back to the
        // UnInhibit method when we cancel our request.
        message_writer.AppendString(
            CommandLine::ForCurrentProcess()->GetProgram().value());
        message_writer.AppendString(DBusPowerSaveBlocker::kPowerSaveReason);
        bus_callback = base::Bind(&KDEPowerSaveBlocker::OnInhibitResponse,
                                  this);
        pending_inhibit_call_ = true;
        break;
      case PowerSaveBlocker::kPowerSaveBlockPreventNone:
        // To cancel our inhibit request, we have to call a different method.
        // It takes one argument, the cookie returned by the corresponding
        // Inhibit method call.
        method_call.SetMember("UnInhibit");
        message_writer.AppendUint32(inhibit_cookie_);
        bus_callback = base::Bind(&KDEPowerSaveBlocker::OnUnInhibitResponse,
                                  this);
        break;
      case PowerSaveBlocker::kPowerSaveBlockPreventStateCount:
        // This is an invalid argument
        NOTREACHED();
        break;
    }

    object_proxy->CallMethod(&method_call,
                             dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
                             bus_callback);
  }

 protected:
  virtual ~KDEPowerSaveBlocker() {}

 private:
  // Inhibit() response callback.
  // Stores the cookie so we can use it later when calling UnInhibit().
  // If the response from D-Bus is successful and there is a postponed
  // uninhibit request, we cancel the cookie that we just received.
  void OnInhibitResponse(dbus::Response* response) {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    DCHECK(pending_inhibit_call_);
    pending_inhibit_call_ = false;
    if (response) {
      dbus::MessageReader message_reader(response);
      if (message_reader.PopUint32(&inhibit_cookie_)) {
        if (postponed_uninhibit_call_) {
          postponed_uninhibit_call_ = false;
          ApplyBlock(PowerSaveBlocker::kPowerSaveBlockPreventNone);
        }
        return;
      } else {
        LOG(ERROR) << "Invalid Inhibit() response: " << response->ToString();
      }
    }
    inhibit_cookie_ = 0;
    postponed_uninhibit_call_ = false;
  }

  // UnInhibit() method callback.
  // We set the |inhibit_cookie_| to 0 even if the D-Bus call failed.
  void OnUnInhibitResponse(dbus::Response* response) {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    inhibit_cookie_ = 0;
  };

  // The cookie that identifies our last inhibit request,
  // or 0 if there is no active inhibit request.
  uint32 inhibit_cookie_;

  // True if we made an inhibit call for which
  // we did not receive a response yet
  bool pending_inhibit_call_;

  // True if we have to cancel the cookie we are about to receive
  bool postponed_uninhibit_call_;

  DISALLOW_COPY_AND_ASSIGN(KDEPowerSaveBlocker);
};

// Delegate implementation for Gnome, based on org.gnome.SessionManager
class GnomePowerSaveBlocker : public DBusPowerSaveBlocker::Delegate {
 public:
  // Inhibit flags defined in the org.gnome.SessionManager interface.
  // Can be OR'd together and passed as argument to the Inhibit() method
  // to specify which power management features we want to suspend.
  enum InhibitFlags {
    kInhibitLogOut            = 1,
    kInhibitSwitchUser        = 2,
    kInhibitSuspendSession    = 4,
    kInhibitMarkSessionAsIdle = 8
  };

  GnomePowerSaveBlocker()
      : inhibit_cookie_(0),
        pending_inhibit_calls_(0),
        postponed_uninhibit_calls_(0) {}

  virtual void ApplyBlock(
      PowerSaveBlocker::PowerSaveBlockerType type) OVERRIDE {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    DCHECK(postponed_uninhibit_calls_ <= pending_inhibit_calls_);

    // If we have a pending inhibit call, we add a postponed uninhibit request,
    // such that it will be canceled as soon as the response arrives. We want to
    // cancel the current inhibit request whether |type| is
    // kPowerSaveBlockPreventNone or not. If |type| represents an inhibit
    // request, we are dealing with the same case as below, just that the reply
    // to the previous inhibit request did not arrive yet, so we have to wait
    // for the cookie in order to cancel it. Meanwhile, we can still make the
    // new request.
    //
    // We also have to check that postponed_uninhibit_calls_ <
    // pending_inhibit_calls_. If this is not the case, then all the pending
    // requests were already canceled and we should not increment the number of
    // postponed uninhibit requests; otherwise we will cancel unwanted future
    // inhibits, that will be made after this call.
    //
    // NOTE: The implementation is based on the fact that we receive the D-Bus
    // replies in the same order in which the requests are made.
    if (pending_inhibit_calls_ > 0 &&
        postponed_uninhibit_calls_ < pending_inhibit_calls_) {
      ++postponed_uninhibit_calls_;
      // If the call was an Uninhibit, then we are done for the moment.
      if (type == PowerSaveBlocker::kPowerSaveBlockPreventNone)
        return;
    }

    // If we have an active inhibit request and no pending inhibit calls,
    // we make an uninhibit request to cancel it now.
    if (type != PowerSaveBlocker::kPowerSaveBlockPreventNone &&
        pending_inhibit_calls_ == 0 &&
        inhibit_cookie_ > 0) {
      ApplyBlock(PowerSaveBlocker::kPowerSaveBlockPreventNone);
    }

    static const char kGnomeSessionManagerName[] = "org.gnome.SessionManager";
    scoped_refptr<dbus::ObjectProxy> object_proxy =
        DBusPowerSaveBlocker::GetInstance()->bus()->GetObjectProxy(
            kGnomeSessionManagerName,
            dbus::ObjectPath("/org/gnome/SessionManager"));
    dbus::MethodCall method_call(kGnomeSessionManagerName, "Inhibit");
    dbus::MessageWriter message_writer(&method_call);
    base::Callback<void(dbus::Response*)> bus_callback;

    unsigned int flags = 0;
    switch (type) {
      case PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep:
        flags |= kInhibitMarkSessionAsIdle;
        break;
      case PowerSaveBlocker::kPowerSaveBlockPreventSystemSleep:
        flags |= kInhibitMarkSessionAsIdle;
        flags |= kInhibitSuspendSession;
        break;
      case PowerSaveBlocker::kPowerSaveBlockPreventNone:
        break;
      case PowerSaveBlocker::kPowerSaveBlockPreventStateCount:
        // This is an invalid argument
        NOTREACHED();
        break;
    }

    switch (type) {
      case PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep:
      case PowerSaveBlocker::kPowerSaveBlockPreventSystemSleep:
        // To temporarily suspend the power management features on Gnome,
        // we call org.gnome.SessionManager.Inhibit().
        // The arguments of the method are:
        //     app_id:        The application identifier
        //     toplevel_xid:  The toplevel X window identifier
        //     reason:        The reason for the inhibit
        //     flags:         Flags that spefify what should be inhibited
        // The method returns and inhibit_cookie, used to uniquely identify
        // this request. It should be used as an argument to Uninhibit()
        // in order to remove the request.
        message_writer.AppendString(
            CommandLine::ForCurrentProcess()->GetProgram().value());
        message_writer.AppendUint32(0);  // should be toplevel_xid
        message_writer.AppendString(DBusPowerSaveBlocker::kPowerSaveReason);
        message_writer.AppendUint32(flags);
        bus_callback = base::Bind(&GnomePowerSaveBlocker::OnInhibitResponse,
                                  this);
        ++pending_inhibit_calls_;
        break;
      case PowerSaveBlocker::kPowerSaveBlockPreventNone:
        // To cancel a previous inhibit request we call
        // org.gnome.SessionManager.Uninhibit().
        // It takes only one argument, the cookie that identifies
        // the request we want to cancel.
        method_call.SetMember("Uninhibit");
        message_writer.AppendUint32(inhibit_cookie_);
        bus_callback = base::Bind(&GnomePowerSaveBlocker::OnUnInhibitResponse,
                                  this);
        ++pending_inhibit_calls_;
        break;
      case PowerSaveBlocker::kPowerSaveBlockPreventStateCount:
        // This is an invalid argument.
        NOTREACHED();
        break;
    }

    object_proxy->CallMethod(&method_call,
                             dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
                             bus_callback);
  }

 protected:
  virtual ~GnomePowerSaveBlocker() {}

 private:
  // Inhibit() response callback.
  // Stores the cookie so we can use it later when calling UnInhibit().
  // If the response from D-Bus is successful and there is a postponed
  // uninhibit request, we cancel the cookie that we just received.
  void OnInhibitResponse(dbus::Response* response) {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    DCHECK_GT(pending_inhibit_calls_, 0);
    --pending_inhibit_calls_;
    if (response) {
      dbus::MessageReader message_reader(response);
      if (message_reader.PopUint32(&inhibit_cookie_)) {
        if (postponed_uninhibit_calls_ > 0) {
          --postponed_uninhibit_calls_;
          ApplyBlock(PowerSaveBlocker::kPowerSaveBlockPreventNone);
        }
        return;
      } else {
        LOG(ERROR) << "Invalid Inhibit() response: " << response->ToString();
      }
    }
    inhibit_cookie_ = 0;
    if (postponed_uninhibit_calls_ > 0) {
      --postponed_uninhibit_calls_;
    }
  }

  // Uninhibit() response callback.
  // We set the |inhibit_cookie_| to 0 even if the D-Bus call failed.
  void OnUnInhibitResponse(dbus::Response* response) {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    inhibit_cookie_ = 0;
  };

  // The cookie that identifies our last inhibit request,
  // or 0 if there is no active inhibit request.
  uint32 inhibit_cookie_;

  // Store the number of inhibit calls for which
  // we did not receive a response yet
  int pending_inhibit_calls_;

  // Store the number of Uninhibit requests that arrived,
  // before the corresponding Inhibit calls were completed.
  int postponed_uninhibit_calls_;

  DISALLOW_COPY_AND_ASSIGN(GnomePowerSaveBlocker);
};

const char DBusPowerSaveBlocker::kPowerSaveReason[] = "Power Save Blocker";

// Initialize the DBusPowerSaveBlocker instance:
// 1. Instantiate a concrete delegate based on the current desktop environment,
// 2. Instantiate the D-Bus object
DBusPowerSaveBlocker::DBusPowerSaveBlocker() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  scoped_ptr<base::Environment> env(base::Environment::Create());
  switch (base::nix::GetDesktopEnvironment(env.get())) {
    case base::nix::DESKTOP_ENVIRONMENT_GNOME:
      if (DPMSEnabled())
        delegate_ = new GnomePowerSaveBlocker();
      break;
    case base::nix::DESKTOP_ENVIRONMENT_XFCE:
    case base::nix::DESKTOP_ENVIRONMENT_KDE4:
      if (DPMSEnabled())
        delegate_ = new KDEPowerSaveBlocker();
      break;
    case base::nix::DESKTOP_ENVIRONMENT_KDE3:
    case base::nix::DESKTOP_ENVIRONMENT_OTHER:
      // Not supported, so we exit.
      // We don't create D-Bus objects.
      break;
  }

  if (delegate_) {
    dbus::Bus::Options options;
    options.bus_type = dbus::Bus::SESSION;
    options.connection_type = dbus::Bus::PRIVATE;
    // Use the FILE thread to service the D-Bus connection,
    // since we need a thread that allows I/O operations.
    options.dbus_thread_message_loop_proxy =
        BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE);
    bus_ = new dbus::Bus(options);
  }
}

DBusPowerSaveBlocker::~DBusPowerSaveBlocker() {
  // We try to shut down the bus, but unfortunately in most of the
  // cases when we delete the singleton instance,
  // the FILE thread is already stopped and there is no way to
  // shutdown the bus object on the origin thread (the UI thread).
  // However, this is not a crucial problem since at this point
  // we are at the very end of the shutting down phase.
  // Connection to D-Bus is just a Unix domain socket, which is not
  // a persistent resource, hence the operating system will take care
  // of closing it when the process terminates.
  if (BrowserThread::IsMessageLoopValid(BrowserThread::FILE)) {
    bus_->ShutdownOnDBusThreadAndBlock();
  }
}

// static
bool DBusPowerSaveBlocker::DPMSEnabled() {
  Display* display = base::MessagePumpForUI::GetDefaultXDisplay();
  BOOL enabled = false;
  int dummy;
  if (DPMSQueryExtension(display, &dummy, &dummy) && DPMSCapable(display)) {
    CARD16 state;
    DPMSInfo(display, &state, &enabled);
  }
  return enabled;
}

// static
DBusPowerSaveBlocker* DBusPowerSaveBlocker::GetInstance() {
  return Singleton<DBusPowerSaveBlocker>::get();
}

}  // namespace

// Called only from UI thread.
// static
void PowerSaveBlocker::ApplyBlock(PowerSaveBlockerType type) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DBusPowerSaveBlocker::GetInstance()->ApplyBlock(type);
}

// TODO(mdm): remove from the beginning of the file up to (and including) this
// line to switch to the new implementation.
#define PowerSaveBlocker PowerSaveBlocker2

namespace {

enum DBusAPI {
  NO_API,           // Disable. No supported API available.
  GNOME_API,        // Use the GNOME API. (Supports more features.)
  FREEDESKTOP_API,  // Use the FreeDesktop API, for KDE4 and XFCE.
};

// Inhibit flags defined in the org.gnome.SessionManager interface.
// Can be OR'd together and passed as argument to the Inhibit() method
// to specify which power management features we want to suspend.
enum GnomeAPIInhibitFlags {
  INHIBIT_LOGOUT            = 1,
  INHIBIT_SWITCH_USER       = 2,
  INHIBIT_SUSPEND_SESSION   = 4,
  INHIBIT_MARK_SESSION_IDLE = 8
};

const char kGnomeAPIServiceName[] = "org.gnome.SessionManager";
const char kGnomeAPIInterfaceName[] = "org.gnome.SessionManager";
const char kGnomeAPIObjectPath[] = "/org/gnome/SessionManager";

const char kFreeDesktopAPIServiceName[] = "org.freedesktop.PowerManagement";
const char kFreeDesktopAPIInterfaceName[] =
    "org.freedesktop.PowerManagement.Inhibit";
const char kFreeDesktopAPIObjectPath[] =
    "/org/freedesktop/PowerManagement/Inhibit";

}  // anonymous namespace

namespace content {

class PowerSaveBlocker::Delegate
    : public base::RefCountedThreadSafe<PowerSaveBlocker::Delegate> {
 public:
  // Picks an appropriate D-Bus API to use based on the desktop environment.
  Delegate(PowerSaveBlockerType type, const std::string& reason);

  // Apply or remove the power save block, respectively. These methods should be
  // called once each, on the same thread, per instance. They block waiting for
  // the action to complete (with a timeout); the thread must thus allow IO.
  void ApplyBlock();
  void RemoveBlock();

 private:
  friend class base::RefCountedThreadSafe<Delegate>;
  ~Delegate() {}

  // If DPMS (the power saving system in X11) is not enabled, then we don't want
  // to try to disable power saving, since on some desktop environments that may
  // enable DPMS with very poor default settings (e.g. turning off the display
  // after only 1 second).
  static bool DPMSEnabled();

  // Returns an appropriate D-Bus API to use based on the desktop environment.
  static DBusAPI SelectAPI();

  const PowerSaveBlockerType type_;
  const std::string reason_;
  const DBusAPI api_;

  scoped_refptr<dbus::Bus> bus_;

  // The cookie that identifies our inhibit request,
  // or 0 if there is no active inhibit request.
  uint32 inhibit_cookie_;

  DISALLOW_COPY_AND_ASSIGN(Delegate);
};

PowerSaveBlocker::Delegate::Delegate(PowerSaveBlockerType type,
                                     const std::string& reason)
    : type_(type),
      reason_(reason),
      api_(SelectAPI()),
      inhibit_cookie_(0) {
  // We're on the client's thread here, so we don't allocate the dbus::Bus
  // object yet. We'll do it below in ApplyBlock(), on the FILE thread.
}

void PowerSaveBlocker::Delegate::ApplyBlock() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  DCHECK(!bus_.get());  // ApplyBlock() should only be called once.
  if (api_ == NO_API)
    return;

  dbus::Bus::Options options;
  options.bus_type = dbus::Bus::SESSION;
  options.connection_type = dbus::Bus::PRIVATE;
  bus_ = new dbus::Bus(options);

  scoped_refptr<dbus::ObjectProxy> object_proxy;
  scoped_ptr<dbus::MethodCall> method_call;
  scoped_ptr<dbus::MessageWriter> message_writer;

  switch (api_) {
    case NO_API:
      NOTREACHED();  // We return early above.
      return;
    case GNOME_API:
      object_proxy = bus_->GetObjectProxy(
          kGnomeAPIServiceName,
          dbus::ObjectPath(kGnomeAPIObjectPath));
      method_call.reset(
          new dbus::MethodCall(kGnomeAPIInterfaceName, "Inhibit"));
      message_writer.reset(new dbus::MessageWriter(method_call.get()));
      // The arguments of the method are:
      //     app_id:        The application identifier
      //     toplevel_xid:  The toplevel X window identifier
      //     reason:        The reason for the inhibit
      //     flags:         Flags that spefify what should be inhibited
      message_writer->AppendString(
          CommandLine::ForCurrentProcess()->GetProgram().value());
      message_writer->AppendUint32(0);  // should be toplevel_xid
      message_writer->AppendString(reason_);
      {
        uint32 flags = 0;
        switch (type_) {
          case kPowerSaveBlockPreventDisplaySleep:
            flags |= INHIBIT_MARK_SESSION_IDLE;
            flags |= INHIBIT_SUSPEND_SESSION;
            break;
          case kPowerSaveBlockPreventAppSuspension:
            flags |= INHIBIT_SUSPEND_SESSION;
            break;
        }
        message_writer->AppendUint32(flags);
      }
      break;
    case FREEDESKTOP_API:
      object_proxy = bus_->GetObjectProxy(
          kFreeDesktopAPIServiceName,
          dbus::ObjectPath(kFreeDesktopAPIObjectPath));
      method_call.reset(
          new dbus::MethodCall(kFreeDesktopAPIInterfaceName, "Inhibit"));
      message_writer.reset(new dbus::MessageWriter(method_call.get()));
      // The arguments of the method are:
      //     app_id:        The application identifier
      //     reason:        The reason for the inhibit
      message_writer->AppendString(
          CommandLine::ForCurrentProcess()->GetProgram().value());
      message_writer->AppendString(reason_);
      break;
  }

  // We could do this method call asynchronously, but if we did, we'd need to
  // handle the case where we want to cancel the block before we get a reply.
  // We're on the FILE thread so it should be OK to block briefly here.
  scoped_ptr<dbus::Response> response(object_proxy->CallMethodAndBlock(
      method_call.get(), dbus::ObjectProxy::TIMEOUT_USE_DEFAULT));
  if (response.get()) {
    // The method returns an inhibit_cookie, used to uniquely identify
    // this request. It should be used as an argument to Uninhibit()
    // in order to remove the request.
    dbus::MessageReader message_reader(response.get());
    if (!message_reader.PopUint32(&inhibit_cookie_))
      LOG(ERROR) << "Invalid Inhibit() response: " << response->ToString();
  } else {
    LOG(ERROR) << "No response to Inhibit() request!";
  }
}

void PowerSaveBlocker::Delegate::RemoveBlock() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  if (api_ == NO_API)
    return;
  DCHECK(bus_.get());  // RemoveBlock() should only be called once.

  scoped_refptr<dbus::ObjectProxy> object_proxy;
  scoped_ptr<dbus::MethodCall> method_call;

  switch (api_) {
    case NO_API:
      NOTREACHED();  // We return early above.
      return;
    case GNOME_API:
      object_proxy = bus_->GetObjectProxy(
          kGnomeAPIServiceName,
          dbus::ObjectPath(kGnomeAPIObjectPath));
      method_call.reset(
          new dbus::MethodCall(kGnomeAPIInterfaceName, "Uninhibit"));
      break;
    case FREEDESKTOP_API:
      object_proxy = bus_->GetObjectProxy(
          kFreeDesktopAPIServiceName,
          dbus::ObjectPath(kFreeDesktopAPIObjectPath));
      method_call.reset(
          new dbus::MethodCall(kFreeDesktopAPIInterfaceName, "Uninhibit"));
      break;
  }

  dbus::MessageWriter message_writer(method_call.get());
  message_writer.AppendUint32(inhibit_cookie_);
  scoped_ptr<dbus::Response> response(object_proxy->CallMethodAndBlock(
      method_call.get(), dbus::ObjectProxy::TIMEOUT_USE_DEFAULT));
  if (!response.get())
    LOG(ERROR) << "No response to Uninhibit() request!";
  // We don't care about checking the result. We assume it works; we can't
  // really do anything about it anyway if it fails.
  inhibit_cookie_ = 0;

  bus_->ShutdownAndBlock();
  bus_ = NULL;
}

// static
bool PowerSaveBlocker::Delegate::DPMSEnabled() {
  Display* display = base::MessagePumpForUI::GetDefaultXDisplay();
  BOOL enabled = false;
  int dummy;
  if (DPMSQueryExtension(display, &dummy, &dummy) && DPMSCapable(display)) {
    CARD16 state;
    DPMSInfo(display, &state, &enabled);
  }
  return enabled;
}

// static
DBusAPI PowerSaveBlocker::Delegate::SelectAPI() {
  scoped_ptr<base::Environment> env(base::Environment::Create());
  switch (base::nix::GetDesktopEnvironment(env.get())) {
    case base::nix::DESKTOP_ENVIRONMENT_GNOME:
      if (DPMSEnabled())
        return GNOME_API;
      break;
    case base::nix::DESKTOP_ENVIRONMENT_XFCE:
    case base::nix::DESKTOP_ENVIRONMENT_KDE4:
      if (DPMSEnabled())
        return FREEDESKTOP_API;
      break;
    case base::nix::DESKTOP_ENVIRONMENT_KDE3:
    case base::nix::DESKTOP_ENVIRONMENT_OTHER:
      // Not supported.
      break;
  }
  return NO_API;
}

PowerSaveBlocker::PowerSaveBlocker(
    PowerSaveBlockerType type, const std::string& reason)
    : delegate_(new Delegate(type, reason)) {
  // The thread we use here becomes the origin and D-Bus thread for the D-Bus
  // library, so we need to use the same thread below in the destructor. It must
  // be a thread that allows I/O operations.
  BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
                          base::Bind(&Delegate::ApplyBlock, delegate_));
}

PowerSaveBlocker::~PowerSaveBlocker() {
  BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
                          base::Bind(&Delegate::RemoveBlock, delegate_));
}

}  // namespace content