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