summaryrefslogtreecommitdiffstats
path: root/kxkb/extension.cpp
blob: 6946ab54f1db14b884cb3c0039847d64bf322ba0 (plain)
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
#include <string.h>
#include <errno.h>

#include <tqstring.h>
#include <tqmap.h>
#include <tqfile.h>
#include <tqdir.h>

#include <kdebug.h>
#include <kstandarddirs.h>
#include <kprocess.h>

#include <X11/Xatom.h>
#include <X11/Xos.h>
#include <X11/Xlib.h>
#include <X11/XKBlib.h>
#include <X11/extensions/XKBfile.h>
#include <X11/extensions/XKBgeom.h>
#include <X11/extensions/XKM.h>

#include "extension.h"


TQMap<TQString, FILE*> XKBExtension::fileCache;	//TODO: move to class?


static TQString getLayoutKey(const TQString& layout, const TQString& variant)
{
	return layout + "." + variant;
}

TQString XKBExtension::getPrecompiledLayoutFilename(const TQString& layoutKey)
{
	TQString compiledLayoutFileName = m_tempDir + layoutKey + ".xkm";
	return compiledLayoutFileName;
}

XKBExtension::XKBExtension(Display *d)
{
	if ( d == NULL )
		d = qt_xdisplay();
	m_dpy = d;
	
//	TQStringList dirs = KGlobal::dirs()->findDirs ( "tmp", "" );
//	m_tempDir = dirs.count() == 0 ? "/tmp/" : dirs[0];
	m_tempDir = locateLocal("tmp", "");
}

bool XKBExtension::init()
{
    // Verify the Xlib has matching XKB extension.

    int major = XkbMajorVersion;
    int minor = XkbMinorVersion;
	
    if (!XkbLibraryVersion(&major, &minor))
    {
        kdError() << "Xlib XKB extension " << major << '.' << minor <<
            " != " << XkbMajorVersion << '.' << XkbMinorVersion << endl;
        return false;
    }

    // Verify the X server has matching XKB extension.

    int opcode_rtrn;
    int error_rtrn;
    int xkb_opcode;
    if (!XkbQueryExtension(m_dpy, &opcode_rtrn, &xkb_opcode, &error_rtrn,
                         &major, &minor))
    {
        kdError() << "X server XKB extension " << major << '.' << minor <<
            " != " << XkbMajorVersion << '.' << XkbMinorVersion << endl;
        return false;
    }

    // Do it, or face horrible memory corrupting bugs
    ::XkbInitAtoms(NULL);

    return true;
}

void XKBExtension::reset()
{
	for(TQMap<TQString, FILE*>::ConstIterator it = fileCache.begin(); it != fileCache.end(); it++) {
		fclose(*it);
//		remove( TQFile::encodeName(getPrecompiledLayoutFileName(*it)) );
	}
	fileCache.clear();
}

XKBExtension::~XKBExtension()
{
/*	if( m_compiledLayoutFileNames.isEmpty() == false )
		deletePrecompiledLayouts();*/
}

bool XKBExtension::setXkbOptions(const TQString& options, bool resetOld)
{
    if (options.isEmpty())
        return true;

    TQString exe = KGlobal::dirs()->findExe("setxkbmap");
    if (exe.isEmpty())
        return false;

    KProcess p;
    p << exe;
    if( resetOld )
        p << "-option";
    p << "-option" << options;

    p.start(KProcess::Block);

    return p.normalExit() && (p.exitStatus() == 0);
}

bool XKBExtension::setLayout(const TQString& model,
		const TQString& layout, const TQString& variant,
		const TQString& includeGroup, bool useCompiledLayouts)
{
	if( useCompiledLayouts == false ) {
		return setLayoutInternal( model, layout, variant, includeGroup );
	}
	
	const TQString layoutKey = getLayoutKey(layout, variant);
	
	bool res;
	if( fileCache.contains(layoutKey) ) {
		res = setCompiledLayout( layoutKey );
		kdDebug() << "setCompiledLayout " << layoutKey << ": " << res << endl;

		if( res )
			return res;
	}
//	else {
		res = setLayoutInternal( model, layout, variant, includeGroup );
		kdDebug() << "setRawLayout " << layoutKey << ": " << res << endl;
		if( res )
			compileCurrentLayout( layoutKey );
		
//	}
	return res;
}

// private
bool XKBExtension::setLayoutInternal(const TQString& model,
		const TQString& layout, const TQString& variant,
		const TQString& includeGroup)
{
    if ( layout.isEmpty() )
        return false;

	TQString exe = KGlobal::dirs()->findExe("setxkbmap");
	if( exe.isEmpty() ) {
		kdError() << "Can't find setxkbmap" << endl;
		return false;
	}

    TQString fullLayout = layout;
    TQString fullVariant = variant;
	if( includeGroup.isEmpty() == false ) {
        fullLayout = includeGroup;
        fullLayout += ",";
        fullLayout += layout;
		
//    fullVariant = baseVar;
        fullVariant = ",";
        fullVariant += variant;
    }
 
    KProcess p;
    p << exe;
//  p << "-rules" << rule;
	if( model.isEmpty() == false )
		p << "-model" << model;
    p << "-layout" << fullLayout;
    if( !fullVariant.isNull() && !fullVariant.isEmpty() )
        p << "-variant" << fullVariant;

    p.start(KProcess::Block); 

    // reload system-wide hotkey-setup keycode -> keysym maps
    KProcess pXmodmap;
    pXmodmap << "xmodmap" << "/opt/trinity/share/apps/kxkb/system.xmodmap &> /dev/null";
    pXmodmap.start(KProcess::Block); 

    KProcess pXmodmapHome;
    pXmodmapHome << "xmodmap" << TQDir::home().path() + "/.Xmodmap &> /dev/null";
    pXmodmapHome.start(KProcess::Block);

    return p.normalExit() && (p.exitStatus() == 0);
}

bool XKBExtension::setGroup(unsigned int group)
{
	kdDebug() << "Setting group " << group << endl;
	return XkbLockGroup( m_dpy, XkbUseCoreKbd, group );
}

unsigned int XKBExtension::getGroup() const
{
	XkbStateRec xkbState;
	XkbGetState( m_dpy, XkbUseCoreKbd, &xkbState );
	return xkbState.group;
}

/**
 * @brief Gets the current layout in its binary compiled form
 *		and write it to the file specified by 'fileName'
 * @param[in] fileName file to store compiled layout to
 * @return true if no problem, false otherwise
 */
bool XKBExtension::compileCurrentLayout(const TQString &layoutKey)
{
    XkbFileInfo result;
    memset(&result, 0, sizeof(result));
    result.type = XkmKeymapFile;
    XkbReadFromServer(m_dpy, XkbAllMapComponentsMask, XkbAllMapComponentsMask, &result);
	 
	const TQString fileName = getPrecompiledLayoutFilename(layoutKey);

	kdDebug() << "compiling layout " << this << " cache size: " << fileCache.count() << endl;
	if( fileCache.contains(layoutKey) ) {
		kdDebug() << "trashing old compiled layout for " << fileName << endl;
		if( fileCache[ layoutKey ] != NULL )
			fclose( fileCache[ layoutKey ] );	// recompiling - trash the old file
		fileCache.remove(fileName);
	}

	FILE *output = fopen(TQFile::encodeName(fileName), "w");
		
    if ( output == NULL )
    {
		kdWarning() << "Could not open " << fileName << " to precompile: " << strerror(errno) << endl;
        XkbFreeKeyboard(result.xkb, XkbAllControlsMask, True);
        return false;
    }

	if( !XkbWriteXKMFile(output, &result) ) {
		kdWarning() << "Could not write compiled layout to " << fileName << endl;
		fclose(output);
        return false;
	}
	
	fclose(output);	// TODO: can we change mode w/out reopening?
	FILE *input = fopen(TQFile::encodeName(fileName), "r");
	fileCache[ layoutKey ] = input;

	XkbFreeKeyboard(result.xkb, XkbAllControlsMask, True);
    return true;
}

/**
 * @brief takes layout from its compiled binary snapshot in file 
 *	and sets it as current
 * TODO: cache layout in memory rather than in file
 */
bool XKBExtension::setCompiledLayout(const TQString &layoutKey)
{
	FILE *input = NULL;
	
	if( fileCache.contains(layoutKey) ) {
		input = fileCache[ layoutKey ];
	}
	
	if( input == NULL ) {
		kdWarning() << "setCompiledLayout trying to reopen xkb file" << endl;	// should never happen
		const TQString fileName = getPrecompiledLayoutFilename(layoutKey);
		input = fopen(TQFile::encodeName(fileName), "r");
		
		// 	FILE *input = fopen(TQFile::encodeName(fileName), "r");
		if ( input == NULL ) {
			kdDebug() << "Unable to open " << fileName << ": " << strerror(errno) << endl;
			fileCache.remove(layoutKey);
			return false;
		}
	}
	else {
		rewind(input);
	}

    XkbFileInfo result;
    memset(&result, 0, sizeof(result));
	if ((result.xkb = XkbAllocKeyboard())==NULL) {
		kdWarning() << "Unable to allocate memory for keyboard description" << endl;
//      fclose(input);
//		fileCache.remove(layoutKey);
    	return false;
	}
	
    unsigned retVal = XkmReadFile(input, 0, XkmKeymapLegal, &result);
    if (retVal == XkmKeymapLegal)
    {
        // this means reading the Xkm didn't manage to read any section
        kdWarning() << "Unable to load map from file" << endl;
        XkbFreeKeyboard(result.xkb, XkbAllControlsMask, True);
        fclose(input);
		fileCache.remove(layoutKey);
		return false;
    }

	//    fclose(input);	// don't close - goes in cache

    if (XkbChangeKbdDisplay(m_dpy, &result) == Success)
    {
        if (!XkbWriteToServer(&result))
        {
            kdWarning() << "Unable to write the keyboard layout to X display" << endl;
            XkbFreeKeyboard(result.xkb, XkbAllControlsMask, True);
            return false;
        }
    }
    else
    {
        kdWarning() << "Unable prepare the keyboard layout for X display" << endl;
    }

    XkbFreeKeyboard(result.xkb, XkbAllControlsMask, True);
    return true;
}


// Deletes the precompiled layouts stored in temporary files
// void XKBExtension::deletePrecompiledLayouts()
// {
// 	TQMapConstIterator<LayoutUnit, TQString> it, end;
// 	end = m_compiledLayoutFileNames.end();
// 	for (it = m_compiledLayoutFileNames.begin(); it != end; ++it)
// 	{
// 		unlink(TQFile::encodeName(it.data()));
// 	}
// 	m_compiledLayoutFileNames.clear();
// }