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