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