summaryrefslogtreecommitdiffstats
path: root/kopete/libkopete/kopetepluginmanager.cpp
blob: dae70b3494ad3019e1c73569b12185a81c682d32 (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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
/*
    kopetepluginmanager.cpp - Kopete Plugin Loader

    Copyright (c) 2002-2003 by Duncan Mac-Vicar Prett <duncan@kde.org>
    Copyright (c) 2002-2003 by Martijn Klingens       <klingens@kde.org>
    Copyright (c) 2002-2004 by Olivier Goffart  <ogoffart @tiscalinet.be>

    Kopete    (c) 2002-2003 by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This library is free software; you can redistribute it and/or         *
    * modify it under the terms of the GNU Lesser General Public            *
    * License as published by the Free Software Foundation; either          *
    * version 2 of the License, or (at your option) any later version.      *
    *                                                                       *
    *************************************************************************
*/

#include "config.h"

#include "kopetepluginmanager.h"

#if defined(HAVE_VALGRIND_H) && !defined(NDEBUG) && defined(__i386__)
// We don't want the per-skin includes, so pretend we have a skin header already
#define __VALGRIND_SOMESKIN_H
#include <valgrind/valgrind.h>
#endif

#include <tqapplication.h>
#include <tqfile.h>
#include <tqregexp.h>
#include <tqtimer.h>
#include <tqvaluestack.h>

#include <kapplication.h>
#include <kdebug.h>
#include <kparts/componentfactory.h>
#include <kplugininfo.h>
#include <ksimpleconfig.h>
#include <kstandarddirs.h>
#include <kstaticdeleter.h>
#include <kurl.h>

#include "kopeteplugin.h"
#include "kopetecontactlist.h"
#include "kopeteaccountmanager.h"

namespace Kopete
{


class PluginManager::Private
{
public:
	Private() : shutdownMode( StartingUp ), isAllPluginsLoaded(false) {}

	// All available plugins, regardless of category, and loaded or not
	TQValueList<KPluginInfo *> plugins;

	// Dict of all currently loaded plugins, mapping the KPluginInfo to
	// a plugin
	typedef TQMap<KPluginInfo *, Plugin *> InfoToPluginMap;
	InfoToPluginMap loadedPlugins;

	// The plugin manager's mode. The mode is StartingUp until loadAllPlugins()
	// has finished loading the plugins, after which it is set to Running.
	// ShuttingDown and DoneShutdown are used during Kopete shutdown by the
	// async unloading of plugins.
	enum ShutdownMode { StartingUp, Running, ShuttingDown, DoneShutdown };
	ShutdownMode shutdownMode;

	// Plugins pending for loading
	TQValueStack<TQString> pluginsToLoad;

	static KStaticDeleter<PluginManager> deleter;

	bool isAllPluginsLoaded;
};

KStaticDeleter<PluginManager> PluginManager::Private::deleter;
PluginManager* PluginManager::s_self = 0L;

PluginManager* PluginManager::self()
{
	if ( !s_self )
		Private::deleter.setObject( s_self, new PluginManager() );

	return s_self;
}

PluginManager::PluginManager() : TQObject( tqApp ), d( new Private )
{
	d->plugins = KPluginInfo::fromServices( KTrader::self()->query( TQString::fromLatin1( "Kopete/Plugin" ),
		TQString::fromLatin1( "[X-Kopete-Version] == 1000900" ) ) );

	// We want to add a reference to the application's event loop so we
	// can remain in control when all windows are removed.
	// This way we can unload plugins asynchronously, which is more
	// robust if they are still doing processing.
	kapp->ref();
}

PluginManager::~PluginManager()
{
	if ( d->shutdownMode != Private::DoneShutdown )
		kdWarning( 14010 ) << k_funcinfo << "Destructing plugin manager without going through the shutdown process! Backtrace is: " << endl << kdBacktrace() << endl;

	// Quick cleanup of the remaining plugins, hope it helps
	// Note that deleting it.data() causes slotPluginDestroyed to be called, which
	// removes the plugin from the list of loaded plugins.
	while ( !d->loadedPlugins.empty() )
	{
		Private::InfoToPluginMap::ConstIterator it = d->loadedPlugins.begin();
		kdWarning( 14010 ) << k_funcinfo << "Deleting stale plugin '" << it.data()->name() << "'" << endl;
		delete it.data();
	}

	delete d;
}

TQValueList<KPluginInfo *> PluginManager::availablePlugins( const TQString &category ) const
{
	if ( category.isEmpty() )
		return d->plugins;

	TQValueList<KPluginInfo *> result;
	TQValueList<KPluginInfo *>::ConstIterator it;
	for ( it = d->plugins.begin(); it != d->plugins.end(); ++it )
	{
		if ( ( *it )->category() == category )
			result.append( *it );
	}

	return result;
}

PluginList PluginManager::loadedPlugins( const TQString &category ) const
{
	PluginList result;
	
	for ( Private::InfoToPluginMap::ConstIterator it = d->loadedPlugins.begin();
	      it != d->loadedPlugins.end(); ++it )
	{
		if ( category.isEmpty() || it.key()->category() == category )
			result.append( it.data() );
	}
	
	return result;
}


KPluginInfo *PluginManager::pluginInfo( const Plugin *plugin ) const
{
	for ( Private::InfoToPluginMap::ConstIterator it = d->loadedPlugins.begin();
	      it != d->loadedPlugins.end(); ++it )
	{
		if ( it.data() == plugin )
			return it.key();
	}
	return 0;
}

void PluginManager::shutdown()
{
	if(d->shutdownMode != Private::Running)
	{
		kdDebug( 14010 ) << k_funcinfo << "called when not running.  / state = " << d->shutdownMode << endl;
		return;
	}

	d->shutdownMode = Private::ShuttingDown;
	

	/* save the contact list now, just in case a change was made very recently
	   and it hasn't autosaved yet
	   from a OO point of view, theses lines should not be there, but i don't
	   see better place -Olivier
	*/
	Kopete::ContactList::self()->save();
	Kopete::AccountManager::self()->save();
	
	// Remove any pending plugins to load, we're shutting down now :)
	d->pluginsToLoad.clear();
	
	// Ask all plugins to unload
	for ( Private::InfoToPluginMap::ConstIterator it = d->loadedPlugins.begin();
	      it != d->loadedPlugins.end(); /* EMPTY */ )
	{
		// Plugins could emit their ready for unload signal directly in response to this,
		// which would tqinvalidate the current iterator. Therefore, we copy the iterator
		// and increment it beforehand.
		Private::InfoToPluginMap::ConstIterator current( it );
		++it;
		// FIXME: a much cleaner approach would be to just delete the plugin now. if it needs
		//  to do some async processing, it can grab a reference to the app itself and create
		//  another object to do it.
		current.data()->aboutToUnload();
	}
	
	// When running under valgrind, don't enable the timer because it will almost
	// certainly fire due to valgrind's much slower processing
#if defined(HAVE_VALGRIND_H) && !defined(NDEBUG) && defined(__i386__)
	if ( RUNNING_ON_VALGRIND )
		kdDebug(14010) << k_funcinfo << "Running under valgrind, disabling plugin unload timeout guard" << endl;
	else
#endif
		TQTimer::singleShot( 3000, this, TQT_SLOT( slotShutdownTimeout() ) );
}

void PluginManager::slotPluginReadyForUnload()
{
	// Using TQObject::sender() is on purpose here, because otherwise all
	// plugins would have to pass 'this' as parameter, which makes the API
	// less clean for plugin authors
	// FIXME: I don't buy the above argument. Add a Kopete::Plugin::emitReadyForUnload(void),
	//        and make readyForUnload be passed a plugin. - Richard
	Plugin *plugin = dynamic_cast<Plugin *>( TQT_TQOBJECT(const_cast<TQT_BASE_OBJECT_NAME*>( sender() ) ) );
	kdDebug( 14010 ) << k_funcinfo << plugin->pluginId() << "ready for unload" << endl;
	if ( !plugin )
	{
		kdWarning( 14010 ) << k_funcinfo << "Calling object is not a plugin!" << endl;
		return;
	}
	
	plugin->deleteLater();
}


void PluginManager::slotShutdownTimeout()
{
	// When we were already done the timer might still fire.
	// Do nothing in that case.
	if ( d->shutdownMode == Private::DoneShutdown )
		return;

	TQStringList remaining;
	for ( Private::InfoToPluginMap::ConstIterator it = d->loadedPlugins.begin(); it != d->loadedPlugins.end(); ++it )
		remaining.append( it.data()->pluginId() );

	kdWarning( 14010 ) << k_funcinfo << "Some plugins didn't shutdown in time!" << endl
		<< "Remaining plugins: " << remaining.join( TQString::fromLatin1( ", " ) ) << endl
		<< "Forcing Kopete shutdown now." << endl;

	slotShutdownDone();
}

void PluginManager::slotShutdownDone()
{
	kdDebug( 14010 ) << k_funcinfo << endl;

	d->shutdownMode = Private::DoneShutdown;

	kapp->deref();
}

void PluginManager::loadAllPlugins()
{
	// FIXME: We need session management here - Martijn

	KConfig *config = KGlobal::config();
	if ( config->hasGroup( TQString::fromLatin1( "Plugins" ) ) )
	{
		TQMap<TQString, bool> pluginsMap;

		TQMap<TQString, TQString> entries = config->entryMap( TQString::fromLatin1( "Plugins" ) );
		TQMap<TQString, TQString>::Iterator it;
		for ( it = entries.begin(); it != entries.end(); ++it )
		{
			TQString key = it.key();
			if ( key.endsWith( TQString::fromLatin1( "Enabled" ) ) )
				pluginsMap.insert( key.left( key.length() - 7 ), (it.data() == TQString::fromLatin1( "true" )) );
		}

		TQValueList<KPluginInfo *> plugins = availablePlugins( TQString() );
		TQValueList<KPluginInfo *>::ConstIterator it2 = plugins.begin();
		TQValueList<KPluginInfo *>::ConstIterator end = plugins.end();
		for ( ; it2 != end; ++it2 )
		{
			// Protocols are loaded automatically so they aren't always in Plugins group. (fixes bug 167113)
			if ( (*it2)->category() == TQString::fromLatin1( "Protocols" ) )
				continue;

			TQString pluginName = (*it2)->pluginName();
			bool inMap = pluginsMap.contains( pluginName );
			if ( (inMap && pluginsMap[pluginName]) || (!inMap && (*it2)->isPluginEnabledByDefault()) )
			{
				if ( !plugin( pluginName ) )
					d->pluginsToLoad.push( pluginName );
			}
			else
			{
				//This happens if the user unloaded plugins with the config plugin page.
				// No real need to be assync because the user usualy unload few plugins
				// compared tto the number of plugin to load in a cold start. - Olivier
				if ( plugin( pluginName ) )
					unloadPlugin( pluginName );
			}
		}
	}
	else
	{
		// we had no config, so we load any plugins that should be loaded by default.
		TQValueList<KPluginInfo *> plugins = availablePlugins( TQString() );
		TQValueList<KPluginInfo *>::ConstIterator it = plugins.begin();
		TQValueList<KPluginInfo *>::ConstIterator end = plugins.end();
		for ( ; it != end; ++it )
		{
			if ( (*it)->isPluginEnabledByDefault() )
				d->pluginsToLoad.push( (*it)->pluginName() );
		}
	}
	// Schedule the plugins to load
	TQTimer::singleShot( 0, this, TQT_SLOT( slotLoadNextPlugin() ) );
}

void PluginManager::slotLoadNextPlugin()
{
	if ( d->pluginsToLoad.isEmpty() )
	{
		if ( d->shutdownMode == Private::StartingUp )
		{
			d->shutdownMode = Private::Running;
			d->isAllPluginsLoaded = true;
			emit allPluginsLoaded();
		}
		return;
	}

	TQString key = d->pluginsToLoad.pop();
	loadPluginInternal( key );

	// Schedule the next run unconditionally to avoid code duplication on the
	// allPluginsLoaded() signal's handling. This has the added benefit that
	// the signal is delayed one event loop, so the accounts are more likely
	// to be instantiated.
	TQTimer::singleShot( 0, this, TQT_SLOT( slotLoadNextPlugin() ) );
}

Plugin * PluginManager::loadPlugin( const TQString &_pluginId, PluginLoadMode mode /* = LoadSync */ )
{
	TQString pluginId = _pluginId;

	// Try to find legacy code
	// FIXME: Find any cases causing this, remove them, and remove this too - Richard
	if ( pluginId.endsWith( TQString::fromLatin1( ".desktop" ) ) )
	{
		kdWarning( 14010 ) << "Trying to use old-style API!" << endl << kdBacktrace() << endl;
		pluginId = pluginId.remove( TQRegExp( TQString::fromLatin1( ".desktop$" ) ) );
	}

	if ( mode == LoadSync )
	{
		return loadPluginInternal( pluginId );
	}
	else
	{
		d->pluginsToLoad.push( pluginId );
		TQTimer::singleShot( 0, this, TQT_SLOT( slotLoadNextPlugin() ) );
		return 0L;
	}
}

Plugin *PluginManager::loadPluginInternal( const TQString &pluginId )
{
	//kdDebug( 14010 ) << k_funcinfo << pluginId << endl;

	KPluginInfo *info = infoForPluginId( pluginId );
	if ( !info )
	{
		kdWarning( 14010 ) << k_funcinfo << "Unable to find a plugin named '" << pluginId << "'!" << endl;
		return 0L;
	}

	if ( d->loadedPlugins.contains( info ) )
		return d->loadedPlugins[ info ];

	int error = 0;
	Plugin *plugin = KParts::ComponentFactory::createInstanceFromQuery<Plugin>( TQString::fromLatin1( "Kopete/Plugin" ),
		TQString::fromLatin1( "[X-KDE-PluginInfo-Name]=='%1'" ).tqarg( pluginId ), this, 0, TQStringList(), &error );

	if ( plugin )
	{
		d->loadedPlugins.insert( info, plugin );
		info->setPluginEnabled( true );

		connect( plugin, TQT_SIGNAL( destroyed( TQObject * ) ), this, TQT_SLOT( slotPluginDestroyed( TQObject * ) ) );
		connect( plugin, TQT_SIGNAL( readyForUnload() ), this, TQT_SLOT( slotPluginReadyForUnload() ) );

		kdDebug( 14010 ) << k_funcinfo << "Successfully loaded plugin '" << pluginId << "'" << endl;

		emit pluginLoaded( plugin );
	}
	else
	{
		switch( error )
		{
		case KParts::ComponentFactory::ErrNoServiceFound:
			kdDebug( 14010 ) << k_funcinfo << "No service implementing the given mimetype "
				<< "and fullfilling the given constraint expression can be found." << endl;
			break;

		case KParts::ComponentFactory::ErrServiceProvidesNoLibrary:
			kdDebug( 14010 ) << "the specified service provides no shared library." << endl;
			break;

		case KParts::ComponentFactory::ErrNoLibrary:
			kdDebug( 14010 ) << "the specified library could not be loaded." << endl;
			break;

		case KParts::ComponentFactory::ErrNoFactory:
			kdDebug( 14010 ) << "the library does not export a factory for creating components." << endl;
			break;

		case KParts::ComponentFactory::ErrNoComponent:
			kdDebug( 14010 ) << "the factory does not support creating components of the specified type." << endl;
			break;
		}

		kdDebug( 14010 ) << k_funcinfo << "Loading plugin '" << pluginId << "' failed, KLibLoader reported error: '" << endl <<
			KLibLoader::self()->lastErrorMessage() << "'" << endl;
	}

	return plugin;
}

bool PluginManager::unloadPlugin( const TQString &spec )
{
	//kdDebug(14010) << k_funcinfo << spec << endl;
	if( Plugin *thePlugin = plugin( spec ) )
	{
		thePlugin->aboutToUnload();
		return true;
	}
	else
		return false;
}



void PluginManager::slotPluginDestroyed( TQObject *plugin )
{
	for ( Private::InfoToPluginMap::Iterator it = d->loadedPlugins.begin();
	      it != d->loadedPlugins.end(); ++it )
	{
		if ( it.data() == plugin )
		{
			d->loadedPlugins.erase( it );
			break;
		}
	}

	if ( d->shutdownMode == Private::ShuttingDown && d->loadedPlugins.isEmpty() )
	{
		// Use a timer to make sure any pending deleteLater() calls have
		// been handled first
		TQTimer::singleShot( 0, this, TQT_SLOT( slotShutdownDone() ) );
	}
}




Plugin* PluginManager::plugin( const TQString &_pluginId ) const
{
	// Hack for compatibility with Plugin::pluginId(), which returns
	// classname() instead of the internal name. Changing that is not easy
	// as it invalidates the config file, the contact list, and most likely
	// other code as well.
	// For now, just transform FooProtocol to kopete_foo.
	// FIXME: In the future we'll need to change this nevertheless to unify
	//        the handling - Martijn
	TQString pluginId = _pluginId;
	if ( pluginId.endsWith( TQString::fromLatin1( "Protocol" ) ) )
		pluginId = TQString::fromLatin1( "kopete_" ) + _pluginId.lower().remove( TQString::fromLatin1( "protocol" ) );
	// End hack

	KPluginInfo *info = infoForPluginId( pluginId );
	if ( !info )
		return 0L;

	if ( d->loadedPlugins.contains( info ) )
		return d->loadedPlugins[ info ];
	else
		return 0L;
}

KPluginInfo * PluginManager::infoForPluginId( const TQString &pluginId ) const
{
	TQValueList<KPluginInfo *>::ConstIterator it;
	for ( it = d->plugins.begin(); it != d->plugins.end(); ++it )
	{
		if ( ( *it )->pluginName() == pluginId )
			return *it;
	}

	return 0L;
}


bool PluginManager::setPluginEnabled( const TQString &_pluginId, bool enabled /* = true */ )
{
	TQString pluginId = _pluginId;

	KConfig *config = KGlobal::config();
	config->setGroup( "Plugins" );

	// FIXME: What is this for? This sort of thing is kconf_update's job - Richard
	if ( !pluginId.startsWith( TQString::fromLatin1( "kopete_" ) ) )
		pluginId.prepend( TQString::fromLatin1( "kopete_" ) );

	if ( !infoForPluginId( pluginId ) )
		return false;

	config->writeEntry( pluginId + TQString::fromLatin1( "Enabled" ), enabled );
	config->sync();

	return true;
}

bool PluginManager::isAllPluginsLoaded() const
{
	return d->isAllPluginsLoaded;
}

} //END namespace Kopete


#include "kopetepluginmanager.moc"