File: qtsingleapplication_x11.cpp

package info (click to toggle)
beid 3.5.2.dfsg-10
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 147,240 kB
  • ctags: 34,507
  • sloc: cpp: 149,944; ansic: 41,577; java: 8,927; cs: 6,528; sh: 2,426; perl: 1,866; xml: 805; python: 463; makefile: 263; lex: 92
file content (344 lines) | stat: -rw-r--r-- 11,172 bytes parent folder | download
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
/****************************************************************************
**
** Copyright (C) 2003-2007 Trolltech ASA. All rights reserved.
**
** This file is part of a Qt Solutions component.
**
** Licensees holding a valid Qt Solutions License Agreement may use this
** file in accordance with the rights, responsibilities, and obligations
** contained therein. Please consult your licensing agreement or contact
** sales@trolltech.com if any conditions of this licensing are not clear
** to you.
**
** Further information about Qt Solutions licensing is available at:
** http://www.trolltech.com/products/qt/addon/solutions/ 
** or by contacting info@trolltech.com.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************/
#include "qtsingleapplication.h"
#include <QtGui/QWidget>
#include <QtCore/QByteArray>
#include <QtCore/QString>
#include <QtCore/QList>
#include <QtGui/QDesktopWidget>
#include <QtGui/QApplication>
#include <QtCore/QDebug>
#include <unistd.h>
#include <pwd.h>
#include <sys/types.h>
#include <X11/Xatom.h>
#include <X11/Xlib.h>
#include <QtGui/QX11Info>


class QtSingletonListener : public QWidget
{
public:
    QtSingletonListener(Atom atom, QWidget* par = 0)
        : QWidget(par)
    {
        QByteArray yes = "YES";
        XChangeProperty(QX11Info::display(),
                        winId(),
                        atom, atom, 8,
                        PropModeReplace,
                        reinterpret_cast<unsigned char *>(yes.data()), 3);
    }
};

class QtSingletonSysPrivate
{
public:
    Atom selAtom;
    Atom typAtom;
    Atom listenAtom;
    QWidget *listener;
    QByteArray xpcs;
    bool owner;

    QString login() const;
    QByteArray toXPCS(const QString &str) const; // X Portable Character Set

    void sendMessageTo(Window wid, Atom sel, Atom typ,
                       const QString &message) const;
    bool getProperty(char** data, unsigned long* nitems,
                     Window win, Atom sel, Atom typ) const;
    void findWindows(QList<Window> &windows);
};

QByteArray QtSingletonSysPrivate::toXPCS(const QString &str) const
{
    QString strtmp(str);
    if (strtmp.isEmpty() || strtmp[0] != '_')
        strtmp.prepend('_');
    QByteArray tmp = strtmp.toLocal8Bit();
    for (int i = 0; i < tmp.size(); ++i) {
	if (!xpcs.contains(tmp[i]))
	    tmp[i] = '_';
    }
    return tmp;
}

bool QtSingletonSysPrivate::getProperty(char** data, unsigned long* nitems,
                                        Window win, Atom sel, Atom typ) const
{
    if (data == 0 || nitems == 0)
        return false;

    Atom actualType;
    int  actualFormat, ret;
    long length = 1024;
    unsigned long bafter;
    for (;;) {
        *data = 0;
        *nitems = 0;

        ret = XGetWindowProperty(QX11Info::display(),
                                 win,
                                 sel,
                                 0L, length,
                                 False,
                                 typ,
                                 &actualType,
                                 &actualFormat,
                                 nitems,
                                 &bafter,
                                 reinterpret_cast<unsigned char **>(data));
        if (ret == Success && actualType == typ && *nitems > 0) {
            if (bafter == 0)
                return TRUE;
            else {
                if (actualFormat == 8)
                    length += (bafter / 4) + 1;
                else if (actualFormat == 16)
                    length += (bafter / 2) + 1;
                else if (actualFormat == 32)
                    length += bafter;
            }
        } else {
            if (*nitems > 0 && *data != 0)
                XFree(*data);
            return FALSE;
        }
        if (*nitems > 0 && *data != 0)
            XFree(*data);
    }
    return FALSE;
}

void QtSingletonSysPrivate::findWindows(QList<Window> &windows)
{
    Window root, parent;
    Window* children = 0;
    unsigned int nchildren;
    QDesktopWidget* desktop = qApp->desktop();
    char* data;
    unsigned long nitems;

    for (int i = 0; i < desktop->numScreens(); ++i) {
        if (XQueryTree(QX11Info::display(),
                       desktop->screen(i)->winId(),
                       &root, &parent,
                       &children, &nchildren) == 0)
            continue;
        if (nchildren > 0 && children != 0) {
            for (unsigned int i = 0; i < nchildren; ++i) {
                if (getProperty(&data, &nitems, children[i],
                                listenAtom, listenAtom)) {
                    if (data != 0)
                        XFree(data);
                    windows.append(children[i]);
                }
            }
            XFree(children);
        }
    }
}

QString QtSingletonSysPrivate::login() const
{
    struct passwd *pwd = getpwuid(getuid());
    if (pwd) {
	return QString(pwd->pw_name);
    }
    return QString();
}

void QtSingletonSysPrivate::sendMessageTo(Window wid, Atom sel, Atom typ,
                                          const QString &message) const
{
    if (typ != None) {
        QByteArray umsg = message.toUtf8();
        XChangeProperty(QX11Info::display(),
                        wid,
                        sel, typ, 8,
                        PropModeReplace,
                        reinterpret_cast<unsigned char *>(umsg.data()),
                        umsg.size());
    }
}

void QtSingleApplication::sysInit()
{
    sysd = new QtSingletonSysPrivate;
    sysd->selAtom = None;
    sysd->typAtom = None;
    sysd->listenAtom = None;
    sysd->listener = 0;
    sysd->xpcs.resize(95);
    sysd->xpcs = QByteArray("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~");
    sysd->owner = false;
}

void QtSingleApplication::sysCleanup()
{
    if (sysd) {
        // make the old owner the current owner
        if (sysd->owner) {
            Window newowner = None;

            // We don't want any of the windows to be destroyed
            // while we're looping over them. So we grab the server.
            XGrabServer(QX11Info::display());

            QList<Window> windows;
            sysd->findWindows(windows);
            QList<Window>::ConstIterator it = windows.begin();
            while (it != windows.end()) {
                if (*it != sysd->listener->winId())
                    newowner = *it;
                ++it;
            }
            if (newowner != None)
                sysd->sendMessageTo(newowner,
                                    sysd->selAtom, sysd->typAtom,
                                    "a");

            XUngrabServer(QX11Info::display());

            // Make sure that the server releases the grab as soon
            // as possible.
            XFlush(QX11Info::display());
        }
        delete sysd->listener;
        delete sysd;
    }
}

void QtSingleApplication::initialize(bool activate)
{
    if (sysd->selAtom != None)
	return;

    QByteArray login = sysd->toXPCS(id()+sysd->login());
    sysd->selAtom = XInternAtom(QX11Info::display(),
				login,
				False);
    sysd->typAtom = XInternAtom(QX11Info::display(),
				"_QTSINGLEAPPLICATION",
				False);
    sysd->listenAtom = XInternAtom(QX11Info::display(),
                                   login+"_LISTENER",
                                   False);

    if (sysd->selAtom != None) {
	sysd->listener = new QtSingletonListener(sysd->listenAtom);
        Window lid = sysd->listener->winId();
	XSetSelectionOwner(QX11Info::display(),
			   sysd->selAtom,
			   lid,
			   CurrentTime);
        if (XGetSelectionOwner(QX11Info::display(), sysd->selAtom) == lid)
            sysd->owner = true;
    }

    if (activate)
	connect(this, SIGNAL(messageReceived(const QString&)),
		this, SLOT(activateWindow()));
}

bool QtSingleApplication::isRunning() const
{
    QByteArray login = sysd->toXPCS(id()+sysd->login());
    Atom tmp = XInternAtom(QX11Info::display(),
			   login,
			   True);

    if (tmp != None) {
	WId wid = XGetSelectionOwner(QX11Info::display(),
				     tmp);
	return (wid != None);
    }
    return FALSE;
}

bool QtSingleApplication::sendMessage(const QString &message, int)
{
    QByteArray login = sysd->toXPCS(id()+sysd->login());
    Atom sel = XInternAtom(QX11Info::display(),
                           login,
                           True);
    if (sel == None)
        return FALSE;
    WId wid = XGetSelectionOwner(QX11Info::display(), sel);
    if (wid != None) {
	Atom typ = XInternAtom(QX11Info::display(),
				"_QTSINGLEAPPLICATION",
				True);
        if (typ != None) {
            sysd->sendMessageTo(wid, sel, typ, message);
            return TRUE;
        }
    }
    return FALSE;
}

/*!
    \internal
*/

bool QtSingleApplication::x11EventFilter(XEvent *msg)
{
    if (sysd->listener != 0) {
        if (msg->type == PropertyNotify) {
            XPropertyEvent pev = msg->xproperty;
            if (pev.window == sysd->listener->winId()) {
                if (!sysd->owner) {
                    // We aren't the current owner, but some program changed our
                    // property. This will happen if more than one
                    // QtSingleApplication instance of the same type is running
                    // and one of them closes and we were the previous owner
                    // of the selection. Try to make ourselves the new owner
                    Window lid = sysd->listener->winId();
                    XSetSelectionOwner(QX11Info::display(),
                                       sysd->selAtom,
                                       lid,
                                       CurrentTime);
                    if (XGetSelectionOwner(QX11Info::display(), sysd->selAtom) == lid)
                        sysd->owner = true;
                    return TRUE;
                }
                char* data = 0;
                unsigned long nitems = 0;
                if (sysd->getProperty(&data, &nitems, pev.window,
                                      sysd->selAtom, sysd->typAtom)) {
                    QString str = QString::fromUtf8(reinterpret_cast<char *>(data), nitems);
                    if (data)
                        XFree(data);
                    emit messageReceived(str);

                    return TRUE;
                }
                if (data)
                    XFree(data);
            }
        } else if (msg->type == SelectionClear) {
            if (msg->xselectionclear.selection == sysd->selAtom)
                sysd->owner = false;
        }
    }
    return QApplication::x11EventFilter(msg);
}