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