summaryrefslogtreecommitdiff
path: root/libopie/pim/otodoaccessxml.cpp
blob: 80b85997ad23039fbb766781620aaafedf4bb1b2 (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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
#include <qfile.h>
#include <qvector.h>

#include <qpe/global.h>
#include <qpe/stringutil.h>
#include <qpe/timeconversion.h>

#include <opie/xmltree.h>

#include "otodoaccessxml.h"

OTodoAccessXML::OTodoAccessXML( const QString& appName,
                                const QString& fileName )
    : OTodoAccessBackend(), m_app( appName ),  m_opened( false ), m_changed( false )
{
    if (!fileName.isEmpty() )
        m_file = fileName;
    else
        m_file = Global::applicationFileName( "todolist", "todolist.xml" );
}
OTodoAccessXML::~OTodoAccessXML() {

}
bool OTodoAccessXML::load() {
    m_opened = true;
    m_changed = false;
    /* initialize dict */
    /*
     * UPDATE dict if you change anything!!!
     */
    QAsciiDict<int> dict(15);
    dict.setAutoDelete( TRUE );
    dict.insert("Categories" ,     new int(OTodo::Category)         );
    dict.insert("Uid" ,            new int(OTodo::Uid)              );
    dict.insert("HasDate" ,        new int(OTodo::HasDate)          );
    dict.insert("Completed" ,      new int(OTodo::Completed)        );
    dict.insert("Description" ,    new int(OTodo::Description)      );
    dict.insert("Summary" ,        new int(OTodo::Summary)          );
    dict.insert("Priority" ,       new int(OTodo::Priority)         );
    dict.insert("DateDay" ,        new int(OTodo::DateDay)          );
    dict.insert("DateMonth" ,      new int(OTodo::DateMonth)        );
    dict.insert("DateYear" ,       new int(OTodo::DateYear)         );
    dict.insert("Progress" ,       new int(OTodo::Progress)         );
    dict.insert("Completed",       new int(OTodo::Completed)        );
    dict.insert("CrossReference",  new int(OTodo::CrossReference)   );
    dict.insert("HasAlarmDateTime",new int(OTodo::HasAlarmDateTime) );
    dict.insert("AlarmDateTime",   new int(OTodo::AlarmDateTime)    );

    // here the custom XML parser from TT it's GPL
    // but we want to push that to TT.....
    QFile f(m_file );
    if (!f.open(IO_ReadOnly) )
        return false;

    QByteArray ba = f.readAll();
    f.close();
    char* dt = ba.data();
    int len = ba.size();
    int i = 0;
    char *point;
    const char* collectionString = "<Task ";
    while ( dt+i != 0 && ( point = strstr( dt+i, collectionString ) ) != 0l ) {
        i = point -dt;
        i+= strlen(collectionString);
        OTodo ev;
        m_year = m_month = m_day = 0;

        while ( TRUE ) {
            while ( i < len && (dt[i] == ' ' || dt[i] == '\n' || dt[i] == '\r') )
		++i;
	    if ( i >= len-2 || (dt[i] == '/' && dt[i+1] == '>') )
		break;

	    // we have another attribute, read it.
	    int j = i;
	    while ( j < len && dt[j] != '=' )
		++j;
	    QCString attr( dt+i, j-i+1);

	    i = ++j; // skip =

	    // find the start of quotes
	    while ( i < len && dt[i] != '"' )
		++i;
	    j = ++i;

	    bool haveUtf = FALSE;
	    bool haveEnt = FALSE;
	    while ( j < len && dt[j] != '"' ) {
		if ( ((unsigned char)dt[j]) > 0x7f )
		    haveUtf = TRUE;
		if ( dt[j] == '&' )
		    haveEnt = TRUE;
		++j;
	    }
	    if ( i == j ) {
		// empty value
		i = j + 1;
		continue;
	    }

	    QCString value( dt+i, j-i+1 );
	    i = j + 1;

	    QString str = (haveUtf ? QString::fromUtf8( value )
		    : QString::fromLatin1( value ) );
	    if ( haveEnt )
		str = Qtopia::plainString( str );

            /*
             * add key + value
             */
            todo( &dict, ev, attr, str );

        }
        /*
         * now add it
         */
        m_events.insert(ev.uid(), ev );
    }

    qWarning("counts %d", m_events.count() );
    return true;
}
bool OTodoAccessXML::reload() {
    return load();
}
bool OTodoAccessXML::save() {
//    qWarning("saving");
    if (!m_opened || !m_changed ) {
//        qWarning("not saving");
        return true;
    }
    QString strNewFile = m_file + ".new";
    QFile f( strNewFile );
    if (!f.open( IO_WriteOnly|IO_Raw ) )
        return false;

    int written;
    QString out;
    out = "<!DOCTYPE Tasks>\n<Tasks>\n";

    // for all todos
    QMap<int, OTodo>::Iterator it;
    for (it = m_events.begin(); it != m_events.end(); ++it ) {
        out+= "<Task " + toString( (*it) ) + " />\n";
        QCString cstr = out.utf8();
        written = f.writeBlock( cstr.data(),  cstr.length() );

        /* less written then we wanted */
        if ( written != (int)cstr.length() ) {
            f.close();
            QFile::remove( strNewFile );
            return false;
        }
        out = QString::null;
    }

    out +=  "</Tasks>";
    QCString cstr = out.utf8();
    written = f.writeBlock( cstr.data(), cstr.length() );

    if ( written != (int)cstr.length() ) {
        f.close();
        QFile::remove( strNewFile );
        return false;
    }
    /* flush before renaming */
    f.close();

    if( ::rename( strNewFile.latin1(),  m_file.latin1() ) < 0 ) {
//        qWarning("error renaming");
        QFile::remove( strNewFile );
    }

    m_changed = false;
    return true;
}
QArray<int> OTodoAccessXML::allRecords()const {
    QArray<int> ids( m_events.count() );
    QMap<int, OTodo>::ConstIterator it;
    int i = 0;

    for ( it = m_events.begin(); it != m_events.end(); ++it ) {
        ids[i] = it.key();
        i++;
    }
    return ids;
}
QArray<int> OTodoAccessXML::queryByExample( const OTodo&, int sort ) {
    QArray<int> ids(0);
    return ids;
}
OTodo OTodoAccessXML::find( int uid )const {
    OTodo todo;
    todo.setUid( 0 ); // isEmpty()
    QMap<int, OTodo>::ConstIterator it = m_events.find( uid );
    if ( it != m_events.end() )
        todo = it.data();

    return todo;
}
void OTodoAccessXML::clear() {
    if (m_opened )
        m_changed = true;

    m_events.clear();
}
bool OTodoAccessXML::add( const OTodo& todo ) {
//    qWarning("add");
    m_changed = true;
    m_events.insert( todo.uid(), todo );

    return true;
}
bool OTodoAccessXML::remove( int uid ) {
    m_changed = true;
    m_events.remove( uid );

    return true;
}
bool OTodoAccessXML::replace( const OTodo& todo) {
    m_changed = true;
    m_events.replace( todo.uid(), todo );

    return true;
}
QArray<int> OTodoAccessXML::effectiveToDos( const QDate& start,
                                            const QDate& end,
                                            bool includeNoDates ) {
    QArray<int> ids( m_events.count() );
    QMap<int, OTodo>::Iterator it;

    int i = 0;
    for ( it = m_events.begin(); it != m_events.end(); ++it ) {
        if ( !it.data().hasDueDate() ) {
            if ( includeNoDates ) {
                ids[i] = it.key();
                i++;
            }
        }else if ( it.data().dueDate() >= start &&
                   it.data().dueDate() <= end ) {
            ids[i] = it.key();
            i++;
        }
    }
    ids.resize( i );
    return ids;
}
QArray<int> OTodoAccessXML::overDue() {
    QArray<int> ids( m_events.count() );
    int i = 0;

    QMap<int, OTodo>::Iterator it;
    for ( it = m_events.begin(); it != m_events.end(); ++it ) {
        if ( it.data().isOverdue() ) {
            ids[i] = it.key();
            i++;
        }
    }
    ids.resize( i );
    return ids;
}


/* private */
void OTodoAccessXML::todo( QAsciiDict<int>* dict, OTodo& ev,
                            const QCString& attr, const QString& val) {
//    qWarning("parse to do from XMLElement" );

    int *find=0;

    find = (*dict)[ attr.data() ];
    if (!find ) {
//            qWarning("Unknown option" + it.key() );
        ev.setCustomField( attr, val );
        return;
    }

    switch( *find ) {
    case OTodo::Uid:
        ev.setUid( val.toInt() );
        break;
    case OTodo::Category:
        ev.setCategories( ev.idsFromString( val ) );
        break;
    case OTodo::HasDate:
        ev.setHasDueDate( val.toInt() );
        break;
    case OTodo::Completed:
        ev.setCompleted( val.toInt() );
        break;
    case OTodo::Description:
        ev.setDescription( val );
        break;
    case OTodo::Summary:
        ev.setSummary( val );
        break;
    case OTodo::Priority:
        ev.setPriority( val.toInt() );
        break;
    case OTodo::DateDay:
        m_day = val.toInt();
        break;
    case OTodo::DateMonth:
        m_month = val.toInt();
        break;
    case OTodo::DateYear:
        m_year = val.toInt();
        break;
    case OTodo::Progress:
        ev.setProgress( val.toInt() );
        break;
    case OTodo::CrossReference:
    {
        /*
         * A cross refernce looks like
         * appname,id;appname,id
         * we need to split it up
         */
        QStringList  refs = QStringList::split(';', val );
        QStringList::Iterator strIt;
        for (strIt = refs.begin(); strIt != refs.end(); ++strIt ) {
            int pos = (*strIt).find(',');
            if ( pos > -1 )
                ev.addRelation( (*strIt).left(pos),  (*strIt).mid(pos+1).toInt() );

        }
        break;
    }
    case OTodo::HasAlarmDateTime:
        ev.setHasAlarmDateTime( val.toInt() );
        break;
    case OTodo::AlarmDateTime: {
        /* this sounds better ;) zecke */
        ev.setAlarmDateTime( TimeConversion::fromISO8601( val.local8Bit() ) );
        break;
    }
    default:
        break;
    }

    if ( ev.hasDueDate() ) {
        QDate date( m_year,  m_month, m_day );
        ev.setDueDate( date );
    }
}
QString OTodoAccessXML::toString( const OTodo& ev )const {
    QString str;

    str += "Completed=\"" + QString::number( ev.isCompleted() ) + "\" ";
    str += "HasDate=\"" + QString::number( ev.hasDueDate() ) + "\" ";
    str += "Priority=\"" + QString::number( ev.priority() ) + "\" ";
    str += "Progress=\"" + QString::number(ev.progress() ) + "\" ";

    str += "Categories=\"" + toString( ev.categories() ) + "\" ";
    str += "Description=\"" + Qtopia::escapeString( ev.description() ) + "\" ";
    str += "Summary=\"" + Qtopia::escapeString( ev.summary() ) + "\" ";

    if ( ev.hasDueDate() ) {
        str += "DateYear=\"" + QString::number( ev.dueDate().year() ) + "\" ";
        str += "DateMonth=\"" + QString::number( ev.dueDate().month() ) + "\" ";
        str += "DateDay=\"" + QString::number( ev.dueDate().day() ) + "\" ";
    }
//    qWarning( "Uid %d",  ev.uid() );
    str += "Uid=\"" + QString::number( ev.uid() ) + "\" ";

// append the extra options
    /* FIXME Qtopia::Record this is currently not
     * possible you can set custom fields
     * but don' iterate over the list
     * I may do #define private protected
     * for this case - cough  --zecke
     */
    /*
    QMap<QString, QString> extras = ev.extras();
    QMap<QString, QString>::Iterator extIt;
    for (extIt = extras.begin(); extIt != extras.end(); ++extIt )
        str += extIt.key() + "=\"" +  extIt.data() + "\" ";
    */
    // cross refernce
    QStringList list = ev.relatedApps();
    QStringList::Iterator listIt;
    QString refs;
    str += "CrossReference=\"";
    bool added = false;
    for ( listIt = list.begin(); listIt != list.end(); ++listIt ) {
        added = true;
        QArray<int> ints = ev.relations( (*listIt) );
        for ( uint i = 0; i< ints.count(); i++ ) {
            str += (*listIt) + "," + QString::number( i ) + ";";
        }
    }
    if ( added )
        str = str.remove( str.length()-1, 1 );

    str += "\" ";

    str += "AlarmDateTime=\"" + TimeConversion::toISO8601( ev.alarmDateTime() ) + "\" ";

    return str;
}
QString OTodoAccessXML::toString( const QArray<int>& ints ) const {
    return Qtopia::Record::idsToString( ints );
}

/* internal class for sorting */

struct OTodoXMLContainer {
    OTodo todo;
};
  /*
   * Returns:
   *       0 if item1 == item2
   *
   *   non-zero if item1 != item2
   *
   *   This function returns int rather than bool so that reimplementations
   *   can return one of three values and use it to sort by:
   *
   *   0 if item1 == item2
   *
   *   > 0 (positive integer) if item1 > item2
   *
   *   < 0 (negative integer) if item1 < item2
   *
   */
class OTodoXMLVector : public QVector<OTodoXMLContainer> {
public:
    OTodoXMLVector(int size, bool asc,  int sort)
        : QVector<OTodoXMLContainer>( size )
        {
            setAutoDelete( true );
            m_asc = asc;
            m_sort = sort;
        }
        /* return the summary/description */
    QString string( const OTodo& todo) {
        return  todo.summary().isEmpty() ?
            todo.description().left(20 ) :
            todo.summary();
    }
    /**
     * we take the sortorder( switch on it )
     *
     */
    int compareItems( Item d1, Item d2 ) {
        qWarning("compare items");
        int ret =0;
        OTodoXMLContainer* con1 = (OTodoXMLContainer*)d1;
        OTodoXMLContainer* con2 = (OTodoXMLContainer*)d2;

        /* same item */
        if ( con1->todo.uid() == con2->todo.uid() )
            return 0;
        qWarning("m_sort %d", m_sort );

        switch ( m_sort ) {
            /* completed */
        case 0: {
            ret = 0;
            if ( con1->todo.isCompleted() ) ret++;
            if ( con2->todo.isCompleted() ) ret--;
            break;
        }
            /* priority */
        case 1: {
            ret = con1->todo.priority() - con2->todo.priority();
            qWarning(" priority %d %d %d",  ret,
                     con1->todo.priority(),
                     con2->todo.priority()
                     );
            break;
        }
            /* description */
        case 2: {
            QString str1 = string( con1->todo );
            QString str2 = string( con2->todo );
            ret  = QString::compare( str1, str2 );
            break;
        }
            /* deadline */
        case 3: {
            /* either bot got a dueDate
             * or one of them got one
             */
            if ( con1->todo.hasDueDate() &&
                 con2->todo.hasDueDate() )
                ret = con1->todo.dueDate().daysTo( con2->todo.dueDate() );
            else if ( con1->todo.hasDueDate() )
                ret = -1;
            else if ( con2->todo.hasDueDate() )
                ret = 0;
            break;
        }
        default:
            ret = 0;
            break;
        };

        /* twist it we're not ascending*/
        if (!m_asc)
            ret = ret * -1;
        return ret;
    }
 private:
    bool m_asc;
    int m_sort;

};

QArray<int> OTodoAccessXML::sorted( bool asc,  int sortOrder,
                                    int sortFilter,  int cat ) {
    OTodoXMLVector vector(m_events.count(), asc,sortOrder );
    QMap<int, OTodo>::Iterator it;
    int item = 0;

    bool bCat = sortFilter & 1 ? true : false;
    bool bOver = sortFilter & 0 ? true : false;
    bool bOnly = sortFilter & 2 ? true : false;
    for ( it = m_events.begin(); it != m_events.end(); ++it ) {

        /* show category */
        if ( bCat )
            if (!(*it).categories().contains( cat ) )
                continue;
        /* isOverdue but we should not show overdue */
        if ( (*it).isOverdue() && ( !bOver || !bOnly ) )
            continue;
        if ( !(*it).isOverdue() && bOnly )
            continue;


        OTodoXMLContainer* con = new OTodoXMLContainer();
        con->todo = (*it);
        vector.insert(item, con );
        item++;
    }
    vector.resize( item );
    /* sort it now */
    vector.sort();
    /* now get the uids */
    QArray<int> array( vector.count() );
    for (uint i= 0; i < vector.count(); i++ ) {
        array[i] = ( vector.at(i) )->todo.uid();
    }
    return array;
};