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