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