Development/Tutorials/KIO Slaves/Hello World

From KDE TechBase
Revision as of 12:40, 24 August 2009 by Icewind (talk | contribs)

Understanding

A kioslave allows you to represent any kind of storage in a way you want. As an example, the kio_http kioslave loads data from the network over the http (protocol) and shows it rendered as html. Technically, a kioslave is a shared object plus its description. E.g. the imap4 kioslave consist of the following files:

tweedleburg:/usr/local # find -iname "*imap4*"
./lib/kde4/kio_imap4.so
./share/kde4/services/imap4.protocol

The files

We want to write a "hello world" kioslave here. This can be seen as a learning exercise and as a template for future programming projects.

CMakeLists.txt

PROJECT( tutorial )
FIND_PACKAGE(KDE4 REQUIRED)
INCLUDE_DIRECTORIES( ${KDE4_INCLUDES} . )

set(kio_hello_PART_SRCS
   hello.cpp)

kde4_add_plugin(kio_hello ${kio_hello_PART_SRCS})

target_link_libraries(kio_hello ${KDE4_KIO_LIBS})

install(TARGETS kio_hello  DESTINATION ${PLUGIN_INSTALL_DIR})


########### install files ###############

install(FILES hello.protocol DESTINATION ${SERVICES_INSTALL_DIR})

hello.h

  1. ifndef HELLO_H
  2. define HELLO_H
  1. include <kio/slavebase.h>

/**

 This class implements a hello-world kioslave
*/

class hello : public KIO::SlaveBase {

 public:
   hello( const QByteArray &pool, const QByteArray &app );
   void get( const KUrl &url );

};

  1. endif

hello.cpp

  1. include "hello.h"
  2. include <kdebug.h>
  3. include <kcomponentdata.h>


extern "C" int KDE_EXPORT kdemain( int argc, char **argv ) {

 kDebug(7000) << "Entering function";
 KComponentData instance( "kio_hello" );
 if (argc != 4) 
 {
   fprintf( stderr, "Usage: kio_hello protocol domain-socket1 domain-socket2\n");
   exit( -1 );
 }
 hello slave( argv[2], argv[3] );
 slave.dispatchLoop();
 return 0;

}

void hello::get( const KUrl &url ) {

 kDebug(7000) << "Entering function";
 mimeType( "text/plain" );
 QByteArray str( "Hello_world" );
 data( str );
 finished();
 kDebug(7000) << "Leaving function";

}

hello::hello( const QByteArray &pool, const QByteArray &app )

SlaveBase( "hello", pool, app ) {}

hello.protocol

[Protocol]
DocPath=kioslave/kio_hello.html 
exec=kio_hello
input=none
output=filesystem
protocol=hello
reading=true

Compile the stuff

g++ -shared -lkdeui -lkio -lkdecore -fPIC -I/usr/local/include hello.cpp -o kio_hello.so

this does not complile if the qt headers are not in /usr/local/include

On my system I could fix it by changing -I/usr/local/include to -I/usr/include/qt4

Install the stuff

Find out where your protocols are lying:

kde4-config --path services
/usr/share/kde4/services/
cp kio_hello.so /usr/local/lib/kde4/
cp kio_hello.so /usr/lib64/kde4/
cp kio_hello.protocol /usr/share/kde4/services/

Test it

Start kinfocenter, choose hello as protocol. If this is possible, start konqueror, type hello:/// into the URL bar.