summaryrefslogtreecommitdiff
path: root/src/dictionary/DictionaryWriter.cpp
blob: 14cd0875d06321ccaefe537df248c7184b7132ca (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
#include "DictionaryWriter.h"
#include "Dictionary.h"
#include "../version.h"
#include "CardPack.h"
#include "DicRecord.h"

DictionaryWriter::DictionaryWriter( const Dictionary* aDict ):
    m_dict( aDict )
{
    setAutoFormatting( true );
}

bool DictionaryWriter::write( QIODevice* aDevice )
{
    setDevice( aDevice );
    writeStartDocument();
    writeDTD( "<!DOCTYPE freshmemory-dict>" );
    writeStartElement("dict");
    writeAttribute( "version", DIC_VERSION );

    writeStartElement( "fields" );
    foreach( Field *field, m_dict->fields() )
        writeField( field );
    writeEndElement();

    writeStartElement( "packs" );
    foreach( const CardPack* pack, m_dict->cardPacks() )
        writePack( pack );
    writeEndElement();

    writeStartElement( "entries" );
    foreach( const DicRecord* entry, m_dict->getRecords() )
        writeEntry( entry, m_dict->fields() );
    writeEndElement();

    writeEndDocument();
    return true;
}

void DictionaryWriter::writeField( Field* aField )
    {
    writeStartElement( "field" );
    QString style = aField->style();
    if( !style.isEmpty() && style != FieldStyleFactory::DefaultStyle )
        writeAttribute( "style", style );
    writeCharacters( aField->name() );
    writeEndElement();
    }

void DictionaryWriter::writePack( const CardPack* aPack )
    {
    writeStartElement( "pack" );
    if(aPack->getUsesExactAnswer())
        writeAttribute( "exact-ans", "true" );
    writeTextElement( "qst", aPack->getQuestionField()->name() );
    foreach( const Field* field, aPack->getAnswerFields() )
        writeTextElement( "ans", field->name() );
    writeEndElement();
    }

void DictionaryWriter::writeEntry( const DicRecord* aEntry, QList<Field*> aFields )
    {
    writeStartElement( "e" );
    int emptyFieldsNum = 0;
    foreach( Field* field, aFields )
        {
        QString fieldValue = aEntry->getFieldValue( field->name() );
        if( fieldValue.isEmpty() )
            emptyFieldsNum++;
        else
            {
            for( int k = 0; k < emptyFieldsNum; k++ )
                writeEmptyElement( "f" );
            emptyFieldsNum = 0;
            writeTextElement( "f", fieldValue );
            }
        }
    writeEndElement();
    }