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