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