Sonde v1.1.0
Embeddable Model Context Protocol server for Qt applications
Loading...
Searching...
No Matches
inputtools_p.h
Go to the documentation of this file.
1#pragma once
2
6
7#include <sonde/objecttree.h>
8#include <sonde/server.h>
9#include <sonde/types.h>
10
11#include <QtCore/QCoreApplication>
12#include <QtCore/QEvent>
13#include <QtCore/QJsonObject>
14#include <QtCore/QList>
15#include <QtCore/QObject>
16#include <QtCore/QString>
17
18#include <functional>
19
20QT_BEGIN_NAMESPACE
21class QWindow;
22QT_END_NAMESPACE
23
24namespace Sonde::Input {
25
26// --- delivery report -------------------------------------------------------
27
29constexpr qsizetype kMaxDeliveries = 256;
30
33bool isWithin(const QObject *o, const QObject *ancestor);
34
50class DeliveryRecorder : public QObject
51{
52public:
54 explicit DeliveryRecorder(const QObject *target = nullptr)
55 : m_previous(s_current), m_target(target)
56 {
57 s_current = this;
58 QCoreApplication::instance()->installEventFilter(this);
59 }
60
62 {
64 if (QCoreApplication *app = QCoreApplication::instance())
65 app->removeEventFilter(this);
66 }
67 Q_DISABLE_COPY_MOVE(DeliveryRecorder)
68
69
70 static void mark(QEvent::Type type)
71 {
72 if (s_current)
73 s_current->m_chains.append({ labelFor(type), { }, false });
74 }
75
77 QString firstChainEvent() const
78 {
79 for (const Chain &c : m_chains) {
80 if (!c.label.isEmpty()) {
81 return c.label == QLatin1StringView("wheel") ? QStringLiteral("wheel event")
82 : c.label;
83 }
84 }
85 return QStringLiteral("press");
86 }
87
90 {
91 for (const Chain &c : m_chains) {
92 if (!c.receivers.isEmpty() || c.label == QLatin1StringView("press"))
93 return c.reachedTarget;
94 }
95 return true;
96 }
97
100 QString report() const
101 {
102 QStringList lines;
103 QStringList labels;
104 const QStringList *previous = nullptr;
105 const auto flush = [&] {
106 if (!previous)
107 return;
108 const QString who = previous->isEmpty() ? QStringLiteral("no object (only the window)")
109 : previous->join(QStringLiteral(" -> "));
110 lines << QStringLiteral(" %1: %2").arg(compactLabels(labels), who);
111 labels.clear();
112 };
113 for (const Chain &c : m_chains) {
114 if (c.label.isEmpty())
115 continue;
116 if (previous && *previous != c.receivers)
117 flush();
118 previous = &c.receivers;
119 labels << c.label;
120 }
121 flush();
122 if (lines.isEmpty())
123 return { };
124 QString text =
125 QStringLiteral(
126 "\nDelivered to (in order; each object before the last ignored the event "
127 "and Qt passed it on):\n")
128 + lines.join(QLatin1Char('\n'));
129 if (m_count >= kMaxDeliveries)
130 text += QStringLiteral("\n (later deliveries not recorded)");
131 return text;
132 }
133
135 bool eventFilter(QObject *receiver, QEvent *event) override
136 {
137 const QString label = labelFor(event->type());
138 if (label.isEmpty() || m_chains.isEmpty() || m_count >= kMaxDeliveries
139 || receiver->isWindowType())
140 return false;
141 Chain &chain = m_chains.last();
142 if (chain.label.isEmpty())
143 return false; // an event this recorder doesn't follow (a release, say)
144 QString who = ObjectTree::describeBrief(receiver);
145 if (label != chain.label) {
146 who = QStringLiteral("(%1) ").arg(label)
147 + who; // e.g. a key press that became a shortcut
148 }
149 chain.receivers << who;
150 if (m_target && isWithin(receiver, m_target))
151 chain.reachedTarget = true;
152 ++m_count;
153 return false;
154 }
155
156private:
158 struct Chain
159 {
160 QString label;
161 QStringList receivers;
162 bool reachedTarget = false;
163 };
164
166 static QString labelFor(QEvent::Type type)
167 {
168 switch (type) {
169 case QEvent::MouseButtonPress:
170 return QStringLiteral("press");
171 case QEvent::MouseButtonDblClick:
172 return QStringLiteral("double-click");
173 case QEvent::Wheel:
174 return QStringLiteral("wheel");
175 case QEvent::KeyPress:
176 return QStringLiteral("key");
177 case QEvent::Shortcut:
178 return QStringLiteral("shortcut");
179 default:
180 return { };
181 }
182 }
183
185 static QString compactLabels(const QStringList &labels)
186 {
187 QStringList out;
188 qsizetype i = 0;
189 while (i < labels.size()) {
190 qsizetype n = 1;
191 while (i + n < labels.size() && labels.at(i + n) == labels.at(i))
192 ++n;
193 out << (n > 1 ? QStringLiteral("%1 x%2").arg(labels.at(i)).arg(n) : labels.at(i));
194 i += n;
195 }
196 return out.join(QStringLiteral(", "));
197 }
198
199 static inline DeliveryRecorder *s_current = nullptr;
201 const QObject *m_target = nullptr;
202 QList<Chain> m_chains;
203 qsizetype m_count = 0;
204};
205
207QJsonObject keyboardSchema(const QString &main, const QJsonObject &mainProperty,
208 const QJsonObject &extra = { });
209
211QString windowText(QWindow *w);
212
219void finishAfterSettle(const ToolCall &call, std::function<QString()> summary);
220
222QString focusSummary();
223
225void addTool(Server &server, const char *name, const char *title, const QString &description,
226 const QJsonObject &schema, AsyncToolHandler handler);
227
229void installKeyboardTools(Server &server);
230
231} // namespace Sonde::Input
Records which objects receive the events the input tools inject.
Definition inputtools_p.h:51
static DeliveryRecorder * s_current
The innermost live recorder.
Definition inputtools_p.h:199
static QString compactLabels(const QStringList &labels)
"press x2, double-click" from a list of labels.
Definition inputtools_p.h:185
bool eventFilter(QObject *receiver, QEvent *event) override
Records receiver if event is one of the recorded types.
Definition inputtools_p.h:135
QString firstChainEvent() const
What the first recorded chain was: "press", "wheel event", "key" ("press" if none).
Definition inputtools_p.h:77
static QString labelFor(QEvent::Type type)
The report label of a recorded event type, or an empty string.
Definition inputtools_p.h:166
QString report() const
The report: one line per run of identical chains, e.g.
Definition inputtools_p.h:100
~DeliveryRecorder() override
Stops recording.
Definition inputtools_p.h:61
QList< Chain > m_chains
One per injected event.
Definition inputtools_p.h:202
bool firstChainReachedTarget() const
Whether the first chain (the first press) reached the target or something inside it.
Definition inputtools_p.h:89
const QObject * m_target
Compared by address only, never dereferenced.
Definition inputtools_p.h:201
DeliveryRecorder * m_previous
The recorder this one hides, if nested.
Definition inputtools_p.h:200
qsizetype m_count
Deliveries recorded so far.
Definition inputtools_p.h:203
DeliveryRecorder(const QObject *target=nullptr)
Starts recording; target (optional) is the object the tool aimed at.
Definition inputtools_p.h:54
static void mark(QEvent::Type type)
Starts a new chain for an injected event of type (no-op without a recorder).
Definition inputtools_p.h:70
An embeddable Model Context Protocol server.
Definition server.h:92
Handle for an in-flight tools/call, used by asynchronous tools.
Definition types.h:142
void installKeyboardTools(Server &server)
Registers input_keys and input_text (keyboardtools.cpp).
Definition keyboardtools.cpp:310
constexpr qsizetype kMaxDeliveries
Most deliveries one recorder keeps (input_text of a long string stops here).
Definition inputtools_p.h:29
void addTool(Server &server, const char *name, const char *title, const QString &description, const QJsonObject &schema, AsyncToolHandler handler)
Registers an asynchronous tool from its parts.
Definition inputtools.cpp:696
bool isWithin(const QObject *o, const QObject *ancestor)
Whether o is ancestor or below it, following Qt Quick's visual parent ("parent" property) where there...
Definition inputtools.cpp:638
QString focusSummary()
"Focus: <object>" for the current focus object.
Definition inputtools.cpp:690
QString windowText(QWindow *w)
describeWindow(), or "(window closed)" for a null window.
Definition inputtools.cpp:667
QJsonObject keyboardSchema(const QString &main, const QJsonObject &mainProperty, const QJsonObject &extra={ })
The argument schema of a keyboard tool: main (required), window, object, settleMs,...
Definition inputtools.cpp:649
void finishAfterSettle(const ToolCall &call, std::function< QString()> summary)
Finishes call after its settleMs and once scrolling views have stopped, with the text summary returns...
Definition inputtools.cpp:672
QString describeBrief(const QObject *o)
Short summary that doesn't change with the object's state: @id Class#name.
Definition objecttree.cpp:363
std::function< void(const ToolCall &call)> AsyncToolHandler
Handler of an asynchronous tool; answer via ToolCall::finish().
Definition types.h:192
Sonde::ObjectTree: the application's object tree, object specs and QVariant/JSON conversion.
Sonde::Server, the embeddable MCP server.
One injected event and the objects it reached.
Definition inputtools_p.h:159
QString label
"press", "key", ...; empty for events that aren't recorded.
Definition inputtools_p.h:160
bool reachedTarget
Whether a receiver was the target or inside it.
Definition inputtools_p.h:162
QStringList receivers
describeBrief() of each receiver, in order.
Definition inputtools_p.h:161
int main(int argc, char **argv)
Connects to the local server and copies lines between it and stdin/stdout.
Definition main.cpp:20
Value types shared by the Sonde API: tool definitions and results, asynchronous tool-call handles,...