bookmarkmanager.cpp 26.2 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2 3 4
**
** This file is part of Qt Creator
**
hjk's avatar
hjk committed
5
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
**
Eike Ziller's avatar
Eike Ziller committed
7
** Contact: http://www.qt-project.org/
con's avatar
con committed
8
**
9
**
10
** GNU Lesser General Public License Usage
11
**
hjk's avatar
hjk committed
12 13 14 15 16 17
** 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.
18
**
con's avatar
con committed
19
** In addition, as a special exception, Nokia gives you certain additional
hjk's avatar
hjk committed
20
** rights. These rights are described in the Nokia Qt LGPL Exception
con's avatar
con committed
21 22
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
23 24 25 26 27
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
con's avatar
con committed
28
**
29
**************************************************************************/
hjk's avatar
hjk committed
30

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

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

37

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

49 50 51
#include <QDebug>
#include <QDir>
#include <QFileInfo>
hjk's avatar
hjk committed
52

53 54 55 56
#include <QAction>
#include <QContextMenuEvent>
#include <QMenu>
#include <QPainter>
57
#include <QInputDialog>
con's avatar
con committed
58 59 60 61 62 63

Q_DECLARE_METATYPE(Bookmarks::Internal::Bookmark*)

using namespace Bookmarks;
using namespace Bookmarks::Internal;
using namespace ProjectExplorer;
64
using namespace Core;
con's avatar
con committed
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

BookmarkDelegate::BookmarkDelegate(QObject *parent)
    : QStyledItemDelegate(parent), m_normalPixmap(0), m_selectedPixmap(0)
{
}

BookmarkDelegate::~BookmarkDelegate()
{
    delete m_normalPixmap;
    delete m_selectedPixmap;
}

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;
}

void BookmarkDelegate::generateGradientPixmap(int width, int height, QColor color, bool selected) const
{

    QColor c = color;
    c.setAlpha(0);

    QPixmap *pixmap = new QPixmap(width+1, height);
    pixmap->fill(c);

    QPainter painter(pixmap);
    painter.setPen(Qt::NoPen);

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

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

        painter.setBrush(lg);
    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);
    static int lwidth = fm.width("8888") + 18;

    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
    QString topLeft = index.data(BookmarkManager::Filename ).toString();
    painter->drawText(6, 2 + opt.rect.top() + fm.ascent(), topLeft);

    QString topRight = index.data(BookmarkManager::LineNumber).toString();
Tobias Hunger's avatar
Tobias Hunger committed
159
    // Check whether we need to be fancy and paint some background
con's avatar
con committed
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
    int fwidth = fm.width(topLeft);
    if (fwidth + lwidth > opt.rect.width()) {
        int left = opt.rect.right() - lwidth;
        painter->drawPixmap(left, opt.rect.top(), selected? *m_selectedPixmap : *m_normalPixmap);
    }
    // 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
185
//            if (idx == -1) {
con's avatar
con committed
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
//                // 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);

202
    QString note = index.data(BookmarkManager::Note).toString().trimmed();
con's avatar
con committed
203
    QString lineText = index.data(BookmarkManager::LineText).toString().trimmed();
204 205

    painter->drawText(6, opt.rect.top() + fm.ascent() + fm.height() + 6, note.isEmpty() ? lineText : note);
con's avatar
con committed
206 207 208 209 210 211 212

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

213 214 215 216
BookmarkView::BookmarkView(QWidget *parent)  :
    QListView(parent),
    m_bookmarkContext(new BookmarkContext(this)),
    m_manager(0)
con's avatar
con committed
217 218 219
{
    setWindowTitle(tr("Bookmarks"));

Robert Loehning's avatar
Robert Loehning committed
220 221
    connect(this, SIGNAL(clicked(QModelIndex)),
            this, SLOT(gotoBookmark(QModelIndex)));
con's avatar
con committed
222

hjk's avatar
hjk committed
223
    ICore::addContextObject(m_bookmarkContext);
con's avatar
con committed
224 225 226 227 228 229 230 231 232

    setItemDelegate(new BookmarkDelegate(this));
    setFrameStyle(QFrame::NoFrame);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setFocusPolicy(Qt::NoFocus);
}

BookmarkView::~BookmarkView()
{
hjk's avatar
hjk committed
233
    ICore::removeContextObject(m_bookmarkContext);
con's avatar
con committed
234 235 236 237 238
}

void BookmarkView::contextMenuEvent(QContextMenuEvent *event)
{
    QMenu menu;
239 240 241 242
    QAction *moveUp = menu.addAction(tr("Move Up"));
    QAction *moveDown = menu.addAction(tr("Move Down"));
    QAction *remove = menu.addAction(tr("&Remove"));
    QAction *removeAll = menu.addAction(tr("Remove All"));
243 244
    QAction *editNote = menu.addAction(tr("Edit note"));

con's avatar
con committed
245
    m_contextMenuIndex = indexAt(event->pos());
246 247 248
    if (!m_contextMenuIndex.isValid()) {
        moveUp->setEnabled(false);
        moveDown->setEnabled(false);
con's avatar
con committed
249
        remove->setEnabled(false);
250
    }
con's avatar
con committed
251 252 253 254

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

255 256 257 258
    connect(moveUp, SIGNAL(triggered()),
            m_manager, SLOT(moveUp()));
    connect(moveDown, SIGNAL(triggered()),
            m_manager, SLOT(moveDown()));
con's avatar
con committed
259 260 261 262
    connect(remove, SIGNAL(triggered()),
            this, SLOT(removeFromContextMenu()));
    connect(removeAll, SIGNAL(triggered()),
            this, SLOT(removeAll()));
263 264
    connect(editNote, SIGNAL(triggered()),
            m_manager, SLOT(editNote()));
con's avatar
con committed
265 266 267 268 269 270 271 272 273 274 275

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

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

void BookmarkView::removeBookmark(const QModelIndex& index)
{
276 277
    Bookmark *bm = m_manager->bookmarkForIndex(index);
    m_manager->removeBookmark(bm);
con's avatar
con committed
278 279 280 281 282 283
}

// The perforcemance of this function could be greatly improved.
//
void BookmarkView::removeAll()
{
284 285
    while (m_manager->rowCount()) {
        QModelIndex index = m_manager->index(0, 0);
con's avatar
con committed
286 287 288 289 290 291 292
        removeBookmark(index);
    }
}

void BookmarkView::setModel(QAbstractItemModel *model)
{
    BookmarkManager *manager = qobject_cast<BookmarkManager *>(model);
hjk's avatar
hjk committed
293
    QTC_ASSERT(manager, return);
294
    m_manager = manager;
con's avatar
con committed
295 296 297 298 299 300 301 302
    QListView::setModel(model);
    setSelectionModel(manager->selectionModel());
    setSelectionMode(QAbstractItemView::SingleSelection);
    setSelectionBehavior(QAbstractItemView::SelectRows);
}

void BookmarkView::gotoBookmark(const QModelIndex &index)
{
303 304 305
    Bookmark *bk = m_manager->bookmarkForIndex(index);
    if (!m_manager->gotoBookmark(bk))
        m_manager->removeBookmark(bk);
con's avatar
con committed
306 307 308 309 310 311
}

////
// BookmarkContext
////

312 313
BookmarkContext::BookmarkContext(QWidget *widget)
    : Core::IContext(widget)
con's avatar
con committed
314
{
315 316
      setWidget(widget);
      setContext(Core::Context(Constants::BOOKMARKS_CONTEXT));
con's avatar
con committed
317 318 319 320 321 322
}

////
// BookmarkManager
////

323 324 325
BookmarkManager::BookmarkManager() :
    m_bookmarkIcon(QLatin1String(":/bookmarks/images/bookmark.png")),
    m_selectionModel(new QItemSelectionModel(this, this))
con's avatar
con committed
326
{
327
    connect(Core::ICore::instance(), SIGNAL(contextChanged(Core::IContext*,Core::Context)),
con's avatar
con committed
328 329
            this, SLOT(updateActionStatus()));

330
    connect(ProjectExplorerPlugin::instance()->session(), SIGNAL(sessionLoaded(QString)),
con's avatar
con committed
331 332 333 334 335 336 337 338 339 340 341
            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
342
        qDeleteAll(*bookmarks);
con's avatar
con committed
343 344 345 346 347 348 349 350 351
        delete bookmarks;
    }
}

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

352 353 354 355 356 357
bool BookmarkManager::hasBookmarkInPosition(const QString &fileName, int lineNumber)
{
    QFileInfo fi(fileName);
    return findBookmark(fi.path(), fi.fileName(), lineNumber);
}

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

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();

    if (role == BookmarkManager::Filename)
        return m_bookmarksList.at(index.row())->fileName();
    else if (role == BookmarkManager::LineNumber)
        return m_bookmarksList.at(index.row())->lineNumber();
    else if (role == BookmarkManager::Directory)
        return m_bookmarksList.at(index.row())->path();
    else if (role == BookmarkManager::LineText)
        return m_bookmarksList.at(index.row())->lineText();
399 400
    else if (role == BookmarkManager::Note)
        return m_bookmarksList.at(index.row())->note();
con's avatar
con committed
401
    else if (role == Qt::ToolTipRole)
402
        return QDir::toNativeSeparators(m_bookmarksList.at(index.row())->filePath());
con's avatar
con committed
403 404 405 406 407 408 409 410 411 412

    return QVariant();
}

void BookmarkManager::toggleBookmark()
{
    TextEditor::ITextEditor *editor = currentTextEditor();
    if (!editor)
        return;

413
    toggleBookmark(editor->document()->fileName(), editor->currentLine());
hjk's avatar
hjk committed
414 415 416 417 418 419
}

void BookmarkManager::toggleBookmark(const QString &fileName, int lineNumber)
{
    const QFileInfo fi(fileName);
    const int editorLine = lineNumber;
con's avatar
con committed
420 421

    // Remove any existing bookmark on this line
hjk's avatar
hjk committed
422
    if (Bookmark *mark = findBookmark(fi.path(), fi.fileName(), lineNumber)) {
con's avatar
con committed
423 424 425 426 427 428 429
        // 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
    Bookmark *bookmark = new Bookmark(fi.filePath(), editorLine, this);
430
    bookmark->init();
con's avatar
con committed
431 432 433 434 435 436 437 438 439 440
    addBookmark(bookmark);
}

void BookmarkManager::updateBookmark(Bookmark *bookmark)
{
    int idx = m_bookmarksList.indexOf(bookmark);
    emit dataChanged(index(idx, 0, QModelIndex()), index(idx, 2, QModelIndex()));
    saveBookmarks();
}

441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
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
464 465
void BookmarkManager::removeBookmark(Bookmark *bookmark)
{
466 467 468
    int idx = m_bookmarksList.indexOf(bookmark);
    beginRemoveRows(QModelIndex(), idx, idx);

con's avatar
con committed
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
    const QFileInfo fi(bookmark->filePath() );
    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;
    }

486

con's avatar
con committed
487 488 489 490 491 492 493 494 495 496
    m_bookmarksList.removeAt(idx);
    endRemoveRows();

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

    updateActionStatus();
    saveBookmarks();
}

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


hjk's avatar
hjk committed
505
bool BookmarkManager::gotoBookmark(Bookmark *bookmark)
con's avatar
con committed
506
{
507
    using namespace TextEditor;
508 509
    if (ITextEditor *editor = qobject_cast<ITextEditor *>(BaseTextEditorWidget::openEditorAt(bookmark->filePath(),
                                                                                             bookmark->lineNumber()))) {
510
        return (editor->currentLine() == bookmark->lineNumber());
511
    }
512
    return false;
con's avatar
con committed
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
}

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

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

void BookmarkManager::documentPrevNext(bool next)
{
    TextEditor::ITextEditor *editor = currentTextEditor();
    int editorLine = editor->currentLine();
529
    QFileInfo fi(editor->document()->fileName());
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
    Core::EditorManager *em = Core::EditorManager::instance();
552
    em->addCurrentPositionToNavigationHistory();
con's avatar
con committed
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
    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;
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
    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
587 588 589 590 591 592 593
}

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

con's avatar
con committed
595
    int row = current.row();
596 597 598 599 600 601 602 603 604 605 606 607 608 609
    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
610 611 612 613
}

TextEditor::ITextEditor *BookmarkManager::currentTextEditor() const
{
hjk's avatar
hjk committed
614
    Core::IEditor *currEditor = EditorManager::currentEditor();
con's avatar
con committed
615 616 617 618
    return qobject_cast<TextEditor::ITextEditor *>(currEditor);
}

/* Returns the current session. */
619
SessionManager *BookmarkManager::sessionManager() const
con's avatar
con committed
620
{
621
    return ProjectExplorerPlugin::instance()->session();
con's avatar
con committed
622 623 624 625 626 627 628 629 630 631 632
}

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

    TextEditor::ITextEditor *editor = currentTextEditor();
    if (!editor)
        return HasBookMarks;

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

    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);
}

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);
}

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
void BookmarkManager::editNote(const QString &fileName, int lineNumber)
{
    QFileInfo fi(fileName);
    Bookmark *b = findBookmark(fi.path(), fi.fileName(), lineNumber);
    QModelIndex current = selectionModel()->currentIndex();
    selectionModel()->setCurrentIndex(current.sibling(m_bookmarksList.indexOf(b), 0),
                                      QItemSelectionModel::Select | QItemSelectionModel::Clear);

    editNote();
}

void BookmarkManager::editNote()
{
    QModelIndex current = selectionModel()->currentIndex();
    Bookmark *b = m_bookmarksList.at(current.row());

    bool inputOk = false;
    QString noteText = QInputDialog::getText(0, tr("Edit note"),
                                             tr("Note text:"), QLineEdit::Normal,
                                             b->note(), &inputOk);
    if (inputOk) {
        b->updateNote(noteText.replace('\t', ' '));
        emit dataChanged(current, current);
    }
}

con's avatar
con committed
712
/* Returns the bookmark at the given file and line number, or 0 if no such bookmark exists. */
hjk's avatar
hjk committed
713
Bookmark *BookmarkManager::findBookmark(const QString &path, const QString &fileName, int lineNumber)
con's avatar
con committed
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
{
    if (m_bookmarksMap.contains(path)) {
        foreach (Bookmark *bookmark, m_bookmarksMap.value(path)->values(fileName)) {
            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());
    const QFileInfo fi(bookmark->filePath());
    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)
{
751 752 753 754 755
    // index3 is a frontier beetween note text and other bookmarks data
    int index3 = s.lastIndexOf('\t');
    if (index3 < 0)
        index3 = s.size();
    int index2 = s.lastIndexOf(':', index3 - 1);
con's avatar
con committed
756
    int index1 = s.indexOf(':');
757 758

    if (index3 != -1 || index2 != -1 || index1 != -1) {
con's avatar
con committed
759
        const QString &filePath = s.mid(index1+1, index2-index1-1);
760 761
        const QString &note = s.mid(index3 + 1);
        const int lineNumber = s.mid(index2 + 1, index3 - index2 - 1).toInt();
con's avatar
con committed
762 763 764 765
        const QFileInfo fi(filePath);

        if (!filePath.isEmpty() && !findBookmark(fi.path(), fi.fileName(), lineNumber)) {
            Bookmark *b = new Bookmark(filePath, lineNumber, this);
766
            b->setNote(note);
767
            b->init();
con's avatar
con committed
768 769 770 771 772 773 774 775 776 777 778
            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(':');
779 780
    // Using \t as delimiter because any another symbol can be a part of note.
    const QLatin1Char noteDelimiter('\t');
con's avatar
con committed
781
    // Empty string was the name of the bookmark, which now is always ""
782 783 784
    return QLatin1String("") + colon + b->filePath() +
            colon + QString::number(b->lineNumber()) +
            noteDelimiter + b->note();
con's avatar
con committed
785 786 787 788 789 790 791 792 793 794
}

/* Saves the bookmarks to the session settings. */
void BookmarkManager::saveBookmarks()
{
    QStringList list;
    foreach (const FileNameBookmarksMap *bookmarksMap, m_bookmarksMap)
        foreach (const Bookmark *bookmark, *bookmarksMap)
            list << bookmarkToString(bookmark);

795
    sessionManager()->setValue("Bookmarks", list);
con's avatar
con committed
796 797
}

798 799 800 801 802 803 804 805 806 807 808 809
void BookmarkManager::operateTooltip(TextEditor::ITextEditor *textEditor, const QPoint &pos, Bookmark *mark)
{
    if (!mark)
        return;

    if (mark->note().isEmpty()) {
        TextEditor::ToolTip::instance()->hide();
    } else {
        TextEditor::ToolTip::instance()->show(pos, TextEditor::TextContent(mark->note()), textEditor->widget());
    }
}

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

    updateActionStatus();
}

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

829 830 831 832 833 834 835 836 837 838
void BookmarkManager::handleBookmarkTooltipRequest(TextEditor::ITextEditor *textEditor, const QPoint &pos,
                                            int line)
{
    if (textEditor->document()) {
        const QFileInfo fi(textEditor->document()->fileName());
        Bookmark *mark = findBookmark(fi.path(), fi.fileName(), line);
        operateTooltip(textEditor, pos, mark);
    }
}

con's avatar
con committed
839 840 841 842 843 844 845
// BookmarkViewFactory

BookmarkViewFactory::BookmarkViewFactory(BookmarkManager *bm)
    : m_manager(bm)
{
}

846
QString BookmarkViewFactory::displayName() const
con's avatar
con committed
847
{
848
    return BookmarkView::tr("Bookmarks");
con's avatar
con committed
849 850
}

851 852 853 854 855
int BookmarkViewFactory::priority() const
{
    return 300;
}

856
Id BookmarkViewFactory::id() const
857
{
858
    return Id("Bookmarks");
859 860 861
}

QKeySequence BookmarkViewFactory::activationSequence() const
con's avatar
con committed
862
{
863
    return QKeySequence(Core::UseMacShortcuts ? tr("Alt+Meta+M") : tr("Alt+M"));
con's avatar
con committed
864 865 866 867 868 869 870 871 872 873
}

Core::NavigationView BookmarkViewFactory::createWidget()
{
    BookmarkView *bookmarkView = new BookmarkView();
    bookmarkView->setModel(m_manager);
    Core::NavigationView view;
    view.widget = bookmarkView;
    return view;
}