bookmarkmanager.cpp 26.3 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
3
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
con's avatar
con committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
con's avatar
con committed
7
**
hjk's avatar
hjk committed
8
9
10
11
12
13
14
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
15
**
16
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
18
19
20
21
22
23
24
25
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
con's avatar
con committed
26
27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
hjk's avatar
hjk committed
29

con's avatar
con committed
30
#include "bookmarkmanager.h"
hjk's avatar
hjk committed
31

con's avatar
con committed
32
33
34
35
36
#include "bookmark.h"
#include "bookmarksplugin.h"
#include "bookmarks_global.h"

#include <coreplugin/editormanager/editormanager.h>
37
#include <coreplugin/icore.h>
38
#include <coreplugin/actionmanager/actionmanager.h>
39
#include <coreplugin/actionmanager/command.h>
40
#include <projectexplorer/projectexplorer.h>
41
#include <projectexplorer/session.h>
42
#include <texteditor/basetexteditor.h>
43
44
#include <utils/tooltip/tooltip.h>
#include <utils/tooltip/tipcontents.h>
hjk's avatar
hjk committed
45
#include <utils/qtcassert.h>
46
#include <utils/checkablemessagebox.h>
con's avatar
con committed
47

48
49
#include <QAction>
#include <QContextMenuEvent>
50
#include <QDebug>
51
52
#include <QDialog>
#include <QDialogButtonBox>
53
54
#include <QDir>
#include <QFileInfo>
55
56
#include <QFormLayout>
#include <QLineEdit>
57
58
#include <QMenu>
#include <QPainter>
59
#include <QSpinBox>
con's avatar
con committed
60
61
62
63

Q_DECLARE_METATYPE(Bookmarks::Internal::Bookmark*)

using namespace ProjectExplorer;
64
using namespace TextEditor;
65
using namespace Core;
hjk's avatar
hjk committed
66
using namespace Utils;
con's avatar
con committed
67

68
69
70
namespace Bookmarks {
namespace Internal {

con's avatar
con committed
71
BookmarkDelegate::BookmarkDelegate(QObject *parent)
hjk's avatar
hjk committed
72
    : QStyledItemDelegate(parent)
con's avatar
con committed
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
{
}

QSize BookmarkDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionViewItemV4 opt = option;
    initStyleOption(&opt, index);

    QFontMetrics fm(option.font);
    QSize s;
    s.setWidth(option.rect.width());
    s.setHeight(fm.height() * 2 + 10);
    return s;
}

88
void BookmarkDelegate::generateGradientPixmap(int width, int height, const QColor &color, bool selected) const
con's avatar
con committed
89
90
91
92
{
    QColor c = color;
    c.setAlpha(0);

hjk's avatar
hjk committed
93
94
    QPixmap pixmap(width+1, height);
    pixmap.fill(c);
con's avatar
con committed
95

hjk's avatar
hjk committed
96
    QPainter painter(&pixmap);
con's avatar
con committed
97
98
99
100
101
102
103
104
105
    painter.setPen(Qt::NoPen);

    QLinearGradient lg;
    lg.setCoordinateMode(QGradient::ObjectBoundingMode);
    lg.setFinalStop(1,0);

    lg.setColorAt(0, c);
    lg.setColorAt(0.4, color);

hjk's avatar
hjk committed
106
    painter.setBrush(lg);
con's avatar
con committed
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
    painter.drawRect(0, 0, width+1, height);

    if (selected)
        m_selectedPixmap = pixmap;
    else
        m_normalPixmap = pixmap;
}

void BookmarkDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionViewItemV4 opt = option;
    initStyleOption(&opt, index);
    painter->save();

    QFontMetrics fm(opt.font);
122
    static int lwidth = fm.width(QLatin1String("8888")) + 18;
con's avatar
con committed
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

    QColor backgroundColor;
    QColor textColor;

    bool selected = opt.state & QStyle::State_Selected;

    if (selected) {
        painter->setBrush(opt.palette.highlight().color());
        backgroundColor = opt.palette.highlight().color();
        if (!m_selectedPixmap)
            generateGradientPixmap(lwidth, fm.height()+1, backgroundColor, selected);
    } else {
        painter->setBrush(opt.palette.background().color());
        backgroundColor = opt.palette.background().color();
        if (!m_normalPixmap)
            generateGradientPixmap(lwidth, fm.height(), backgroundColor, selected);
    }
    painter->setPen(Qt::NoPen);
    painter->drawRect(opt.rect);

    // Set Text Color
    if (opt.state & QStyle::State_Selected)
        textColor = opt.palette.highlightedText().color();
    else
        textColor = opt.palette.text().color();

    painter->setPen(textColor);


    // TopLeft
hjk's avatar
hjk committed
153
    QString topLeft = index.data(BookmarkManager::Filename).toString();
con's avatar
con committed
154
155
156
    painter->drawText(6, 2 + opt.rect.top() + fm.ascent(), topLeft);

    QString topRight = index.data(BookmarkManager::LineNumber).toString();
Tobias Hunger's avatar
Tobias Hunger committed
157
    // Check whether we need to be fancy and paint some background
con's avatar
con committed
158
159
160
    int fwidth = fm.width(topLeft);
    if (fwidth + lwidth > opt.rect.width()) {
        int left = opt.rect.right() - lwidth;
hjk's avatar
hjk committed
161
        painter->drawPixmap(left, opt.rect.top(), selected ? m_selectedPixmap : m_normalPixmap);
con's avatar
con committed
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
    }
    // topRight
    painter->drawText(opt.rect.right() - fm.width(topRight) - 6 , 2 + opt.rect.top() + fm.ascent(), topRight);

    // Directory
    QColor mix;
    mix.setRgbF(0.7 * textColor.redF()   + 0.3 * backgroundColor.redF(),
                0.7 * textColor.greenF() + 0.3 * backgroundColor.greenF(),
                0.7 * textColor.blueF()  + 0.3 * backgroundColor.blueF());
    painter->setPen(mix);
//
//    QString directory = index.data(BookmarkManager::Directory).toString();
//    int availableSpace = opt.rect.width() - 12;
//    if (fm.width(directory) > availableSpace) {
//        // We need a shorter directory
//        availableSpace -= fm.width("...");
//
//        int pos = directory.size();
//        int idx;
//        forever {
//            idx = directory.lastIndexOf("/", pos-1);
hjk's avatar
hjk committed
183
//            if (idx == -1) {
con's avatar
con committed
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
//                // Can't happen, this means the string did fit after all?
//                break;
//            }
//            int width = fm.width(directory.mid(idx, pos-idx));
//            if (width > availableSpace) {
//                directory = "..." + directory.mid(pos);
//                break;
//            } else {
//                pos = idx;
//                availableSpace -= width;
//            }
//        }
//    }
//
//    painter->drawText(3, opt.rect.top() + fm.ascent() + fm.height() + 6, directory);

Orgad Shaneh's avatar
Orgad Shaneh committed
200
201
202
    QString lineText = index.data(BookmarkManager::Note).toString().trimmed();
    if (lineText.isEmpty())
        lineText = index.data(BookmarkManager::LineText).toString().trimmed();
203

Orgad Shaneh's avatar
Orgad Shaneh committed
204
    painter->drawText(6, opt.rect.top() + fm.ascent() + fm.height() + 6, lineText);
con's avatar
con committed
205
206
207
208
209
210
211

    // Separator lines
    painter->setPen(QColor::fromRgb(150,150,150));
    painter->drawLine(0, opt.rect.bottom(), opt.rect.right(), opt.rect.bottom());
    painter->restore();
}

hjk's avatar
hjk committed
212
213
214
BookmarkView::BookmarkView(BookmarkManager *manager)  :
    m_bookmarkContext(new Core::IContext(this)),
    m_manager(manager)
con's avatar
con committed
215
216
217
{
    setWindowTitle(tr("Bookmarks"));

hjk's avatar
hjk committed
218
219
    m_bookmarkContext->setWidget(this);
    m_bookmarkContext->setContext(Core::Context(Constants::BOOKMARKS_CONTEXT));
con's avatar
con committed
220

hjk's avatar
hjk committed
221
    ICore::addContextObject(m_bookmarkContext);
con's avatar
con committed
222

hjk's avatar
hjk committed
223
224
    Utils::ListView::setModel(manager);

con's avatar
con committed
225
226
227
228
    setItemDelegate(new BookmarkDelegate(this));
    setFrameStyle(QFrame::NoFrame);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setFocusPolicy(Qt::NoFocus);
hjk's avatar
hjk committed
229
230
231
232
233
234
235
236
    setSelectionModel(manager->selectionModel());
    setSelectionMode(QAbstractItemView::SingleSelection);
    setSelectionBehavior(QAbstractItemView::SelectRows);

    connect(this, SIGNAL(clicked(QModelIndex)),
            this, SLOT(gotoBookmark(QModelIndex)));
    connect(this, SIGNAL(activated(QModelIndex)),
            this, SLOT(gotoBookmark(QModelIndex)));
con's avatar
con committed
237
238
239
240
}

BookmarkView::~BookmarkView()
{
hjk's avatar
hjk committed
241
    ICore::removeContextObject(m_bookmarkContext);
con's avatar
con committed
242
243
244
245
246
}

void BookmarkView::contextMenuEvent(QContextMenuEvent *event)
{
    QMenu menu;
247
248
    QAction *moveUp = menu.addAction(tr("Move Up"));
    QAction *moveDown = menu.addAction(tr("Move Down"));
249
    QAction *edit = menu.addAction(tr("&Edit"));
250
    menu.addSeparator();
251
    QAction *remove = menu.addAction(tr("&Remove"));
252
    menu.addSeparator();
253
    QAction *removeAll = menu.addAction(tr("Remove All"));
254

con's avatar
con committed
255
    m_contextMenuIndex = indexAt(event->pos());
256
257
258
    if (!m_contextMenuIndex.isValid()) {
        moveUp->setEnabled(false);
        moveDown->setEnabled(false);
con's avatar
con committed
259
        remove->setEnabled(false);
260
        edit->setEnabled(false);
261
    }
con's avatar
con committed
262
263
264
265

    if (model()->rowCount() == 0)
        removeAll->setEnabled(false);

266
267
268
269
    connect(moveUp, SIGNAL(triggered()),
            m_manager, SLOT(moveUp()));
    connect(moveDown, SIGNAL(triggered()),
            m_manager, SLOT(moveDown()));
con's avatar
con committed
270
271
272
273
    connect(remove, SIGNAL(triggered()),
            this, SLOT(removeFromContextMenu()));
    connect(removeAll, SIGNAL(triggered()),
            this, SLOT(removeAll()));
274
275
    connect(edit, SIGNAL(triggered()),
            m_manager, SLOT(edit()));
con's avatar
con committed
276
277
278
279
280
281
282
283
284
285
286

    menu.exec(mapToGlobal(event->pos()));
}

void BookmarkView::removeFromContextMenu()
{
    removeBookmark(m_contextMenuIndex);
}

void BookmarkView::removeBookmark(const QModelIndex& index)
{
287
288
    Bookmark *bm = m_manager->bookmarkForIndex(index);
    m_manager->removeBookmark(bm);
con's avatar
con committed
289
290
}

291
292
293
294
295
296
297
void BookmarkView::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Delete) {
        removeBookmark(currentIndex());
        event->accept();
        return;
    }
298
    Utils::ListView::keyPressEvent(event);
299
300
}

con's avatar
con committed
301
302
void BookmarkView::removeAll()
{
303
304
305
306
307
308
    if (Utils::CheckableMessageBox::doNotAskAgainQuestion(this,
            tr("Remove All Bookmarks"),
            tr("Are you sure you want to remove all bookmarks from all files in the current session?"),
            ICore::settings(),
            QLatin1String("RemoveAllBookmarks")) != QDialogButtonBox::Yes)
        return;
309
310

    // The performance of this function could be greatly improved.
311
312
    while (m_manager->rowCount()) {
        QModelIndex index = m_manager->index(0, 0);
con's avatar
con committed
313
314
315
316
317
318
        removeBookmark(index);
    }
}

void BookmarkView::gotoBookmark(const QModelIndex &index)
{
319
320
321
    Bookmark *bk = m_manager->bookmarkForIndex(index);
    if (!m_manager->gotoBookmark(bk))
        m_manager->removeBookmark(bk);
con's avatar
con committed
322
323
324
325
326
327
}

////
// BookmarkManager
////

328
329
330
BookmarkManager::BookmarkManager() :
    m_bookmarkIcon(QLatin1String(":/bookmarks/images/bookmark.png")),
    m_selectionModel(new QItemSelectionModel(this, this))
con's avatar
con committed
331
{
332
    connect(Core::ICore::instance(), SIGNAL(contextChanged(QList<Core::IContext*>,Core::Context)),
con's avatar
con committed
333
334
            this, SLOT(updateActionStatus()));

hjk's avatar
hjk committed
335
    connect(SessionManager::instance(), SIGNAL(sessionLoaded(QString)),
con's avatar
con committed
336
337
338
339
340
341
342
343
344
345
346
            this, SLOT(loadBookmarks()));

    updateActionStatus();
}

BookmarkManager::~BookmarkManager()
{
    DirectoryFileBookmarksMap::iterator it, end;
    end = m_bookmarksMap.end();
    for (it = m_bookmarksMap.begin(); it != end; ++it) {
        FileNameBookmarksMap *bookmarks = it.value();
con's avatar
con committed
347
        qDeleteAll(*bookmarks);
con's avatar
con committed
348
349
350
351
352
353
354
355
356
        delete bookmarks;
    }
}

QItemSelectionModel *BookmarkManager::selectionModel() const
{
    return m_selectionModel;
}

357
358
bool BookmarkManager::hasBookmarkInPosition(const QString &fileName, int lineNumber)
{
hjk's avatar
hjk committed
359
    return findBookmark(fileName, lineNumber);
360
361
}

con's avatar
con committed
362
363
364
365
366
QModelIndex BookmarkManager::index(int row, int column, const QModelIndex &parent) const
{
    if (parent.isValid())
        return QModelIndex();
    else
367
        return createIndex(row, column);
con's avatar
con committed
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
}

QModelIndex BookmarkManager::parent(const QModelIndex &) const
{
    return QModelIndex();
}

int BookmarkManager::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid())
        return 0;
    else
        return m_bookmarksList.count();
}

int BookmarkManager::columnCount(const QModelIndex &parent) const
{
    if (parent.isValid())
        return 0;
    return 3;
}

QVariant BookmarkManager::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.column() !=0 || index.row() < 0 || index.row() >= m_bookmarksList.count())
        return QVariant();

hjk's avatar
hjk committed
395
    Bookmark *bookMark = m_bookmarksList.at(index.row());
con's avatar
con committed
396
    if (role == BookmarkManager::Filename)
hjk's avatar
hjk committed
397
        return QFileInfo(bookMark->fileName()).fileName();
hjk's avatar
hjk committed
398
    if (role == BookmarkManager::LineNumber)
hjk's avatar
hjk committed
399
        return bookMark->lineNumber();
hjk's avatar
hjk committed
400
    if (role == BookmarkManager::Directory)
hjk's avatar
hjk committed
401
        return QFileInfo(bookMark->fileName()).path();
hjk's avatar
hjk committed
402
    if (role == BookmarkManager::LineText)
hjk's avatar
hjk committed
403
        return bookMark->lineText();
hjk's avatar
hjk committed
404
    if (role == BookmarkManager::Note)
hjk's avatar
hjk committed
405
        return bookMark->note();
hjk's avatar
hjk committed
406
    if (role == Qt::ToolTipRole)
hjk's avatar
hjk committed
407
        return QDir::toNativeSeparators(bookMark->fileName());
con's avatar
con committed
408
409
410
411
412
    return QVariant();
}

void BookmarkManager::toggleBookmark()
{
413
    BaseTextEditor *editor = BaseTextEditor::currentTextEditor();
con's avatar
con committed
414
415
416
    if (!editor)
        return;

417
    toggleBookmark(editor->document()->filePath(), editor->currentLine());
hjk's avatar
hjk committed
418
419
420
421
422
}

void BookmarkManager::toggleBookmark(const QString &fileName, int lineNumber)
{
    const int editorLine = lineNumber;
con's avatar
con committed
423
424

    // Remove any existing bookmark on this line
hjk's avatar
hjk committed
425
    if (Bookmark *mark = findBookmark(fileName, lineNumber)) {
con's avatar
con committed
426
427
428
429
430
431
        // TODO check if the bookmark is really on the same markable Interface
        removeBookmark(mark);
        return;
    }

    // Add a new bookmark if no bookmark existed on this line
hjk's avatar
hjk committed
432
    addBookmark(new Bookmark(fileName, editorLine, this));
con's avatar
con committed
433
434
435
436
}

void BookmarkManager::updateBookmark(Bookmark *bookmark)
{
437
438
439
440
    const int idx = m_bookmarksList.indexOf(bookmark);
    if (idx == -1)
        return;

con's avatar
con committed
441
442
443
444
    emit dataChanged(index(idx, 0, QModelIndex()), index(idx, 2, QModelIndex()));
    saveBookmarks();
}

445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
void BookmarkManager::removeAllBookmarks()
{
    if (m_bookmarksList.isEmpty())
        return;
    beginRemoveRows(QModelIndex(), 0, m_bookmarksList.size() - 1);

    DirectoryFileBookmarksMap::const_iterator it, end;
    end = m_bookmarksMap.constEnd();
    for (it = m_bookmarksMap.constBegin(); it != end; ++it) {
        FileNameBookmarksMap *files = it.value();
        FileNameBookmarksMap::const_iterator jt, jend;
        jend = files->constEnd();
        for (jt = files->constBegin(); jt != jend; ++jt) {
            delete jt.value();
        }
        files->clear();
        delete files;
    }
    m_bookmarksMap.clear();
    m_bookmarksList.clear();
    endRemoveRows();
}

con's avatar
con committed
468
469
void BookmarkManager::removeBookmark(Bookmark *bookmark)
{
470
471
472
    int idx = m_bookmarksList.indexOf(bookmark);
    beginRemoveRows(QModelIndex(), idx, idx);

hjk's avatar
hjk committed
473
    const QFileInfo fi(bookmark->fileName());
con's avatar
con committed
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
    FileNameBookmarksMap *files = m_bookmarksMap.value(fi.path());

    FileNameBookmarksMap::iterator i = files->begin();
    while (i != files->end()) {
        if (i.value() == bookmark) {
            files->erase(i);
            delete bookmark;
            break;
        }
        ++i;
    }
    if (files->count() <= 0) {
        m_bookmarksMap.remove(fi.path());
        delete files;
    }

490

con's avatar
con committed
491
492
493
494
495
496
497
498
499
500
    m_bookmarksList.removeAt(idx);
    endRemoveRows();

    if (selectionModel()->currentIndex().isValid())
        selectionModel()->setCurrentIndex(selectionModel()->currentIndex(), QItemSelectionModel::Select | QItemSelectionModel::Clear);

    updateActionStatus();
    saveBookmarks();
}

hjk's avatar
hjk committed
501
Bookmark *BookmarkManager::bookmarkForIndex(const QModelIndex &index) const
con's avatar
con committed
502
503
504
505
506
507
{
    if (!index.isValid() || index.row() >= m_bookmarksList.size())
        return 0;
    return m_bookmarksList.at(index.row());
}

hjk's avatar
hjk committed
508
bool BookmarkManager::gotoBookmark(Bookmark *bookmark)
con's avatar
con committed
509
{
hjk's avatar
hjk committed
510
    if (IEditor *editor = EditorManager::openEditorAt(bookmark->fileName(), bookmark->lineNumber()))
hjk's avatar
hjk committed
511
        return editor->currentLine() == bookmark->lineNumber();
512
    return false;
con's avatar
con committed
513
514
515
516
517
518
519
520
521
522
523
524
525
526
}

void BookmarkManager::nextInDocument()
{
    documentPrevNext(true);
}

void BookmarkManager::prevInDocument()
{
    documentPrevNext(false);
}

void BookmarkManager::documentPrevNext(bool next)
{
527
    BaseTextEditor *editor = BaseTextEditor::currentTextEditor();
con's avatar
con committed
528
    int editorLine = editor->currentLine();
529
    QFileInfo fi(editor->document()->filePath());
con's avatar
con committed
530
531
532
533
534
535
536
    if (!m_bookmarksMap.contains(fi.path()))
        return;

    int firstLine = -1;
    int lastLine = -1;
    int prevLine = -1;
    int nextLine = -1;
hjk's avatar
hjk committed
537
    const QList<Bookmark *> marks = m_bookmarksMap.value(fi.path())->values(fi.fileName());
con's avatar
con committed
538
539
540
541
542
543
544
545
546
547
548
549
550
    for (int i = 0; i < marks.count(); ++i) {
        int markLine = marks.at(i)->lineNumber();
        if (firstLine == -1 || firstLine > markLine)
            firstLine = markLine;
        if (lastLine < markLine)
            lastLine = markLine;
        if (markLine < editorLine && prevLine < markLine)
            prevLine = markLine;
        if (markLine > editorLine &&
            (nextLine == -1 || nextLine > markLine))
            nextLine = markLine;
    }

551
    EditorManager::addCurrentPositionToNavigationHistory();
con's avatar
con committed
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
    if (next) {
        if (nextLine == -1)
            editor->gotoLine(firstLine);
        else
            editor->gotoLine(nextLine);
    } else {
        if (prevLine == -1)
            editor->gotoLine(lastLine);
        else
            editor->gotoLine(prevLine);
    }
}

void BookmarkManager::next()
{
    QModelIndex current = selectionModel()->currentIndex();
    if (!current.isValid())
        return;
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
    int row = current.row();
    ++row;
    while (true) {
        if (row == m_bookmarksList.size())
            row = 0;

        Bookmark *bk = m_bookmarksList.at(row);
        if (gotoBookmark(bk)) {
            QModelIndex newIndex = current.sibling(row, current.column());
            selectionModel()->setCurrentIndex(newIndex, QItemSelectionModel::Select | QItemSelectionModel::Clear);
            return;
        }
        removeBookmark(bk);
        if (m_bookmarksList.isEmpty()) // No bookmarks anymore ...
            return;
    }
con's avatar
con committed
586
587
588
589
590
591
592
}

void BookmarkManager::prev()
{
    QModelIndex current = selectionModel()->currentIndex();
    if (!current.isValid())
        return;
593

con's avatar
con committed
594
    int row = current.row();
595
596
597
598
599
600
601
602
603
604
605
606
607
608
    while (true) {
        if (row == 0)
            row = m_bookmarksList.size();
        --row;
        Bookmark *bk = m_bookmarksList.at(row);
        if (gotoBookmark(bk)) {
            QModelIndex newIndex = current.sibling(row, current.column());
            selectionModel()->setCurrentIndex(newIndex, QItemSelectionModel::Select | QItemSelectionModel::Clear);
            return;
        }
        removeBookmark(bk);
        if (m_bookmarksList.isEmpty())
            return;
    }
con's avatar
con committed
609
610
611
612
613
614
615
}

BookmarkManager::State BookmarkManager::state() const
{
    if (m_bookmarksMap.empty())
        return NoBookMarks;

616
    BaseTextEditor *editor = BaseTextEditor::currentTextEditor();
con's avatar
con committed
617
618
619
    if (!editor)
        return HasBookMarks;

620
    const QFileInfo fi(editor->document()->filePath());
con's avatar
con committed
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

    const DirectoryFileBookmarksMap::const_iterator dit = m_bookmarksMap.constFind(fi.path());
    if (dit == m_bookmarksMap.constEnd())
        return HasBookMarks;

    return HasBookmarksInDocument;
}

void BookmarkManager::updateActionStatus()
{
    emit updateActions(state());
}

void BookmarkManager::moveUp()
{
    QModelIndex current = selectionModel()->currentIndex();
    int row = current.row();
    if (row == 0)
        row = m_bookmarksList.size();
     --row;

    // swap current.row() and row

    Bookmark *b = m_bookmarksList.at(row);
    m_bookmarksList[row] = m_bookmarksList.at(current.row());
    m_bookmarksList[current.row()] = b;

    QModelIndex topLeft = current.sibling(row, 0);
    QModelIndex bottomRight = current.sibling(current.row(), 2);
    emit dataChanged(topLeft, bottomRight);
    selectionModel()->setCurrentIndex(current.sibling(row, 0), QItemSelectionModel::Select | QItemSelectionModel::Clear);
Vasiliy Sorokin's avatar
Vasiliy Sorokin committed
652
653

    saveBookmarks();
con's avatar
con committed
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
}

void BookmarkManager::moveDown()
{
    QModelIndex current = selectionModel()->currentIndex();
    int row = current.row();
    ++row;
    if (row == m_bookmarksList.size())
        row = 0;

    // swap current.row() and row
    Bookmark *b = m_bookmarksList.at(row);
    m_bookmarksList[row] = m_bookmarksList.at(current.row());
    m_bookmarksList[current.row()] = b;

    QModelIndex topLeft = current.sibling(current.row(), 0);
    QModelIndex bottomRight = current.sibling(row, 2);
    emit dataChanged(topLeft, bottomRight);
    selectionModel()->setCurrentIndex(current.sibling(row, 0), QItemSelectionModel::Select | QItemSelectionModel::Clear);
Vasiliy Sorokin's avatar
Vasiliy Sorokin committed
673
674

    saveBookmarks();
con's avatar
con committed
675
676
}

677
void BookmarkManager::edit(const QString &fileName, int lineNumber)
678
{
hjk's avatar
hjk committed
679
    Bookmark *b = findBookmark(fileName, lineNumber);
680
681
682
683
    QModelIndex current = selectionModel()->currentIndex();
    selectionModel()->setCurrentIndex(current.sibling(m_bookmarksList.indexOf(b), 0),
                                      QItemSelectionModel::Select | QItemSelectionModel::Clear);

684
    edit();
685
686
}

687
void BookmarkManager::edit()
688
689
690
691
{
    QModelIndex current = selectionModel()->currentIndex();
    Bookmark *b = m_bookmarksList.at(current.row());

692
693
694
695
    QDialog dlg;
    dlg.setWindowTitle(tr("Edit Bookmark"));
    auto layout = new QFormLayout(&dlg);
    auto noteEdit = new QLineEdit(b->note());
696
    noteEdit->setMinimumWidth(300);
697
698
699
    auto lineNumberSpinbox = new QSpinBox;
    lineNumberSpinbox->setRange(1, INT_MAX);
    lineNumberSpinbox->setValue(b->lineNumber());
700
    lineNumberSpinbox->setMaximumWidth(100);
701
702
703
704
    auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    connect(buttonBox, SIGNAL(accepted()), &dlg, SLOT(accept()));
    connect(buttonBox, SIGNAL(rejected()), &dlg, SLOT(reject()));
    layout->addRow(tr("Note text:"), noteEdit);
705
    layout->addRow(tr("Line number:"), lineNumberSpinbox);
706
707
    layout->addWidget(buttonBox);
    if (dlg.exec() == QDialog::Accepted) {
708
        b->move(lineNumberSpinbox->value());
709
        b->updateNote(noteEdit->text().replace(QLatin1Char('\t'), QLatin1Char(' ')));
710
        emit dataChanged(current, current);
Vasiliy Sorokin's avatar
Vasiliy Sorokin committed
711
        saveBookmarks();
712
713
714
    }
}

con's avatar
con committed
715
/* Returns the bookmark at the given file and line number, or 0 if no such bookmark exists. */
hjk's avatar
hjk committed
716
Bookmark *BookmarkManager::findBookmark(const QString &filePath, int lineNumber)
con's avatar
con committed
717
{
hjk's avatar
hjk committed
718
719
    QFileInfo fi(filePath);
    QString path = fi.path();
con's avatar
con committed
720
    if (m_bookmarksMap.contains(path)) {
hjk's avatar
hjk committed
721
        foreach (Bookmark *bookmark, m_bookmarksMap.value(path)->values(fi.fileName())) {
con's avatar
con committed
722
723
724
725
726
727
728
729
730
731
732
733
734
735
            if (bookmark->lineNumber() == lineNumber)
                return bookmark;
        }
    }
    return 0;
}

/* Adds a bookmark to the internal data structures. The 'userset' parameter
 * determines whether action status should be updated and whether the bookmarks
 * should be saved to the session settings.
 */
void BookmarkManager::addBookmark(Bookmark *bookmark, bool userset)
{
    beginInsertRows(QModelIndex(), m_bookmarksList.size(), m_bookmarksList.size());
hjk's avatar
hjk committed
736
    const QFileInfo fi(bookmark->fileName());
con's avatar
con committed
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
    const QString &path = fi.path();

    if (!m_bookmarksMap.contains(path))
        m_bookmarksMap.insert(path, new FileNameBookmarksMap());
    m_bookmarksMap.value(path)->insert(fi.fileName(), bookmark);

    m_bookmarksList.append(bookmark);

    endInsertRows();
    if (userset) {
        updateActionStatus();
        saveBookmarks();
    }
    selectionModel()->setCurrentIndex(index(m_bookmarksList.size()-1 , 0, QModelIndex()), QItemSelectionModel::Select | QItemSelectionModel::Clear);
}

/* Adds a new bookmark based on information parsed from the string. */
void BookmarkManager::addBookmark(const QString &s)
{
756
    // index3 is a frontier beetween note text and other bookmarks data
757
    int index3 = s.lastIndexOf(QLatin1Char('\t'));
758
759
    if (index3 < 0)
        index3 = s.size();
760
761
    int index2 = s.lastIndexOf(QLatin1Char(':'), index3 - 1);
    int index1 = s.indexOf(QLatin1Char(':'));
762
763

    if (index3 != -1 || index2 != -1 || index1 != -1) {
con's avatar
con committed
764
        const QString &filePath = s.mid(index1+1, index2-index1-1);
765
766
        const QString &note = s.mid(index3 + 1);
        const int lineNumber = s.mid(index2 + 1, index3 - index2 - 1).toInt();
hjk's avatar
hjk committed
767
        if (!filePath.isEmpty() && !findBookmark(filePath, lineNumber)) {
con's avatar
con committed
768
            Bookmark *b = new Bookmark(filePath, lineNumber, this);
769
            b->setNote(note);
con's avatar
con committed
770
771
772
773
774
775
776
777
778
779
780
            addBookmark(b, false);
        }
    } else {
        qDebug() << "BookmarkManager::addBookmark() Invalid bookmark string:" << s;
    }
}

/* Puts the bookmark in a string for storing it in the settings. */
QString BookmarkManager::bookmarkToString(const Bookmark *b)
{
    const QLatin1Char colon(':');
781
782
    // Using \t as delimiter because any another symbol can be a part of note.
    const QLatin1Char noteDelimiter('\t');
hjk's avatar
hjk committed
783
    return colon + b->fileName() +
784
785
            colon + QString::number(b->lineNumber()) +
            noteDelimiter + b->note();
con's avatar
con committed
786
787
788
789
790
791
}

/* Saves the bookmarks to the session settings. */
void BookmarkManager::saveBookmarks()
{
    QStringList list;
Vasiliy Sorokin's avatar
Vasiliy Sorokin committed
792
    foreach (const Bookmark *bookmark, m_bookmarksList)
hjk's avatar
hjk committed
793
        list << bookmarkToString(bookmark);
con's avatar
con committed
794

hjk's avatar
hjk committed
795
    SessionManager::setValue(QLatin1String("Bookmarks"), list);
con's avatar
con committed
796
797
}

798
void BookmarkManager::operateTooltip(BaseTextEditor *textEditor, const QPoint &pos, Bookmark *mark)
799
800
801
802
{
    if (!mark)
        return;

803
    if (mark->note().isEmpty())
hjk's avatar
hjk committed
804
        ToolTip::hide();
805
    else
hjk's avatar
hjk committed
806
        ToolTip::show(pos, TextContent(mark->note()), textEditor->widget());
807
808
}

con's avatar
con committed
809
810
811
/* Loads the bookmarks from the session settings. */
void BookmarkManager::loadBookmarks()
{
812
    removeAllBookmarks();
hjk's avatar
hjk committed
813
    const QStringList &list = SessionManager::value(QLatin1String("Bookmarks")).toStringList();
con's avatar
con committed
814
815
816
817
818
819
    foreach (const QString &bookmarkString, list)
        addBookmark(bookmarkString);

    updateActionStatus();
}

820
void BookmarkManager::handleBookmarkRequest(BaseTextEditor *textEditor,
821
                                            int line,
822
                                            BaseTextEditor::MarkRequestKind kind)
823
{
824
    if (kind == BaseTextEditor::BookmarkRequest && textEditor->document())
825
        toggleBookmark(textEditor->document()->filePath(), line);
826
827
}

828
void BookmarkManager::handleBookmarkTooltipRequest(BaseTextEditor *textEditor, const QPoint &pos,
829
830
831
                                            int line)
{
    if (textEditor->document()) {
hjk's avatar
hjk committed
832
        Bookmark *mark = findBookmark(textEditor->document()->filePath(), line);
833
834
835
836
        operateTooltip(textEditor, pos, mark);
    }
}

con's avatar
con committed
837
838
839
840
841
// BookmarkViewFactory

BookmarkViewFactory::BookmarkViewFactory(BookmarkManager *bm)
    : m_manager(bm)
{
842
843
844
845
    setDisplayName(BookmarkView::tr("Bookmarks"));
    setPriority(300);
    setId("Bookmarks");
    setActivationSequence(QKeySequence(Core::UseMacShortcuts ? tr("Alt+Meta+M") : tr("Alt+M")));
con's avatar
con committed
846
847
}

848
NavigationView BookmarkViewFactory::createWidget()
con's avatar
con committed
849
{
850
    return NavigationView(new BookmarkView(m_manager));
con's avatar
con committed
851
}
852
853
854

} // namespace Internal
} // namespace Bookmarks