summaryrefslogtreecommitdiffstats
path: root/rbutil/rbutilqt/configure.cpp
blob: 61d3d7e457d72a83f6c6c67ea653b6bce33a8ac4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
/***************************************************************************
 *             __________               __   ___.
 *   Open      \______   \ ____   ____ |  | _\_ |__   _______  ___
 *   Source     |       _//  _ \_/ ___\|  |/ /| __ \ /  _ \  \/  /
 *   Jukebox    |    |   (  <_> )  \___|    < | \_\ (  <_> > <  <
 *   Firmware   |____|_  /\____/ \___  >__|_ \|___  /\____/__/\_ \
 *                     \/            \/     \/    \/            \/
 *
 *   Copyright (C) 2007 by Dominik Riebeling
 *   $Id$
 *
 * All files in this archive are subject to the GNU General Public License.
 * See the file COPYING in the source tree root for full license agreement.
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 ****************************************************************************/

#include <QtGui>

#include "configure.h"
#include "autodetection.h"
#include "ui_configurefrm.h"
#include "browsedirtree.h"
#include "encoders.h"
#include "tts.h"
#include "utils.h"

#include <stdio.h>
#if defined(Q_OS_WIN32)
#if defined(UNICODE)
#define _UNICODE
#endif
#include <tchar.h>
#include <windows.h>
#endif

#define DEFAULT_LANG "English (C)"

Config::Config(QWidget *parent,int index) : QDialog(parent)
{
    programPath = qApp->applicationDirPath() + "/";
    ui.setupUi(this);
    ui.tabConfiguration->setCurrentIndex(index);
    ui.radioManualProxy->setChecked(true);
    QRegExpValidator *proxyValidator = new QRegExpValidator(this);
    QRegExp validate("[0-9]*");
    proxyValidator->setRegExp(validate);
    ui.proxyPort->setValidator(proxyValidator);
#if !defined(Q_OS_LINUX) && !defined(Q_OS_WIN32)
    ui.radioSystemProxy->setEnabled(false); // not on macox for now
#endif
    // build language list and sort alphabetically
    QStringList langs = findLanguageFiles();
    for(int i = 0; i < langs.size(); ++i)
        lang.insert(languageName(langs.at(i)) + tr(" (%1)").arg(langs.at(i)), langs.at(i));
    lang.insert(DEFAULT_LANG, "");
    QMap<QString, QString>::const_iterator i = lang.constBegin();
    while (i != lang.constEnd()) {
        ui.listLanguages->addItem(i.key());
        i++;
    }
    ui.listLanguages->setSelectionMode(QAbstractItemView::SingleSelection);
    connect(ui.listLanguages, SIGNAL(itemSelectionChanged()), this, SLOT(updateLanguage()));
    ui.proxyPass->setEchoMode(QLineEdit::Password);
    ui.treeDevices->setAlternatingRowColors(true);
    ui.listLanguages->setAlternatingRowColors(true);

    this->setModal(true);

    connect(ui.buttonOk, SIGNAL(clicked()), this, SLOT(accept()));
    connect(ui.buttonCancel, SIGNAL(clicked()), this, SLOT(abort()));
    connect(ui.radioNoProxy, SIGNAL(toggled(bool)), this, SLOT(setNoProxy(bool)));
    connect(ui.radioSystemProxy, SIGNAL(toggled(bool)), this, SLOT(setSystemProxy(bool)));
    connect(ui.browseMountPoint, SIGNAL(clicked()), this, SLOT(browseFolder()));
    connect(ui.buttonAutodetect,SIGNAL(clicked()),this,SLOT(autodetect()));
    connect(ui.buttonCacheBrowse, SIGNAL(clicked()), this, SLOT(browseCache()));
    connect(ui.buttonCacheClear, SIGNAL(clicked()), this, SLOT(cacheClear()));
    connect(ui.configTts, SIGNAL(clicked()), this, SLOT(configTts()));
    connect(ui.configEncoder, SIGNAL(clicked()), this, SLOT(configEnc()));
    connect(ui.comboTts, SIGNAL(currentIndexChanged(int)), this, SLOT(updateTtsState(int)));
    connect(ui.comboEncoder, SIGNAL(currentIndexChanged(int)), this, SLOT(updateEncState(int)));
    
}



void Config::accept()
{
    qDebug() << "Config::accept()";
    // proxy: save entered proxy values, not displayed.
    if(ui.radioManualProxy->isChecked()) {
        proxy.setScheme("http");
        proxy.setUserName(ui.proxyUser->text());
        proxy.setPassword(ui.proxyPass->text());
        proxy.setHost(ui.proxyHost->text());
        proxy.setPort(ui.proxyPort->text().toInt());
    }
    
    settings->setProxy(proxy.toString());
    qDebug() << "new proxy:" << proxy;
    // proxy type
    QString proxyType;
    if(ui.radioNoProxy->isChecked()) proxyType = "none";
    else if(ui.radioSystemProxy->isChecked()) proxyType = "system";
    else proxyType = "manual";
    settings->setProxyType(proxyType);

    // language
    if(settings->curLang() != language)
        QMessageBox::information(this, tr("Language changed"),
            tr("You need to restart the application for the changed language to take effect."));
    settings->setLang(language);

    // mountpoint
    QString mp = ui.mountPoint->text();
    if(QFileInfo(mp).isDir())
        settings->setMountpoint( mp);

    // platform
    QString nplat;
    if(ui.treeDevices->selectedItems().size() != 0) {
        nplat = ui.treeDevices->selectedItems().at(0)->data(0, Qt::UserRole).toString();
        settings->setCurPlatform(nplat);
    }

    // cache settings
    if(QFileInfo(ui.cachePath->text()).isDir())
        settings->setCachePath(ui.cachePath->text());
    else // default to system temp path
        settings->setCachePath( QDir::tempPath());
    settings->setCacheDisable(ui.cacheDisable->isChecked());
    settings->setCacheOffline(ui.cacheOfflineMode->isChecked());

    // tts settings
    int i = ui.comboTts->currentIndex();
    settings->setCurTTS(ui.comboTts->itemData(i).toString());
    //encoder settings
    i = ui.comboEncoder->currentIndex();
    settings->setCurEncoder(ui.comboEncoder->itemData(i).toString());

    // sync settings
    settings->sync();
    this->close();
    emit settingsUpdated();
}


void Config::abort()
{
    qDebug() << "Config::abort()";
    this->close();
}

void Config::setSettings(RbSettings* sett)
{
    settings = sett;
      
    setUserSettings();
    setDevices();
}

void Config::setUserSettings()
{
    // set proxy
    proxy = settings->proxy();

    if(proxy.port() > 0)
        ui.proxyPort->setText(QString("%1").arg(proxy.port()));
    else ui.proxyPort->setText("");
    ui.proxyHost->setText(proxy.host());
    ui.proxyUser->setText(proxy.userName());
    ui.proxyPass->setText(proxy.password());

    QString proxyType = settings->proxyType();
    if(proxyType == "manual") ui.radioManualProxy->setChecked(true);
    else if(proxyType == "system") ui.radioSystemProxy->setChecked(true);
    else ui.radioNoProxy->setChecked(true);

    // set language selection
    QList<QListWidgetItem*> a;
    QString b;
    // find key for lang value
    QMap<QString, QString>::const_iterator i = lang.constBegin();
    while (i != lang.constEnd()) {
        if(i.value() == settings->curLang()) {
            b = i.key();
            break;
        }
        i++;
    }
    a = ui.listLanguages->findItems(b, Qt::MatchExactly);
    if(a.size() <= 0)
        a = ui.listLanguages->findItems(DEFAULT_LANG, Qt::MatchExactly);
    if(a.size() > 0)
        ui.listLanguages->setCurrentItem(a.at(0));

    // devices tab
    ui.mountPoint->setText(settings->mountpoint());

    // cache tab
    if(!QFileInfo(settings->cachePath()).isDir())
        settings->setCachePath(QDir::tempPath());
    ui.cachePath->setText(settings->cachePath());
    ui.cacheDisable->setChecked(settings->cacheDisabled());
    ui.cacheOfflineMode->setChecked(settings->cacheOffline());
    updateCacheInfo(settings->cachePath());
}


void Config::updateCacheInfo(QString path)
{
    QList<QFileInfo> fs;
    fs = QDir(path + "/rbutil-cache/").entryInfoList(QDir::Files | QDir::NoDotAndDotDot);
    qint64 sz = 0;
    for(int i = 0; i < fs.size(); i++) {
        sz += fs.at(i).size();
        qDebug() << fs.at(i).fileName() << fs.at(i).size();
    }
    ui.cacheSize->setText(tr("Current cache size is %L1 kiB.")
            .arg(sz/1024));
}


void Config::setDevices()
{
    
    // setup devices table
    qDebug() << "Config::setDevices()";
    
    QStringList platformList = settings->allPlatforms();

    QMap <QString, QString> manuf;
    QMap <QString, QString> devcs;
    for(int it = 0; it < platformList.size(); it++) 
    {
        QString curname = settings->name(platformList.at(it));
        QString curbrand = settings->brand(platformList.at(it));
        manuf.insertMulti(curbrand, platformList.at(it));
        devcs.insert(platformList.at(it), curname);
    }

    QString platform;
    platform = devcs.value(settings->curPlatform());

    // set up devices table
    ui.treeDevices->header()->hide();
    ui.treeDevices->expandAll();
    ui.treeDevices->setColumnCount(1);
    QList<QTreeWidgetItem *> items;

    // get manufacturers
    QStringList brands = manuf.uniqueKeys();
    QTreeWidgetItem *w;
    QTreeWidgetItem *w2;
    QTreeWidgetItem *w3 = 0;
    for(int c = 0; c < brands.size(); c++) {
        qDebug() << brands.at(c);
        w = new QTreeWidgetItem();
        w->setFlags(Qt::ItemIsEnabled);
        w->setText(0, brands.at(c));
        items.append(w);

        // go through platforms again for sake of order
        for(int it = 0; it < platformList.size(); it++) {
           
            QString curname = settings->name(platformList.at(it));
            QString curbrand = settings->brand(platformList.at(it));
       
            if(curbrand != brands.at(c)) continue;
            qDebug() << "adding:" << brands.at(c) << curname;
            w2 = new QTreeWidgetItem(w, QStringList(curname));
            w2->setData(0, Qt::UserRole, platformList.at(it));

            if(platform.contains(curname)) {
                w2->setSelected(true);
                w->setExpanded(true);
                w3 = w2; // save pointer to hilight old selection
            }
            items.append(w2);
        }
    }
    ui.treeDevices->insertTopLevelItems(0, items);
    if(w3 != 0)
        ui.treeDevices->setCurrentItem(w3); // hilight old selection

    // tts / encoder tab
    
    //encoders
    int index;
    QStringList encoders = EncBase::getEncoderList();
    for(int a = 0; a < encoders.size(); a++)
        ui.comboEncoder->addItem(EncBase::getEncoderName(encoders.at(a)), encoders.at(a));
    //update index of combobox
    index = ui.comboEncoder->findData(settings->curEncoder());
    if(index < 0) index = 0;
    ui.comboEncoder->setCurrentIndex(index);
    updateEncState(index);

    //tts
    QStringList ttslist = TTSBase::getTTSList();
    for(int a = 0; a < ttslist.size(); a++)
        ui.comboTts->addItem(TTSBase::getTTSName(ttslist.at(a)), ttslist.at(a));
    //update index of combobox
    index = ui.comboTts->findData(settings->curTTS());
    if(index < 0) index = 0;
    ui.comboTts->setCurrentIndex(index);
    updateTtsState(index);
    
}


void Config::updateTtsState(int index)
{
    QString ttsName = ui.comboTts->itemData(index).toString();
    TTSBase* tts = TTSBase::getTTS(ttsName);
    tts->setCfg(settings);
    
    if(tts->configOk())
    {
        ui.configTTSstatus->setText("Configuration OK");
        ui.configTTSstatusimg->setPixmap(QPixmap(QString::fromUtf8(":/icons/go-next.png")));
    }
    else
    {
        ui.configTTSstatus->setText("Configuration INVALID");
        ui.configTTSstatusimg->setPixmap(QPixmap(QString::fromUtf8(":/icons/dialog-error.png")));
    }
}

void Config::updateEncState(int index)
{
    QString encoder = ui.comboEncoder->itemData(index).toString();
    EncBase* enc = EncBase::getEncoder(encoder);
    enc->setCfg(settings);
    
    if(enc->configOk())
    {
        ui.configEncstatus->setText("Configuration OK");
        ui.configEncstatusimg->setPixmap(QPixmap(QString::fromUtf8(":/icons/go-next.png")));
    }
    else
    {
        ui.configEncstatus->setText("Configuration INVALID");
        ui.configEncstatusimg->setPixmap(QPixmap(QString::fromUtf8(":/icons/dialog-error.png")));
    }        
}

void Config::setNoProxy(bool checked)
{
    bool i = !checked;
    ui.proxyPort->setEnabled(i);
    ui.proxyHost->setEnabled(i);
    ui.proxyUser->setEnabled(i);
    ui.proxyPass->setEnabled(i);
}


void Config::setSystemProxy(bool checked)
{
    bool i = !checked;
    ui.proxyPort->setEnabled(i);
    ui.proxyHost->setEnabled(i);
    ui.proxyUser->setEnabled(i);
    ui.proxyPass->setEnabled(i);
    if(checked) {
        // save values in input box
        proxy.setScheme("http");
        proxy.setUserName(ui.proxyUser->text());
        proxy.setPassword(ui.proxyPass->text());
        proxy.setHost(ui.proxyHost->text());
        proxy.setPort(ui.proxyPort->text().toInt());
        // show system values in input box
        QUrl envproxy = systemProxy();

        ui.proxyHost->setText(envproxy.host());

        ui.proxyPort->setText(QString("%1").arg(envproxy.port()));
        ui.proxyUser->setText(envproxy.userName());
        ui.proxyPass->setText(envproxy.password());

    }
    else {
        ui.proxyHost->setText(proxy.host());
        if(proxy.port() > 0)
            ui.proxyPort->setText(QString("%1").arg(proxy.port()));
        else ui.proxyPort->setText("");
        ui.proxyUser->setText(proxy.userName());
        ui.proxyPass->setText(proxy.password());
    }

}


QStringList Config::findLanguageFiles()
{
    QDir dir(programPath);
    QStringList fileNames;
    QStringList langs;
    fileNames = dir.entryList(QStringList("*.qm"), QDir::Files, QDir::Name);

    QDir resDir(":/lang");
    fileNames += resDir.entryList(QStringList("*.qm"), QDir::Files, QDir::Name);

    QRegExp exp("^rbutil_(.*)\\.qm");
    for(int i = 0; i < fileNames.size(); i++) {
        QString a = fileNames.at(i);
        a.replace(exp, "\\1");
        langs.append(a);
    }
    langs.sort();
    qDebug() << "Config::findLanguageFiles()" << langs;

    return langs;
}


QString Config::languageName(const QString &qmFile)
{
    QTranslator translator;

    QString file = "rbutil_" + qmFile;
    if(!translator.load(file, programPath))
        translator.load(file, ":/lang");

    return translator.translate("Configure", "English");
}


void Config::updateLanguage()
{
    qDebug() << "updateLanguage()";
    QList<QListWidgetItem*> a = ui.listLanguages->selectedItems();
    if(a.size() > 0)
        language = lang.value(a.at(0)->text());
    qDebug() << language;
}


void Config::browseFolder()
{
    browser = new BrowseDirtree(this,tr("Select your device"));
#if defined(Q_OS_LINUX) || defined(Q_OS_MACX)
    browser->setFilter(QDir::AllDirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
#elif defined(Q_OS_WIN32)
    browser->setFilter(QDir::Drives);
#endif
#if defined(Q_OS_MACX)
    browser->setRoot("/Volumes");
#elif defined(Q_OS_LINUX)
    browser->setDir("/media");
#endif
    if( ui.mountPoint->text() != "" )
    {
        browser->setDir(ui.mountPoint->text());
    }
    browser->show();
    connect(browser, SIGNAL(itemChanged(QString)), this, SLOT(setMountpoint(QString)));
}


void Config::browseCache()
{
    cbrowser = new BrowseDirtree(this);
#if defined(Q_OS_LINUX) || defined(Q_OS_MACX)
    cbrowser->setFilter(QDir::AllDirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
#elif defined(Q_OS_WIN32)
    cbrowser->setFilter(QDir::Drives);
#endif
    cbrowser->setDir(ui.cachePath->text());
    cbrowser->show();
    connect(cbrowser, SIGNAL(itemChanged(QString)), this, SLOT(setCache(QString)));
}

void Config::setMountpoint(QString m)
{
    ui.mountPoint->setText(m);
}


void Config::setCache(QString c)
{
    ui.cachePath->setText(c);
    updateCacheInfo(c);
}


void Config::autodetect()
{
    Autodetection detector(this);
    detector.setSettings(settings);

    if(detector.detect())  //let it detect
    {
        QString devicename = detector.getDevice();
        // deexpand all items
        for(int a = 0; a < ui.treeDevices->topLevelItemCount(); a++)
            ui.treeDevices->topLevelItem(a)->setExpanded(false);
        //deselect the selected item(s)
        for(int a = 0; a < ui.treeDevices->selectedItems().size(); a++)
            ui.treeDevices->selectedItems().at(a)->setSelected(false);

        // find the new item
        // enumerate all platform items
        QList<QTreeWidgetItem*> itmList= ui.treeDevices->findItems("*",Qt::MatchWildcard);
        for(int i=0; i< itmList.size();i++)
        {
            //enumerate device items
            for(int j=0;j < itmList.at(i)->childCount();j++)
            {
                QString data = itmList.at(i)->child(j)->data(0, Qt::UserRole).toString();

                if(devicename == data) // item found
                {
                    itmList.at(i)->child(j)->setSelected(true); //select the item
                    itmList.at(i)->setExpanded(true); //expand the platform item
                    //ui.treeDevices->indexOfTopLevelItem(itmList.at(i)->child(j));
                    break;
                }
            }
        }

        if(!detector.errdev().isEmpty()) {
            QString text;
            if(detector.errdev() == "sansae200")
                text = tr("Sansa e200 in MTP mode found!\n"
                        "You need to change your player to MSC mode for installation. ");
            if(detector.errdev() == "h10")
                text = tr("H10 20GB in MTP mode found!\n"
                        "You need to change your player to UMS mode for installation. ");
            text += tr("Unless you changed this installation will fail!");

            QMessageBox::critical(this, tr("Fatal error"), text, QMessageBox::Ok);
            return;
        }

        if(detector.getMountPoint() != "" )
        {
            ui.mountPoint->setText(detector.getMountPoint());
        }
        else
        {
            QMessageBox::warning(this, tr("Autodetection"),
                    tr("Could not detect a Mountpoint.\n"
                    "Select your Mountpoint manually."),
                    QMessageBox::Ok ,QMessageBox::Ok);
        }
    }
    else
    {
        QMessageBox::warning(this, tr("Autodetection"),
                tr("Could not detect a device.\n"
                   "Select your device and Mountpoint manually."),
                   QMessageBox::Ok ,QMessageBox::Ok);

    }
}

void Config::cacheClear()
{
    if(QMessageBox::critical(this, tr("Really delete cache?"),
       tr("Do you really want to delete the cache? "
         "Make absolutely sure this setting is correct as it will "
         "remove <b>all</b> files in this folder!").arg(ui.cachePath->text()),
       QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)
        return;

    QString cache = ui.cachePath->text() + "/rbutil-cache/";
    if(!QFileInfo(cache).isDir()) {
        QMessageBox::critical(this, tr("Path wrong!"),
            tr("The cache path is invalid. Aborting."), QMessageBox::Ok);
        return;
    }
    QDir dir(cache);
    QStringList fn;
    fn = dir.entryList(QStringList("*"), QDir::Files, QDir::Name);
    qDebug() << fn;

    for(int i = 0; i < fn.size(); i++) {
        QString f = cache + fn.at(i);
        QFile::remove(f);
        qDebug() << "removed:" << f;
    }
    updateCacheInfo(settings->cachePath());
}


void Config::configTts()
{
    int index = ui.comboTts->currentIndex();
    TTSBase* tts = TTSBase::getTTS(ui.comboTts->itemData(index).toString());
    
    tts->setCfg(settings);
    tts->showCfg();
    updateTtsState(ui.comboTts->currentIndex());
}


void Config::configEnc()
{
    int index = ui.comboEncoder->currentIndex();
    EncBase* enc = EncBase::getEncoder(ui.comboEncoder->itemData(index).toString());
    
    enc->setCfg(settings);
    enc->showCfg();
    updateEncState(ui.comboEncoder->currentIndex());
}