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