Debian Codegraph @

recorder/src/main.c

raw
1 /* X11::GUITest ($Id: main.c 253 2026-08-19 22:37:51Z ctrondlp $)
2 *
3 * Copyright (c) 2003-2026 Dennis K. Paulsen, All Rights Reserved.
4 * Email: [email protected]
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License as
8 * published by the Free Software Foundation; either version 2 of
9 * the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses>.
18 *
19 */
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <popt.h>
24 #include <math.h>
25 #include <unistd.h>
26 #include <locale.h> /* setlocale(); libintl.h doesn't reliably pull this in */
27 #include <X11/Xutil.h>
28 #include "record.h"
29 #include "record_event.h"
30 #include "KeyUtil.h"
31 #include "script_file.h"
32 #include "Common.h"
33 #include "main.h"
34
35
36 static char *scriptFile = NULL;
37 static char *exitKey = "ESC";
38 static KeySym exitKeySym = 0;
39 static BOOL excludeDelays = FALSE;
40 static int waitSeconds = DEFAULT_WAIT_SECS;
41 static int delayThresholdMs = DEFAULT_DELAY_MS;
42 static int granularity = MAX_GRANULARITY;
43 static struct record_event lastEvent = {0};
44 static char buttonName[MAX_MBUTTON_NAME] = "\0";
45 static char keyBuffer[MAX_KEY_BUFFER] = "\0";
46
47
48 int main (int argc, char *argv[])
49 {
50 poptContext optCon = {0};
51
52 // International support
53 setlocale(LC_MESSAGES, "");
54 #ifdef HAVE_GETTEXT
55 bindtextdomain(APP_NAME, APP_TEXTDOMAIN);
56 textdomain(APP_NAME);
57 #endif
58
59 // Parse arguments
60 struct poptOption optTbl[] = {
61 {"script", 's', POPT_ARG_STRING, &scriptFile, 0, _("Script file to create"), NULL},
62 {"wait", 'w', POPT_ARG_INT | POPT_ARGFLAG_SHOW_DEFAULT, &waitSeconds, 0, _("Seconds to wait before recording"), NULL},
63 {"delaythreshold", 'd', POPT_ARG_INT | POPT_ARGFLAG_SHOW_DEFAULT, &delayThresholdMs, 0, _("Event delay (ms) threshold to account for / record"), NULL},
64 {"exitkey", 'e', POPT_ARG_STRING | POPT_ARGFLAG_SHOW_DEFAULT, &exitKey, 0, _("Exit key to stop recording"), NULL},
65 {"nodelay", 'n', POPT_ARG_NONE, &excludeDelays, 0, _("Don't include user delays"), NULL},
66 {"granularity", 'g', POPT_ARG_INT | POPT_ARGFLAG_SHOW_DEFAULT, &granularity, 0, _("Level of granularity, mouse move frequency, 1-10"), NULL},
67 POPT_AUTOHELP
68 POPT_TABLEEND
69 };
70 optCon = poptGetContext(NULL, argc, (const char **)argv, optTbl, 0);
71 if (argc <= 1) {
72 PrintAppInfo();
73 poptPrintHelp(optCon, stderr, 0);
74 exit(1);
75 }
76 while (poptGetNextOpt(optCon) >= 0) {}
77 poptFreeContext(optCon);
78
79 // Check arguments
80 if (scriptFile == NULL || !*scriptFile) {
81 fprintf(stderr, _("No script file specified.\n"));
82 exit(1);
83 }
84 if (!GetKeySym(exitKey, &exitKeySym)) {
85 fprintf(stderr, _("Invalid exit key defined.\n"));
86 exit(1);
87 }
88 if (waitSeconds < MIN_WAIT_SECONDS || waitSeconds > MAX_WAIT_SECONDS) {
89 fprintf(stderr, _("Invalid wait defined (supplied %d, but needs 1-%d).\n"),
90 waitSeconds, MAX_WAIT_SECONDS);
91 exit(1);
92 }
93 if (granularity < MIN_GRANULARITY || granularity > MAX_GRANULARITY) {
94 fprintf(stderr, _("Invalid granularity defined (supplied %d, but needs %d-%d).\n"),
95 granularity, MIN_GRANULARITY, MAX_GRANULARITY);
96 exit(1);
97 }
98 if (delayThresholdMs < MIN_DELAY_MS || delayThresholdMs > MAX_DELAY_MS) {
99 fprintf(stderr, _("Invalid delay theshold defined (supplied %d, but needs %d-%d).\n"),
100 delayThresholdMs, MIN_DELAY_MS, MAX_DELAY_MS);
101 exit(1);
102 }
103
104 if (!OpenScript(scriptFile)) {
105 exit(1);
106 }
107
108 // Starting up...
109 usleep(waitSeconds * 1000000);
110 printf(_("Recording Started, press %s to exit.\n"), exitKey);
111
112 WriteScript("#!/usr/bin/perl\n\n");
113 WriteScript("use X11::GUITest qw/:ALL/;\n");
114 WriteScript("use strict;\n");
115 WriteScript("use warnings;\n\n\n");
116 WriteScript(_("# Begin (Recorder Version %s).\n"), APP_VERSION);
117
118 ////
119 RecordEvents(ProcessEvent);
120 ////
121
122 WriteScript(_("\n\n# End.\n"));
123 CloseScript();
124
125 printf(_("\nRecording Finished.\n"));
126 exit(0);
127 }
128
129 static void PrintAppInfo(void)
130 {
131 printf("%s (%s: %s)\n\n", APP_NAME, _("Version"), APP_VERSION);
132 }
133
134 static BOOL GetMouseButtonFromIndex(int index, char *button)
135 {
136 if (button == NULL) {
137 return FALSE;
138 }
139 *button = NUL;
140
141 if (index == 1) {
142 strcpy(button, "M_LEFT");
143 } else if (index == 2) {
144 strcpy(button, "M_MIDDLE");
145 } else if (index == 3) {
146 strcpy(button, "M_RIGHT");
147 } else if (index == 4) {
148 strcpy(button, "M_UP");
149 } else if (index == 5) {
150 strcpy(button, "M_DOWN");
151 } else {
152 return FALSE;
153 }
154
155 return TRUE;
156 }
157
158 static void HandleDelay(unsigned long delay)
159 {
160 if (excludeDelays == FALSE) {
161 /* delayThresholdMs stays a plain int (see main.h/main()) since
162 * popt's POPT_ARG_INT writes through an int* -- it's already
163 * validated to MIN_DELAY_MS..MAX_DELAY_MS (non-negative) in
164 * main(), so this cast can't turn a negative value huge. */
165 if (delay > (unsigned long)delayThresholdMs) {
166 float secs = ((float)delay / 1000); // ms to secs
167 WriteScript("WaitSeconds(%0.3f);\n", secs);
168 }
169 }
170 }
171
172 static void HandleKeyBuffer(BOOL forceKeyFlush)
173 {
174 int len = strlen(keyBuffer);
175 if (forceKeyFlush || len >= KEY_BUFFER_THRESHOLD) {
176 if (len > 0) {
177 WriteScript("SendKeys('%s');\n", keyBuffer);
178 *keyBuffer = '\0'; // clear
179 }
180 }
181 }
182
183 /* Appends str to keyBuffer, flushing the buffer out as its own SendKeys()
184 * call first if str wouldn't otherwise fit. str is expected to be one
185 * complete syntactic keyUnit (e.g. "{KeyName}" or "mod("); callers must
186 * not split a keyUnit across multiple calls, or a flush here could break
187 * it across two separate SendKeys() calls in the recorded script. */
188 static void AppendKeyBuffer(const char *str)
189 {
190 size_t curlen = 0, addlen = 0, avail = 0;
191
192 if (str == NULL || *str == '\0') {
193 return;
194 }
195 addlen = strlen(str);
196 curlen = strlen(keyBuffer);
197
198 if (curlen + addlen >= MAX_KEY_BUFFER) {
199 HandleKeyBuffer(TRUE);
200 curlen = strlen(keyBuffer); /* Now 0, barring a single str that
201 * alone exceeds MAX_KEY_BUFFER. */
202 }
203
204 avail = MAX_KEY_BUFFER - curlen - 1; /* Leave room for the NUL. */
205 strncat(keyBuffer, str, avail);
206 }
207
208 static void ProcessEvent(struct record_event ev)
209 {
210 if (ev.type == KEY) {
211 // TODO: Granular delay between buffered key events
212 BOOL forceKeyFlush = (ev.delay > MAX_KEYDELAY_BEFOREFLUSH_MS);
213 HandleKeyBuffer(forceKeyFlush);
214 HandleDelay(ev.delay);
215
216 // Are we exiting?
217 /* ev.data holds a KeySym on the KEY path (see record_event.h);
218 * compare as KeySym rather than plain long so this doesn't
219 * become a signed/unsigned mismatch. */
220 if ((KeySym)ev.data == exitKeySym) {
221 HandleKeyBuffer(TRUE);
222 StopRecording();
223 return;
224 }
225
226 const char *nam = GetKeyName(ev.data);
227 if (nam != NULL) {
228 const char *mod = GetModifierCode(ev.data);
229 char keyUnit[MAX_KEY_BUFFER] = "\0";
230
231 if (mod != NULL) {
232 //// handle modifiers
233 if (ev.state == DOWN) {
234 snprintf(keyUnit, sizeof(keyUnit), "%s(", mod);
235 } else {
236 snprintf(keyUnit, sizeof(keyUnit), ")");
237 }
238 AppendKeyBuffer(keyUnit);
239 } else {
240 //// handle other keys
241 if (ev.state == UP) {
242 //printf("Key: %s (%s)\n", nam, mod);
243 if (strlen(nam) > 1) {
244 // special key
245 snprintf(keyUnit, sizeof(keyUnit), "{%s}", nam);
246 } else if (nam[0] == '\'') { // escape this
247 snprintf(keyUnit, sizeof(keyUnit), "\\%s", nam);
248 } else {
249 snprintf(keyUnit, sizeof(keyUnit), "%s", nam);
250 }
251 AppendKeyBuffer(keyUnit);
252 }
253 }
254 } else {
255 WriteScript(_("# [Unhandled Key %ld/%d]\n"), ev.data, ev.state);
256 }
257 } else { // Mouse, etc.
258 HandleKeyBuffer(TRUE); // Flush out others events...
259 HandleDelay(ev.delay);
260
261 if (ev.type == MOUSEMOVE) {
262 if (!IsMouseMoveTooGranular(ev)) {
263 WriteScript("MoveMouseAbs(%d, %d);\n", ev.posX, ev.posY);
264 }
265 } else if (ev.type == MOUSEBUTTON) {
266 /* MOUSEBUTTON events only ever carry a small button index
267 * (1-5) in data, never a KeySym, so this narrowing is safe. */
268 GetMouseButtonFromIndex((int)ev.data, buttonName);
269 if (!*buttonName) {
270 WriteScript(_("# [Unhandled Mouse Button %ld/%d]\n"), ev.data, ev.state);
271 } else {
272 // TODO: Simplify to 'ClickMouseButton' where possible...
273 if (ev.state == UP) {
274 WriteScript("ReleaseMouseButton(%s);\n", buttonName);
275 } else {
276 WriteScript("PressMouseButton(%s);\n", buttonName);
277 }
278 }
279 } else {
280 //printf("Unhandled event type: %d\n", ev.type);
281 }
282 }
283 memcpy(&lastEvent, &ev, sizeof(struct record_event));
284 }
285
286 static BOOL IsMouseMoveTooGranular(struct record_event ev)
287 {
288 if (lastEvent.type != MOUSEMOVE) {
289 return(FALSE); // must be mousemove -> mousemove to count
290 } else {
291 // TODO: Adjust
292 /* granularity stays a plain int (see main.h/main()) since popt's
293 * POPT_ARG_INT writes through an int* -- it's already validated
294 * to MIN_GRANULARITY..MAX_GRANULARITY in main(), so threshold is
295 * always in [0, MAX_GRANULARITY-1] and this cast is safe. */
296 int threshold = (int)MAX_GRANULARITY / granularity - 1;
297 if (ev.delay < (unsigned long)threshold) {
298 return(TRUE);
299 }
300 }
301 return(FALSE);
302 }