summaryrefslogtreecommitdiffstats
path: root/kicker/proxy/appletproxy.cpp
blob: daf6312d9c86daee8e44807ed0ace3823f33cbd0 (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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
/*****************************************************************

Copyright (c) 2000 Matthias Elter <elter@kde.org>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTDHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

******************************************************************/

#include <stdlib.h>

#include <tqstring.h>
#include <tqfile.h>
#include <tqobjectlist.h>
#include <qxembed.h>

#include <tdeapplication.h>
#include <tdeglobal.h>
#include <klibloader.h>
#include <tdelocale.h>
#include <kstandarddirs.h>
#include <tdecmdlineargs.h>
#include <kdebug.h>
#include <tdemessagebox.h>
#include <kpanelapplet.h>
#include <tdeaboutdata.h>
#include <tqfileinfo.h>
#include <dcopclient.h>
#include <twin.h>

#include "appletinfo.h"

#include "appletproxy.h"
#include "appletproxy.moc"

#include <X11/Xlib.h>

KPanelApplet::Position directionToPosition( int d )
{
    switch( d ) {
    case 1:   return KPanelApplet::pTop;
    case 2:   return KPanelApplet::pRight;
    case 3:   return KPanelApplet::pLeft;
    default:
    case 0:   return KPanelApplet::pBottom;
    }
}

static TDECmdLineOptions options[] =
{
  { "+desktopfile", I18N_NOOP("The applet's desktop file"), 0 },
  { "configfile <file>", I18N_NOOP("The config file to be used"), 0 },
  { "callbackid <id>", I18N_NOOP("DCOP callback id of the applet container"), 0 },
  TDECmdLineLastOption
};

extern "C" KDE_EXPORT int kdemain( int argc, char ** argv )
{
    TDEAboutData aboutData( "kicker", I18N_NOOP("Panel applet proxy.")
                          , "v0.1.0"
                          ,I18N_NOOP("Panel applet proxy.")
                          , TDEAboutData::License_BSD
                          , "(c) 2000, The KDE Developers");
    TDECmdLineArgs::init(argc, argv, &aboutData );
    aboutData.addAuthor("Matthias Elter",0, "elter@kde.org");
    aboutData.addAuthor("Matthias Ettrich",0, "ettrich@kde.org");
    TDEApplication::addCmdLineOptions();
    TDECmdLineArgs::addCmdLineOptions(options); // Add our own options.

    TDEApplication a;
    a.disableSessionManagement();

    TDEGlobal::dirs()->addResourceType("applets", TDEStandardDirs::kde_default("data") +
				     "kicker/applets");

    // setup proxy object
    AppletProxy proxy(0, "appletproxywidget");

    // parse cmdline args
    TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();

    if ( args->count() == 0 )
        TDECmdLineArgs::usage(i18n("No desktop file specified") );

    // Perhaps we should use a konsole-like solution here (shell, list of args...)
    TQString desktopfile( args->arg(0) );

    // load applet DSO
    if ( !TQFile::exists( desktopfile ) &&
         !desktopfile.endsWith( ".desktop" ) )
        desktopfile.append( ".desktop" );

    if ( !TQFile::exists( desktopfile ) )
        desktopfile = locate( "applets", desktopfile ).latin1();

    proxy.loadApplet( desktopfile, args->getOption("configfile"));

    // dock into our applet container
    TQCString callbackid = args->getOption( "callbackid");
    if ( callbackid.isEmpty() )
	proxy.showStandalone();
    else
	proxy.dock(args->getOption("callbackid"));

    return a.exec();
}

AppletProxy::AppletProxy(TQObject* parent, const char* name)
  : TQObject(parent, name)
  , DCOPObject("AppletProxy")
  , _info(0)
  , _applet(0)
{
    // try to attach to DCOP server
    if (!kapp->dcopClient()->attach()) {
	kdError() << "Failed to attach to DCOP server." << endl;
        KMessageBox::error(0,
                           i18n("The applet proxy could not be started due to DCOP communication problems."),
                           i18n("Applet Loading Error"));
	exit(0);
    }

    if (kapp->dcopClient()->registerAs("applet_proxy", true) == 0) {
	kdError() << "Failed to register at DCOP server." << endl;
        KMessageBox::error(0,
                           i18n("The applet proxy could not be started due to DCOP registration problems."),
                           i18n("Applet Loading Error"));
	exit(0);
    }

    _bg = TQPixmap();
}

AppletProxy::~AppletProxy()
{
    kapp->dcopClient()->detach();
    delete _info;
    delete _applet;
}

void AppletProxy::loadApplet(const TQString& desktopFile, const TQString& configFile)
{
    TQString df;

    // try simple path first
    TQFileInfo finfo( desktopFile );
    if ( finfo.exists() ) {
	df = finfo.absFilePath();
    } else {
	// locate desktop file
	df = TDEGlobal::dirs()->findResource("applets", desktopFile);
    }

    TQFile file(df);
    // does the config file exist?
    if (df.isNull() || !file.exists()) {
	kdError() << "Failed to locate applet desktop file: " << desktopFile << endl;
        KMessageBox::error(0,
                           i18n("The applet proxy could not load the applet information from %1.").arg(desktopFile), 
                           i18n("Applet Loading Error"));
	exit(0);
    }

    // create AppletInfo instance
    delete _info;
    _info = new AppletInfo(df);

    // set the config file
    if (!configFile.isNull())
	_info->setConfigFile(configFile);

    // load applet DSO
    _applet = loadApplet(*_info);

    // sanity check
    if (!_applet)
    {
	kdError() << "Failed to load applet: " << _info->library() << endl;
        KMessageBox::error(0,
                           i18n("The applet %1 could not be loaded via the applet proxy.").arg(_info->name()), 
                           i18n("Applet Loading Error"));
	exit(0);
    }

    // connect updateLayout signal
    connect(_applet, TQ_SIGNAL(updateLayout()), TQ_SLOT(slotUpdateLayout()));
    // connect requestFocus signal
    connect(_applet, TQ_SIGNAL(requestFocus()), TQ_SLOT(slotRequestFocus()));
}

KPanelApplet* AppletProxy::loadApplet(const AppletInfo& info)
{
    KLibLoader* loader = KLibLoader::self();
    KLibrary* lib = loader->library(TQFile::encodeName(info.library()));

    if (!lib)
    {
        kdWarning() << "cannot open applet: " << info.library()
                    << " because of " << loader->lastErrorMessage() << endl;
        return 0;
    }

    KPanelApplet* (*init_ptr)(TQWidget *, const TQString&);
    init_ptr = (KPanelApplet* (*)(TQWidget *, const TQString&))lib->symbol( "init" );

    if (!init_ptr)
    {
        kdWarning() << info.library() << " is not a kicker plugin!" << endl;
        return 0;
    }

    return init_ptr(0, info.configFile());
}

void AppletProxy::repaintApplet(TQWidget* widget) 
{
    widget->repaint();
 
    const TQObjectList children = widget->childrenListObject();

    if (children.isEmpty())
    {
        return;
    }

    TQObjectList::iterator it = children.begin();
    for (; it != children.end(); ++it)
    {
        TQWidget *w = dynamic_cast<TQWidget*>(*it);
        if (w)
        {
            repaintApplet(w);
        }
    }
}

void AppletProxy::dock(const TQCString& callbackID)
{
    kdDebug(1210) << "Callback ID: " << callbackID << endl;

    _callbackID = callbackID;

    // try to attach to DCOP server
    DCOPClient* dcop = kapp->dcopClient();

    dcop->setNotifications(true);
    connect(dcop, TQ_SIGNAL(applicationRemoved(const TQCString&)),
	    TQ_SLOT(slotApplicationRemoved(const TQCString&)));

    WId win;

    // get docked
    {
	TQCString replyType;
	TQByteArray data, replyData;
	TQDataStream dataStream( data, IO_WriteOnly );

	int actions = 0;
	if (_applet) actions = _applet->actions();
	dataStream << actions;

	int type = 0;
	if (_applet) type = static_cast<int>(_applet->type());
	dataStream << type;

	// we use "call" to know whether it was sucessful

	int screen_number = 0;
	if (tqt_xdisplay())
	    screen_number = DefaultScreen(tqt_xdisplay());
	TQCString appname;
	if (screen_number == 0)
	    appname = "kicker";
	else
	    appname.sprintf("kicker-screen-%d", screen_number);

	if ( !dcop->call(appname, _callbackID, "dockRequest(int,int)",
			 data, replyType, replyData ) )
        {
            kdError() << "Failed to dock into the panel." << endl;
            KMessageBox::error(0,
                               i18n("The applet proxy could not dock into the panel due to DCOP communication problems."),
                               i18n("Applet Loading Error"));
            exit(0);
        }

	TQDataStream reply( replyData, IO_ReadOnly );
	reply >> win;

        // request background
        dcop->send(appname, _callbackID, "getBackground()", data);
    }

    if (win)
    {
        if (_applet)
        {
            _applet->hide();
        }
        QXEmbed::initialize();
        QXEmbed::embedClientIntoWindow(_applet, win);
    }
    else
    {
        kdError() << "Failed to dock into the panel." << endl;
        KMessageBox::error(0,
                           i18n("The applet proxy could not dock into the panel."),
                           i18n("Applet Loading Error"));
        delete _applet;
        _applet = 0;

        exit(0);
    }

}

bool AppletProxy::process(const TQCString &fun, const TQByteArray &data,
                          TQCString& replyType, TQByteArray &replyData)
{
    if ( fun == "widthForHeight(int)" )
	{
	    TQDataStream dataStream( data, IO_ReadOnly );
	    int height;
	    dataStream >> height;
	    TQDataStream reply( replyData, IO_WriteOnly );
	    replyType = "int";

	    if (!_applet)
		reply << height;
	    else
		reply << _applet->widthForHeight(height);

	    return true;
	}
    else if ( fun == "heightForWidth(int)" )
	{
	    TQDataStream dataStream( data, IO_ReadOnly );
	    int width;
	    dataStream >> width;
	    TQDataStream reply( replyData, IO_WriteOnly );
	    replyType = "int";

	    if(!_applet)
		reply << width;
	    else
		reply << _applet->heightForWidth(width);

	    return true;
	}
    else if ( fun == "setDirection(int)" )
	{
	    TQDataStream dataStream( data, IO_ReadOnly );
	    int dir;
	    dataStream >> dir;

	    if(_applet) {
		_applet->setPosition(directionToPosition(dir));
	    }
	    return true;
	}
    else if ( fun == "setAlignment(int)" )
	{
	    TQDataStream dataStream( data, IO_ReadOnly );
	    int alignment;
	    dataStream >> alignment;

	    if(_applet) {
		_applet->setAlignment( (KPanelApplet::Alignment)alignment );
	    }
	    return true;
	}
    else if ( fun == "removedFromPanel()" )
	{
            delete _applet;
            _applet = 0;
            exit(0);
	    return true;
	}
    else if ( fun == "about()" )
	{
	    if(_applet) _applet->action( KPanelApplet::About );
	    return true;
	}
    else if ( fun == "help()" )
	{
	    if(_applet) _applet->action( KPanelApplet::Help );
	    return true;
	}
    else if ( fun == "preferences()" )
	{
	    if(_applet) _applet->action( KPanelApplet::Preferences );
	    return true;
	}
    else if (fun == "reportBug()" )
  {
      if(_applet) _applet->action( KPanelApplet::ReportBug );
      return true;
  }
    else if ( fun == "actions()" )
	{
	    TQDataStream reply( replyData, IO_WriteOnly );
	    int actions = 0;
	    if(_applet) actions = _applet->actions();
	    reply << actions;
	    replyType = "int";
	    return true;
	}
    else if ( fun == "type()" )
	{
	    TQDataStream reply( replyData, IO_WriteOnly );
	    int type = 0;
	    if (_applet) type = static_cast<int>(_applet->type());
	    reply << type;
	    replyType = "int";
	    return true;
	}
    else if ( fun == "setBackground(TQPixmap)" )
        {
            TQDataStream dataStream( data, IO_ReadOnly ); 
            dataStream >> _bg;
            if(_applet)
                if ( _bg.isNull() ) { // no transparency
		    _applet->unsetPalette();
		    _applet->repaint();
		}
                else { //transparency
		    _applet->blockSignals(true);
		    _applet->setBackgroundMode(TQt::FixedPixmap);
		    _applet->setPaletteBackgroundPixmap(_bg);
		    repaintApplet(_applet);
		    _applet->blockSignals(false);
                }
            return true;
        }
    return false;
}

void AppletProxy::slotUpdateLayout()
{
    if(_callbackID.isNull()) return;

    TQByteArray data;
    int screen_number = 0;
    if (tqt_xdisplay())
	screen_number = DefaultScreen(tqt_xdisplay());
    TQCString appname;
    if (screen_number == 0)
	appname = "kicker";
    else
	appname.sprintf("kicker-screen-%d", screen_number);

    kapp->dcopClient()->send(appname, _callbackID, "updateLayout()", data);
}

void AppletProxy::slotRequestFocus()
{
    if(_callbackID.isNull()) return;

    TQByteArray data;
    int screen_number = 0;
    if (tqt_xdisplay())
	screen_number = DefaultScreen(tqt_xdisplay());
    TQCString appname;
    if (screen_number == 0)
	appname = "kicker";
    else
	appname.sprintf("kicker-screen-%d", screen_number);

    kapp->dcopClient()->send(appname, _callbackID, "requestFocus()", data);
}

void AppletProxy::slotApplicationRemoved(const TQCString& appId)
{
    int screen_number = 0;
    if (tqt_xdisplay())
	screen_number = DefaultScreen(tqt_xdisplay());
    TQCString appname;
    if (screen_number == 0)
	appname = "kicker";
    else
	appname.sprintf("kicker-screen-%d", screen_number);

    if(appId == appname) {
	kdDebug(1210) << "Connection to kicker lost, shutting down" << endl;
	kapp->quit();
    }
}

void AppletProxy::showStandalone()
{
    if (!_applet)
    {
        return;
    }

    _applet->resize( _applet->widthForHeight( 48 ), 48 );
    _applet->setMinimumSize( _applet->size() );
    _applet->setCaption( _info->name() );
    kapp->setMainWidget( _applet );
    _applet->show();
}