pluginmanager.cpp
1 // -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 2; -*-
23 #include "pluginmanager.h"
24 
25 #include "plugin.h"
26 
27 #include <tqapplication.h>
28 #include <tqfile.h>
29 #include <tqregexp.h>
30 #include <tqtimer.h>
31 #include <tqvaluestack.h>
32 
33 #include <kapplication.h>
34 #include <kdebug.h>
35 #include <kparts/componentfactory.h>
36 #include <kplugininfo.h>
37 #include <ksettings/dispatcher.h>
38 #include <ksimpleconfig.h>
39 #include <kstandarddirs.h>
40 #include <kstaticdeleter.h>
41 #include <kurl.h>
42 
43 
44 namespace Komposer
45 {
46 
47 class PluginManager::Private
48 {
49 public:
50  // All available plugins, regardless of category, and loaded or not
51  TQValueList<KPluginInfo*> plugins;
52 
53  // Dict of all currently loaded plugins, mapping the KPluginInfo to
54  // a plugin
55  TQMap<KPluginInfo*, Plugin*> loadedPlugins;
56 
57  // The plugin manager's mode. The mode is StartingUp until loadAllPlugins()
58  // has finished loading the plugins, after which it is set to Running.
59  // ShuttingDown and DoneShutdown are used during Komposer shutdown by the
60  // async unloading of plugins.
61  enum ShutdownMode { StartingUp, Running, ShuttingDown, DoneShutdown };
62  ShutdownMode shutdownMode;
63 
64  KSharedConfig::Ptr config;
65  // Plugins pending for loading
66  TQValueStack<TQString> pluginsToLoad;
67 };
68 
69 PluginManager::PluginManager( TQObject *parent )
70  : TQObject( parent )
71 {
72  d = new Private;
73 
74  // We want to add a reference to the application's event loop so we
75  // can remain in control when all windows are removed.
76  // This way we can unload plugins asynchronously, which is more
77  // robust if they are still doing processing.
78  kapp->ref();
79  d->shutdownMode = Private::StartingUp;
80 
81  KSettings::Dispatcher::self()->registerInstance( KGlobal::instance(),
82  this, TQT_SLOT( loadAllPlugins() ) );
83 
84  d->plugins = KPluginInfo::fromServices(
85  KTrader::self()->query( TQString::fromLatin1( "Komposer/Plugin" ),
86  TQString::fromLatin1( "[X-Komposer-Version] == 1" ) ) );
87 }
88 
89 PluginManager::~PluginManager()
90 {
91  if ( d->shutdownMode != Private::DoneShutdown ) {
92  slotShutdownTimeout();
93 #if 0
94  kdWarning() << k_funcinfo
95  << "Destructing plugin manager without going through "
96  << "the shutdown process!"
97  << endl
98  << kdBacktrace(10) << endl;
99 #endif
100  }
101 
102  // Quick cleanup of the remaining plugins, hope it helps
103  TQMap<KPluginInfo*, Plugin*>::ConstIterator it;
104  for ( it = d->loadedPlugins.begin(); it != d->loadedPlugins.end(); /* EMPTY */ )
105  {
106  // Remove causes the iterator to become invalid, so pre-increment first
107  TQMap<KPluginInfo*, Plugin*>::ConstIterator nextIt( it );
108  ++nextIt;
109  kdWarning() << k_funcinfo << "Deleting stale plugin '"
110  << it.data()->name() << "'" << endl;
111  delete it.data();
112  it = nextIt;
113  }
114 
115  delete d;
116 }
117 
118 TQValueList<KPluginInfo*>
119 PluginManager::availablePlugins( const TQString &category ) const
120 {
121  if ( category.isEmpty() )
122  return d->plugins;
123 
124  TQValueList<KPluginInfo*> result;
125  TQValueList<KPluginInfo*>::ConstIterator it;
126  for ( it = d->plugins.begin(); it != d->plugins.end(); ++it )
127  {
128  if ( ( *it )->category() == category )
129  result.append( *it );
130  }
131 
132  return result;
133 }
134 
135 TQMap<KPluginInfo*, Plugin*>
136 PluginManager::loadedPlugins( const TQString &category ) const
137 {
138  TQMap<KPluginInfo*, Plugin*> result;
139  TQMap<KPluginInfo*, Plugin*>::ConstIterator it;
140  for ( it = d->loadedPlugins.begin(); it != d->loadedPlugins.end(); ++it )
141  {
142  if ( category.isEmpty() || it.key()->category() == category )
143  result.insert( it.key(), it.data() );
144  }
145 
146  return result;
147 }
148 
149 void
150 PluginManager::shutdown()
151 {
152  d->shutdownMode = Private::ShuttingDown;
153 
154  // Remove any pending plugins to load, we're shutting down now :)
155  d->pluginsToLoad.clear();
156 
157  // Ask all plugins to unload
158  if ( d->loadedPlugins.empty() ) {
159  d->shutdownMode = Private::DoneShutdown;
160  } else {
161  TQMap<KPluginInfo*, Plugin*>::ConstIterator it;
162  for ( it = d->loadedPlugins.begin(); it != d->loadedPlugins.end(); /* EMPTY */ )
163  {
164  // Remove causes the iterator to become invalid, so pre-increment first
165  TQMap<KPluginInfo*, Plugin*>::ConstIterator nextIt( it );
166  ++nextIt;
167  it.data()->aboutToUnload();
168  it = nextIt;
169  }
170  }
171 
172  TQTimer::singleShot( 3000, this, TQT_SLOT(slotShutdownTimeout()) );
173 }
174 
175 void
176 PluginManager::slotPluginReadyForUnload()
177 {
178  // Using TQObject::sender() is on purpose here, because otherwise all
179  // plugins would have to pass 'this' as parameter, which makes the API
180  // less clean for plugin authors
181  Plugin* plugin = dynamic_cast<Plugin*>( const_cast<TQObject*>( sender() ) );
182  if ( !plugin )
183  {
184  kdWarning() << k_funcinfo << "Calling object is not a plugin!" << endl;
185  return;
186 
187  }
188  kdDebug()<<"manager unloading"<<endl;
189  plugin->deleteLater();
190 }
191 
192 void
193 PluginManager::slotShutdownTimeout()
194 {
195  // When we were already done the timer might still fire.
196  // Do nothing in that case.
197  if ( d->shutdownMode == Private::DoneShutdown )
198  return;
199 
200 #ifndef NDEBUG
201  TQStringList remaining;
202  for ( TQMap<KPluginInfo*, Plugin*>::ConstIterator it = d->loadedPlugins.begin();
203  it != d->loadedPlugins.end(); ++it )
204  remaining.append( it.key()->pluginName() );
205 
206  kdWarning() << k_funcinfo << "Some plugins didn't shutdown in time!" << endl
207  << "Remaining plugins: "
208  << remaining.join( TQString::fromLatin1( ", " ) ) << endl
209  << "Forcing Komposer shutdown now." << endl;
210 #endif
211 
212  slotShutdownDone();
213 }
214 
215 void
216 PluginManager::slotShutdownDone()
217 {
218  d->shutdownMode = Private::DoneShutdown;
219 
220  kapp->deref();
221 }
222 
223 void
224 PluginManager::loadAllPlugins()
225 {
226  // FIXME: We need session management here - Martijn
227 
228  if ( !d->config )
229  d->config = KSharedConfig::openConfig( "komposerrc" );
230 
231  TQMap<TQString, TQString> entries = d->config->entryMap(
232  TQString::fromLatin1( "Plugins" ) );
233 
234  TQMap<TQString, TQString>::Iterator it;
235  for ( it = entries.begin(); it != entries.end(); ++it )
236  {
237  TQString key = it.key();
238  if ( key.endsWith( TQString::fromLatin1( "Enabled" ) ) )
239  {
240  key.setLength( key.length() - 7 );
241  //kdDebug() << k_funcinfo << "Set " << key << " to " << it.data() << endl;
242 
243  if ( it.data() == TQString::fromLatin1( "true" ) )
244  {
245  if ( !plugin( key ) )
246  d->pluginsToLoad.push( key );
247  }
248  else
249  {
250  // FIXME: Does this ever happen? As loadAllPlugins is only called on startup
251  // I'd say 'no'. If it does, it should be made async
252  // though. - Martijn
253  if ( plugin( key ) )
254  unloadPlugin( key );
255  }
256  }
257  }
258 
259  // Schedule the plugins to load
260  TQTimer::singleShot( 0, this, TQT_SLOT( slotLoadNextPlugin() ) );
261 }
262 
263 void PluginManager::slotLoadNextPlugin()
264 {
265  if ( d->pluginsToLoad.isEmpty() )
266  {
267  if ( d->shutdownMode == Private::StartingUp )
268  {
269  d->shutdownMode = Private::Running;
270  emit allPluginsLoaded();
271  }
272  return;
273  }
274 
275  TQString key = d->pluginsToLoad.pop();
276  loadPluginInternal( key );
277 
278  // Schedule the next run unconditionally to avoid code duplication on the
279  // allPluginsLoaded() signal's handling. This has the added benefit that
280  // the signal is delayed one event loop, so the accounts are more likely
281  // to be instantiated.
282  TQTimer::singleShot( 0, this, TQT_SLOT( slotLoadNextPlugin() ) );
283 }
284 
285 Plugin*
286 PluginManager::loadPlugin( const TQString &pluginId,
287  PluginLoadMode mode /* = LoadSync */ )
288 {
289  if ( mode == LoadSync ) {
290  return loadPluginInternal( pluginId );
291  } else {
292  d->pluginsToLoad.push( pluginId );
293  TQTimer::singleShot( 0, this, TQT_SLOT( slotLoadNextPlugin() ) );
294  return 0;
295  }
296 }
297 
298 Plugin*
299 PluginManager::loadPluginInternal( const TQString &pluginId )
300 {
301  KPluginInfo* info = infoForPluginId( pluginId );
302  if ( !info ) {
303  kdWarning() << k_funcinfo << "Unable to find a plugin named '"
304  << pluginId << "'!" << endl;
305  return 0;
306  }
307 
308  if ( d->loadedPlugins.contains( info ) )
309  return d->loadedPlugins[ info ];
310 
311  int error = 0;
312  Plugin *plugin = KParts::ComponentFactory::createInstanceFromQuery<Komposer::Plugin>(
313  TQString::fromLatin1( "Komposer/Plugin" ),
314  TQString::fromLatin1( "[X-KDE-PluginInfo-Name]=='%1'" ).arg( pluginId ),
315  this, 0, TQStringList(), &error );
316 
317  if ( plugin ) {
318  d->loadedPlugins.insert( info, plugin );
319  info->setPluginEnabled( true );
320 
321  connect( plugin, TQT_SIGNAL(destroyed(TQObject*)),
322  this, TQT_SLOT(slotPluginDestroyed(TQObject*)) );
323  connect( plugin, TQT_SIGNAL(readyForUnload()),
324  this, TQT_SLOT(slotPluginReadyForUnload()) );
325 
326  kdDebug() << k_funcinfo << "Successfully loaded plugin '"
327  << pluginId << "'" << endl;
328 
329  emit pluginLoaded( plugin );
330  } else {
331  switch ( error ) {
332  case KParts::ComponentFactory::ErrNoServiceFound:
333  kdDebug() << k_funcinfo << "No service implementing the given mimetype "
334  << "and fullfilling the given constraint expression can be found."
335  << endl;
336  break;
337 
338  case KParts::ComponentFactory::ErrServiceProvidesNoLibrary:
339  kdDebug() << "the specified service provides no shared library." << endl;
340  break;
341 
342  case KParts::ComponentFactory::ErrNoLibrary:
343  kdDebug() << "the specified library could not be loaded." << endl;
344  break;
345 
346  case KParts::ComponentFactory::ErrNoFactory:
347  kdDebug() << "the library does not export a factory for creating components."
348  << endl;
349  break;
350 
351  case KParts::ComponentFactory::ErrNoComponent:
352  kdDebug() << "the factory does not support creating components "
353  << "of the specified type."
354  << endl;
355  break;
356  }
357 
358  kdDebug() << k_funcinfo << "Loading plugin '" << pluginId
359  << "' failed, KLibLoader reported error: '"
360  << KLibLoader::self()->lastErrorMessage()
361  << "'" << endl;
362  }
363 
364  return plugin;
365 }
366 
367 bool
368 PluginManager::unloadPlugin( const TQString &spec )
369 {
370  TQMap<KPluginInfo*, Plugin*>::ConstIterator it;
371  for ( it = d->loadedPlugins.begin(); it != d->loadedPlugins.end(); ++it )
372  {
373  if ( it.key()->pluginName() == spec )
374  {
375  it.data()->aboutToUnload();
376  return true;
377  }
378  }
379 
380  return false;
381 }
382 
383 void
384 PluginManager::slotPluginDestroyed( TQObject *plugin )
385 {
386  TQMap<KPluginInfo*, Plugin*>::Iterator it;
387  for ( it = d->loadedPlugins.begin(); it != d->loadedPlugins.end(); ++it )
388  {
389  if ( it.data() == plugin )
390  {
391  d->loadedPlugins.erase( it );
392  break;
393  }
394  }
395 
396  if ( d->shutdownMode == Private::ShuttingDown && d->loadedPlugins.isEmpty() )
397  {
398  // Use a timer to make sure any pending deleteLater() calls have
399  // been handled first
400  TQTimer::singleShot( 0, this, TQT_SLOT(slotShutdownDone()) );
401  }
402 }
403 
404 Plugin*
405 PluginManager::plugin( const TQString &pluginId ) const
406 {
407  KPluginInfo *info = infoForPluginId( pluginId );
408  if ( !info )
409  return 0;
410 
411  if ( d->loadedPlugins.contains( info ) )
412  return d->loadedPlugins[ info ];
413  else
414  return 0;
415 }
416 
417 TQString
418 PluginManager::pluginName( const Plugin *plugin ) const
419 {
420  TQMap<KPluginInfo*, Plugin*>::ConstIterator it;
421  for ( it = d->loadedPlugins.begin(); it != d->loadedPlugins.end(); ++it )
422  {
423  if ( it.data() == plugin )
424  return it.key()->name();
425  }
426 
427  return TQString::fromLatin1( "Unknown" );
428 }
429 
430 TQString
431 PluginManager::pluginId( const Plugin *plugin ) const
432 {
433  TQMap<KPluginInfo*, Plugin*>::ConstIterator it;
434  for ( it = d->loadedPlugins.begin(); it != d->loadedPlugins.end(); ++it )
435  {
436  if ( it.data() == plugin )
437  return it.key()->pluginName();
438  }
439 
440  return TQString::fromLatin1( "unknown" );
441 }
442 
443 TQString
444 PluginManager::pluginIcon( const Plugin *plugin ) const
445 {
446  TQMap<KPluginInfo*, Plugin*>::ConstIterator it;
447  for ( it = d->loadedPlugins.begin(); it != d->loadedPlugins.end(); ++it )
448  {
449  if ( it.data() == plugin )
450  return it.key()->icon();
451  }
452 
453  return TQString::fromLatin1( "Unknown" );
454 }
455 
456 KPluginInfo*
457 PluginManager::infoForPluginId( const TQString &pluginId ) const
458 {
459  TQValueList<KPluginInfo*>::ConstIterator it;
460  for ( it = d->plugins.begin(); it != d->plugins.end(); ++it )
461  {
462  if ( ( *it )->pluginName() == pluginId )
463  return *it;
464  }
465 
466  return 0;
467 }
468 
469 bool
470 PluginManager::setPluginEnabled( const TQString &pluginId, bool enabled /* = true */ )
471 {
472  if ( !d->config )
473  d->config = KSharedConfig::openConfig( "komposerrc" );
474 
475  d->config->setGroup( "Plugins" );
476 
477 
478  if ( !infoForPluginId( pluginId ) )
479  return false;
480 
481  d->config->writeEntry( pluginId + TQString::fromLatin1( "Enabled" ), enabled );
482  d->config->sync();
483 
484  return true;
485 }
486 
487 }
488 
489 #include "pluginmanager.moc"