summaryrefslogtreecommitdiff
path: root/src/frontend/bookshelfmanager/installpage/btinstallpage.cpp
blob: d3bac59e410bd10fcb1539dbd4457fed171540e4 (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
/*********
*
* This file is part of BibleTime's source code, http://www.bibletime.info/.
*
* Copyright 1999-2011 by the BibleTime developers.
* The BibleTime source code is licensed under the GNU General Public License version 2.0.
*
**********/

#include "frontend/bookshelfmanager/installpage/btinstallpage.h"

#include <QApplication>
#include <QComboBox>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QLabel>
#include <QPushButton>
#include <QSettings>
#include <QSharedPointer>
#include <QStackedLayout>
#include <QToolButton>
#include "backend/config/cbtconfig.h"
#include "backend/btinstallbackend.h"
#include "frontend/bookshelfmanager/btmodulemanagerdialog.h"
#include "frontend/bookshelfmanager/cswordsetupinstallsourcesdialog.h"
#include "frontend/bookshelfmanager/installpage/btinstallmodulechooserdialog.h"
#include "frontend/bookshelfmanager/installpage/btinstallpageworkswidget.h"
#include "frontend/bookshelfmanager/installpage/btinstallpathdialog.h"
#include "frontend/bookshelfmanager/installpage/btinstallprogressdialog.h"
#include "frontend/btbookshelfview.h"
#include "util/cresmgr.h"
#include "util/dialogutil.h"
#include "util/directory.h"
#include "util/tool.h"


namespace {
const QString groupingOrderKey ("GUI/BookshelfManager/InstallPage/grouping");
const QString headerStateKey   ("GUI/BookshelfManager/InstallPage/headerState");
const QString selectedModuleKey("GUI/BookshelfManager/InstallPage/selectedModule");
} // anonymous namespace


// *********************************************************
// *********** Config dialog page: Install/Update **********
// *********************************************************

BtInstallPage::BtInstallPage(QWidget *parent)
        : BtConfigPage(parent)
        , m_groupingOrder(groupingOrderKey)
        , m_modulesSelected(0)
        , m_modulesSelectedSources(0)
{
    // Read settings:
    m_headerState = CBTConfig::getConfig()->value(headerStateKey).toByteArray();

    // Initialize widgets:
    initView();
    initConnections();
}

void BtInstallPage::setInstallEnabled(bool b) {
    qDebug() << "void BtInstallPage::setInstallEnabled(bool b) start";
    m_installButton->setEnabled(b);
}

QString BtInstallPage::selectedInstallPath() {
    return m_pathCombo->currentText();
}

void BtInstallPage::initView() {
    namespace DU = util::directory;

    // Warning label:

    m_warningLabel = util::tool::explanationLabel(this, tr("WARNING!!!"),
        tr("If you live in a persecuted country and don't want to risk "
           "detection don't use remote sources."));

    // Source chooser:
    m_sourceGroupBox = new QGroupBox(tr("Select installation &source:"), this);
    m_sourceGroupBox->setFlat(true);

    m_sourceComboBox = new QComboBox(this);
    m_sourceComboBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);
    initSourcesCombo();

    m_sourceAddButton = new QPushButton(tr("&Add..."));
    m_sourceAddButton ->setToolTip(tr("Add new source"));
    m_sourceAddButton ->setIcon(DU::getIcon(CResMgr::bookshelfmgr::installpage::add_icon));

    m_sourceDeleteButton = new QPushButton(tr("&Delete..."));
    m_sourceDeleteButton->setToolTip(tr("Delete this source"));
    m_sourceDeleteButton->setIcon(DU::getIcon(CResMgr::bookshelfmgr::installpage::delete_icon));

    QHBoxLayout *sourceChooserLayout = new QHBoxLayout();
    sourceChooserLayout->setContentsMargins(0, 0, 0, 0);
    sourceChooserLayout->addWidget(m_sourceComboBox, 1);
    sourceChooserLayout->addWidget(m_sourceAddButton);
    sourceChooserLayout->addWidget(m_sourceDeleteButton);
    m_sourceGroupBox->setLayout(sourceChooserLayout);

    // Works chooser:
    m_worksGroupBox = new QGroupBox(tr("Select &works to install:"), this);
    m_worksGroupBox->setFlat(true);
    m_worksLayout = new QStackedLayout();
    m_worksGroupBox->setLayout(m_worksLayout);
    slotSourceIndexChanged(m_sourceComboBox->currentIndex());

    // Installation path chooser:
    m_installGroupBox = new QGroupBox(this);
    m_installGroupBox->setFlat(true);
    retranslateInstallGroupBox();

    m_pathLabel = new QLabel(tr("Install &folder:"));
    m_pathCombo = new QComboBox(this);
    m_pathCombo->setMinimumContentsLength(20);
    m_pathCombo->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLengthWithIcon);
    m_pathCombo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);
    m_pathCombo->setToolTip(tr("The folder where the new works will be installed"));
    m_pathCombo->view()->setTextElideMode(Qt::ElideMiddle);
    m_pathLabel->setBuddy(m_pathCombo);
    initPathCombo();

    m_configurePathButton = new QToolButton(this);
    m_configurePathButton->setToolTip(tr("Configure folders where works are installed and found"));
    m_configurePathButton->setIcon(DU::getIcon(CResMgr::bookshelfmgr::installpage::path_icon));

    m_installButton = new QPushButton(tr("&Install..."), this);
    m_installButton->setToolTip(tr("Install or update selected works"));
    m_installButton->setIcon(DU::getIcon(CResMgr::bookshelfmgr::installpage::install_icon));
    m_installButton->setEnabled(false);

    QHBoxLayout *pathLayout = new QHBoxLayout();
    pathLayout->setContentsMargins(0, 0, 0, 0);
    pathLayout->addWidget(m_pathLabel);
    pathLayout->addWidget(m_pathCombo);
    pathLayout->addWidget(m_configurePathButton);
    pathLayout->addWidget(m_installButton);
    m_installGroupBox->setLayout(pathLayout);

    Q_ASSERT(qobject_cast<QVBoxLayout*>(layout()) != 0);
    QVBoxLayout *mainLayout = static_cast<QVBoxLayout*>(layout());
    mainLayout->addWidget(m_warningLabel);
    mainLayout->addWidget(m_sourceGroupBox);
    mainLayout->addWidget(m_worksGroupBox, 1);
    mainLayout->addWidget(m_installGroupBox);
}

void BtInstallPage::initConnections() {
    connect(m_sourceComboBox, SIGNAL(currentIndexChanged(int)),
            this,             SLOT(slotSourceIndexChanged(int)));
    connect(m_sourceAddButton, SIGNAL(clicked()),
            this,              SLOT(slotSourceAdd()));
    connect(m_sourceDeleteButton, SIGNAL(clicked()),
            this,                 SLOT(slotSourceDelete()));
    connect(m_installButton, SIGNAL(clicked()),
            this,            SLOT(slotInstall()));
    connect(m_pathCombo, SIGNAL(activated(const QString&)),
            this , SLOT(slotPathChanged(const QString&)));
    connect(m_configurePathButton, SIGNAL(clicked()),
            this, SLOT(slotEditPaths()));
    connect(CSwordBackend::instance(),
            SIGNAL(sigSwordSetupChanged(CSwordBackend::SetupChangedReason)),
            this, SLOT(slotSwordSetupChanged()));
}

void BtInstallPage::initPathCombo() {
    //populate the combo list
    m_pathCombo->clear();

    QStringList targets = BtInstallBackend::targetList();
    for (QStringList::iterator it = targets.begin(); it != targets.end(); ++it)  {
        // Add the path only if it's writable
        if ((*it).isEmpty()) continue;
        QDir dir(*it);
        if (!dir.exists()) continue;
        if (!dir.isReadable()) continue;
        QFileInfo fi( dir.canonicalPath());
        if (!fi.isWritable()) continue;
        m_pathCombo->addItem(util::directory::convertDirSeparators(*it));
    }

    // choose the current value from config but check whether we have so many items
    int configValue = CBTConfig::get(CBTConfig::installPathIndex);
    int index = configValue > (m_pathCombo->count() - 1) ? m_pathCombo->count() - 1 : configValue;
    m_pathCombo->setCurrentIndex(index);
}

void BtInstallPage::initSourcesCombo() {
    /// \todo Implement a proper model for this

    m_sourceComboBox->clear();
    QStringList sourceList = BtInstallBackend::sourceNameList();

    // Add a default entry, the Crosswire main repository
    if (sourceList.empty()) {
        /// \todo Open a dialog which asks whether to get list from server and add sources
        sword::InstallSource is("FTP");   //default return value
        is.caption = "CrossWire Bible Society";
        is.source = "ftp.crosswire.org";
        is.directory = "/pub/sword/raw";
        // passive ftp is not needed here, it's the default

        BtInstallBackend::addSource(is);

        sourceList = BtInstallBackend::sourceNameList();
        Q_ASSERT(!sourceList.empty());
    }

    // Read selected module from config:
    QString selected = CBTConfig::getConfig()->value(selectedModuleKey).toString();

    // Populate combo box
    bool selectionOk = false;
    for (int i = 0; i < sourceList.size(); i++) {
        m_sourceComboBox->addItem(sourceList.at(i));

        // Select configured item:
        if (!selectionOk && sourceList.at(i) == selected) {
            m_sourceComboBox->setCurrentIndex(i);
            selectionOk = true;
        }
    }

    // Set selection, if it wasn't properly configured:
    if (!selectionOk) {
        m_sourceComboBox->setCurrentIndex(0);
        CBTConfig::getConfig()->setValue(selectedModuleKey, sourceList.at(0));
    }
}

void BtInstallPage::activateSource(const sword::InstallSource &src) {
    qDebug() << "Selected source" << src.caption;
    qApp->setOverrideCursor(Qt::WaitCursor);
    BtInstallPageWorksWidget *w = m_sourceMap.value(QString(src.caption), 0);
    if (w == 0) {
        if (parentDialog() != 0) parentDialog()->setEnabled(false);
        qApp->processEvents();
        w = new BtInstallPageWorksWidget(src, m_groupingOrder, this);
        m_sourceMap.insert(QString(src.caption), w);
        m_worksLayout->addWidget(w);
        connect(w->treeModel(), SIGNAL(groupingOrderChanged(BtBookshelfTreeModel::Grouping)),
                this,           SLOT(slotGroupingOrderChanged(const BtBookshelfTreeModel::Grouping&)));
        connect(w->treeModel(), SIGNAL(moduleChecked(CSwordModuleInfo*,bool)),
                this,           SLOT(slotSelectedModulesChanged()));
        if (parentDialog() != 0) parentDialog()->setEnabled(true);
    } else {
        disconnect(w->treeView()->header(), SIGNAL(geometriesChanged()),
                   this,                    SLOT(slotHeaderChanged()));
    }
    m_worksLayout->setCurrentWidget(w);
    w->treeModel()->setGroupingOrder(m_groupingOrder);
    w->treeView()->header()->restoreState(m_headerState);
    connect(w->treeView()->header(), SIGNAL(geometriesChanged()),
            this,                    SLOT(slotHeaderChanged()));
    qApp->restoreOverrideCursor();
}

void BtInstallPage::retranslateInstallGroupBox() {
    if (m_modulesSelected > 0) {
        m_installGroupBox->setTitle(tr("Start installation of %1 works from %2 sources:")
                                    .arg(m_modulesSelected)
                                    .arg(m_modulesSelectedSources));
    } else {
        m_installGroupBox->setTitle(tr("Start installation:"));
    }
}

void BtInstallPage::slotGroupingOrderChanged(const BtBookshelfTreeModel::Grouping &g) {
    m_groupingOrder = g;
    m_groupingOrder.saveTo(groupingOrderKey);
}

void BtInstallPage::slotHeaderChanged() {
    typedef BtInstallPageWorksWidget IPWW;
    Q_ASSERT(qobject_cast<IPWW*>(m_worksLayout->currentWidget()) != 0);
    IPWW *w = static_cast<IPWW*>(m_worksLayout->currentWidget());
    m_headerState = w->treeView()->header()->saveState();
    CBTConfig::getConfig()->setValue(headerStateKey, m_headerState);
}

void BtInstallPage::slotInstall() {
    qDebug() << "BtInstallPage::slotInstall";

    // check that the destination path is writable, do nothing if not and user doesn't want to continue
    QDir dir = selectedInstallPath();
    bool canWrite = true;
    if (dir.isReadable()) {
        const QFileInfo fi( dir.canonicalPath() );
        if (!fi.exists() || !fi.isWritable()) {
            canWrite = false;
        }
    }
    else {
        canWrite = false;
    }
    if (!canWrite) {
        const int result = util::showWarning(this, tr("Warning"), tr("The destination directory is not writable or does not exist. Installation will fail unless this has first been fixed."), QMessageBox::Ignore | QMessageBox::Cancel, QMessageBox::Cancel);
        if (result != QMessageBox::Ignore) {
            return;
        }
    }

    // create the confirmation dialog
    BtInstallModuleChooserDialog *dlg = new BtInstallModuleChooserDialog(m_groupingOrder, this);

    // Add all checked modules from all tabs:
    Q_FOREACH (BtInstallPageWorksWidget *w, m_sourceMap.values()) {
        Q_FOREACH (CSwordModuleInfo *module, w->treeModel()->checkedModules()) {
            dlg->addModuleItem(module, QString(w->installSource().caption));
        }
    }

    if (dlg->exec() == QDialog::Accepted) {
        QSet<const CSwordModuleInfo*> cm;
        Q_FOREACH(const CSwordModuleInfo *m, dlg->checkedModules()) {
            cm.insert(m);
        }

        if (cm.empty()) return;

        /// \todo first remove all modules which will be updated from the module list
        // but what modules? all with the same real name? (there may be _n modules...)

        BtModuleManagerDialog *parentDlg = dynamic_cast<BtModuleManagerDialog*>(parentDialog());

        BtInstallProgressDialog *dlg = new BtInstallProgressDialog(cm, selectedInstallPath(), parentDlg);

        if (!parentDlg) qDebug() << "error, wrong parent!";

        m_installButton->setEnabled(false);

        // the progress dialog is now modal, it can be made modeless later.
        dlg->exec();

        qDebug() << "BtSourceWidget::slotInstallAccepted end";
    }
    delete dlg;
}

void BtInstallPage::slotPathChanged(const QString& /*pathText*/) {
    CBTConfig::set(CBTConfig::installPathIndex, m_pathCombo->currentIndex( ) );
}

void BtInstallPage::slotEditPaths() {
    BtInstallPathDialog* dlg = new BtInstallPathDialog();
    int result = dlg->exec();
    if (result == QDialog::Accepted) {
        //dynamic_cast<BtModuleManagerDialog*>(parentDialog())->slotSwordSetupChanged();
        CSwordBackend::instance()->reloadModules(CSwordBackend::PathChanged);
    }
}

void BtInstallPage::slotSourceAdd() {
    typedef CSwordSetupInstallSourcesDialog SSISD;

    QSharedPointer<SSISD> dlg(new SSISD());
    if (dlg->exec() == QDialog::Accepted) {
        if (!dlg->wasRemoteListAdded()) {
            sword::InstallSource newSource = dlg->getSource();
            if ( !((QString)newSource.type.c_str()).isEmpty() ) { // we have a valid source to add
                BtInstallBackend::addSource(newSource);
            }
            initSourcesCombo();
            for (int i = 0; i < m_sourceComboBox->count(); i++) {
                if (m_sourceComboBox->itemText(i) == newSource.caption) {
                    m_sourceComboBox->setCurrentIndex(i);
                    break;
                }
            }
        }
    }
}

void BtInstallPage::slotSourceDelete() {
    typedef BtInstallPageWorksWidget IPWW;

    int ret = util::showWarning(this, tr("Delete Source?"),
                                tr("Do you really want to delete this source?"),
                                QMessageBox::Yes | QMessageBox::No);

    if (ret == QMessageBox::Yes) {
        Q_ASSERT(qobject_cast<IPWW*>(m_worksLayout->currentWidget()));
        IPWW *w = static_cast<IPWW*>(m_worksLayout->currentWidget());
        w->deleteSource();
        initSourcesCombo();
        slotSourceIndexChanged(m_sourceComboBox->currentIndex());
        delete w;
    }
}

void BtInstallPage::slotSourceIndexChanged(int index) {
    if (index < 0) index = 0;

    /// \todo use pointers instead of text
    QString moduleName = m_sourceComboBox->itemText(index);
    CBTConfig::getConfig()->setValue(selectedModuleKey, moduleName);
    activateSource(BtInstallBackend::source(moduleName));
}

void BtInstallPage::slotSelectedModulesChanged() {
    m_modulesSelected = 0;
    m_modulesSelectedSources = 0;
    Q_FOREACH (BtInstallPageWorksWidget *w, m_sourceMap.values()) {
        int selected = w->treeModel()->checkedModules().size();
        if (selected > 0) {
            m_modulesSelectedSources++;
            m_modulesSelected += selected;
        }
    }

    m_installButton->setEnabled(m_modulesSelected > 0);
    retranslateInstallGroupBox();
}

// implement the BtConfigPage methods

const QIcon &BtInstallPage::icon() const {
    return util::directory::getIcon(CResMgr::bookshelfmgr::installpage::icon);
}

QString BtInstallPage::header() const {
    return tr("Install/Update");
}

void BtInstallPage::slotSwordSetupChanged() {
    QString moduleName = m_sourceComboBox->currentText();

    initSourcesCombo();
    qDeleteAll(m_sourceMap.values());
    m_sourceMap.clear();
    m_sourceComboBox->setCurrentIndex(m_sourceComboBox->findText(moduleName));
    initPathCombo();
    m_modulesSelected = 0;
    m_modulesSelectedSources = 0;
    retranslateInstallGroupBox();
}