Development/Tutorials/Writing file analyzers

From KDE TechBase

Note: this tutorial is not finished yet

Writing KDE4 file analyzers

File analyzers extract data from files to display in the file dialogs and file managers. The data gathered this way is also used to search for files. KDE4 allows the use of multiple analyzers per file type. Analyzers can extract text which is used for indexing, but they can also retrieve other data such as song title, album title, recipient, md5 sum, the mimetype of a file, and much more.

This tutorial describes how you can write new analyzers.

Primer

What are file analyzers?

File analyzers in KDE4

KDE4 uses stream based file analyzers for retrieving text and metadata from files. This has a number of advantages over file based methods. Stream based access

  • is faster for 90% of the file types,
  • allows easy analysis of embedded files such as email attachments or entries from zip files, rpms and many other container file formats.

Writing stream-based analyzers requires a different approach than the usual file-based methods and in the tutorial we will explain how to go about it.

Finding documentation

Look for existing code

If you want to see some code examples, take a look at the already implemented file analyzers at /kdesupport/strigi/src/streamindexer/

Choosing the type of analyzer

There are two types of analyzers: StreamThroughAnalyzer and StreamEndAnalyzer. The latter is more powerful and a bit easier to program, but has a limition: only one StreamEndAnalyzer can analyze a particular resource, while you can use as many StreamThroughAnalyzers as you like. Most analyzers can be written as StreamThroughAnalyzers. The most import exception is for analyzers that extract embedded resources from a stream. Examples of this are the ZipEndAnalyzer, the MailEndAnalyzer and the RpmEndAnalyzer.

In this tutorial we focus on a simple example file type: BMP images. The information we will get from this file is located at the start of the file. It turns out that in this case, it is just as easy to implement the analyzer as a StreamEndAnalyzer as a StreamThroughAnalyzer. We will do both.

StreamEndAnalyzer

Three functions need to be implemented in a StreamEndAnalyzer. The function of getName() is obvious so we will discuss only two: checkHeader() and analyzer().

class BmpEndAnalyzer : public jstreams::StreamEndAnalyzer { private:

   const BmpEndAnalyzerFactory* factory;

public:

   BmpEndAnalyzer(const BmpEndAnalyzerFactory* f) :factory(f) {}
   bool checkHeader(const char* header, int32_t headersize) const;
   char analyze(jstreams::Indexable& idx, jstreams::InputStream* in);
   const char* getName() const { return "BmpEndAnalyzer"; }

};

Since only one StreamEndAnalyzer can be used per resource, it is important to quickly select the right one. For this, we dont rely on the mimetype, but on the actual contents of the resource. As a first sifting, the initial bytes of a file are checked. This is usually just as fast as comparing a mimetype identifier, but has the advantage of being more direct and thus often more accurate.

It is by no means necessary for checkHeader to be 100% correct. The most important thing is that it should allow one to quickly determine if an analyzer can not handle a resource. Should it by accident return true and thus indicate that a resource can be handled, then it can always handle this in the analyze() method.

bool BmpEndAnalyzer::checkHeader(const char* header, int32_t headersize) const {

   bool ok = false;
   if (headersize > 2) {
       ok |= strncmp(header, "BM", 2) == 0;
       ok |= strncmp(header, "BA", 2) == 0;
       ok |= strncmp(header, "CI", 2) == 0;
       ok |= strncmp(header, "CP", 2) == 0;
       ok |= strncmp(header, "IC", 2) == 0;
       ok |= strncmp(header, "PT", 2) == 0;
   }
   return ok;

}

A BMP file can start with six different initial bytes. If the header matches any of them, we return true.

If a resource passes this test, the analyze() function will be called. The ral work occurs in this function. In this tutorial, we will not do a complete analysis, but we only look at the way the pixels are stored in the BMP file. This information is stored in the bytes 30-33 that encode a number. char BmpEndAnalyzer::analyze(Indexable& idx, InputStream* in) {

   // read compression type (bytes #30-33)
   const char* h;
   int32_t n = in->read(h, 34, 34); // read exactly 34 bytes
   in->reset(0);   // rewind to the start of the stream
   if (n < 34) return Error;
   uint32_t bmpi_compression = (unsigned char)h[33] + ((unsigned char)h[32]<<8)
        + ((unsigned char)h[31]<<16) + ((unsigned char)h[30]<<24);
   switch (bmpi_compression) {
   case 0 :
       idx.setField(factory->compressionField, "None");
       break;
   case 1 :
       idx.setField(factory->compressionField, "RLE 8bit/pixel");
       break;
   case 2 :
       idx.setField(factory->compressionField, "RLE 4bit/pixel");
       break;
   case 3 :
       idx.setField(factory->compressionField, "Bitfields");
       break;
   default :
       idx.setField(factory->compressionField, "Unknown");
   }
   return Ok;

} First we read exactly 34 bytes from the stream. We dont need to allocate a buffer; this is handled by the stream. The stream returns a pointer to its internal buffer, which avoid data copying and buffer allocation. If the resource has less then 34 bytes or if an error occurred during reading, we return with an error code.

The bytes 30-33 contain the information we need and we write this into the Indexable object. This object collects all metadata and passes it to the code that initiated the analysis. The data may get written into an index or get passed to for example a file dialog. To indicate the type of metadata, we pass a pointer to a registered field.

StreamThroughAnalyzer

Registering the analyzer

KDE4 keeps a register of the capabilities of each analyzer. This allows it to speed up determining which analyzers to use. In addition, when it knows what data type an analyzer provides under what name, it can use this information to optimize the storage of the data or search queries. For this, each loadable analyzer must define two factories. An AnalyzerFactoryFactory and either a StreamThroughAnalyzerFactory or a StreamEndAnalyzerFactory.

AnalyzerFactoryFactory

The AnalyzerFactoryFactory is used only in the loadable plugins. It is not needed for analyzers that are part of the Strigi core. To initialize the StreamThroughAnalyzerFactories and StreamEndAnalyzerFactories in plugins, we need to implement an AnalyzerFactoryFactory. We do so by implementing one or two functions: getStreamThroughAnalyzerFactories() and getStreamEndAnalyzerFactories(). This function returns instances of all the factories available in a plugin. Here is for example the AnalyzerFactoryFactory for the KDE trash file analyzer (we cannot use the BMP analyzer here, because it is in Strigi core): class Factory : public AnalyzerFactoryFactory { public:

   list<StreamAnalyzerFactory*>
   getStreamThroughAnalyzerFactories() const {
       list<StreamThroughAnalyzerFactory*> af;
       af.push_back(new TrashThroughAnalyzerFactory());
       return af;
   }

};

// macro that initializes the Factory when the plugin is loaded STRIGI_ANALYZER_FACTORY(Factory)

StreamEndAnalyzerFactory

StreamEndAnalyzerFactories and StreamThroughAnalyzerFactories are very similar. They provide information about analyzers and the create instances of the analyzers. Each analyzer must hava a factory. StreamThroughAnalyzers have StreamThroughAnalyzerFactories and StreamEndAnalyzers have StreamEndAnalyzerFactories. Here, we look at the factory for the BmpEndAnalyzer.

The class BmpEndAnalyzerFactory looks like this:

class BmpEndAnalyzerFactory : public jstreams::StreamEndAnalyzerFactory { friend class BmpEndAnalyzer; private:

   static const cnstr typeFieldName;
   static const cnstr compressionFieldName;
   const jstreams::RegisteredField* typeField;
   const jstreams::RegisteredField* compressionField;
   const char* getName() const {
       return "BmpEndAnalyzer";
   }
   jstreams::StreamEndAnalyzer* newInstance() const {
       return new BmpEndAnalyzer(this);
   }
   void registerFields(jstreams::FieldRegister&);

};

All members are private, which is ok, because the important functions are virtual and thus accessible anyway. The functions getName() and newInstance() are selfexplanatory. The other important function is registerFields(jstreams::FieldRegister&). To speed up the extraction of fields, we dont use strings to identify fiels, but we use pointers to registered fields. These RegisteredField instances are stored in a global register. When you extract a piece of metadata, you pass the pointer to the registered field to identify the metadata.

But first we need to register the fields:

void BmpEndAnalyzerFactory::registerFields(FieldRegister& reg) {

   typeField = reg.registerField(typeFieldName, FieldRegister::stringType,
       1, 0);
   compressionField = reg.registerField(compressionFieldName,
       FieldRegister::stringType, 1, 0);

}

We pass the key of the field to the register, along with it's type, the maximum number of times the field occurs per resource and the parent of the field. The parent of a song tile, for example, could be a more general title field. The datatype of this field should be the same or a subset of the fieldtype of the parent.

The pointers to the registered fields are used during the analysis to identify the type of data we have analyzed:

  idx.setField(factory->typeField, "OS/2 Color Icon");

Building the analyzer

Building your analyzer is easy. There are three things you must take into account:

  • Link the analyzer as a module,
  • Let the name of the analyzer start with 'strigita_' for a StreamThroughAnalyzer and 'strigiea_' for a StreamEndAnalyzer,
  • Install the plugin in the lib/strigi directory.

add_library(trash MODULE trashthroughanalyzer.cpp trashimpl.cpp) target_link_libraries(trash ${STREAMINDEXER_LIBRARY} ${KDE4_KIO_LIBS} ${KDE4_SOLID_LIBS}) set_target_properties(trash PROPERTIES

   PREFIX strigita_)

install(TARGETS trash LIBRARY DESTINATION ${LIB_DESTINATION}/strigi)

Testing your code

Strigi comes with a simple command line tool to check if your plugins work. This tool is called xmlindexer. It extracts data from files and outputs it as simple xml. To use it call it like this:

xmlindexer [FILE]

or

xmlindexer [DIR]

This is very fast and I recommend using it with valgrind. This hardly slows down your workflow but helps to keep memory management in good shape:

valgrind xmlindexer [DIR]