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