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