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