Use QDialog instead of QWidget for Settings
[qcpufreq] / src / mainwindow.cpp
1 /*
2  * QCPUFreq - a simple cpufreq GUI
3  * Copyright (C) 2010 Daniel Klaffenbach <danielklaffenbach@gmail.com>
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18
19 #include "mainwindow.h"
20 #include "ui_mainwindow.h"
21
22 #include <QFile>
23 #include <QMessageBox>
24 #include <QTextStream>
25 #include <QDesktopWidget>
26 #if defined(Q_WS_MAEMO_5)
27     #include <QMaemo5InformationBox>
28 #endif
29
30 #define APPNAME "QCPUFreq"
31 #define APPVERSION "0.3.4"
32
33 MainWindow::MainWindow(QWidget *parent) :
34     QMainWindow(parent),
35     ui(new Ui::MainWindow),
36     //do not allow overclocking per default
37     allowOverclocking(false),
38     //create helper process
39     helperProcess( this ),
40     //create a new, stackable help window
41     helpWindow( this ),
42     //create UI refresh timer
43     refreshTimer( this ),
44     //create a QGraphicsScene for the little chip icon
45     scene( this ),
46     //the settings widget
47     settings(this),
48     //show errors about the sudo setup only once
49     showSudoError( true )
50 {
51     //this is a stacked window on Maemo 5
52     #if defined(Q_WS_MAEMO_5)
53         setAttribute(Qt::WA_Maemo5StackedWindow);
54     #endif
55
56     ui->setupUi(this);
57
58     init();
59     refresh();
60
61     // enable auto rotation
62     setAutoRotation();
63
64     //initialize orientation
65     orientationChanged();
66
67     //refresh UI every 10 seconds
68     refreshTimer.start( 10000 );
69
70     // initialize stackable help window
71     #if defined(Q_WS_MAEMO_5)
72         helpWindow.setAttribute(Qt::WA_Maemo5StackedWindow);
73     #endif
74     helpWindow.setWindowFlags( windowFlags() | Qt::Window );
75
76     //Settings widget
77     //settings.setWindowFlags(Qt::Popup);
78     settings.hide();
79
80     //connect signals and slots
81     connect(ui->actionHelp, SIGNAL(triggered()), this, SLOT(showHelp()));
82     connect( ui->actionAbout, SIGNAL(triggered()), this, SLOT(about()) );
83     connect( ui->freq_adjust, SIGNAL(valueChanged(int)), this, SLOT(adjustFreq()) );
84     connect(QApplication::desktop(), SIGNAL(resized(int)), this, SLOT(orientationChanged()));
85     connect(ui->sr_box, SIGNAL(clicked()), this, SLOT(setSmartReflex()));
86     connect(&refreshTimer, SIGNAL(timeout()), this, SLOT(refresh()));
87     connect(ui->actionOverclocking, SIGNAL(toggled(bool)), this, SLOT(setOverclocking()));
88     connect(ui->actionSettings, SIGNAL(triggered()), this, SLOT(showSettings()));
89
90
91     //disable overclocking button on vanilla kernels
92     if (!powerKernel) {
93         ui->actionOverclocking->setDisabled(true);
94     }
95
96 }
97
98 MainWindow::~MainWindow()
99 {
100     delete ui;
101 }
102
103
104 /**
105   * SLOT: Displays an about box
106   */
107 void MainWindow::about()
108 {
109     QMessageBox::about(this, APPNAME " " APPVERSION, "<p style=\"align:center;\">&copy; 2010 Daniel Klaffenbach</p>" );
110     refresh();
111 }
112
113
114 /**
115   * SLOT: Adjusts the maximum CPU frequency according to the scaler
116   */
117 void MainWindow::adjustFreq()
118 {
119     int newmax = getScalingFreq( ui->freq_adjust->sliderPosition() );
120
121     if (newmax == getMaxFreq() ) {
122         //we do not need to change anything in this case
123         return;
124     }
125
126     QString max;
127
128     //maxfreq should not be smaller than minfreq, because we do not want to decrease minfreq
129     if (newmax < getMinFreq())
130         newmax = getMinFreq();
131
132     max.setNum( newmax );
133
134     //check for overclocking
135     #if defined(Q_WS_MAEMO_5)
136     if (this->allowOverclocking == false && newmax > 600000) {
137         QMaemo5InformationBox::information(this, tr( "You need to enable overclocking in QCPUFreq's menu for setting frequencies above 600MHz!"), 0);
138         refresh();
139         return;
140     }
141     #endif
142
143     callHelper( "set_maxfreq", max );
144
145     refresh();
146 }
147
148
149 /**
150   * Calls the QCPUFreq helper script with "sudo action param"
151   *
152   * @param  action : the action of the helper script
153   * @param  param : the parameter for the action
154   * @return exit code
155   */
156 int MainWindow::callHelper(QString action, QString param)
157 {
158     QStringList arguments;
159
160     #if defined(Q_WS_MAEMO_5)
161     //On Maemo 5 the helper script resides in /opt/usr/bin, which is usually not in $PATH
162     arguments.append( "/opt/usr/bin/QCPUFreq.helper" );
163     #else
164     arguments.append( "QCPUFreq.helper" );
165     #endif
166
167     arguments.append( action );
168     arguments.append( param );
169
170     helperProcess.start( "sudo", arguments, QIODevice::NotOpen );
171
172     if ( showSudoError && !helperProcess.waitForFinished( 400 )) {
173         //do not show this error again
174         showSudoError = false;
175         QMessageBox::critical(this, tr("QCPUFreq"), tr("There seems to be a problem with your sudo setup!"));
176     }
177
178     return helperProcess.exitCode();
179 }
180
181
182 /**
183   * Returns the current CPU temperature
184   */
185 QString MainWindow::getCPUTemp()
186 {
187 #if defined(Q_WS_MAEMO_5)
188     QFile file( "/sys/class/power_supply/bq27200-0/temp" );
189
190     //check if we can read a more accurate temperature (only for power kernel)
191     if (file.exists())
192         return QString( readSysFile( "class/power_supply/bq27200-0/temp" ) + " " + QString::fromUtf8("\302\260") + "C" );
193     else {
194         /*
195           We actually only need to read the raw temperature, but it appears that by also reading temp1_input
196           the raw temperature (temp1_input_raw) is being updated more frequently.
197         */
198         readSysFile( "devices/platform/omap34xx_temp/temp1_input" );
199
200         //read the current system temperature
201         QString tstring = readSysFile( "devices/platform/omap34xx_temp/temp1_input_raw" );
202         if (tstring == "0")
203             return tr( "Unknown" );
204
205         //convert it to an integer and calculate the approx. temperature from the raw value
206         int tint = tstring.toInt();
207         tint = ( 0.65 * tint );
208         tstring.setNum(tint);
209         return QString( tstring + " " + QString::fromUtf8("\302\260") + "C" );
210     }
211 #endif
212     return tr( "Unknown" );
213 }
214
215
216 /**
217   * Returns the maximum CPU frequency
218   */
219 int MainWindow::getMaxFreq()
220 {
221     QString tmp = readSysFile( "devices/system/cpu/cpu0/cpufreq/scaling_max_freq" );
222     return tmp.toInt();
223 }
224
225
226 /**
227   * Returns the minimum CPU frequency
228   */
229 int MainWindow::getMinFreq()
230 {
231     return this->minFreq;
232 }
233
234
235 /**
236   * Returns the CPU frequency for the specified scaling step
237   */
238 int MainWindow::getScalingFreq(int step)
239 {
240     step = step - 1;
241     if ( step < 0 )
242          step = 0;
243     if ( step > getScalingSteps() - 1 )
244         step = getScalingSteps() - 1;
245
246     return this->scalingFrequencies[ step ].toInt();
247 }
248
249
250 /**
251   * Returns the name of the current CPU frequency scaling governor
252   *
253   * @return     QString - name of governor
254   */
255 QString MainWindow::getScalingGovernor()
256 {
257     return readSysFile( "devices/system/cpu/cpu0/cpufreq/scaling_governor" );
258 }
259
260
261 /**
262   * Returns the amount of available scaling steps.
263   *
264   * @return int
265   */
266 int MainWindow::getScalingSteps()
267 {
268     return this->scalingSteps;
269 }
270
271
272 /**
273   * Returns the scaling step for the specified frequency.
274   *
275   * @return int
276   */
277 int MainWindow::getScalingStep( int freq )
278 {
279     QString tmp;
280     tmp.setNum(freq);
281     return this->scalingFrequencies.indexOf(tmp) + 1;
282 }
283
284
285 /**
286   * Returns the SmartReflex(tm) state
287   *
288   * \return     0|1
289   */
290 int MainWindow::getSmartReflexState()
291 {
292 //SmartReflex is only supprted on Maemo5
293 #if defined(Q_WS_MAEMO_5)
294     QString tmp = readSysFile( "power/sr_vdd1_autocomp" );
295
296     if ( tmp == "1" ) {
297         return 1;
298     } else {
299         return 0;
300     }
301 #else
302     //disable UI checkbox
303     ui->sr_box->setDisabled( true );
304
305     return 0;
306 #endif
307 }
308
309
310 /**
311   * Initializes internal variables, such as:
312   *  - scalingSteps
313   *  - scalingFrequencies
314   *  - minFreq
315   *  - powerKernel
316   */
317 void MainWindow::init()
318 {
319     this->minFreq = 0;
320     QString freqs = readSysFile( "devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies" );
321     QStringList freqList = freqs.split( " " );
322     //change the order of the QStringList - last element becomes first
323     for (int i=freqList.size() - 1; i>=0; --i) {
324         if (freqList.at(i) != "")
325             this->scalingFrequencies << freqList.at(i);
326     }
327     this->scalingSteps = (this->scalingFrequencies.size());
328
329     //set minFreq and check avoid_frequencies
330     QString min = readSysFile( "devices/system/cpu/cpu0/cpufreq/scaling_min_freq" );
331     //check if avoid file exists (only on power kernel)
332     QFile file( "/sys/devices/system/cpu/cpu0/cpufreq/ondemand/avoid_frequencies" );
333     if (file.exists()) {
334         QString avoid = readSysFile( "devices/system/cpu/cpu0/cpufreq/ondemand/avoid_frequencies" );
335         QStringList avoidList = avoid.split( " " );
336
337         //check if min is in avoid_frequencies
338         for (int i = getScalingStep( min.toInt() ); i <= this->scalingSteps; ++i) {
339             min.setNum( getScalingFreq(i) );
340             if (!avoidList.contains(min)) {
341                 this->minFreq = min.toInt();
342                 break;
343             }
344         }
345     } else {
346         this->minFreq = min.toInt();
347     }
348
349     //check if we are using a power kernel
350     if ( getScalingFreq(getScalingSteps()) > 600000 ) {
351         this->powerKernel = true;
352     } else {
353         this->powerKernel = false;
354     }
355 }
356
357
358 /**
359   * Reads any file in /sys/
360   *
361   * \param      sys_file : full path to sys file - omit "/sys/"
362   * \return     content of sys file
363   */
364 QString MainWindow::readSysFile(QString sys_file)
365 {
366     QFile file( "/sys/"+sys_file );
367
368     //open the file
369     if ( !file.exists() || !file.open( QIODevice::ReadOnly ) ) {
370         QMessageBox::critical(this, tr("QCPUFreq"), tr("Could not get information from /sys!"));
371         return "";
372     }
373
374     //read the file
375     QTextStream in( &file );
376     QString txt = in.readLine();
377
378     //close the file
379     file.close();
380
381     return txt;
382 }
383
384
385 /**
386   * Refreshes all of the values to display
387   */
388 void MainWindow::refresh()
389 {
390     //get the current frequency and calculate the MHz value
391     int freq = ( getMinFreq() / 1000 );
392     QString display;
393     display.setNum( freq );
394     display.append( " MHz" );
395     ui->freq_min->setText( display );
396
397     //do the same thing for the maximum frequency
398     freq = ( getMaxFreq() / 1000 );
399     display.setNum( freq );
400     display.append( " MHz" );
401     ui->freq_max->setText( display );
402
403     //display the current governor
404     ui->freq_governor->setText( getScalingGovernor() );
405
406     //display current temperature
407     ui->cpu_temp->setText( getCPUTemp() );
408
409     //smart reflex button
410     if ( getSmartReflexState() == 1 )
411         ui->sr_box->setCheckState( Qt::Checked );
412     else
413         ui->sr_box->setCheckState( Qt::Unchecked );
414
415
416     //display frequency slider
417     ui->freq_adjust->setMinimum( 1 );
418     ui->freq_adjust->setMaximum( getScalingSteps() );
419     ui->freq_adjust->setSliderPosition( getScalingStep(getMaxFreq()) );
420
421     //ui->retranslateUi(this);
422 }
423
424
425 /**
426   * Repaints part of the GUI after the device was rotated
427   */
428 void MainWindow::orientationChanged()
429 {
430     QPixmap image;
431
432     //check whether we are using portrait or landscape mode
433     if ( usePortrait() ) {
434         //in portrait mode we want to display the large image
435         image.load( ":/img/chip256" );
436         scene.clear();
437         scene.addPixmap(  image  );
438
439         ui->graphicsPortrait->setScene( &scene );
440         ui->graphicsPortrait->setMaximumSize( 256, 256 );
441         ui->graphicsLandscape->setMaximumSize( 0, 0 );
442     } else {
443         image.load( ":/img/chip128" );
444         scene.clear();
445         scene.addPixmap(  image  );
446
447         ui->graphicsLandscape->setScene( &scene );
448         ui->graphicsLandscape->setMaximumSize( 128, 128 );
449         ui->graphicsPortrait->setMaximumSize( 0, 0 );
450     }
451 }
452
453
454 /**
455   * Enables the auto-rotation feature of Maemo5 devices
456   */
457 void MainWindow::setAutoRotation()
458 {
459 #if defined(Q_WS_MAEMO_5)
460     setAttribute(Qt::WA_Maemo5AutoOrientation, true);
461 #endif
462 }
463
464
465 /**
466   * SLOT: enable/disable overclocking.
467   */
468 void MainWindow::setOverclocking()
469 {
470     if (ui->actionOverclocking->isChecked()) {
471         #if defined(Q_WS_MAEMO_5)
472         QMaemo5InformationBox::information(this, tr( "Please note that overclocking voids your warranty and may break your device! Be careful!"), 0);
473         #endif
474         this->allowOverclocking = true;
475     } else {
476         this->allowOverclocking = false;
477     }
478 }
479
480
481 /**
482   * SLOT: Enables or disables Smart Reflex(tm) after pressing sr_btn
483   */
484 void MainWindow::setSmartReflex()
485 {
486 //SmartReflex is only supported on Maemo5
487 #if defined(Q_WS_MAEMO_5)
488     if ( getSmartReflexState() == 1 )
489         callHelper( "set_sr", "off");
490     else {
491         QMaemo5InformationBox::information(this, tr( "SmartReflex support is known to be unstable on some devices and may cause random reboots." ), 0);
492         callHelper( "set_sr", "on");
493     }
494
495 #endif
496     //refresh the UI
497     refresh();
498 }
499
500
501 /**
502   * SLOT: display the help window
503   */
504 void MainWindow::showHelp()
505 {
506     helpWindow.show();
507 }
508
509
510 /**
511   * SLOT: displays the settings widget
512   */
513 void MainWindow::showSettings()
514 {
515     settings.reset();
516     settings.show();
517 }
518
519
520 /**
521   * Returns true when the device is in portrait mode
522   */
523 bool MainWindow::usePortrait()
524 {
525     QRect screenGeometry = QApplication::desktop()->screenGeometry();
526     if (screenGeometry.width() > screenGeometry.height())
527         return false;
528     else
529         return true;
530 }