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