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