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