summaryrefslogtreecommitdiff
path: root/src/frontend/mainindex/bookmarks/cbookmarkindex.cpp
blob: 6d357938600f6a434e80304e54bf2f27feb40106 (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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
/*********
*
* This file is part of BibleTime's source code, http://www.bibletime.info/.
*
* Copyright 1999-2008 by the BibleTime developers.
* The BibleTime source code is licensed under the GNU General Public License version 2.0.
*
**********/

//BibleTime includes
#include "cbookmarkindex.h"

#include "btbookmarkitembase.h"
#include "btbookmarkitem.h"
#include "btbookmarkfolder.h"
#include "btbookmarkloader.h"

#include "backend/managers/creferencemanager.h"
#include "backend/drivers/cswordmoduleinfo.h"

#include "frontend/searchdialog/csearchdialog.h"
#include "backend/config/cbtconfig.h"
#include "frontend/cinfodisplay.h"

#include "frontend/cprinter.h"
#include "frontend/cdragdrop.h"

#include "util/cresmgr.h"
#include "util/directoryutil.h"
#include "util/ctoolclass.h"

#include <boost/scoped_ptr.hpp>

//Qt includes
#include <QInputDialog>
#include <QDragLeaveEvent>
#include <QDragMoveEvent>
#include <QDropEvent>
#include <QHeaderView>
#include <QTimer>
#include <QToolTip>
#include <QList>
#include <QTreeWidget>
#include <QTreeWidgetItem>
#include <QCursor>
#include <QMouseEvent>
#include <QMessageBox>
#include <QMenu>
#include <QAction>
#include <QPaintEvent>
#include <QPainter>
#include <QApplication>
#include <QDrag>

#include <QDebug>

CBookmarkIndex::CBookmarkIndex(QWidget *parent)
        : QTreeWidget(parent),
        m_magTimer(this),
        m_previousEventItem(0) {
    setMouseTracking(true);
    m_magTimer.setSingleShot(true);
    m_magTimer.setInterval(CBTConfig::get(CBTConfig::magDelay));
    setContextMenuPolicy(Qt::CustomContextMenu);
    initView();
    initConnections();
    initTree();
}

CBookmarkIndex::~CBookmarkIndex() {
    saveBookmarks();
}


/** Initializes the view. */
void CBookmarkIndex::initView() {
    //qDebug("CBookmarkIndex::initView");

    header()->hide();

    setFocusPolicy(Qt::WheelFocus);

    //d'n'd related settings
    setDragEnabled( true );
    setAcceptDrops( true );
    setDragDropMode(QAbstractItemView::DragDrop);
    viewport()->setAcceptDrops(true);
    setAutoScroll(true);
    setAutoExpandDelay(800);

    setItemsExpandable(true);
    setRootIsDecorated(true);
    setAllColumnsShowFocus(true);
    setSelectionMode(QAbstractItemView::ExtendedSelection);

    //setup the popup menu
    m_popup = new QMenu(viewport());
    m_popup->setTitle(tr("Bookmarks"));

    m_actions.newFolder = newQAction(tr("New folder"), CResMgr::mainIndex::newFolder::icon, 0, this, SLOT(createNewFolder()), this);
    m_actions.changeFolder = newQAction(tr("Rename folder"), CResMgr::mainIndex::changeFolder::icon, 0, this, SLOT(changeFolder()), this);

    m_actions.changeBookmark = newQAction(tr("Change bookmark description..."), CResMgr::mainIndex::changeBookmark::icon, 0, this, SLOT(changeBookmark()), this);
    m_actions.importBookmarks = newQAction(tr("Import to folder..."), CResMgr::mainIndex::importBookmarks::icon, 0, this, SLOT(importBookmarks()), this);
    m_actions.exportBookmarks = newQAction(tr("Export from folder..."), CResMgr::mainIndex::exportBookmarks::icon, 0, this, SLOT(exportBookmarks()), this);
    m_actions.printBookmarks = newQAction(tr("Print bookmarks..."), CResMgr::mainIndex::printBookmarks::icon, 0, this, SLOT(printBookmarks()), this);

    m_actions.deleteEntries = newQAction(tr("Remove selected items..."), CResMgr::mainIndex::deleteItems::icon, 0, this, SLOT(deleteEntries()), this);


    //fill the popup menu itself
    m_popup->addAction(m_actions.newFolder);
    m_popup->addAction(m_actions.changeFolder);
    QAction* separator = new QAction(this);
    separator->setSeparator(true);
    m_popup->addAction(separator);
    m_popup->addAction(m_actions.changeBookmark);
    m_popup->addAction(m_actions.importBookmarks);
    m_popup->addAction(m_actions.exportBookmarks);
    m_popup->addAction(m_actions.printBookmarks);
    separator = new QAction(this);
    separator->setSeparator(true);
    m_popup->addAction(separator);
    m_popup->addAction(m_actions.deleteEntries);

    //qDebug("CBookmarkIndex::initView end");
}

/** Convenience function for creating a new QAction.
* Should be replaced with something better; it was easier to make a new function
* than to modify all QAction constructors.
*/
QAction* CBookmarkIndex::newQAction(const QString& text, const QString& pix, const int /*shortcut*/, const QObject* receiver, const char* slot, QObject* parent) {
    QAction* action = new QAction(util::filesystem::DirectoryUtil::getIcon(pix), text, parent);
    QObject::connect(action, SIGNAL(triggered()), receiver, slot);
    return action;
}

/** Initialize the SIGNAL<->SLOT connections */
void CBookmarkIndex::initConnections() {
    //qDebug("CBookmarkIndex::initConnections");
    bool ok;
    ok = connect(this, SIGNAL(itemActivated(QTreeWidgetItem*, int)), this, SLOT(slotExecuted(QTreeWidgetItem*)));
    Q_ASSERT(ok);
    ok = connect(this, SIGNAL(customContextMenuRequested(const QPoint&)),
                 SLOT(contextMenu(const QPoint&)));
    Q_ASSERT(ok);
    ok = connect(&m_magTimer, SIGNAL(timeout()), this, SLOT(magTimeout()));
    Q_ASSERT(ok);
    ok = connect(this, SIGNAL(itemEntered(QTreeWidgetItem*, int)), this, SLOT(slotItemEntered(QTreeWidgetItem*, int)) );
    Q_ASSERT(ok);
}


/**
* Hack to get single click and selection working. See slotExecuted.
*/
void CBookmarkIndex::mouseReleaseEvent(QMouseEvent* event) {
    //qDebug("CBookmarkIndex::mouseReleaseEvent");
    m_mouseReleaseEventModifiers = event->modifiers();
    QTreeWidget::mouseReleaseEvent(event);
}

/** Called when an item is clicked with mouse or activated with keyboard. */
void CBookmarkIndex::slotExecuted( QTreeWidgetItem* i ) {
    qDebug("CBookmarkIndex::slotExecuted");

    //HACK: checking the modifier keys from the last mouseReleaseEvent
    //depends on executing order: mouseReleaseEvent first, then itemClicked signal
    int modifiers = m_mouseReleaseEventModifiers;
    m_mouseReleaseEventModifiers = Qt::NoModifier;
    if (modifiers != Qt::NoModifier) {
        return;
    }

    BtBookmarkItemBase* btItem = dynamic_cast<BtBookmarkItemBase*>(i);
    if (!btItem) {
        return;
    }

    BtBookmarkFolder* folderItem = 0;
    BtBookmarkItem* bookmarkItem = 0;
    if ((folderItem = dynamic_cast<BtBookmarkFolder*>(btItem))) {
        i->setExpanded( !i->isExpanded() );
    }
    else if (( bookmarkItem = dynamic_cast<BtBookmarkItem*>(btItem) )) { //clicked on a bookmark
        if (CSwordModuleInfo* mod = bookmarkItem->module()) {
            QList<CSwordModuleInfo*> modules;
            modules.append(mod);
            emit createReadDisplayWindow(modules, bookmarkItem->key());
        }
    }
}

/** Creates a drag mime data object for the current selection. */
QMimeData* CBookmarkIndex::dragObject() {
    BTMimeData::ItemList dndItems;
    BTMimeData* mimeData = new BTMimeData;

    foreach( QTreeWidgetItem* widgetItem, selectedItems() ) {
        if (!widgetItem)
            break;
        if (dynamic_cast<BtBookmarkItemBase*>(widgetItem)) {
            if (BtBookmarkItem* bookmark = dynamic_cast<BtBookmarkItem*>( widgetItem )) {
                //take care of bookmarks which have no valid module any more, e.g. if it was uninstalled
                const QString moduleName = bookmark->module() ? bookmark->module()->name() : QString::null;
                mimeData->appendBookmark(moduleName, bookmark->key(), bookmark->description());
            }
        }
    }
    return mimeData;
}

void CBookmarkIndex::dragEnterEvent( QDragEnterEvent* event ) {
    //qDebug("CBookmarkIndex::dragEnterEvent");
    setState(QAbstractItemView::DraggingState);
    QTreeWidget::dragEnterEvent(event);
    if (event->source() == this || event->mimeData()->hasFormat("BibleTime/Bookmark")) {
        event->acceptProposedAction();
    }
}


void CBookmarkIndex::dragMoveEvent( QDragMoveEvent* event ) {
    //qDebug("CBookmarkIndex::dragMoveEvent");

    // do this first, otherwise the event may be ignored
    QTreeWidget::dragMoveEvent(event);

    event->acceptProposedAction();
    event->accept();

    // do this to paint the arrow
    m_dragMovementPosition = event->pos();
    viewport()->update();

}

void CBookmarkIndex::dragLeaveEvent( QDragLeaveEvent* ) {
    qDebug("CBookmarkIndex::dragLeaveEvent");
    setState(QAbstractItemView::NoState); // not dragging anymore
    viewport()->update(); // clear the arrow
}


void CBookmarkIndex::paintEvent(QPaintEvent* event) {
    static QPixmap pix;
    static int halfPixHeight;
    static bool arrowInitialized = false;

    // Initialize the static variables, including the arrow pixmap
    if (!arrowInitialized) {
        arrowInitialized = true;
        int arrowSize = CToolClass::mWidth(this, 1);
        QString fileName;
        if (util::filesystem::DirectoryUtil::getIconDir().exists("pointing_arrow.svg")) {
            fileName = util::filesystem::DirectoryUtil::getIconDir().filePath("pointing_arrow.svg");
        }
        else {
            if (util::filesystem::DirectoryUtil::getIconDir().exists("pointing_arrow.png")) {
                fileName = util::filesystem::DirectoryUtil::getIconDir().filePath("pointing_arrow.png");
            }
            else {
                qWarning() << "Picture file pointing_arrow.svg or .png not found!";
            }
        }

        pix = QPixmap(fileName);
        pix = pix.scaled(arrowSize, arrowSize, Qt::KeepAspectRatioByExpanding);
        halfPixHeight = pix.height() / 2;
    }

    // Do the normal painting first
    QTreeWidget::paintEvent(event);

    // Paint the arrow if the drag is going on
    if (QAbstractItemView::DraggingState == state()) {
        bool rtol = QApplication::isRightToLeft();

        QPainter painter(this->viewport());
        QTreeWidgetItem* item = itemAt(m_dragMovementPosition);
        bool isFolder = dynamic_cast<BtBookmarkFolder*>(item);
        bool isBookmark = dynamic_cast<BtBookmarkItem*>(item);

        // Find the place for the arrow
        QRect rect = visualItemRect(item);
        int xCoord = rtol ? rect.right() : rect.left();
        int yCoord;
        if (isFolder) {
            if (m_dragMovementPosition.y() > rect.bottom() - (2* rect.height() / 3) ) {
                yCoord = rect.bottom() - halfPixHeight; // bottom
                xCoord = rtol ? (xCoord - indentation()) : (xCoord + indentation());
            }
            else {
                yCoord = rect.top() - halfPixHeight - 1; // top
            }

        }
        else {
            if (isBookmark) {
                if (m_dragMovementPosition.y() > rect.bottom() - rect.height() / 2) {
                    yCoord = rect.bottom() - halfPixHeight; // bottom
                }
                else {
                    yCoord = rect.top() - halfPixHeight - 1; // top
                }
            }
            else {
                if (item) { // the extra item
                    yCoord = rect.top() - halfPixHeight - 1;
                }
                else { // empty area
                    rect = visualItemRect(m_extraItem);
                    yCoord = rect.top() - halfPixHeight - 1;
                    xCoord = rtol ? rect.right() : rect.left();
                }
            }
        }

        painter.drawPixmap(xCoord, yCoord, pix);
    }
}


void CBookmarkIndex::dropEvent( QDropEvent* event ) {
    qDebug("CBookmarkIndex::dropEvent");

    //setState(QAbstractItemView::NoState);
    // Try to prevent annoying timed autocollapsing. Remember to disconnect before return.
    QObject::connect(this, SIGNAL(itemCollapsed(QTreeWidgetItem*)), this, SLOT(expandAutoCollapsedItem(QTreeWidgetItem*)));
    QTreeWidgetItem* item = itemAt(event->pos());
    QTreeWidgetItem* parentItem = 0;
    int indexUnderParent = 0;

    // Find the place where the drag is dropped
    if (item) {
        qDebug() << "there was item";

        QRect rect = visualItemRect(item);
        bool isFolder = dynamic_cast<BtBookmarkFolder*>(item);
        bool isBookmark = dynamic_cast<BtBookmarkItem*>(item);

        if (isFolder) { // item is a folder
            qDebug() << "item was folder";
            if (event->pos().y() > rect.bottom() - (2* rect.height() / 3) ) {
                parentItem = item;
            }
            else {
                parentItem = item->parent();
                if (!parentItem) {
                    parentItem = invisibleRootItem();
                }
                qDebug() << "item:" << item << "parent:" << parentItem;
                indexUnderParent = parentItem->indexOfChild(item); // before the current folder
            }
        }
        else {
            if (isBookmark) { // item is a bookmark
                qDebug() << "item was bookmark";
                parentItem = item->parent();
                if (!parentItem) {
                    parentItem = invisibleRootItem();
                }
                indexUnderParent = parentItem->indexOfChild(item); // before the current bookmark
                if (event->pos().y() > rect.bottom() - rect.height() / 2) {
                    indexUnderParent++; // after the current bookmark
                }
            }
            else { // item is the extra item
                parentItem = item->parent();
                if (!parentItem) {
                    parentItem = invisibleRootItem();
                }
                indexUnderParent = parentItem->indexOfChild(item); // before the current bookmark
            }
        }

    }
    else { // no item under event point: drop to the end
        qDebug() << "there was no item";
        parentItem = invisibleRootItem();
        indexUnderParent = parentItem->childCount() - 1;
    }


    if ( event->source() == this ) {
        qDebug("dropping internal drag");
        event->accept();

        bool bookmarksOnly = true;
        bool targetIncluded = false;
        bool moreThanOneFolder = false;

        QList<QTreeWidgetItem*> newItems = addItemsToDropTree(parentItem, bookmarksOnly, targetIncluded, moreThanOneFolder);

        if (moreThanOneFolder) {
            QToolTip::showText(QCursor::pos(), tr("Can drop only bookmarks or one folder"));
            QObject::disconnect(this, SIGNAL(itemCollapsed(QTreeWidgetItem*)), this, SLOT(expandAutoCollapsedItem(QTreeWidgetItem*)));
            return;
        }
        if (targetIncluded) {
            QToolTip::showText(QCursor::pos(), tr("Can't drop folder into the folder itself or into its subfolder"));
            QObject::disconnect(this, SIGNAL(itemCollapsed(QTreeWidgetItem*)), this, SLOT(expandAutoCollapsedItem(QTreeWidgetItem*)));
            return;
        }
        // Ask whether to copy or move with a popup menu

        QMenu* dropPopupMenu = new QMenu(this);
        QAction* copy = dropPopupMenu->addAction(tr("Copy"));
        QAction* move = dropPopupMenu->addAction(tr("Move"));
        QAction* dropAction = dropPopupMenu->exec(QCursor::pos());
        if (dropAction == copy) {
            qDebug() << "copy";
            parentItem->insertChildren(indexUnderParent, newItems);
        }
        else {
            if (dropAction == move) {
                qDebug() << "move";
                parentItem->insertChildren(indexUnderParent, newItems);
                deleteEntries(false);
            }
            else {
                QObject::disconnect(this, SIGNAL(itemCollapsed(QTreeWidgetItem*)), this, SLOT(expandAutoCollapsedItem(QTreeWidgetItem*)));
                return; // user canceled
            }
        }

    }
    else {
        qDebug() << "the source was outside this";
        createBookmarkFromDrop(event, parentItem, indexUnderParent);
    }
    QObject::disconnect(this, SIGNAL(itemCollapsed(QTreeWidgetItem*)), this, SLOT(expandAutoCollapsedItem(QTreeWidgetItem*)));
    setState(QAbstractItemView::NoState);
}


void CBookmarkIndex::createBookmarkFromDrop(QDropEvent* event, QTreeWidgetItem* parentItem, int indexInParent) {
    //qDebug("CBookmarkIndex::createBookmarkFromDrop");
    //take the bookmark data from the mime source
    const BTMimeData* mdata = dynamic_cast<const BTMimeData*>(event->mimeData());
    if (mdata) {
        //create the new bookmark
        QString moduleName = mdata->bookmark().module();
        QString keyText = mdata->bookmark().key();
        QString description = mdata->bookmark().description();
        CSwordModuleInfo* minfo = CPointers::backend()->findModuleByName(moduleName);

        QTreeWidgetItem* newItem = new BtBookmarkItem(minfo, keyText, description);
        parentItem->insertChild(indexInParent, newItem);
    }
}


/** Load the tree from file */
void CBookmarkIndex::initTree() {
    qDebug("CBookmarkIndex::initTree");
    BtBookmarkLoader loader;
    addTopLevelItems(loader.loadTree());

    // add the invisible extra item at the end
    m_extraItem = new QTreeWidgetItem();
    m_extraItem->setFlags(Qt::ItemIsDropEnabled);
    addTopLevelItem(m_extraItem);
}

void CBookmarkIndex::slotItemEntered(QTreeWidgetItem* item, int) {
    qDebug() << "CBookmarkIndex::slotItemEntered";
    if (item == m_extraItem) {
        m_extraItem->setText(0, tr("Drag references from text views to this view"));
    }
    else {
        m_extraItem->setText(0, QString::null);
    }
}


/** Returns the correct QAction object for the given type of action. */
QAction* CBookmarkIndex::action( BtBookmarkItemBase::MenuAction type ) const {
    switch (type) {
        case BtBookmarkItemBase::NewFolder:
            return m_actions.newFolder;
        case BtBookmarkItemBase::ChangeFolder:
            return m_actions.changeFolder;

        case BtBookmarkItemBase::ChangeBookmark:
            return m_actions.changeBookmark;
        case BtBookmarkItemBase::ImportBookmarks:
            return m_actions.importBookmarks;
        case BtBookmarkItemBase::ExportBookmarks:
            return m_actions.exportBookmarks;
        case BtBookmarkItemBase::PrintBookmarks:
            return m_actions.printBookmarks;

        case BtBookmarkItemBase::DeleteEntries:
            return m_actions.deleteEntries;

        default:
            return 0;
    }
}

/** Shows the context menu at the given position. */
void CBookmarkIndex::contextMenu(const QPoint& p) {
    //qDebug("CBookmarkIndex::contextMenu");
    //setup menu entries depending on current selection
    QTreeWidgetItem* i = itemAt(p);
    QList<QTreeWidgetItem *> items = selectedItems();
    //The item which was clicked may not be selected
    if (i && !items.contains(i) && i != m_extraItem)
        items.append(i);

    if (items.count() == 0) {
        //special handling for no selection
        BtBookmarkItemBase::MenuAction actionType;
        for (int index = BtBookmarkItemBase::ActionBegin; index <= BtBookmarkItemBase::ActionEnd; ++index) {
            actionType = static_cast<BtBookmarkItemBase::MenuAction>(index);
            if (QAction* a = action(actionType)) {
                switch (index) {
                        //case BtBookmarkItemBase::ExportBookmarks:
                        //case BtBookmarkItemBase::ImportBookmarks:
                    case BtBookmarkItemBase::NewFolder:
                        //case BtBookmarkItemBase::PrintBookmarks:
                        a->setEnabled(true);
                        break;
                    default:
                        a->setEnabled(false);
                }
            }
        }
    }
    else if (items.count() == 1) {
        //special handling for one selected item

        BtBookmarkItemBase* item = dynamic_cast<BtBookmarkItemBase*>(items.at(0));
        BtBookmarkItemBase::MenuAction actionType;
        for (int index = BtBookmarkItemBase::ActionBegin; index <= BtBookmarkItemBase::ActionEnd; ++index) {
            actionType = static_cast<BtBookmarkItemBase::MenuAction>(index);
            if (QAction* a = action(actionType))
                a->setEnabled( item->enableAction(actionType) );
        }
    }
    else {
        //first disable all actions
        BtBookmarkItemBase::MenuAction actionType;
        for (int index = BtBookmarkItemBase::ActionBegin; index <= BtBookmarkItemBase::ActionEnd; ++index) {
            actionType = static_cast<BtBookmarkItemBase::MenuAction>(index);
            if (QAction* a = action(actionType))
                a->setEnabled(false);
        }
        //enable the menu items depending on the types of the selected items.
        for (int index = BtBookmarkItemBase::ActionBegin; index <= BtBookmarkItemBase::ActionEnd; ++index) {
            actionType = static_cast<BtBookmarkItemBase::MenuAction>(index);
            bool enableAction = isMultiAction(actionType);
            QListIterator<QTreeWidgetItem *> it(items);
            while (it.hasNext()) {
                BtBookmarkItemBase* i = dynamic_cast<BtBookmarkItemBase*>(it.next());
                enableAction = enableAction && i->enableAction(actionType);
            }
            if (enableAction) {
                QAction* a = action(actionType) ;
                if (i && a)
                    a->setEnabled(enableAction);
            }
        }
    }
    //finally, open the popup
    m_popup->exec(mapToGlobal(p));
    //qDebug("CBookmarkIndex::contextMenu end");
}

/** Adds a new subfolder to the current item. */
void CBookmarkIndex::createNewFolder() {
    //qDebug("CBookmarkIndex::createNewFolder");
    QList<QTreeWidgetItem*> selected = selectedItems();
    if (selected.count() > 0) {
        BtBookmarkFolder* i = dynamic_cast<BtBookmarkFolder*>(currentItem());
        if (i) {
            i->newSubFolder();
        }
    }
    else {
        // create a top level folder
        BtBookmarkFolder* newFolder = new BtBookmarkFolder(0, QObject::tr("New folder"));
        //parentFolder->addChild(newFolder);
        insertTopLevelItem(topLevelItemCount() - 1, newFolder);
        newFolder->update();
        newFolder->rename();
    }
}

/** Opens a dialog to change the current folder. */
void CBookmarkIndex::changeFolder() {
    BtBookmarkFolder* i = dynamic_cast<BtBookmarkFolder*>(currentItem());
    Q_ASSERT(i);
    if (i) {
        i->rename();
    }
}

/** Changes the current bookmark. */
void CBookmarkIndex::changeBookmark() {
    BtBookmarkItem* i = dynamic_cast<BtBookmarkItem*>(currentItem());
    Q_ASSERT(i);

    if (i) {
        i->rename();
    }
}

/** Exports the bookmarks being in the selected folder. */
void CBookmarkIndex::exportBookmarks() {
    BtBookmarkFolder* i = dynamic_cast<BtBookmarkFolder*>(currentItem());
    Q_ASSERT(i);

    if (i) {
        i->exportBookmarks();
    }
}

/** Import bookmarks from a file and add them to the selected folder. */
void CBookmarkIndex::importBookmarks() {
    BtBookmarkFolder* i = dynamic_cast<BtBookmarkFolder*>(currentItem());
    Q_ASSERT(i);

    if (i) {
        i->importBookmarks();
    }
}

/** Prints the selected bookmarks. */
void CBookmarkIndex::printBookmarks() {
    Printing::CPrinter::KeyTree tree;
    Printing::CPrinter::KeyTreeItem::Settings settings;
    settings.keyRenderingFace = Printing::CPrinter::KeyTreeItem::Settings::CompleteShort;

    QList<QTreeWidgetItem*> items;
    BtBookmarkFolder* bf = dynamic_cast<BtBookmarkFolder*>(currentItem());

    if (bf) {
        items = bf->getChildList();
    }
    else {
        items = selectedItems();
    }

    //create a tree of keytreeitems using the bookmark hierarchy.
    QListIterator<QTreeWidgetItem*> it(items);
    while (it.hasNext()) {
        BtBookmarkItem* i = dynamic_cast<BtBookmarkItem*>(it.next());
        if (i) {
            qDebug() << "printBookmarks: add to list" << i->key();
            tree.append( new Printing::CPrinter::KeyTreeItem( i->key(), i->module(), settings ) );
        }
    }

    if (items.count() == 0) {
        qWarning("Tried to print empty bookmark list.");
        return;
    }
    boost::scoped_ptr<Printing::CPrinter> printer(
        new Printing::CPrinter( this, CBTConfig::getDisplayOptionDefaults(), CBTConfig::getFilterOptionDefaults() )
    );
    printer->printKeyTree(tree);
}

/** Deletes the selected entries. */
void CBookmarkIndex::deleteEntries(bool confirm) {
    if (confirm) {
        if (!selectedItems().count()) {
            BtBookmarkItemBase* f = dynamic_cast<BtBookmarkItemBase*>(currentItem());
            if (f) {
                currentItem()->setSelected(true);
            }
            else {
                return;
            }
        }

        if (QMessageBox::question(this, tr("Delete Items"), tr("Do you really want to delete the selected items and child-items?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No ) != QMessageBox::Yes) {
            return;
        }
    }

    while (selectedItems().size() > 0) {
        delete selectedItems().at(0); // deleting all does not work because it may cause double deletion
    }

}


/*
Reimplementation from QAbstractItemView/QTreeWidget. Takes care of movable items.
It's easier to use this than to start drag with mouse event handlers.
The default implementation would drag items, but we don't call it. Instead we create
a BibleTime mimedata object. It can be dragged and dropped to a text view or somewhere else.
The internal drag is handled differently, it doesn't use the mimedata (see dropEvent()).
*/
void CBookmarkIndex::startDrag(Qt::DropActions) {
    qDebug("CBookmarkIndex::startDrag");

    QMimeData* mData = dragObject(); // create the data which can be used in other widgets
    QDrag* drag = new QDrag(this);
    drag->setMimeData(mData);
    drag->exec();

    viewport()->update(); // because of the arrow
}






/* Returns true if more than one entry is supported by this action type. Returns false for actions which support only one entry, e.g. about module etc. */
bool CBookmarkIndex::isMultiAction( const BtBookmarkItemBase::MenuAction type ) const {
    switch (type) {
        case BtBookmarkItemBase::NewFolder:
            return false;
        case BtBookmarkItemBase::ChangeFolder:
            return false;

        case BtBookmarkItemBase::ChangeBookmark:
            return false;
        case BtBookmarkItemBase::ImportBookmarks:
            return false;
        case BtBookmarkItemBase::ExportBookmarks:
            return false;
        case BtBookmarkItemBase::PrintBookmarks:
            return true;

        case BtBookmarkItemBase::DeleteEntries:
            return true;
    }

    return false;
}

/* Saves the bookmarks to the default bookmarks file. */
void CBookmarkIndex::saveBookmarks() {

    qDebug("CBookmarkIndex::saveBookmarks()");
    BtBookmarkLoader loader;
    loader.saveTreeFromRootItem(invisibleRootItem());
    //qDebug("CBookmarkIndex::saveBookmarks end");
}

void CBookmarkIndex::mouseMoveEvent(QMouseEvent* event) {
    //qDebug() << "CBookmarkIndex::mouseMoveEvent";

    // Restart the mag timer if we have moved to another item and shift was not pressed.
    QTreeWidgetItem* itemUnderPointer = itemAt(event->pos());
    if (itemUnderPointer && (itemUnderPointer != m_previousEventItem) ) {
        //qDebug("CBookmarkIndex::mouseMoveEvent, moved onto another item");
        if ( !(event->modifiers() & Qt::ShiftModifier)) {
            m_magTimer.start(); // see the ctor for the timer properties
        }
    }
    m_previousEventItem = itemUnderPointer;

    // Clear the extra item text unless we are on top of it
    if ( (itemUnderPointer != m_extraItem) && !m_extraItem->text(0).isNull()) {
        m_extraItem->setText(0, QString::null);
    }

    QTreeWidget::mouseMoveEvent(event);
}

void CBookmarkIndex::magTimeout() {
    //qDebug("CBookmarkIndex::magTimeout");

    QTreeWidgetItem* itemUnderPointer = 0;
    if (underMouse()) {
        itemUnderPointer = itemAt(mapFromGlobal(QCursor::pos()));
    }
    // if the mouse pointer have been over the same item since the timer was started
    if (itemUnderPointer && (m_previousEventItem == itemUnderPointer)) {
        BtBookmarkItem* bitem = dynamic_cast<BtBookmarkItem*>(itemUnderPointer);
        if (bitem) {
            //qDebug("CBookmarkIndex::timerEvent: update the infodisplay");
            // Update the mag
            if (bitem->module()) {
                (CPointers::infoDisplay())->setInfo(
                    InfoDisplay::CInfoDisplay::CrossReference,
                    bitem->module()->name() + ":" + bitem->key()
                );
            }
            else {
                (CPointers::infoDisplay())->setInfo(InfoDisplay::CInfoDisplay::Text, tr("The work to which the bookmark points to is not installed."));
            }

        }
    }
}

/*
Creates a list of new items based on the current selection.
If there are only bookmarks in the selection they are all included.
If there is one folder it's included as a deep copy.
Sets bookmarksOnly=false if it finds a folder.
Sets targetIncluded=true if the target is in the list.
Sets moreThanOneFolder=true if selection includes one folder and something more.
If moreThanOneFolder or targetIncluded is detected the creation of list is stopped
and the list is incomplete.
*/
QList<QTreeWidgetItem*> CBookmarkIndex::addItemsToDropTree(
    QTreeWidgetItem* target, bool& bookmarksOnly, bool& targetIncluded, bool& moreThanOneFolder) {
    qDebug() << "CBookmarkIndex::addItemsToDropTree";
    QList<QTreeWidgetItem*> selectedList = selectedItems();
    QList<QTreeWidgetItem*> newList;

    foreach(QTreeWidgetItem* item, selectedList) {
        qDebug() << "go through all items:" << item;
        if ( BtBookmarkFolder* folder = dynamic_cast<BtBookmarkFolder*>(item)) {
            bookmarksOnly = false;
            if (selectedList.count() > 1) { // only one item allowed if a folder is selected
                qDebug() << "one folder and something else is selected";
                moreThanOneFolder = true;
                break;
            }
            if (folder->hasDescendant(target)) { // dropping to self or descendand not allowed
                qDebug() << "addItemsToDropTree: target is included";
                targetIncluded = true;
                break;
            }
        }
        else {
            qDebug() << "append new QTreeWidget item (should be BtBookmarkItem?)";
            newList.append(new BtBookmarkItem( *(dynamic_cast<BtBookmarkItem*>(item)) ));
        }
    }
    if (!bookmarksOnly && selectedList.count() == 1) {
        qDebug() << "exactly one folder";
        BtBookmarkFolder* folder = dynamic_cast<BtBookmarkFolder*>(selectedList.value(0));
        BtBookmarkFolder* copy = folder->deepCopy();
        newList.append(copy);
    }
    if (!bookmarksOnly && selectedList.count() > 1) {
        // wrong amount of items
        qDebug() << "one folder and something else is selected 2";
        moreThanOneFolder = true;
    }
    qDebug() << "return the new list" << newList;
    return newList;
}