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