2 * SPDX-FileCopyrightText: 2011 Tirtha Chatterjee <tirtha.p.chatterjee@gmail.com>
4 * Based on the Itemviews NG project from Trolltech Labs
6 * SPDX-License-Identifier: GPL-2.0-or-later
9 #include "kitemlistkeyboardsearchmanager.h"
11 KItemListKeyboardSearchManager::KItemListKeyboardSearchManager(QObject
* parent
) :
13 m_isSearchRestarted(false),
16 m_keyboardInputTime
.invalidate();
19 KItemListKeyboardSearchManager::~KItemListKeyboardSearchManager()
23 bool KItemListKeyboardSearchManager::shouldClearSearchIfInputTimeReached()
25 const bool keyboardTimeWasValid
= m_keyboardInputTime
.isValid();
26 const qint64 keyboardInputTimeElapsed
= m_keyboardInputTime
.restart();
27 return (keyboardInputTimeElapsed
> m_timeout
) || !keyboardTimeWasValid
;
30 void KItemListKeyboardSearchManager::addKeys(const QString
& keys
)
32 if (shouldClearSearchIfInputTimeReached()) {
33 m_searchedString
.clear();
36 const bool newSearch
= m_searchedString
.isEmpty();
38 // Do not start a new search if the user pressed Space. Only add
39 // it to the search string if a search is in progress already.
40 if (newSearch
&& keys
== QLatin1Char(' ')) {
44 if (!keys
.isEmpty()) {
45 m_searchedString
.append(keys
);
48 // If the same key is pressed repeatedly, the next item matching that key should be highlighted
49 const QChar firstKey
= m_searchedString
.length() > 0 ? m_searchedString
.at(0) : QChar();
50 const bool sameKey
= m_searchedString
.length() > 1 && m_searchedString
.count(firstKey
) == m_searchedString
.length();
52 // Searching for a matching item should start from the next item if either
53 // 1. a new search is started and a search has not been restarted or
54 // 2. a 'repeated key' search is done.
55 const bool searchFromNextItem
= (!m_isSearchRestarted
&& newSearch
) || sameKey
;
57 // to remember not to searchFromNextItem if selection was deselected
58 // loosing keyboard search context basically
59 m_isSearchRestarted
= false;
61 emit
changeCurrentItem(sameKey
? firstKey
: m_searchedString
, searchFromNextItem
);
63 m_keyboardInputTime
.start();
66 void KItemListKeyboardSearchManager::setTimeout(qint64 milliseconds
)
68 m_timeout
= milliseconds
;
71 qint64
KItemListKeyboardSearchManager::timeout() const
76 void KItemListKeyboardSearchManager::cancelSearch()
78 m_isSearchRestarted
= true;
79 m_searchedString
.clear();
82 void KItemListKeyboardSearchManager::slotCurrentChanged(int current
, int previous
)
87 // The current item has been removed. We should cancel the search.
92 void KItemListKeyboardSearchManager::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
94 if (!previous
.isEmpty() && current
.isEmpty() && previous
.count() > 0 && current
.count() == 0) {
95 // The selection has been emptied. We should cancel the search.