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