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