Exemple #1
0
getModule KonqSidebarTree::getPluginFactory(QString name)
{
  if (!pluginFactories.contains(name))
  {
    KLibLoader *loader = KLibLoader::self();
    QString libName    = pluginInfo[name];
    KLibrary *lib      = loader->library(QFile::encodeName(libName));
    if (lib)
    {
      // get the create_ function
      QString factory = "create_" + libName;
      void *create    = lib->symbol(QFile::encodeName(factory));
      if (create)
      {
        getModule func = (getModule)create;
        pluginFactories.insert(name, func);
        kdDebug()<<"Added a module"<<endl;
      }
      else
      {
        kdWarning()<<"No create function found in"<<libName<<endl;
      }
    }
    else
      kdWarning() << "Module " << libName << " can't be loaded!" << endl;
  }

  return pluginFactories[name];
}
/**
 * Attempt to load a plugin and see if it has the symbol create_audiocd_encoders.
 * @param libFileName file to try to load.
 * @returns pointer to the symbol or NULL
 */
void *loadPlugin(const QString &libFileName)
{
#ifdef DEBUG
    kdDebug(7117) << "Trying to load library. File: \"" << libFileName.latin1() << "\"." << endl;
#endif
    KLibLoader *loader = KLibLoader::self();
    if (!loader)
        return NULL;
#ifdef DEBUG
    kdDebug(7117) << "We have a loader. File:  \"" << libFileName.latin1() << "\"." << endl;
#endif
    KLibrary *lib = loader->library(libFileName.latin1());
    if (!lib)
        return NULL;
#ifdef DEBUG
    kdDebug(7117) << "We have a library. File: \"" << libFileName.latin1() << "\"." << endl;
#endif
    void *cplugin = lib->symbol("create_audiocd_encoders");
    if (!cplugin)
        return NULL;
#ifdef DEBUG
    kdDebug(7117) << "We have a plugin. File:  \"" << libFileName.latin1() << "\"." << endl;
#endif
    return cplugin;
}
Exemple #3
0
KLibFactory* KLibLoader::factory( const char* name )
{
    KLibrary* lib = library( name );
    if ( !lib )
        return 0;

    return lib->factory();
}
void KLibLoaderTest::testLibrary()
{
    KLibrary *lib = KLibLoader::self()->library(s_kpluginFactoryModule);
    QVERIFY(lib);
    QVERIFY(lib->isLoaded());
    QCOMPARE(QFileInfo(lib->fileName()).canonicalFilePath(),
             MODULE_PATH(s_kpluginFactoryModule));
}
Exemple #5
0
void addBackEnd::activatedAddMenu(int id)
{
	kdDebug() << "activatedAddMenu: " << QString("%1").arg(id) << endl;
	if (((uint)id) == libNames.size())
		doRollBack();
	if(((uint)id) >= libNames.size())
		return;

	KLibLoader *loader = KLibLoader::self();

        // try to load the library
	QString libname = *libNames.at(id);
        KLibrary *lib = loader->library(QFile::encodeName(libname));
        if (lib)
       	{
		// get the create_ function
		QString factory("add_");
		factory = factory+(*libNames.at(id));
		void *add = lib->symbol(QFile::encodeName(factory));

		if (add)
		{
			//call the add function
			bool (*func)(QString*, QString*, QMap<QString,QString> *);
			QMap<QString,QString> map;
			func = (bool (*)(QString*, QString*, QMap<QString,QString> *)) add;
			QString *tmp = new QString("");
			if (func(tmp,libParam.at(id),&map))
			{
				QString myFile = findFileName(tmp,m_universal,m_currentProfile);

				if (!myFile.isEmpty())
				{
					kdDebug() <<"trying to save to file: "<<myFile << endl;
					KSimpleConfig scf(myFile,false);
					scf.setGroup("Desktop Entry");
					for (QMap<QString,QString>::ConstIterator it = map.begin(); it != map.end(); ++it) {
						kdDebug() <<"writing:"<<it.key()<<" / "<<it.data()<<endl;
						scf.writePathEntry(it.key(), it.data());
					}
					scf.sync();
					emit updateNeeded();

				} else {
					kdWarning() << "No unique filename found" << endl;
				}
			} else {
				kdWarning() << "No new entry (error?)" << endl;
			}
			delete tmp;
		}
	} else {
		kdWarning() << "libname:" << libNames.at(id)
			<< " doesn't specify a library!" << endl;
	}
}
Exemple #6
0
QObject* Manager::module(const QString& modulename)
{
    if( d->modules.contains(modulename) ) {
        QObject* obj = d->modules[modulename];
        if( obj )
            return obj;
    }

    if( modulename.isEmpty() || modulename.contains( QRegExp("[^a-zA-Z0-9]") ) ) {
        qrosswarning( QString("Invalid module name '%1'").arg(modulename) );
        return 0;
    }

    QByteArray libraryname = QString("qrossmodule%1").arg(modulename).toLower().toLatin1();

#if 0
    KLibLoader* loader = KLibLoader::self();
    KLibrary* lib = loader->library( libraryname, QLibrary::ExportExternalSymbolsHint );
    if( ! lib ) { //FIXME this fallback-code should be in KLibLoader imho.
        lib = loader->library( QString("lib%1").arg(libraryname), QLibrary::ExportExternalSymbolsHint );
        if( ! lib ) {
            qrosswarning( QString("Failed to load module '%1': %2").arg(modulename).arg(loader->lastErrorMessage()) );
            return 0;
        }
    }

    def_module_func func;
    func = (def_module_func) lib->resolveFunction("qrossmodule");
    if( ! func ) {
        qrosswarning( QString("Failed to determinate init function in module '%1'").arg(modulename) );
        return 0;
    }

    QObject* module = (QObject*) (func)(); // call the function
    lib->unload(); // unload the library

    if( ! module ) {
        qrosswarning( QString("Failed to load module object '%1'").arg(modulename) );
        return 0;
    }
#else
    if( void* funcPtr = loadLibrary(libraryname, "qrossmodule") ) {
        def_module_func func = (def_module_func) funcPtr;
        Q_ASSERT( func );
        QObject* module = (QObject*) (func)(); // call the function
        Q_ASSERT( module );
        //qrossdebug( QString("Manager::module Module successfully loaded: modulename=%1 module.objectName=%2 module.className=%3").arg(modulename).arg(module->objectName()).arg(module->metaObject()->className()) );
        d->modules.insert(modulename, module);
        return module;
    }
    else {
        qrosswarning( QString("Failed to load module '%1'").arg(modulename) );
    }
#endif
    return 0;
}
void KLibLoaderTest::testLibrary_hints()
{
    // the hints will be ignored, but we want to check the call will still compile
    KLibrary *lib = KLibLoader::self()->library(s_kpluginFactoryModule,
            QLibrary::ResolveAllSymbolsHint);
    QVERIFY(lib);
    QVERIFY(lib->isLoaded());
    QCOMPARE(QFileInfo(lib->fileName()).canonicalFilePath(),
             MODULE_PATH(s_kpluginFactoryModule));
}
Exemple #8
0
const TDEInstance *Factory::partInstanceFromLibrary( const TQCString &libraryName )
{
    KLibrary *library = KLibLoader::self()->library( libraryName );
    if ( !library )
        return 0;
    KLibFactory *factory = library->factory();
    if ( !factory )
        return 0;
    KParts::Factory *pfactory = tqt_dynamic_cast<KParts::Factory *>( factory );
    if ( !pfactory )
        return 0;
    return pfactory->partInstance();
}
FormatPlugin *FormatFactory::format(const QString &type)
{
    FormatPlugin *format = 0;

    if(type.isEmpty())
        return 0;

    if(type == "vcard")
    {
        format = new VCardFormatPlugin;
        format->setType(type);
        format->setNameLabel(i18n("vCard"));
        format->setDescriptionLabel(i18n("vCard Format"));
        return format;
    }

    FormatInfo *fi = mFormatList[type];
    if(!fi)
        return 0;
    QString libName = fi->library;

    KLibrary *library = openLibrary(libName);
    if(!library)
        return 0;

    void *format_func = library->symbol("format");

    if(format_func)
    {
        format = ((FormatPlugin * (*)())format_func)();
        format->setType(type);
        format->setNameLabel(fi->nameLabel);
        format->setDescriptionLabel(fi->descriptionLabel);
    }
    else
    {
        kdDebug(5700) << "'" << libName << "' is not a format plugin." << endl;
        return 0;
    }

    return format;
}
Exemple #10
0
KPanelExtension* ExtensionProxy::loadExtension(const AppletInfo& info)
{
    KLibLoader* loader = KLibLoader::self();
    KLibrary* lib = loader->library(TQFile::encodeName(info.library()));

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

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

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

    return init_ptr(0, info.configFile());
}
Exemple #11
0
Plugin*
PluginManager::createFromService( const KService::Ptr service )
{
    debug() << "Trying to load: " << service->library() << endl;

    //get the library loader instance
    KLibLoader *loader = KLibLoader::self();
    //try to load the specified library
    KLibrary *lib = loader->globalLibrary( QFile::encodeName( service->library() ) );

    if ( !lib ) {
        KMessageBox::error( 0, i18n( "<p>KLibLoader could not load the plugin:<br/><i>%1</i></p>"
                                     "<p>Error message:<br/><i>%2</i></p>" )
                               .arg( service->library() )
                               .arg( loader->lastErrorMessage() ) );
        return 0;
    }
    //look up address of init function and cast it to pointer-to-function
    Plugin* (*create_plugin)() = ( Plugin* (*)() ) lib->symbol( "create_plugin" );

    if ( !create_plugin ) {
        warning() << k_funcinfo << "create_plugin == NULL\n";
        return 0;
    }
    //create plugin on the heap
    Plugin* plugin = create_plugin();

    //put plugin into store
    StoreItem item;
    item.plugin = plugin;
    item.library = lib;
    item.service = service;
    m_store.push_back( item );

    dump( service );
    return plugin;
}
Exemple #12
0
KWMailMergeDataSource *KWMailMergeDataBase::loadPlugin(const QString& name)
{
  if (!name.isEmpty())
  {
      // get the library loader instance

      KLibLoader *loader = KLibLoader::self();

      // try to load the library
      QString libname=name;
//      QString libname("lib%1");
      KLibrary *lib = loader->library(QFile::encodeName(libname));
      if (lib) {
          // get the create_ function
          QString factory=QString("create_%1").arg(name);
          void *create = lib->symbol(QFile::encodeName(factory));

          if (create)
          {
              // create the module
              KWMailMergeDataSource * (*func)(KInstance*,QObject*);
              func = (KWMailMergeDataSource* (*)(KInstance*,QObject*)) create;
              KWMailMergeDataSource *tmpsource =func(KWFactory::instance(),this);
              if (tmpsource)
              {
                  QDataStream tmpstream(tmpsource->info,IO_WriteOnly);
                  tmpstream<<name;
              }
              return tmpsource;
          }
      }
      kdWarning() << "Couldn't load plugin " << name <<  endl;
  }
  else
      kdWarning()<< "No plugin name specified" <<endl;
  return 0;
}
Exemple #13
0
bool KHotKeys::init()
{
    khotkeys_inited = true;
    KLibrary *lib = KLibLoader::self()->library("kcm_khotkeys.la");
    if(lib == NULL)
        return false;

    khotkeys_init_2 = (void (*)(void))(lib->symbol("khotkeys_init"));
    khotkeys_cleanup_2 = (void (*)(void))(lib->symbol("khotkeys_cleanup"));
    khotkeys_get_menu_entry_shortcut_2 = (QString(*)(const QString &))(lib->symbol("khotkeys_get_menu_entry_shortcut"));
    khotkeys_change_menu_entry_shortcut_2 = (QString(*)(const QString &, const QString &))(lib->symbol("khotkeys_change_menu_entry_shortcut"));
    khotkeys_menu_entry_moved_2 = (bool (*)(const QString &, const QString &))(lib->symbol("khotkeys_menu_entry_moved"));
    khotkeys_menu_entry_deleted_2 = (void (*)(const QString &))(lib->symbol("khotkeys_menu_entry_deleted"));
    if(khotkeys_init_2 && khotkeys_cleanup_2 && khotkeys_get_menu_entry_shortcut_2 && khotkeys_change_menu_entry_shortcut_2
       && khotkeys_menu_entry_moved_2 && khotkeys_menu_entry_deleted_2)
    {
        khotkeys_init_2();
        khotkeys_present = true;
        return true;
    }
    return false;
}
Exemple #14
0
void KCMStyle::styleSpecificConfig()
{
	TQString libname = styleEntries[currentStyle()]->configPage;

	// Use KLibLoader to get the library, handling
	// any errors that arise
	KLibLoader* loader = KLibLoader::self();

	KLibrary* library = loader->library( TQFile::encodeName(libname) );
	if (!library)
	{
		KMessageBox::detailedError(this,
			i18n("There was an error loading the configuration dialog for this style."),
			loader->lastErrorMessage(),
			i18n("Unable to Load Dialog"));
		return;
	}

	void* allocPtr = library->symbol("allocate_tdestyle_config");

	if (!allocPtr)
	{
		KMessageBox::detailedError(this,
			i18n("There was an error loading the configuration dialog for this style."),
			loader->lastErrorMessage(),
			i18n("Unable to Load Dialog"));
		return;
	}

	//Create the container dialog
	StyleConfigDialog* dial = new StyleConfigDialog(this, styleEntries[currentStyle()]->name);
	dial->enableButtonSeparator(true);

	typedef TQWidget*(* factoryRoutine)( TQWidget* parent );

	//Get the factory, and make the widget.
	factoryRoutine factory      = (factoryRoutine)(allocPtr); //Grmbl. So here I am on my
	//"never use C casts" moralizing streak, and I find that one can't go void* -> function ptr
	//even with a reinterpret_cast.

	TQWidget*       pluginConfig = factory( dial );

	//Insert it in...
	dial->setMainWidget( pluginConfig );

	//..and connect it to the wrapper
	connect(pluginConfig, TQT_SIGNAL(changed(bool)), dial, TQT_SLOT(setDirty(bool)));
	connect(dial, TQT_SIGNAL(defaults()), pluginConfig, TQT_SLOT(defaults()));
	connect(dial, TQT_SIGNAL(save()), pluginConfig, TQT_SLOT(save()));

	if (dial->exec() == TQDialog::Accepted  && dial->isDirty() ) {
		// Force re-rendering of the preview, to apply settings
		switchStyle(currentStyle(), true);

		//For now, ask all TDE apps to recreate their styles to apply the setitngs
		KIPC::sendMessageAll(KIPC::StyleChanged);

		// We call setStyleDirty here to make sure we force style re-creation
		setStyleDirty();
	}

	delete dial;
}
// tests whether the plugin can be loaded
bool KDecorationPlugins::canLoad(QString nameStr, KLibrary **loadedLib)
{
    if (nameStr.isEmpty())
        return false; // we can't load that

    // Check if this library is not already loaded.
    if (pluginStr == nameStr) {
        if (loadedLib) {
            *loadedLib = library;
        }
        return true;
    }

    KConfigGroup group(config, QString("Style"));
    if (group.readEntry<bool>("NoPlugin", false)) {
        error(i18n("Loading of window decoration plugin library disabled in configuration."));
        return false;
    }

    KLibrary libToFind(nameStr);
    QString path = libToFind.fileName();
    kDebug(1212) << "kwin : path " << path << " for " << nameStr;

    if (path.isEmpty()) {
        return false;
    }

    // Try loading the requested plugin
    KLibrary *lib = new KLibrary(path);

    if (!lib)
        return false;

    // TODO this would be a nice shortcut, but for "some" reason QtCurve with wrong ABI slips through
    // TODO figure where it's loaded w/o being unloaded and check whether that can be fixed.
#if 0
    if (lib->isLoaded()) {
        if (loadedLib) {
            *loadedLib = lib;
        }
        return true;
    }
#endif
    // so we check whether this lib was loaded before and don't unload it in case
    bool wasLoaded = lib->isLoaded();

    KDecorationFactory*(*cptr)() = NULL;
    int (*vptr)()  = NULL;
    int deco_version = 0;
    KLibrary::void_function_ptr version_func = lib->resolveFunction("decoration_version");
    if (version_func) {
        vptr = (int(*)())version_func;
        deco_version = vptr();
    } else {
        // block some decos known to link the unstable API but (for now) let through other legacy stuff
        const bool isLegacyStableABI = !(nameStr.contains("qtcurve", Qt::CaseInsensitive) ||
                                         nameStr.contains("crystal", Qt::CaseInsensitive) ||
                                         nameStr.contains("oxygen", Qt::CaseInsensitive));
        if (isLegacyStableABI) {
            // it's an old build of a legacy decoration that very likely uses the stable API
            // so we just set the API version to the current one
            // TODO: remove for 4.9.x or 4.10 - this is just to cover recompiles
            deco_version = KWIN_DECORATION_API_VERSION;
        }
        kWarning(1212) << QString("****** The library %1 has no API version ******").arg(path);
        kWarning(1212) << "****** Please use the KWIN_DECORATION macro in extern \"C\" to get this decoration loaded in future versions of kwin";
    }
    if (deco_version != KWIN_DECORATION_API_VERSION) {
        if (version_func)
            kWarning(1212) << i18n("The library %1 has wrong API version %2", path, deco_version);
        lib->unload();
        delete lib;
        return false;
    }

    KLibrary::void_function_ptr create_func = lib->resolveFunction("create_factory");
    if (create_func)
        cptr = (KDecorationFactory * (*)())create_func;

    if (!cptr) {
        kDebug(1212) << i18n("The library %1 is not a KWin plugin.", path);
        lib->unload();
        delete lib;
        return false;
    }

    if (loadedLib) {
        *loadedLib = lib;
    } else {
        if (!wasLoaded)
            lib->unload();
        delete lib;
    }
    return true;
}
Exemple #16
0
void ThumbnailProtocol::get(const KURL &url)
{
    m_mimeType = metaData("mimeType");
    kdDebug(7115) << "Wanting MIME Type:" << m_mimeType << endl;
#ifdef THUMBNAIL_HACK
    // ### HACK
    bool direct=false;
    if (m_mimeType.isEmpty())
    {
        kdDebug(7115) << "PATH: " << url.path() << endl;
        TQFileInfo info(url.path());
        if (info.isDir())
        {
            // We cannot process a directory
            error(TDEIO::ERR_IS_DIRECTORY,url.path());
            return;
        }
        else if (!info.exists())
        {
            // The file does not exist
            error(TDEIO::ERR_DOES_NOT_EXIST,url.path());
            return;
        }
        else if (!info.isReadable())
        {
            // The file is not readable!
            error(TDEIO::ERR_COULD_NOT_READ,url.path());
            return;
        }
        m_mimeType = KMimeType::findByURL(url)->name();
        kdDebug(7115) << "Guessing MIME Type:" << m_mimeType << endl;
        direct=true; // thumbnail: was probably called from Konqueror
    }
#endif

    if (m_mimeType.isEmpty())
    {
        error(TDEIO::ERR_INTERNAL, i18n("No MIME Type specified."));
        return;
    }

    m_width = metaData("width").toInt();
    m_height = metaData("height").toInt();
    int iconSize = metaData("iconSize").toInt();

    if (m_width < 0 || m_height < 0)
    {
        error(TDEIO::ERR_INTERNAL, i18n("No or invalid size specified."));
        return;
    }
#ifdef THUMBNAIL_HACK
    else if (!m_width || !m_height)
    {
        kdDebug(7115) << "Guessing height, width, icon size!" << endl;
        m_width=128;
        m_height=128;
        iconSize=128;
    }
#endif

    if (!iconSize)
        iconSize = TDEGlobal::iconLoader()->currentSize(TDEIcon::Desktop);
    if (iconSize != m_iconSize)
        m_iconDict.clear();
    m_iconSize = iconSize;

    m_iconAlpha = metaData("iconAlpha").toInt();
    if (m_iconAlpha)
        m_iconAlpha = (m_iconAlpha << 24) | 0xffffff;

    TQImage img;

    TDEConfigGroup group( TDEGlobal::config(), "PreviewSettings" );

    
    // ### KFMI
    bool kfmiThumb = false;
    if (group.readBoolEntry( "UseFileThumbnails", true )) {
        KService::Ptr service =
            KServiceTypeProfile::preferredService( m_mimeType, "KFilePlugin");

        if ( service && service->isValid() && /*url.isLocalFile() && */
            service->property("SupportsThumbnail").toBool())
        {
            KFileMetaInfo info(url.path(), m_mimeType, KFileMetaInfo::Thumbnail);
            if (info.isValid())
            {
                KFileMetaInfoItem item = info.item(KFileMimeTypeInfo::Thumbnail);
                if (item.isValid() && item.value().type() == TQVariant::Image)
                {
                    img = item.value().toImage();
                    kdDebug(7115) << "using KFMI for the thumbnail\n";
                    kfmiThumb = true;
                }
            }
        }
    }
    ThumbCreator::Flags flags = ThumbCreator::None;

    if (!kfmiThumb)
    {
        kdDebug(7115) << "using thumb creator for the thumbnail\n";
        TQString plugin = metaData("plugin");
#ifdef THUMBNAIL_HACK
        if (plugin.isEmpty())
        {
            TDETrader::OfferList plugins = TDETrader::self()->query("ThumbCreator");
            TQMap<TQString, KService::Ptr> mimeMap;
    
            for (TDETrader::OfferList::ConstIterator it = plugins.begin(); it != plugins.end(); ++it)
            {
                TQStringList mimeTypes = (*it)->property("MimeTypes").toStringList();
                for (TQStringList::ConstIterator mt = mimeTypes.begin(); mt != mimeTypes.end(); ++mt)
                {
                    if  ((*mt)==m_mimeType)
                    {
                        plugin=(*it)->library();
                        break;
                    }
                }
                if (!plugin.isEmpty())
                    break;
            }
        }
        kdDebug(7115) << "Guess plugin: " << plugin << endl;
#endif
        if (plugin.isEmpty())
        {
            error(TDEIO::ERR_INTERNAL, i18n("No plugin specified."));
            return;
        }
        
        ThumbCreator *creator = m_creators[plugin];
        if (!creator)
        {
            // Don't use KLibFactory here, this is not a TQObject and
            // neither is ThumbCreator
            KLibrary *library = KLibLoader::self()->library(TQFile::encodeName(plugin));
            if (library)
            {
                newCreator create = (newCreator)library->symbol("new_creator");
                if (create)
                    creator = create();
            }
            if (!creator)
            {
                error(TDEIO::ERR_INTERNAL, i18n("Cannot load ThumbCreator %1").arg(plugin));
                return;
            }
            m_creators.insert(plugin, creator);
        }

        if (!creator->create(url.path(), m_width, m_height, img))
        {
            error(TDEIO::ERR_INTERNAL, i18n("Cannot create thumbnail for %1").arg(url.path()));
            return;
        }
        flags = creator->flags();
    }

    if (img.width() > m_width || img.height() > m_height)
    {
        double imgRatio = (double)img.height() / (double)img.width();
        if (imgRatio > (double)m_height / (double)m_width)
            img = img.smoothScale( int(TQMAX((double)m_height / imgRatio, 1)), m_height);
        else
            img = img.smoothScale(m_width, int(TQMAX((double)m_width * imgRatio, 1)));
    }

// ### FIXME
#ifndef USE_KINSTANCE
    if (flags & ThumbCreator::DrawFrame)
    {
        TQPixmap pix;
        pix.convertFromImage(img);
        int x2 = pix.width() - 1;
        int y2 = pix.height() - 1;
        // paint a black rectangle around the "page"
        TQPainter p;
        p.begin( &pix );
        p.setPen( TQColor( 48, 48, 48 ));
        p.drawLine( x2, 0, x2, y2 );
        p.drawLine( 0, y2, x2, y2 );
        p.setPen( TQColor( 215, 215, 215 ));
        p.drawLine( 0, 0, x2, 0 );
        p.drawLine( 0, 0, 0, y2 );
        p.end();

        const TQBitmap *mask = pix.mask();
        if ( mask ) // need to update it so we can see the frame
        {
            TQBitmap bitmap( *mask );
            TQPainter painter;
            painter.begin( &bitmap );
            painter.drawLine( x2, 0, x2, y2 );
            painter.drawLine( 0, y2, x2, y2 );
            painter.drawLine( 0, 0, x2, 0 );
            painter.drawLine( 0, 0, 0, y2 );
            painter.end();

            pix.setMask( bitmap );
        }

        img = pix.convertToImage();
    }
#endif

    if ((flags & ThumbCreator::BlendIcon) && TDEGlobal::iconLoader()->alphaBlending(TDEIcon::Desktop))
    {
        // blending the mimetype icon in
        TQImage icon = getIcon();

        int x = img.width() - icon.width() - 4;
        x = TQMAX( x, 0 );
        int y = img.height() - icon.height() - 6;
        y = TQMAX( y, 0 );
        KImageEffect::blendOnLower( x, y, icon, img );
    }

    if (img.isNull())
    {
        error(TDEIO::ERR_INTERNAL, i18n("Failed to create a thumbnail."));
        return;
    }

    const TQString shmid = metaData("shmid");
    if (shmid.isEmpty())
    {
#ifdef THUMBNAIL_HACK
        if (direct)
        {
            // If thumbnail was called directly from Konqueror, then the image needs to be raw
            //kdDebug(7115) << "RAW IMAGE TO STREAM" << endl;
            TQBuffer buf;
            if (!buf.open(IO_WriteOnly))
            {
                error(TDEIO::ERR_INTERNAL, i18n("Could not write image."));
                return;
            }
            img.save(&buf,"PNG");
            buf.close();
            data(buf.buffer());
        }
        else
#endif
        {
            TQByteArray imgData;
            TQDataStream stream( imgData, IO_WriteOnly );
            //kdDebug(7115) << "IMAGE TO STREAM" << endl;
            stream << img;
            data(imgData);
        }
    }
    else
    {
        TQByteArray imgData;
        TQDataStream stream( imgData, IO_WriteOnly );
        //kdDebug(7115) << "IMAGE TO SHMID" << endl;
        void *shmaddr = shmat(shmid.toInt(), 0, 0);
        if (shmaddr == (void *)-1)
        {
            error(TDEIO::ERR_INTERNAL, i18n("Failed to attach to shared memory segment %1").arg(shmid));
            return;
        }
        if (img.width() * img.height() > m_width * m_height)
        {
            error(TDEIO::ERR_INTERNAL, i18n("Image is too big for the shared memory segment"));
            shmdt((char*)shmaddr);
            return;
        }
        if( img.depth() != 32 )           // TDEIO::PreviewJob and this code below completely
            img = img.convertDepth( 32 ); // ignores colortable :-/, so make sure there is none
        stream << img.width() << img.height() << img.depth()
               << img.hasAlphaBuffer();
        memcpy(shmaddr, img.bits(), img.numBytes());
        shmdt((char*)shmaddr);
        data(imgData);
    }
    finished();
}
Exemple #17
0
bool Greeter::loadGreetPlugin()
{
    if (m_pluginHandle.library) {
        //we were locked once before, so all the plugin loading's done already
        //FIXME should I be unloading the plugin on unlock instead?
        return true;
    }
    for (QStringList::ConstIterator it = m_plugins.constBegin(); it != m_plugins.constEnd(); ++it) {
        GreeterPluginHandle plugin;
        KLibrary *lib = new KLibrary( (*it)[0] == QLatin1Char( '/' ) ? *it : QLatin1String( "kgreet_" ) + *it );
        if (lib->fileName().isEmpty()) {
            kWarning(1212) << "GreeterPlugin " << *it << " does not exist" ;
            delete lib;
            continue;
        }
        if (!lib->load()) {
            kWarning(1212) << "Cannot load GreeterPlugin " << *it << " (" << lib->fileName() << ")" ;
            delete lib;
            continue;
        }
        plugin.library = lib;
        plugin.info = (KGreeterPluginInfo *)lib->resolveFunction( "kgreeterplugin_info" );
        if (!plugin.info ) {
            kWarning(1212) << "GreeterPlugin " << *it << " (" << lib->fileName() << ") is no valid greet widget plugin" ;
            lib->unload();
            delete lib;
            continue;
        }
        if (plugin.info->method && !m_method.isEmpty() && m_method != QLatin1String(  plugin.info->method )) {
            kDebug(1212) << "GreeterPlugin " << *it << " (" << lib->fileName() << ") serves " << plugin.info->method << ", not " << m_method;
            lib->unload();
            delete lib;
            continue;
        }
        if (!plugin.info->init( m_method, getConf, this )) {
            kDebug(1212) << "GreeterPlugin " << *it << " (" << lib->fileName() << ") refuses to serve " << m_method;
            lib->unload();
            delete lib;
            continue;
        }
        kDebug(1212) << "GreeterPlugin " << *it << " (" << plugin.info->method << ", " << plugin.info->name << ") loaded";
        m_pluginHandle = plugin;
        return true;
    }
    return false;
}
void PukeController::messageHandler(int fd, PukeMessage *pm) { 
  widgetId wI, wIret;
  wI.fd = fd;
  wI.iWinId = pm->iWinId;

  commandStruct *cs;

  cs = qidCommandTable[pm->iCommand];

  if(cs != NULL){
    (this->*(cs->cmd))(fd,pm);
  }
  else if(pm->iCommand == PUKE_WIDGET_CREATE){
    wIret = wI;
    wIret.iWinId = createWidget(wI, pm).iWinId; // Create the acutal pw

    PukeMessage pmRet;
    pmRet.iCommand = PUKE_WIDGET_CREATE_ACK;
    pmRet.iWinId = wIret.iWinId;
    pmRet.iArg = 0;
    pmRet.cArg = strdup(pm->cArg);
    pmRet.iTextSize = strlen(pm->cArg);
    emit outputMessage(fd, &pmRet);
    free(pmRet.cArg);
  }
  else if(pm->iCommand == PUKE_WIDGET_LOAD){
    PukeMessage pmRet = *pm;
    KLibrary *library;
    PObject *(*wc)(CreateArgs &ca);
    widgetCreate *wC;

    if(widgetCF[pm->iArg]){
      pmRet.iCommand = -pm->iCommand;
      pmRet.iTextSize = 0;
      emit outputMessage(fd, &pmRet);
      return;
    }

    if(pm->iTextSize == 0){
      emit(errorCommandFailed(-pm->iCommand, 1));
      return;
    }

    QString libName = "ksirc/lib"+QString::fromLatin1(pm->cArg);
    if (libName.right(3) == ".so")
       libName = libName.left(libName.length()-2)+"la";

    library = KLibLoader::self()->library(libName);
    if (!library) {
      emit(errorCommandFailed(-pm->iCommand, 1));
      return;
    }
    wc =  (PObject *(*)(CreateArgs &ca) )
        library->symbol("createWidget");

    wC = new widgetCreate;
    wC->wc = wc;
    wC->library = library;
    widgetCF.insert(pm->iArg, wC);

    pmRet.iCommand = -pm->iCommand;
    pmRet.iTextSize = 0;
    emit outputMessage(fd, &pmRet);
  }
  else if(pm->iCommand == PUKE_WIDGET_UNLOAD){
    if(widgetCF[pm->iArg]){
//      delete widgetCF[pm->iArg]->library;
      widgetCF.remove(pm->iArg);
      pm->iCommand = -pm->iCommand;
      emit outputMessage(fd, pm);
    }
  }
  else{
    if(checkWidgetId(&wI) == TRUE){
      WidgetList[wI.fd]->find(wI.iWinId)->pwidget->messageHandler(fd, pm);
    }
    else{
      PukeMessage pmRet;
      pmRet.iCommand = PUKE_INVALID;
      pmRet.iWinId = wI.iWinId;
      pmRet.iArg = 0;
      pmRet.iTextSize = 0;
      emit outputMessage(fd, &pmRet);
    }
  }
}
Exemple #19
0
    bool isBreakableThai( const QChar *string, const int pos, const int len)
    {
        static QTextCodec *thaiCodec = QTextCodec::codecForMib(2259);
	//printf("Entering isBreakableThai with pos = %d\n", pos);

#ifndef HAVE_LIBTHAI
	
	KLibrary *lib = 0;

        /* load libthai dynamically */
	if (( !th_brk ) && thaiCodec  ) {
	    printf("Try to load libthai dynamically...\n");
            KLibLoader *loader = KLibLoader::self();
            lib = loader->library("libthai");
            if (lib && lib->hasSymbol("th_brk")) {
                th_brk = (th_brk_def) lib->symbol("th_brk");
            } else {
                // indication that loading failed and we shouldn't try to load again
		printf("Error, can't load libthai...\n");
                thaiCodec = 0;
                if (lib)
                    lib->unload();
            }
        }

        if (!th_brk ) {
            return true;
        }
#endif

	if (!cache ) {
            cache = new ThaiCache;
#ifndef HAVE_LIBTHAI
            cache->library = lib;
#endif
	}

        // build up string of thai chars
        if ( string != cache->string ) {
            //fprintf(stderr,"new string found (not in cache), calling libthai\n");
            QCString cstr = thaiCodec->fromUnicode( QConstString(string,len).string());
            //printf("About to call libthai::th_brk with str: %s",cstr.data());

            cache->numwbrpos = th_brk((const unsigned char*) cstr.data(), cache->wbrpos, cache->allocated);
            //fprintf(stderr,"libthai returns with value %d\n",cache->numwbrpos);
            if (cache->numwbrpos > cache->allocated) {
                cache->allocated = cache->numwbrpos;
                cache->wbrpos = (int *)realloc(cache->wbrpos, cache->allocated*sizeof(int));
                cache->numwbrpos = th_brk((const unsigned char*) cstr.data(), cache->wbrpos, cache->allocated);
            }
	    if ( len > cache->numisbreakable ) {
		cache->numisbreakable=len;
                cache->isbreakable = (int *)realloc(cache->isbreakable, cache->numisbreakable*sizeof(int));
	    }
	    for (int i = 0 ; i < len ; ++i) {
		cache->isbreakable[i] = 0;
	    }
            if ( cache->numwbrpos > 0 ) {
            	for (int i = cache->numwbrpos-1; i >= 0; --i) {
                	cache->isbreakable[cache->wbrpos[i]] = 1;
		}
	    }
            cache->string = string;
        }
	//printf("Returning %d\n", cache->isbreakable[pos]);
	return cache->isbreakable[pos];
    }
Exemple #20
0
Plugin *
PluginLoader::loadPlugin(const QString &name)
{
    KLibrary *lib = NULL;
    KLibFactory *factory = NULL;
    Plugin *plugin = NULL;
    PluginMap::iterator it;
    bool success = true;

    // if the plugin has already been loaded, increment
    // its reference and return.
    if((it = _plugins.find(name)) != _plugins.end()) {
        plugin = it.data();
        plugin->ref();
        return plugin;
    }

    // use KLibLoader to get a reference to the library
    lib = KLibLoader::self()->library(name.latin1());
    if(!lib) {
        kdError() << "failed loading plugin library " << name << endl;
        success = false;
    }

    // get the factory from the library
    if(success) {
        factory = lib->factory();
        if(!factory) {
            kdError() << "failed to find factory for " << name << endl;
            success = false;
        }
    }

    // use the factory to create the plugin
    if(success) {
        plugin = dynamic_cast<Plugin *>(factory->create((QObject*)0, name.latin1()));
        if(!plugin) {
            kdError() << "failed to create a plugin object for " << name << endl;
            success = false;
        }
        else {
            // we have to register the plugin here, otherwise, we can get
            // recursive loads
            _plugins[name] = plugin;
            _categories[plugin->category()].append(plugin);
        }
    }

    // initialize the plugin
    if(success && plugin) {
        success = plugin->init();
        if(!success) {
            // on failure, delete the plugin. this should cause the
            // library to unload.
            kdError() << "failure initializing " << name << endl;
            _categories[plugin->category()].remove(plugin);
            _plugins.remove(name);
            delete plugin;
        }
    }

    // finally, finally connect to the destroyed signal and keep a
    // reference to it
    if(success) {
        plugin->ref();
        connect(plugin, SIGNAL(destroyed(QObject *)), SLOT(slotDestroyed(QObject *)));
    }

    return plugin;
}
Exemple #21
0
int main(int argc, char **argv)
{
	KAboutData about("kdedtester", I18N_NOOP("KDED Module tester"), version, description,
		     KAboutData::License_GPL, "(C) 2004 Diego 'Flameeyes' Pettenò", 0, 0, "*****@*****.**");
	about.addAuthor( "Diego 'Flameeyes' Pettenò", 0, "*****@*****.**" );
	KCmdLineArgs::init(argc, argv, &about);
	KCmdLineArgs::addCmdLineOptions( options );
	KApplication app;

	// no session.. just start up normally
	KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
	
	if ( args->count() == 0 )
	{
		kdError() << "You must call kdedtester with a valid kded module name." << endl;
		return -1;
	}

	/// @todo do something with the command line args here
	QCString modulename = args->arg(0);
	args->clear();
	
	if ( modulename.isEmpty() )
	{
		kdError() << "You must call kdedtester with a valid kded module name." << endl;
		return -1;
	}
	
	KService::Ptr s = KService::serviceByDesktopPath("kded/"+modulename+".desktop");
	if ( ! s || s->library().isEmpty() )
	{
		kdError() << "Unable to load the service for requested module." << endl;
		return -2;
	}
	
	// get the library loader instance
	KLibLoader *loader = KLibLoader::self();
	
	QVariant v = s->property("X-KDE-Factory");
	QString factory = v.isValid() ? v.toString() : QString::null;
	if (factory.isEmpty())
		factory = s->library();

	factory = "create_" + factory;
	QString libname = "kded_"+s->library();
	
	kdWarning() << "Recap: the factory is '" << factory << "', and the library '" << libname << "'." << endl;

	KLibrary *lib = loader->library(QFile::encodeName(libname));
	if ( ! lib )
	{
		kdWarning() << "Library not found, trying '" << libname << "' instead" << endl
			<< "KLibLoader says: " << loader->lastErrorMessage() << endl;
		
		libname.prepend("lib");
		lib = loader->library(QFile::encodeName(libname));
	}
	
	if ( ! lib )
	{
		kdError() << "Library still not found. Exiting." << endl
			<< "KLibLoader says: " << loader->lastErrorMessage() << endl;
		return -3;
	}
	
	void *create = lib->symbol(QFile::encodeName(factory));
	if ( ! create )
	{
		kdError() << "Unable to find factory symbol into library. Exiting." << endl;
		loader->unloadLibrary(QFile::encodeName(libname));
		return -4;
	}
	
        KDEDModule* (*func)(const QCString &);
        func = (KDEDModule* (*)(const QCString &)) create;
	
	KDEDModule *module = func(modulename);
	if ( ! module )
	{
		kdError() << "Factory returned NULL module. Exiting." << endl;
		loader->unloadLibrary(QFile::encodeName(libname));
		return -5;
	}
	
	delete module;
	loader->unloadLibrary(QFile::encodeName(libname));
	kdWarning() << "Module loaded (and already unloaded) correctly." << endl;
	return 0;
}