Do not set maxfreq twice
[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
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     if (this->minFreq == 0) {
225         QString min = readSysFile( "devices/system/cpu/cpu0/cpufreq/scaling_min_freq" );
226         //check if avoid file exists (only on power kernel)
227         QFile file( "/sys/devices/system/cpu/cpu0/cpufreq/ondemand/avoid_frequencies" );
228         if (file.exists()) {
229             QString avoid = readSysFile( "devices/system/cpu/cpu0/cpufreq/ondemand/avoid_frequencies" );
230             QStringList avoidList = avoid.split( " " );
231
232             //check if min is in avoid_frequencies
233             for (int i = getScalingStep( min.toInt() ); i>0; --i) {
234                 if (!avoidList.contains(min.setNum( getScalingFreq(i) ))) {
235                     this->minFreq = min.toInt();
236                     return this->minFreq;
237                 }
238             }
239
240             //should not happen at all
241             this->minFreq = 125000;
242             return this->minFreq;
243         } else {
244             this->minFreq = min.toInt();
245             return this->minFreq;
246         }
247     } else {
248         return this->minFreq;
249     }
250 }
251
252
253 /**
254   * Returns the CPU frequency for the specified scaling step
255   */
256 int MainWindow::getScalingFreq(int step)
257 {
258     QString tmp = readSysFile( "devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies" );
259     QStringList freqs = tmp.split( " " );
260     step = step - 1;
261     if ( step < 0 )
262          step = 0;
263     if ( step > getScalingSteps() )
264         step = getScalingSteps();
265
266     tmp = freqs[ step ];
267     return tmp.toInt();
268 }
269
270
271 /**
272   * Returns the name of the current CPU frequency scaling governor
273   *
274   * @return     QString - name of governor
275   */
276 QString MainWindow::getScalingGovernor()
277 {
278     return readSysFile( "devices/system/cpu/cpu0/cpufreq/scaling_governor" );
279 }
280
281
282 /**
283   * Returns the amount of available scaling steps.
284   *
285   * @return int
286   */
287 int MainWindow::getScalingSteps()
288 {
289     QString tmp = readSysFile( "devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies" );
290     QStringList freqs = tmp.split( " " );
291     return (freqs.size() - 1);
292 }
293
294
295 /**
296   * Returns the scaling step for the specified frequency.
297   *
298   * @return int
299   */
300 int MainWindow::getScalingStep( int freq )
301 {
302     for( int i = 1; i <= getScalingSteps(); ++i ) {
303            if ( getScalingFreq(i) == freq )
304                 return i;
305     }
306
307     return 1;
308 }
309
310
311 /**
312   * Returns the SmartReflex(tm) state
313   *
314   * \return     0|1
315   */
316 int MainWindow::getSmartReflexState()
317 {
318 //SmartReflex is only supprted on Maemo5
319 #if defined(Q_WS_MAEMO_5)
320     QString tmp = readSysFile( "power/sr_vdd1_autocomp" );
321
322     if ( tmp == "1" ) {
323         return 1;
324     } else {
325         return 0;
326     }
327 #else
328     //disable UI checkbox
329     ui->sr_box->setDisabled( true );
330
331     return 0;
332 #endif
333 }
334
335
336 /**
337   * Reads any file in /sys/
338   *
339   * \param      sys_file : full path to sys file - omit "/sys/"
340   * \return     content of sys file
341   */
342 QString MainWindow::readSysFile(QString sys_file)
343 {
344     QFile file( "/sys/"+sys_file );
345
346     //open the file
347     if ( !file.exists() || !file.open( QIODevice::ReadOnly ) ) {
348         QMessageBox::critical(this, tr("QCPUFreq"), tr("Could not get information from /sys!"));
349         return "";
350     }
351
352     //read the file
353     QTextStream in( &file );
354     QString txt = in.readLine();
355
356     //close the file
357     file.close();
358
359     return txt;
360 }
361
362
363 /**
364   * Refreshes all of the values to display
365   */
366 void MainWindow::refresh()
367 {
368     //get the current frequency and calculate the MHz value
369     int freq = ( getMinFreq() / 1000 );
370     QString display;
371     display.setNum( freq );
372     display.append( " MHz" );
373     ui->freq_min->setText( display );
374
375     //do the same thing for the maximum frequency
376     freq = ( getMaxFreq() / 1000 );
377     display.setNum( freq );
378     display.append( " MHz" );
379     ui->freq_max->setText( display );
380
381     //display the current governor
382     ui->freq_governor->setText( getScalingGovernor() );
383
384     //display current temperature
385     ui->cpu_temp->setText( getCPUTemp() );
386
387     //smart reflex button
388     if ( getSmartReflexState() == 1 )
389         ui->sr_box->setCheckState( Qt::Checked );
390     else
391         ui->sr_box->setCheckState( Qt::Unchecked );
392
393
394     //display frequency slider
395     ui->freq_adjust->setMinimum( 1 );
396     ui->freq_adjust->setMaximum( getScalingSteps() );
397     ui->freq_adjust->setInvertedAppearance( true );
398     ui->freq_adjust->setSliderPosition( getScalingStep(getMaxFreq()) );
399
400     //ui->retranslateUi(this);
401 }
402
403
404 /**
405   * Repaints part of the GUI after the device was rotated
406   */
407 void MainWindow::orientationChanged()
408 {
409     QPixmap image;
410
411     //check whether we are using portrait or landscape mode
412     if ( usePortrait() ) {
413         //in portrait mode we want to display the large image
414         image.load( ":/img/chip256" );
415         scene.clear();
416         scene.addPixmap(  image  );
417
418         ui->graphicsPortrait->setScene( &scene );
419         ui->graphicsPortrait->setMaximumSize( 256, 256 );
420         ui->graphicsLandscape->setMaximumSize( 0, 0 );
421     } else {
422         image.load( ":/img/chip128" );
423         scene.clear();
424         scene.addPixmap(  image  );
425
426         ui->graphicsLandscape->setScene( &scene );
427         ui->graphicsLandscape->setMaximumSize( 128, 128 );
428         ui->graphicsPortrait->setMaximumSize( 0, 0 );
429     }
430 }
431
432
433 /**
434   * Enables the auto-rotation feature of Maemo5 devices
435   */
436 void MainWindow::setAutoRotation()
437 {
438 #if defined(Q_WS_MAEMO_5)
439     setAttribute(Qt::WA_Maemo5AutoOrientation, true);
440 #endif
441 }
442
443
444 /**
445   * SLOT: enable/disable overclocking.
446   */
447 void MainWindow::setOverclocking()
448 {
449     if (ui->actionOverclocking->isChecked()) {
450         #if defined(Q_WS_MAEMO_5)
451         QMaemo5InformationBox::information(this, tr( "Please note that overclocking voids your warranty and may break your device! Be careful!"), 0);
452         #endif
453         this->allowOverclocking = true;
454     } else {
455         this->allowOverclocking = false;
456     }
457 }
458
459
460 /**
461   * SLOT: Enables or disables Smart Reflex(tm) after pressing sr_btn
462   */
463 void MainWindow::setSmartReflex()
464 {
465 //SmartReflex is only supported on Maemo5
466 #if defined(Q_WS_MAEMO_5)
467     if ( getSmartReflexState() == 1 )
468         callHelper( "set_sr", "off");
469     else {
470         QMaemo5InformationBox::information(this, tr( "SmartReflex support is known to be unstable on some devices and may cause random reboots." ), 0);
471         callHelper( "set_sr", "on");
472     }
473
474 #endif
475     //refresh the UI
476     refresh();
477 }
478
479
480 /**
481   * SLOT: display the help window
482   */
483 void MainWindow::showHelp()
484 {
485     helpWindow.show();
486 }
487
488
489 /**
490   * Returns true when the device is in portrait mode
491   */
492 bool MainWindow::usePortrait()
493 {
494     QRect screenGeometry = QApplication::desktop()->screenGeometry();
495     if (screenGeometry.width() > screenGeometry.height())
496         return false;
497     else
498         return true;
499 }