Fix updatepot script
[ladish.git] / example-apps / level1-qt.cpp
blob644eddd7255c3c00a3f127135c717b419081b621
1 /* Basic code to enable LADISH level 1 support to an event driven Qt (3/4)
2 * application
3 * (c) 2010 Guido Scholz, License: GNU GPL v2
4 */
7 /* (1) */
8 /* Add this declaration to the header file of your MainWindow class:*/
10 private:
11 static int sigpipe[2];
13 static void handleSignal(int);
14 bool installSignalHandlers();
16 private slots:
17 void signalAction(int);
21 /* (2) */
22 /* Add this code to the cpp file of your MainWindow class:*/
24 #include <cerrno> // for errno
25 #include <csignal> // for sigaction()
26 #include <cstring> // for strerror()
27 #include <unistd.h> // for pipe()
28 #include <QSocketNotifier>
31 int MainWindow::sigpipe[2];
34 MainWindow::MainWindow(...)
36 /* ... */
37 /*add this lines to the constuctor of your MainWindow class: */
38 if (!installSignalHandlers())
39 qWarning("%s", "Signal handlers not installed!");
40 /* ... */
45 /* Handler for system signals (SIGUSR1, SIGINT...)
46 * Write a message to the pipe and leave as soon as possible
48 void MainWindow::handleSignal(int sig)
50 if (write(sigpipe[1], &sig, sizeof(sig)) == -1) {
51 qWarning("write() failed: %s", std::strerror(errno));
55 /* Install signal handlers (may be more than one; called from the
56 * constructor of your MainWindow class*/
57 bool MainWindow::installSignalHandlers()
59 /*install pipe to forward received system signals*/
60 if (pipe(sigpipe) < 0) {
61 qWarning("pipe() failed: %s", std::strerror(errno));
62 return false;
65 /*install notifier to handle pipe messages*/
66 QSocketNotifier* signalNotifier = new QSocketNotifier(sigpipe[0],
67 QSocketNotifier::Read, this);
68 connect(signalNotifier, SIGNAL(activated(int)),
69 this, SLOT(signalAction(int)));
71 /*install signal handlers*/
72 struct sigaction action;
73 memset(&action, 0, sizeof(action));
74 action.sa_handler = handleSignal;
76 if (sigaction(SIGUSR1, &action, NULL) == -1) {
77 qWarning("sigaction() failed: %s", std::strerror(errno));
78 return false;
81 /* optional: register more signals to handle:
82 if (sigaction(SIGINT, &action, NULL) == -1) {
83 qWarning("sigaction() failed: %s", std::strerror(errno));
84 return false;
88 return true;
91 /* Slot to give response to the incoming pipe message;
92 e.g.: save current file */
93 void MainWindow::signalAction(int fd)
95 int message;
97 if (read(fd, &message, sizeof(message)) == -1) {
98 qWarning("read() failed: %s", std::strerror(errno));
99 return;
102 switch (message) {
103 case SIGUSR1:
104 saveFile();
105 break;
106 /* optional: handle more signals:
107 case SIGINT:
108 //do something usefull like ...
109 close();
110 break;
112 default:
113 qWarning("Unexpected signal received: %d", message);
114 break;