File indexing completed on 2025-01-05 05:19:56
0001 /* 0002 * SPDX-FileCopyrightText: 2022 Pablo Rauzy <r .at. uzy .dot. me> 0003 * SPDX-License-Identifier: LGPL-2.0-or-later 0004 */ 0005 0006 #pragma once 0007 0008 #include <utility> 0009 0010 #include <QDebug> 0011 #include <QJsonArray> 0012 #include <QJsonValue> 0013 #include <QKeyEvent> 0014 #include <QKeySequence> 0015 #include <QString> 0016 0017 class KeyCombination 0018 { 0019 private: 0020 int m_key = -1; 0021 Qt::KeyboardModifiers m_modifiers; 0022 QString m_text; 0023 0024 public: 0025 KeyCombination(){}; 0026 0027 KeyCombination(const int key, const Qt::KeyboardModifiers modifiers, const QString &text) 0028 : m_key(key) 0029 , m_modifiers(modifiers) 0030 , m_text(text){}; 0031 0032 explicit KeyCombination(const QKeyEvent *keyEvent) 0033 : m_key(keyEvent->key()) 0034 , m_modifiers(keyEvent->modifiers()) 0035 , m_text(keyEvent->text()){}; 0036 0037 static const std::pair<const KeyCombination, bool> fromJson(const QJsonArray &json) 0038 { 0039 if (json.size() != 3 || json[0].type() != QJsonValue::Double || json[1].type() != QJsonValue::Double || json[2].type() != QJsonValue::String) { 0040 return std::pair(KeyCombination(), false); 0041 } 0042 return std::pair(KeyCombination(json[0].toInt(0), static_cast<Qt::KeyboardModifiers>(json[1].toInt(0)), json[2].toString()), true); 0043 }; 0044 0045 const QKeyEvent keyPress() const 0046 { 0047 return QKeyEvent(QEvent::KeyPress, m_key, m_modifiers, m_text); 0048 }; 0049 0050 const QKeyEvent keyRelease() const 0051 { 0052 return QKeyEvent(QEvent::KeyRelease, m_key, m_modifiers, m_text); 0053 }; 0054 0055 const QJsonArray toJson() const 0056 { 0057 QJsonArray json; 0058 json.append(QJsonValue(m_key)); 0059 json.append(QJsonValue(static_cast<int>(m_modifiers))); 0060 json.append(QJsonValue(m_text)); 0061 return json; 0062 }; 0063 0064 const QString toString() const 0065 { 0066 if (isVisibleInput()) { 0067 return m_text; 0068 } 0069 return QKeySequence(m_key | m_modifiers).toString(); 0070 }; 0071 0072 bool isVisibleInput() const 0073 { 0074 return m_text.size() == 1 && (m_modifiers == Qt::NoModifier || m_modifiers == Qt::ShiftModifier) && m_text[0].isPrint(); 0075 }; 0076 0077 friend QDebug operator<<(QDebug dbg, const KeyCombination &kc) 0078 { 0079 return dbg << kc.toString(); 0080 }; 0081 };