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