-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
344 lines (304 loc) · 11.7 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
#include <iostream>
#include <cstdlib> // to read environment variables
#include <thread>
#include "MyTrayIcon.h"
#include <X11/Xlib.h>
#include <X11/XKBlib.h>
#include <X11/extensions/XTest.h>
#include <X11/keysym.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#include <string>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fstream>
#include <sstream>
#include <unordered_map>
#include <vector>
#include <syslog.h>
const char* g_PATH = ".xcmd-settings.csv";
inline bool static g_running = TRUE;
void send_to_socket(const std::string& message);
int socket_fd = -1;
struct AppConfig
{
std::string executable;
std::string flag;
std::string arguments;
std::string socketMessage;
bool isSocketAction;
pid_t pid;
bool g_running;
// Default constructor
AppConfig() : executable(""), flag(""), arguments(""), socketMessage(""), isSocketAction(false), pid(0), g_running(false) {}
AppConfig(const std::string& exe, const std::string& flg, const std::string& args, const std::string& socketMsg, bool socketAction)
: executable(exe), flag(flg), arguments(args), socketMessage(socketMsg), isSocketAction(socketAction), pid(0), g_running(false) {}
};
std::unordered_map<KeySym, AppConfig> g_keyAppMap;
// Trim doesn't exist natively so I need this function to trim whitespace from a string
std::string trim(const std::string &str)
{
size_t first = str.find_first_not_of(' ');
if (first == std::string::npos)
return str;
size_t last = str.find_last_not_of(' ');
return str.substr(first, last - first + 1);
}
void init_logging()
{
openlog("XCmd", LOG_PID | LOG_CONS, LOG_USER);
}
// Logging function
void logMessage(const std::string& message)
{
std::ofstream logFile;
logFile.open("/var/log/XCmd", std::ios_base::app);
if (logFile.is_open())
{
logFile << message << std::endl;
logFile.close();
}
else
{
std::cerr << "Failed to open log file: /var/log/XCmd" << std::endl;
}
}
std::string envValue(const std::string& envVariable)
{
const char* envValue = std::getenv(envVariable.c_str());
return (envValue != nullptr) ? std::string(envValue) : "";
}
void run_gtk_main()
{
Gtk::Main::run();
exit(0);
}
void readConfig(const std::string& filename)
{
std::ifstream file(filename);
if (!file.is_open())
{
std::cerr << "Failed to open config file: " << filename << std::endl;
exit(1);
}
std::string line;
g_keyAppMap.clear(); // Clear the existing configuration
while (std::getline(file, line))
{
std::stringstream ss(line);
std::string keySymStr, executable, flag, arguments, socketMessage;
bool isSocketAction = false;
std::getline(ss, keySymStr, ',');
std::getline(ss, executable, ',');
std::getline(ss, flag, ',');
std::getline(ss, arguments, ',');
std::getline(ss, socketMessage, ',');
keySymStr = trim(keySymStr);
if (!socketMessage.empty())
{
isSocketAction = true;
}
// Directly use the character to get the KeySym
KeySym keySym = XStringToKeysym(keySymStr.c_str());
if (keySym == NoSymbol)
{
std::cerr << "Invalid KeySym: " << keySymStr << std::endl;
continue;
}
g_keyAppMap[keySym] = AppConfig(executable, flag, arguments, socketMessage, isSocketAction);
std::cout << "Configured: " << keySymStr << " -> " << executable << " " << flag << " " << arguments << " " << socketMessage << std::endl; // Debugging info
}
file.close();
}
void launchApp(const KeySym &keySym, MyTrayIcon &tray_icon)
{
auto& config = g_keyAppMap[keySym];
if (config.isSocketAction)
{
send_to_socket(config.socketMessage);
}
else
{
if (config.g_running)
{
kill(config.pid, SIGTERM);
config.g_running = false;
tray_icon.set_status(FALSE);
logMessage("Application " + config.executable + " killed");
std::cout << "\nApplication " << config.executable << " killed" << std::endl;
}
else
{
pid_t pid = fork();
if (pid == 0)
{
// Child process --
std::cout << "Launching: " << config.executable << " " << config.flag << " " << config.arguments << std::endl;
logMessage("Launching " + config.executable + " " + config.flag + " " + config.arguments);
execl(config.executable.c_str(), config.executable.c_str(), (config.flag.length()<1?NULL:config.flag.c_str()), config.arguments.c_str(), (char *)NULL);
// If execl returns, it must have failed
perror("execl failed, check your settings file.");
exit(1);
}
else if (pid > 0)
{
config.pid = pid;
config.g_running = true;
tray_icon.set_status(TRUE);
logMessage("Application " + config.executable + " launched");
std::cout << "Application " << config.executable << " launched" << std::endl;
}
else
{
std::string message = "Failed to launch application " + config.executable;
logMessage(message);
std::cerr << message << std::endl;
}
}
}
}
void send_to_socket(const std::string& message)
{
if (socket_fd == -1)
{
socket_fd = socket(AF_INET, SOCK_STREAM, 0);
if (socket_fd < 0)
{
logMessage("Failed to create socket");
std::cerr << "Failed to create socket" << std::endl;
return;
}
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(21002);
if (inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr) <= 0)
{
logMessage("Invalid address");
std::cerr << "Invalid address" << std::endl;
close(socket_fd);
socket_fd = -1;
return;
}
if (connect(socket_fd, reinterpret_cast<struct sockaddr*>(&server_addr), sizeof(server_addr)) < 0)
{
logMessage("Failed to connect to server");
std::cerr << "Failed to connect to server" << std::endl;
close(socket_fd);
socket_fd = -1;
return;
}
}
if (write(socket_fd, message.c_str(), message.length()) < 0)
{
logMessage("Failed to send message");
std::cerr << "Failed to send message" << std::endl;
close(socket_fd);
socket_fd = -1;
return;
}
std::string wmessage = "Message sent to socket: " + message;
logMessage(wmessage);
}
void on_next()
{
std::cout << "Next action triggered from main" << std::endl;
send_to_socket("next");
}
int main(int argc, char* argv[])
{
bool super_r_pressed = false;
bool combination_detected = false;
// Initialize logging
init_logging();
//read settings
std::string home = envValue("HOME");
std::string path = home + "/" + g_PATH;
readConfig(path);
Gtk::Main kit(argc, argv); // Initialize GTK
std::string icon_path = "red-icon.png";
std::string icon_path_g_running = "green-icon.png";
MyTrayIcon tray_icon(icon_path, icon_path_g_running);
std::thread gtk_thread(run_gtk_main);
// Connect the next signal to the on_next function
tray_icon.signal_next().connect(sigc::ptr_fun(&on_next));
/* Get the DISPLAY environment variable */
char *xDisp = getenv ("DISPLAY");
if (xDisp == NULL)
{
std::cerr << "DISPLAY environment variable is not set." << std::endl;
return 1;
}
Display* display = XOpenDisplay(xDisp);
if (display == NULL)
{
logMessage("Cannot open display");
std::cerr << "Cannot open display" << std::endl;
return 1;
}
Window root = DefaultRootWindow(display);
XEvent event;
KeyCode superRKeyCode = XKeysymToKeycode(display, XK_Super_R);
XGrabKey(display, superRKeyCode, AnyModifier, root, True, GrabModeAsync, GrabModeAsync);
XSelectInput(display, root, KeyPressMask | KeyReleaseMask);
logMessage("XCmd started");
while (g_running)
{
XNextEvent(display, &event);
if (event.type == KeyPress || event.type == KeyRelease)
{
XKeyEvent* keyEvent = (XKeyEvent*)&event;
if (keyEvent->keycode == superRKeyCode)
{
if (event.type == KeyPress)
{
super_r_pressed = true;
combination_detected = false;
}
else if (event.type == KeyRelease)
{
super_r_pressed = false;
if (!combination_detected)
{
logMessage("No action configured for this key combination");
std::cerr << "No action configured for this key combination" << std::endl;
}
}
}
if (event.type == KeyPress && super_r_pressed)
{
KeySym keySym = XkbKeycodeToKeysym(display, keyEvent->keycode, 0, 0);
if (keySym == XK_q)
{
Gtk::Main::quit();
break; //to exit.
}
if (keySym == XK_r)
{
logMessage("Reloading configuration...");
std::cout << "Reloading configuration..." << std::endl;
readConfig(path);
logMessage("Configuration reloaded.");
std::cout << "Configuration reloaded." << std::endl;
}
else if (g_keyAppMap.find(keySym) != g_keyAppMap.end())
{
combination_detected = true;
launchApp(keySym, tray_icon);
}
else
{
combination_detected = true; // Consider it detected even if no action is configured
}
}
}
}
gtk_thread.join();
Gtk::Main::quit();
XCloseDisplay(display);
logMessage("XCmd stopped");
std::cout << "XCmd stopped\n";
closelog();
return 0;
}