swift
lineedithistory.cpp
1 // SPDX-FileCopyrightText: Copyright (C) 2017 swift Project Community / Contributors
2 // SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3 
4 #include "lineedithistory.h"
5 
6 #include <QKeyEvent>
7 #include <QMenu>
8 
9 namespace swift::gui
10 {
12  {
13  if (m_history.isEmpty()) return {};
14  return m_history.first();
15  }
16 
18  {
19  return this->getLastEnteredLine().trimmed().simplified();
20  }
21 
22  void CLineEditHistory::clearHistory() { m_history.clear(); }
23 
25  {
26  const int key = event->key();
27  bool nonEmpty = false;
28 
29  if (key == Qt::Key_Up)
30  {
31  // move back in history
32  if (m_history.size() > m_position) { this->setText(m_history.at(m_position++)); }
33  }
34  else if (key == Qt::Key_Down)
35  {
36  // move forward in history
37  if (m_position <= 0)
38  {
39  this->clear();
40  return;
41  }
42  if (m_position == m_history.size()) { --m_position; } // avoid need of 2xKeyDown at end
43  if (m_position > 0 && m_history.size() > --m_position) { this->setText(m_history.at(m_position)); }
44  }
45  else if (key == Qt::Key_Return || key == Qt::Key_Enter) // normal and keypad enter
46  {
47  const QString t = this->text().trimmed();
48  if (!t.isEmpty())
49  {
50  m_history.push_front(t);
51  m_position = 0;
52  this->clear();
53  nonEmpty = true;
54  }
55  }
56  // default handler for event
58 
59  // signal
60  if (nonEmpty) { emit this->returnPressedUnemptyLine(); }
61  }
62 
64  {
65  if (!event) { return; }
66  QMenu *menu = this->createStandardContextMenu();
67  menu->addSeparator();
68  menu->addAction("Clear history");
70  menu->exec(event->globalPos());
71  delete menu;
72  }
73 } // namespace swift::gui
virtual void keyPressEvent(QKeyEvent *event)
virtual void contextMenuEvent(QContextMenuEvent *event)
QString getLastEnteredLineFormatted() const
Get the last entered line but simplified and trimmed.
void returnPressedUnemptyLine()
Return has been pressed, line is NOT empty (spaces are trimmed)
QString getLastEnteredLine() const
Get the last entered line.
void clearHistory()
Clear the history.
GUI related classes.
void triggered(bool checked)
void clear()
QMenu * createStandardContextMenu()
virtual bool event(QEvent *e) override
virtual void keyPressEvent(QKeyEvent *event) override
void setText(const QString &)
QList< T >::const_reference at(qsizetype i) const const
void clear()
T & first()
bool isEmpty() const const
T & last()
void push_front(QList< T >::parameter_type value)
qsizetype size() const const
QAction * addAction(const QIcon &icon, const QString &text, Functor functor, const QKeySequence &shortcut)
QAction * addSeparator()
QAction * exec()
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
bool isEmpty() const const
QString simplified() const const
QString trimmed() const const
QList< QAction * > actions() const const