Logo Search packages:      
Sourcecode: shutdown-qapps version File versions  Download package

gui.cpp

/* qshutdown, a program to shutdown the system
 * Copyright (C) 2009 2010  Christian Metscher <hakaishi@web.de>

 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#ifndef GUI_CPP
#define GUI_CPP

#include "gui.h"

Gui::Gui(QWidget *parent)
     : QWidget(parent){

      setupUi(this);

     datetime = QDateTime::currentDateTime();
     elapsedTime.start();

     setWindowFlags(Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint |
       Qt::WindowTitleHint | Qt::WindowMinimizeButtonHint);    //always in front

   //Changing SizePolicy for Spacers
     horizontalSpacer1->changeSize(40,45,QSizePolicy::Expanding,QSizePolicy::Expanding);
     horizontalSpacer3->changeSize(85,13,QSizePolicy::Maximum,QSizePolicy::Expanding);
     horizontalSpacer4->changeSize(85,13,QSizePolicy::Maximum,QSizePolicy::Expanding);
     horizontalSpacer5->changeSize(85,13,QSizePolicy::Maximum,QSizePolicy::Expanding);

   //TrayIcon
     icon = QIcon(":/pixmap/red_glasses.png");
     TIcon = new QSystemTrayIcon(this);
     TIcon->setIcon(icon);
     TIcon->show();

   //TrayIconContextMenu
     menu = new QMenu(this);
     reset_action = new QAction("&Reset",this);
     quit_action = new QAction("&Quit",this);
     info_action = new QAction("&Info",this);
     log_action = new QAction("&Logfile",this);
     log_action->setCheckable(true);
     menu->addAction(info_action);
     menu->addAction(reset_action);
     menu->addAction(log_action);
     reset_action->setVisible(false);
     menu->addSeparator();
     menu->addAction(quit_action);
     
     TIcon->setContextMenu(menu);  //setting contextmenu for the systray

   //InfoMessageBox
     infoBox = new QMessageBox;
     infoBox->setWindowTitle("Info");
     infoBox->setIcon(QMessageBox::Information);
     infoBox->setWindowModality(Qt::NonModal);
     infoBox->setWindowFlags(Qt::WindowStaysOnTopHint);
     infoBox->setInformativeText(tr("qshutdown will show it self 3 times as a warning "
     "if there are less than 70 seconds left.\n\n"
     "This program uses qdbus to send a shutdown request to the gnome- or kde-session. "
     "If it won't do gnome-power-cmd or gnome-power-cmd.sh will be used. When this also "
     "fails then qdbus will send the shutdown request to HAL (note that when sending the "
     "request to HAL the Session will never be saved). And if this won't do as well, the "
     "sudo shutdown command will be used. In this case you need root-rights, so one needs "
     "to do the following:\n\n"
     "Paste the following in a terminal:\n"
     "\"EDITOR:nano sudo -E visudo\" and add this line:\n"
     "\"* ALL = NOPASSWD:/sbin/shutdown\" whereas * replaces the username or %groupname.\n\n"
     "The maximum Number of countdown_minutes is 1440 (24 hours).\n"
     "The configurationfile (and logfile) is located at ~/.qshutdown (under Linux/Unix)."));

   //PushButton Minimize
     minim = new QPushButton(this); //to minimize
     minim->setText(tr("&Minimize!"));
     minim->setHidden(true); //not yet visible
     minim->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
     gridLayout5->addWidget(minim,0,1,3,1);

   //LCD-Anzeige
     lcd = new QLCDNumber(4, this); //display for countdown
     lcd->setSegmentStyle(QLCDNumber::Flat);
     lcd->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
     gridLayout4->addWidget(lcd,0,1,1,1);

   //Fonts
     font1 = new QFont;
     font1->setFamily(QString::fromUtf8("Times"));
     font1->setBold(true);

     font2 = new QFont;
     font2->setFamily(QString::fromUtf8("Times"));
     font2->setBold(true);

     font3 = new QFont;
     font3->setFamily(QString::fromUtf8("Times"));

   //Timer
     timer = new QTimer(this); //for updating countdown display and check if time is over
     ti = new QTimer(this); //for displaying the window, till the OK-Button is clicked
     ti->start(30000); //gives every 30 seconds a timeout()-signal

   //Connect signals with slots (actions with funktions)
     connect(ti, SIGNAL(timeout()), this, SLOT(showW())); //set window state for ti
     connect(ok, SIGNAL(clicked(bool)), this, SLOT(set()));     //runs set()
     connect(ok, SIGNAL(clicked(bool)), this, SLOT(starter())); //starts timer & stopps ti
     connect(timer, SIGNAL(timeout()), this, SLOT(update()));    //runs update() every 10 seconds
     connect(now, SIGNAL(clicked(bool)), this, SLOT(shutdown()));  //closes the program & starts the shutdown immediately
     connect(minim, SIGNAL(clicked(bool)), this, SLOT(mini())); //minimizes window
     connect(TIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
       this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason))); //handles systray-symbol
     connect(quit_action, SIGNAL(triggered()), this, SLOT(close())); //contextmenu "Quit" for the systray closes Programm
     connect(reset_action, SIGNAL(triggered()), this, SLOT(reset()));
     connect(info_action, SIGNAL(triggered()), this, SLOT(info()));
}

Gui::~Gui(){}

void Gui::center(){
     QDesktopWidget *desktop = qApp->desktop();
     QPoint pos((desktop->width() - frameGeometry().width()) / 2,
                (desktop->height() - frameGeometry().height()) / 2);
     move(pos);
}

void Gui::iconActivated(QSystemTrayIcon::ActivationReason reason){
     if(reason == QSystemTrayIcon::Trigger){
       if(isHidden()||isMinimized())  //in case thant the window is minimized or hidden
         showNormal();
       else
         hide();
     }
}

void Gui::showW(){
     if(check2->isChecked()) //warnings is checked
       showRunningProgram();
}

void Gui::showRunningProgram(){
     if(isMinimized() || isHidden())
       showNormal();
     else
       activateWindow();
}

void Gui::update(){
     Time();  //calculates i or rather the new time every second
     if(check2->isChecked() && (((i<=100) && (i>95)) || ((i<=40) && (i>35))) && !ti->isActive())
       ti->start();
     QString tip;
     if((i/60.0)>=60) //look at iconActivated()
       tip = ("'shutdown' " + QString::number(i/3600) + tr(" hour(s) + ")
              + QString::number(i/60 - (i/3600)*60) + tr(" minute(s)"));
     else if(((i/60.0)<60) && (i>=60)) //look at iconActivated()
       tip = ("'shutdown' " + QString::number(i/60) + tr(" minute(s)"));
     else if(i<60) //look at iconActivated()
       tip = ("'shutdown' " + QString::number(i) + tr(" second(s)"));
     setWindowTitle(tip);
     TIcon->setToolTip(tip);
     if((i<=70) && check3->isChecked()) //only show when i<=70 secs
       reset_action->setVisible(true);
     else
       reset_action->setVisible(false);
     if(i>=60){
       lcdL->setText(tr("Minute(s)"));
       lcd->display(i/60);
     }
     else if(i<60){
       lcdL->setText(tr("Second(s)"));
       lcd->display(i);
     }
     if(i<=86390)
       n = 10; //any number to keep i in check
     if((i==0) || ((i>n) && (i>86390)))
       shutdown(); //execute shutdown
}

void Gui::starter(){ ti->stop(); timer->start(1000); } //stops ti-Qtimer and starts timer-Qtimer

void Gui::mini(){ setWindowState(Qt::WindowMinimized); } //minimizes window

void Gui::set(){
     localTime = QTime::currentTime(); //the time now
     if(check->isChecked()==false) //if minute-countdown
       futureTime = localTime.addSecs(spin->value()*60); //add spinbox-value to the current time
     else
       futureTime = timeEdit->time(); //else the future time is the time of the timeEdit
     n = 86400; // any number bigger than i - just for initializing

     if(check3->isChecked()==true){       //when OK-button is clicked
       spin->setDisabled(true);             //deaktivate spinbox
       check->setDisabled(true);            //deaktivate radiobutton
       check3->setDisabled(true);            //deaktivate radiobutton
       timeEdit->setDisabled(true);         //deaktivate timeEdit
       shutdown_time->setDisabled(true);
       minutes->setDisabled(true);
       ok->hide();                          //hides OK-button
       minim->show();                       //shows Minimieren-Button
       minim->setFocus();                   //sets focus to minimize-button
       minim->setAutoDefault(true);         //minimize-button will accept the return key
     }
     setWindowState(Qt::WindowMinimized); //minimize window
}

void Gui::Time(){
     localTime = QTime::currentTime(); //current time
     i = localTime.secsTo(futureTime); //the difference of the localTime and the future time
     if(i<0)                           //if the date is on the next day
       i = 86400 + localTime.secsTo(futureTime); //add 1 day in seconds
}

void Gui::saveWindowSize(){
   #ifdef Q_OS_WIN32
     QString file(QDir::homePath() + "/Anwendungsdaten/qshutdown/qshutdown.conf");
     QSettings settings(file, QSettings::IniFormat);
   #else
     QString file(QDir::homePath() + "/.qshutdown/qshutdown.conf");
     QSettings settings(file, QSettings::NativeFormat);
   #endif
     settings.setValue("Window_Size/size", size());
}

void Gui::shutdown(){
     saveWindowSize();
   #ifdef Q_OS_WIN32
     QProcess::startDetached("shutdown -s -t 00"); // Windows command to shutdown immediately
   #else
     bool shutdown_works = false;
     bool gnome_power1 = false;
     bool gnome_power2 = false;
     QDBusMessage response;

     QDBusInterface gnomeSessionManager("org.gnome.SessionManager", "/org/gnome/SessionManager",
       "org.gnome.SessionManager", QDBusConnection::sessionBus());
     response = gnomeSessionManager.call("RequestShutdown");
     if(response.type() == QDBusMessage::ErrorMessage){
       gnome_power1 = QProcess::startDetached("gnome-power-cmd.sh shutdown");
       gnome_power2 = QProcess::startDetached("gnome-power-cmd shutdown");
     }
     else
       shutdown_works = true;

     QDBusInterface kdeSessionManager("org.kde.ksmserver", "/KSMServer",
       "org.kde.KSMServerInterface", QDBusConnection::sessionBus());
     response = kdeSessionManager.call("logout", 0, 2, 2);
     if(response.type() == QDBusMessage::ErrorMessage){ /*nothing to do*/ ; }
     else
       shutdown_works = true;

     if((shutdown_works == false) && (gnome_power1 == false) && (gnome_power2 == false)){
       QDBusInterface powermanagement("org.freedesktop.Hal", "/org/freedesktop/Hal/devices/computer",
         "org.freedesktop.Hal.Device.SystemPowerManagement", QDBusConnection::systemBus());
       response = powermanagement.call("Shutdown");
       if(response.type() == QDBusMessage::ErrorMessage)
         QProcess::startDetached("sudo shutdown -P now");
     }
   #endif
}

void Gui::closeEvent(QCloseEvent* window_close){
     saveWindowSize();
   #ifdef Q_OS_WIN32
     QString file(QDir::homePath() + "/Anwendungsdaten/qshutdown/qshutdown.conf");
     QSettings settings(file, QSettings::IniFormat);
   #else
     QString file(QDir::homePath() + "/.qshutdown/qshutdown.conf");
     QSettings settings(file, QSettings::NativeFormat);
   #endif
     if(log_action->isChecked()){ //if logfile is set in the icon contextmenu
       settings.setValue("Logfile/logging", true); //save for next session
     #ifdef Q_OS_WIN32
       QFile logfile(QDir::homePath() + "/Anwendungsdaten/qshutdown/log.txt");
     #else
       QFile logfile(QDir::homePath() + "/.qshutdown/log.txt");
     #endif
       if(!logfile.open(QIODevice::ReadWrite | QIODevice::Text))
         return;
       QTextStream out(&logfile);
       if(logfile.size()>1700){     //if the logfile is bigger than 1700 Bytes
         out.readLine();           //read or rather skip one line
         QString content = out.readAll(); //read rest
         logfile.resize(0);        //empty the file
         out << content;           //write saved rest
       }
       while(!logfile.atEnd())     //while the end of the file is not reached
         out.readLine();           //read one or rather the next line
       out << "[" << datetime.toString("dddd hh:mm") << "] "
           << 1/(60000.0/elapsedTime.elapsed()) << " Minutes uptime\n";
     }
     else
       settings.setValue("Logfile/logging", false); //if the logfile is not set in the icon-contextmenu

  #ifndef Q_OS_WIN32
     QDBusConnection::sessionBus().unregisterObject(OBJECT_NAME, QDBusConnection::UnregisterNode);
     QDBusConnection::sessionBus().unregisterService(SERVICE_NAME);
  #endif
       
     QWidget::closeEvent(window_close);
}

void Gui::resizeEvent(QResizeEvent* window_resize){
   #ifndef Q_OS_WIN32
     center();
   #endif
     QWidget::resizeEvent(window_resize);
}

void Gui::saved(){
#ifdef Q_OS_WIN32
     QString file("C:/Programme/qshutdown/qshutdown.conf");
     QSettings settings(file, QSettings::IniFormat);
#else
     QString file(QDir::homePath() + "/.qshutdown/qshutdown.conf");
     QSettings settings(file, QSettings::NativeFormat);
#endif
     if(!QFile::exists(file)){ //if the file doesn't exist
       settings.setValue("Time/time_hour", 22);
       settings.setValue("Time/time_minute", 00);
       settings.setValue("Time/countdown_minutes", 60);
       settings.setValue("Window_Size/size", QSize(440, 300));
       settings.setValue("Fonts/font1", 13);
       settings.setValue("Fonts/font2", 20);
       settings.setValue("Fonts/font3", 11);
       settings.setValue("CheckBoxes/time_or_countdown", false);
       settings.setValue("CheckBoxes/lock", true);
       settings.setValue("CheckBoxes/warnings", true);
     }

     timeEdit->setTime(QTime(settings.value("Time/time_hour").toInt(),settings.value("Time/time_minute").toInt()));
     spin->setValue(settings.value("Time/countdown_minutes").toInt());
     resize(settings.value("Window_Size/size").toSize());
     font1->setPointSize(settings.value("Fonts/font1").toInt());
     font2->setPointSize(settings.value("Fonts/font2").toInt());
     font3->setPointSize(settings.value("Fonts/font3").toInt());
     check->setChecked(settings.value("CheckBoxes/time_or_countdown").toBool());
     check3->setChecked(settings.value("CheckBoxes/lock").toBool());
     check2->setChecked(settings.value("CheckBoxes/warnings").toBool());
     log_action->setChecked(settings.value("Logfile/logging").toBool());

     shutdown_time->setFont(*font1);
     minutes->setFont(*font1);
     spin->setFont(*font1);
     timeEdit->setFont(*font1);
     lcdL->setFont(*font1);
     ok->setFont(*font2);
     minim->setFont(*font2);
     check2->setFont(*font3);
     check3->setFont(*font3);
     now->setFont(*font3);
}

void Gui::reset(){
     ti->stop();
     timer->stop();
     if(check->isChecked())
       timeEdit->setEnabled(true);
     else
       spin->setEnabled(true);
     check->setEnabled(true);
     check3->setEnabled(true);    
     shutdown_time->setEnabled(true);
     minutes->setEnabled(true);
     ok->show();
     minim->hide();
}

void Gui::info(){ infoBox->show(); ti->stop(); }


#endif

Generated by  Doxygen 1.6.0   Back to index