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