Welcome to mirror list, hosted at ThFree Co, Russian Federation.

AutoTypeSelectDialog.cpp « autotype « src - github.com/keepassxreboot/keepassxc.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 752d23e3d75e72bf2f85142770b3cfb06ebd5afe (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
/*
 *  Copyright (C) 2021 KeePassXC Team <team@keepassxc.org>
 *  Copyright (C) 2012 Felix Geyer <debfx@fobos.de>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 2 or (at your option)
 *  version 3 of the License.
 *
 *  This program 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "AutoTypeSelectDialog.h"
#include "ui_AutoTypeSelectDialog.h"

#include <QCloseEvent>
#include <QMenu>
#include <QShortcut>
#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
#include <QScreen>
#else
#include <QDesktopWidget>
#endif

#include "core/Config.h"
#include "core/Database.h"
#include "core/Entry.h"
#include "core/EntrySearcher.h"
#include "gui/Clipboard.h"
#include "gui/Icons.h"

AutoTypeSelectDialog::AutoTypeSelectDialog(QWidget* parent)
    : QDialog(parent)
    , m_ui(new Ui::AutoTypeSelectDialog())
{
    setAttribute(Qt::WA_DeleteOnClose);
    // Places the window on the active (virtual) desktop instead of where the main window is.
    setAttribute(Qt::WA_X11BypassTransientForHint);
    setWindowFlags((windowFlags() | Qt::WindowStaysOnTopHint) & ~Qt::WindowContextHelpButtonHint);
    setWindowIcon(icons()->applicationIcon());

    buildActionMenu();

    m_ui->setupUi(this);

    connect(m_ui->view, &AutoTypeMatchView::matchActivated, this, &AutoTypeSelectDialog::submitAutoTypeMatch);
    connect(m_ui->view, &AutoTypeMatchView::currentMatchChanged, this, &AutoTypeSelectDialog::updateActionMenu);
    connect(m_ui->view, &QWidget::customContextMenuRequested, this, [this](const QPoint& pos) {
        if (m_ui->view->currentMatch().first) {
            m_actionMenu->popup(m_ui->view->viewport()->mapToGlobal(pos));
        }
    });

    m_ui->search->setFocus();
    m_ui->search->installEventFilter(this);

    m_searchTimer.setInterval(300);
    m_searchTimer.setSingleShot(true);

    connect(m_ui->search, SIGNAL(textChanged(QString)), &m_searchTimer, SLOT(start()));
    connect(m_ui->search, SIGNAL(returnPressed()), SLOT(activateCurrentMatch()));
    connect(&m_searchTimer, SIGNAL(timeout()), SLOT(performSearch()));

    m_ui->searchCheckBox->setShortcut(Qt::CTRL + Qt::Key_F);
    connect(m_ui->searchCheckBox, &QCheckBox::toggled, this, [this](bool checked) {
        if (checked) {
            performSearch();
            m_ui->search->setFocus();
        } else {
            // Reset to original match list
            m_ui->view->setMatchList(m_matches, true);
            performSearch();
            m_ui->search->setFocus();
        }
    });

    m_actionMenu->installEventFilter(this);
    m_ui->action->setMenu(m_actionMenu);
    m_ui->action->installEventFilter(this);
    connect(m_ui->action, &QToolButton::clicked, this, &AutoTypeSelectDialog::activateCurrentMatch);

    connect(m_ui->cancelButton, SIGNAL(clicked()), SLOT(reject()));
}

// Required for QScopedPointer
AutoTypeSelectDialog::~AutoTypeSelectDialog()
{
}

void AutoTypeSelectDialog::setMatches(const QList<AutoTypeMatch>& matches, const QList<QSharedPointer<Database>>& dbs)
{
    m_matches = matches;
    m_dbs = dbs;

    m_ui->view->setMatchList(m_matches, !m_matches.isEmpty() || !m_ui->search->text().isEmpty());
    m_ui->searchCheckBox->setChecked(m_matches.isEmpty());
}

void AutoTypeSelectDialog::submitAutoTypeMatch(AutoTypeMatch match)
{
    if (match.first) {
        m_accepted = true;
        accept();
        emit matchActivated(std::move(match));
    }
}

void AutoTypeSelectDialog::performSearch()
{
    if (!m_ui->searchCheckBox->isChecked()) {
        m_ui->view->filterList(m_ui->search->text());
        return;
    }

    auto searchText = m_ui->search->text();
    // If no search text, find all entries
    if (searchText.isEmpty()) {
        searchText.append("*");
    }

    EntrySearcher searcher;
    QList<AutoTypeMatch> matches;
    for (const auto& db : m_dbs) {
        auto found = searcher.search(searchText, db->rootGroup());
        for (auto* entry : found) {
            QSet<QString> sequences;
            auto defSequence = entry->effectiveAutoTypeSequence();
            if (!defSequence.isEmpty()) {
                matches.append({entry, defSequence});
                sequences << defSequence;
            }
            for (const auto& assoc : entry->autoTypeAssociations()->getAll()) {
                if (!sequences.contains(assoc.sequence) && !assoc.sequence.isEmpty()) {
                    matches.append({entry, assoc.sequence});
                    sequences << assoc.sequence;
                }
            }
        }
    }

    m_ui->view->setMatchList(matches, !m_ui->search->text().isEmpty());
}

void AutoTypeSelectDialog::activateCurrentMatch()
{
    submitAutoTypeMatch(m_ui->view->currentMatch());
}

bool AutoTypeSelectDialog::eventFilter(QObject* obj, QEvent* event)
{
    if (obj == m_ui->action) {
        if (event->type() == QEvent::FocusIn) {
            m_ui->action->showMenu();
            return true;
        } else if (event->type() == QEvent::KeyPress && static_cast<QKeyEvent*>(event)->key() == Qt::Key_Return) {
            // handle case where the menu is closed but the button has focus
            activateCurrentMatch();
            return true;
        }
    } else if (obj == m_actionMenu) {
        if (event->type() == QEvent::KeyPress) {
            auto* keyEvent = static_cast<QKeyEvent*>(event);
            switch (keyEvent->key()) {
            case Qt::Key_Tab:
                m_actionMenu->close();
                focusNextPrevChild(true);
                return true;
            case Qt::Key_Backtab:
                m_actionMenu->close();
                focusNextPrevChild(false);
                return true;
            case Qt::Key_Return:
                // accept the dialog with default sequence if no action selected
                if (!m_actionMenu->activeAction()) {
                    activateCurrentMatch();
                    return true;
                }
            default:
                break;
            }
        }
    } else if (obj == m_ui->search) {
        if (event->type() == QEvent::KeyPress) {
            auto* keyEvent = static_cast<QKeyEvent*>(event);
            switch (keyEvent->key()) {
            case Qt::Key_Up:
                m_ui->view->moveSelection(-1);
                return true;
            case Qt::Key_Down:
                m_ui->view->moveSelection(1);
                return true;
            case Qt::Key_PageUp:
                m_ui->view->moveSelection(-5);
                return true;
            case Qt::Key_PageDown:
                m_ui->view->moveSelection(5);
                return true;
            case Qt::Key_Escape:
                if (m_ui->search->text().isEmpty()) {
                    reject();
                } else {
                    m_ui->search->clear();
                }
                return true;
            default:
                break;
            }
        }
    }

    return QDialog::eventFilter(obj, event);
}

void AutoTypeSelectDialog::updateActionMenu(const AutoTypeMatch& match)
{
    if (!match.first) {
        m_ui->action->setEnabled(false);
        return;
    }

    m_ui->action->setEnabled(true);

    bool hasUsername = !match.first->username().isEmpty();
    bool hasPassword = !match.first->password().isEmpty();
    bool hasTotp = match.first->hasTotp();

    auto actions = m_actionMenu->actions();
    Q_ASSERT(actions.size() >= 6);
    actions[0]->setEnabled(hasUsername);
    actions[1]->setEnabled(hasPassword);
    actions[2]->setEnabled(hasTotp);
    actions[3]->setEnabled(hasUsername);
    actions[4]->setEnabled(hasPassword);
    actions[5]->setEnabled(hasTotp);
}

void AutoTypeSelectDialog::buildActionMenu()
{
    m_actionMenu = new QMenu(this);
    auto typeUsernameAction = new QAction(icons()->icon("auto-type"), tr("Type {USERNAME}"), this);
    auto typePasswordAction = new QAction(icons()->icon("auto-type"), tr("Type {PASSWORD}"), this);
    auto typeTotpAction = new QAction(icons()->icon("auto-type"), tr("Type {TOTP}"), this);
    auto copyUsernameAction = new QAction(icons()->icon("username-copy"), tr("Copy Username"), this);
    auto copyPasswordAction = new QAction(icons()->icon("password-copy"), tr("Copy Password"), this);
    auto copyTotpAction = new QAction(icons()->icon("chronometer"), tr("Copy TOTP"), this);
    m_actionMenu->addAction(typeUsernameAction);
    m_actionMenu->addAction(typePasswordAction);
    m_actionMenu->addAction(typeTotpAction);
    m_actionMenu->addAction(copyUsernameAction);
    m_actionMenu->addAction(copyPasswordAction);
    m_actionMenu->addAction(copyTotpAction);

    auto shortcut = new QShortcut(Qt::CTRL + Qt::Key_1, this);
    connect(shortcut, &QShortcut::activated, typeUsernameAction, &QAction::trigger);
    connect(typeUsernameAction, &QAction::triggered, this, [&] {
        auto match = m_ui->view->currentMatch();
        match.second = "{USERNAME}";
        submitAutoTypeMatch(match);
    });

    shortcut = new QShortcut(Qt::CTRL + Qt::Key_2, this);
    connect(shortcut, &QShortcut::activated, typePasswordAction, &QAction::trigger);
    connect(typePasswordAction, &QAction::triggered, this, [&] {
        auto match = m_ui->view->currentMatch();
        match.second = "{PASSWORD}";
        submitAutoTypeMatch(match);
    });

    shortcut = new QShortcut(Qt::CTRL + Qt::Key_3, this);
    connect(shortcut, &QShortcut::activated, typeTotpAction, &QAction::trigger);
    connect(typeTotpAction, &QAction::triggered, this, [&] {
        auto match = m_ui->view->currentMatch();
        match.second = "{TOTP}";
        submitAutoTypeMatch(match);
    });

    connect(copyUsernameAction, &QAction::triggered, this, [&] {
        auto entry = m_ui->view->currentMatch().first;
        if (entry) {
            clipboard()->setText(entry->resolvePlaceholder(entry->username()));
            reject();
        }
    });
    connect(copyPasswordAction, &QAction::triggered, this, [&] {
        auto entry = m_ui->view->currentMatch().first;
        if (entry) {
            clipboard()->setText(entry->resolvePlaceholder(entry->password()));
            reject();
        }
    });
    connect(copyTotpAction, &QAction::triggered, this, [&] {
        auto entry = m_ui->view->currentMatch().first;
        if (entry) {
            clipboard()->setText(entry->totp());
            reject();
        }
    });
}

void AutoTypeSelectDialog::showEvent(QShowEvent* event)
{
    QDialog::showEvent(event);

#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
    auto screen = QApplication::screenAt(QCursor::pos());
    if (!screen) {
        // screenAt can return a nullptr, default to the primary screen
        screen = QApplication::primaryScreen();
    }
    QRect screenGeometry = screen->availableGeometry();
#else
    QRect screenGeometry = QApplication::desktop()->availableGeometry(QCursor::pos());
#endif

    // Resize to last used size
    QSize size = config()->get(Config::GUI_AutoTypeSelectDialogSize).toSize();
    size.setWidth(qMin(size.width(), screenGeometry.width()));
    size.setHeight(qMin(size.height(), screenGeometry.height()));
    resize(size);

    // move dialog to the center of the screen
    move(screenGeometry.center().x() - (size.width() / 2), screenGeometry.center().y() - (size.height() / 2));
}

void AutoTypeSelectDialog::hideEvent(QHideEvent* event)
{
    config()->set(Config::GUI_AutoTypeSelectDialogSize, size());
    if (!m_accepted) {
        emit rejected();
    }
    QDialog::hideEvent(event);
}