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