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 <QJsonArray>
0011 #include <QJsonValue>
0012 #include <QList>
0013 #include <QRegularExpression>
0014 
0015 #include "keycombination.h"
0016 
0017 class Macro : public QList<KeyCombination>
0018 {
0019 public:
0020     explicit Macro()
0021         : QList<KeyCombination>(){};
0022 
0023     static const std::pair<const Macro, bool> fromJson(const QJsonValue &json)
0024     {
0025         if (json.type() != QJsonValue::Array) {
0026             std::pair(Macro(), false);
0027         }
0028         Macro macro;
0029         for (const auto &jsonKeyCombination : json.toArray()) {
0030             if (jsonKeyCombination.type() != QJsonValue::Array) {
0031                 return std::pair(Macro(), false);
0032             }
0033             auto maybeKeyCombination = KeyCombination::fromJson(jsonKeyCombination.toArray());
0034             if (!maybeKeyCombination.second) {
0035                 return std::pair(Macro(), false);
0036             }
0037             macro.append(maybeKeyCombination.first);
0038         }
0039         return std::pair(macro, true);
0040     };
0041 
0042     const QJsonArray toJson() const
0043     {
0044         QJsonArray json;
0045         Macro::ConstIterator it;
0046         for (it = this->constBegin(); it != this->constEnd(); ++it) {
0047             json.append(it->toJson());
0048         }
0049         return json;
0050     };
0051 
0052     const QString toString() const
0053     {
0054         QString str;
0055         for (const auto &kc : *this) {
0056             if (kc.isVisibleInput()) {
0057                 str += kc.toString();
0058             } else {
0059                 str += QStringLiteral(" ") + kc.toString() + QStringLiteral(" ");
0060             }
0061         }
0062         return str.trimmed().replace(QRegularExpression(QStringLiteral("\\s+")), QStringLiteral(" "));
0063     };
0064 };