Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically prevent linux computer from sleeping or turning on screensaver?

While developing a small cross-platform game on C++, I got stuck with following issue: when players are playing with a USB gamepad without touching a keyboard or mouse, the computer sleeps automatically while they're playing.

In Windows, it can be done easily using SetThreadExecutionState function. In OS X, I think it can be done with UpdateSystemActivity but not tested yet.

But the problem is, in Linux there's nothing like a common API between DE's. I've found that in Gnome you can stop the auto-suspending by using DBus calls Inhibit() and Uninhibit(), but it works only for Gnome.

So, is there exists a programatically cross-DE way (or non-DE way, for example if user is using something like dwm or awesome wm) to prevent a Linux system (using Xorg and without root access of course) from sleeping or turning on screensaver without changing user configuration files?

PS: Don't think that it's too complicated, but don't know how unfortunately.

like image 407
FalconUA Avatar asked Jul 19 '15 04:07

FalconUA


2 Answers

From a quick look at how mplayer and SDL do it, there are two things you can do to prevent the screensaver from firing up:

  • Disable it for the duration of the program:
    • Using XScreenSaverSuspend
    • Using DBus, calling org.freedesktop.ScreenSaver.Inhibit
  • Ping it periodically:
    • Using XResetScreenSaver
    • Using DBus, calling org.freedesktop.ScreenSaver.SimulateUserActivity
like image 118
ninjalj Avatar answered Nov 16 '22 15:11

ninjalj


I'm using QTDBUS using that

QDBusConnection bus = QDBusConnection::sessionBus();
if(bus.isConnected())
{
    QString services[MAX_SERVICES] = {
        "org.freedesktop.ScreenSaver",
        "org.gnome.SessionManager"
    };
    QString paths[MAX_SERVICES] = {
        "/org/freedesktop/ScreenSaver",
        "/org/gnome/SessionManager"
    };

    for(int i = 0; i < MAX_SERVICES ; i++)
    {        
        QDBusInterface screenSaverInterface(
            services[i], paths[i],services[i], bus, this);
        if (!screenSaverInterface.isValid())
            continue;       

        QDBusReply<uint> reply = screenSaverInterface.call(
            "Inhibit", "YOUR_APP_NAME", "REASON");
        if (reply.isValid())
        {
            cookieID = reply.value();
            qDebug()<<"succesful"
        } else {   
            QDBusError error =reply.error();
            qDebug()<<error.message()<<error.name();   
        }
    }
}
like image 4
Virupaksha Avatar answered Nov 16 '22 15:11

Virupaksha