tabswitcher.cpp 9.56 KB
Newer Older
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
/* This file is part of the KDE project

   Copyright (C) 2014 Dominik Haumann <dhaumann@kde.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

#include "tabswitcher.h"
#include "tabswitchertreeview.h"

#include <KTextEditor/Application>
#include <KTextEditor/Document>
#include <KTextEditor/Editor>
#include <KTextEditor/View>

#include <KActionCollection>
#include <KLocalizedString>
#include <KPluginFactory>
#include <KXMLGUIFactory>

#include <QAction>
#include <QMimeDatabase>
#include <QScrollBar>
#include <QStandardItemModel>

K_PLUGIN_FACTORY_WITH_JSON(TabSwitcherPluginFactory, "tabswitcherplugin.json", registerPlugin<TabSwitcherPlugin>();)

TabSwitcherPlugin::TabSwitcherPlugin(QObject *parent, const QList<QVariant> &):
    KTextEditor::Plugin(parent)
{
}

QObject *TabSwitcherPlugin::createView(KTextEditor::MainWindow *mainWindow)
{
    return new TabSwitcherPluginView(this, mainWindow);
}

TabSwitcherPluginView::TabSwitcherPluginView(TabSwitcherPlugin *plugin, KTextEditor::MainWindow *mainWindow)
    : QObject(mainWindow)
    , m_plugin(plugin)
    , m_mainWindow(mainWindow)
{
    // register this view
    m_plugin->m_views.append(this);

    m_model = new QStandardItemModel(this);
    m_treeView = new TabSwitcherTreeView();
    m_treeView->setModel(m_model);

    KXMLGUIClient::setComponentName(QStringLiteral("tabswitcher"), i18n("Document Switcher"));
    setXMLFile(QStringLiteral("ui.rc"));

    // note: call after m_treeView is created
    setupActions();

    // fill the model
    setupModel();

    // register action in menu
    m_mainWindow->guiFactory()->addClient(this);

    // popup connections
    connect(m_treeView, SIGNAL(pressed(QModelIndex)), SLOT(switchToClicked(QModelIndex)));
    connect(m_treeView, SIGNAL(itemActivated(QModelIndex)), SLOT(activateView(QModelIndex)));

    // track existing documents
    connect(KTextEditor::Editor::instance()->application(), SIGNAL(documentCreated(KTextEditor::Document*)),
            this, SLOT(registerDocument(KTextEditor::Document*)));
    connect(KTextEditor::Editor::instance()->application(), SIGNAL(documentWillBeDeleted(KTextEditor::Document*)),
            this, SLOT(unregisterDocument(KTextEditor::Document*)));

    // track lru activation of views to raise the respective documents in the model
    connect(m_mainWindow, SIGNAL(viewChanged(KTextEditor::View*)),
            this, SLOT(raiseView(KTextEditor::View*)));
}

TabSwitcherPluginView::~TabSwitcherPluginView()
{
    // delete popup widget
    delete m_treeView;

    // unregister action in menu
    m_mainWindow->guiFactory()->removeClient(this);

    // unregister this view
    m_plugin->m_views.removeAll(this);
}

void TabSwitcherPluginView::setupActions()
{
    auto aNext = actionCollection()->addAction(QStringLiteral("view_lru_document_next"));
    aNext->setText(i18n("Last Used Views"));
    aNext->setIcon(QIcon::fromTheme(QStringLiteral("go-next-view-page")));
    actionCollection()->setDefaultShortcut(aNext, Qt::CTRL | Qt::Key_Tab);
    aNext->setWhatsThis(i18n("Opens a list to walk through the list of last used views."));
    aNext->setStatusTip(i18n("Walk through the list of last used views"));
    connect(aNext, SIGNAL(triggered()), SLOT(walkForward()));

    auto aPrev = actionCollection()->addAction(QStringLiteral("view_lru_document_prev"));
    aPrev->setText(i18n("Last Used Views (Reverse)"));
    aPrev->setIcon(QIcon::fromTheme(QStringLiteral("go-previous-view-page")));
    actionCollection()->setDefaultShortcut(aPrev, Qt::CTRL | Qt::SHIFT | Qt::Key_Tab);
    aPrev->setWhatsThis(i18n("Opens a list to walk through the list of last used views in reverse."));
    aPrev->setStatusTip(i18n("Walk through the list of last used views"));
    connect(aPrev, SIGNAL(triggered()), SLOT(walkBackward()));

    // make sure action work when the popup has focus
    m_treeView->addAction(aNext);
    m_treeView->addAction(aPrev);
}

static QIcon iconForDocument(KTextEditor::Document * doc)
{
127
    return QIcon::fromTheme(QMimeDatabase().mimeTypeForUrl(doc->url()).iconName());
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
}

void TabSwitcherPluginView::setupModel()
{
    // initial fill of model
    foreach (auto doc, KTextEditor::Editor::instance()->application()->documents()) {
        registerDocument(doc);
    }
}

void TabSwitcherPluginView::registerDocument(KTextEditor::Document * document)
{
    auto item = new QStandardItem(iconForDocument(document), document->documentName());
    item->setData(QVariant::fromValue(document));
    m_model->insertRow(0, item);

    // track document name changes
    connect(document, SIGNAL(documentNameChanged(KTextEditor::Document*)),
            this, SLOT(updateDocumentName(KTextEditor::Document*)));
}

void TabSwitcherPluginView::unregisterDocument(KTextEditor::Document * document)
{
    const auto rowCount = m_model->rowCount();
    for (int i = 0; i < rowCount; ++i) {
        auto doc = m_model->item(i)->data().value<KTextEditor::Document*>();
        if (doc == document) {
            m_model->removeRow(i);

            // disconnect documentNameChanged() signal
            disconnect(document, 0, this, 0);

            break;
        }
    }
}

void TabSwitcherPluginView::updateDocumentName(KTextEditor::Document * document)
{
    const auto rowCount = m_model->rowCount();
    for (int i = 0; i < rowCount; ++i) {
        auto doc = m_model->item(i)->data().value<KTextEditor::Document*>();
        if (doc == document) {
            m_model->item(i)->setText(document->documentName());
            break;
        }
    }
}

void TabSwitcherPluginView::raiseView(KTextEditor::View * view)
{
179
180
181
182
    if (!view) {
        return;
    }

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
    unregisterDocument(view->document());
    registerDocument(view->document());
}

void TabSwitcherPluginView::walk(const int from, const int to)
{
    QModelIndex index;
    const int step = from < to ? 1 : -1;
    if (! m_treeView->isVisible()) {
        updateViewGeometry();
        index = m_model->index(from + step, 0);
        if(! index.isValid()) {
            index = m_model->index(0, 0);
        }
        m_treeView->show();
        m_treeView->setFocus();
    } else {
        int newRow = m_treeView->selectionModel()->currentIndex().row() + step;
        if(newRow == to + step) { newRow = from; }
        index = m_model->index(newRow, 0);
    }

    m_treeView->selectionModel()->select(index, QItemSelectionModel::Rows | QItemSelectionModel::ClearAndSelect);
    m_treeView->selectionModel()->setCurrentIndex(index, QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows);
}

void TabSwitcherPluginView::walkForward()
{
    walk(0, m_model->rowCount() - 1);
}

void TabSwitcherPluginView::walkBackward()
{
    walk(m_model->rowCount() - 1, 0);
}

void TabSwitcherPluginView::updateViewGeometry()
{
    QWidget * window = m_mainWindow->window();
    const QSize centralSize = window->size();

    // Maximum size of the view is 3/4th of the central widget (the editor area)
    // so the view does not overlap the mainwindow since that looks awkward.
    const QSize viewMaxSize( centralSize.width() * 3/4, centralSize.height() * 3/4 );

    // The actual view size should be as big as the columns/rows need it, but
    // smaller than the max-size. This means the view will get quite high with
    // many open files but I think thats ok. Otherwise one can easily tweak the
    // max size to be only 1/2th of the central widget size
232
233
234
235
    const int rowHeight = m_treeView->sizeHintForRow(0);
    const int frameWidth = m_treeView->frameWidth();
    const QSize viewSize(std::min(m_treeView->sizeHintForColumn(0) + 2 * frameWidth + m_treeView->verticalScrollBar()->width(), viewMaxSize.width()),
                         std::min(std::max(rowHeight * m_model->rowCount() + 2 * frameWidth, rowHeight * 6 ), viewMaxSize.height()));
236
237
238

    // Position should be central over the editor area, so map to global from
    // parent of central widget since the view is positioned in global coords
239
    const QPoint centralWidgetPos = window->parentWidget() ? window->mapToGlobal(window->pos()) : window->pos();
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
    const int xPos = std::max(0, centralWidgetPos.x() + (centralSize.width()  - viewSize.width()  ) / 2);
    const int yPos = std::max(0, centralWidgetPos.y() + (centralSize.height() - viewSize.height() ) / 2);

    m_treeView->setFixedSize(viewSize);
    m_treeView->move(xPos, yPos);
}

void TabSwitcherPluginView::switchToClicked(const QModelIndex & index)
{
    m_treeView->selectionModel()->select(index, QItemSelectionModel::ClearAndSelect);
    activateView(index);
}

void TabSwitcherPluginView::activateView(const QModelIndex & index)
{
    Q_UNUSED(index)

    // guard against empty selection
    if (m_treeView->selectionModel()->selectedRows().isEmpty()) {
        return;
    }

    const int row = m_treeView->selectionModel()->selectedRows().first().row();

    auto doc = m_model->item(row)->data().value<KTextEditor::Document*>();
    m_mainWindow->activateView(doc);

    m_treeView->hide();
}

// required for TabSwitcherPluginFactory vtable
#include "tabswitcher.moc"