summaryrefslogtreecommitdiff
path: root/core/pim/datebook/datebookday.cpp
blob: 00ddd05fe7e48d62f324a0e436fbb1cb4fcda3ec (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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
/**********************************************************************
** Copyright (C) 2000 Trolltech AS.  All rights reserved.
**
** This file is part of Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#include "datebookday.h"
#include "datebooktypes.h"
#include "datebookdayheaderimpl.h"
#include "datebookdayallday.h"

#include <opie2/oholidayplugin.h>
#include <qpe/resource.h>
#include <qpe/qpeapplication.h>
#include <qpe/ir.h>

#include <qsimplerichtext.h>
#include <qpopupmenu.h>


#include <qtimer.h>

DateBookDayView::DateBookDayView( bool whichClock, QWidget *parent, const char *name )
    : QTable( 24, 1, parent, name ), ampm( whichClock ), currDate( QDate::currentDate() )
{
    enableClipper(TRUE);
    setTopMargin( 0 );
    horizontalHeader()->hide();
    setLeftMargin(38);
    setColumnStretchable( 0, TRUE );
    setHScrollBarMode( QScrollView::AlwaysOff );
    verticalHeader()->setPalette(white);
    verticalHeader()->setResizeEnabled(FALSE);
    setSelectionMode( Single );

    // get rid of being able to edit things...
    QTableItem *tmp;
    int row;
    for ( row = 0; row < numRows(); row++ ) {
        tmp = new QTableItem( this, QTableItem::Never, QString::null);
        setItem( row, 0, tmp );
        //setRowHeight( row, 40);
    }

    initHeader();
    QObject::connect( qApp, SIGNAL(clockChanged(bool)), this, SLOT(slotChangeClock(bool)) );
}

void DateBookDayView::initHeader()
{
    QString strTmp;
    int preferredWidth = 0;
    for ( int i = 0; i < 24; ++i ) {
        if ( ampm ) {
            if ( i == 0 )
            strTmp = QString::number(12) + ":00";
            else if ( i == 12 )
            strTmp = QString::number(12) + tr(":00p");
            else if ( i > 12 )
            strTmp = QString::number( i - 12 ) + tr(":00p");
            else
            strTmp = QString::number(i) + ":00";
        } else {
            if ( i < 10 )
            strTmp = "0" + QString::number(i) + ":00";
            else
            strTmp = QString::number(i) + ":00";
        }
        strTmp = strTmp.rightJustify( 6, ' ' );
        verticalHeader()->setLabel( i, strTmp );

        // Compute correct width for current Font (Add some space right)
        int actWidth = QFontMetrics( QFont::defaultFont() ).width( strTmp + QString("  ") );
        if ( preferredWidth < actWidth )
            preferredWidth = actWidth;
        setRowStretchable( i, FALSE );
    }

    // It seems as if the header has a bug. It does not resize
    // correct horizontally if it is used vertical..
    // Thus, we do it manually..
    setLeftMargin( preferredWidth );
}

void DateBookDayView::slotDateChanged( int y, int m, int d )
{
    currDate.setYMD(y,m,d);
}

void DateBookDayView::slotChangeClock( bool newClock )
{
    ampm = newClock;
    initHeader();
}

bool DateBookDayView::whichClock() const
{
    return ampm;
}

void DateBookDayView::moveUp()
{
    scrollBy(0, -20);
}

void DateBookDayView::moveDown()
{
    scrollBy(0, 20);
}

void DateBookDayView::paintCell( QPainter *p, int, int, const QRect &cr, bool )
{
    int w = cr.width();
    int h = cr.height();
    p->fillRect( 0, 0, w, h, colorGroup().brush( QColorGroup::Base ) );
    if ( showGrid() ) {
        // Draw our lines
        int x2 = w - 1;
        int y2 = h - 1;
        QPen pen( p->pen() );
        p->setPen( colorGroup().dark() );
        p->drawLine( x2, 0, x2, y2 );
        p->drawLine( 0, y2, x2, y2 );

        p->setPen( colorGroup().midlight() );
        p->drawLine( 0, y2 - h/2, x2, y2 - h/2);

        p->setPen( pen );
    }
}

void DateBookDayView::paintFocus( QPainter *, const QRect & )
{
}

void DateBookDayView::resizeEvent( QResizeEvent *e )
{
    QTable::resizeEvent( e );
    columnWidthChanged( 0 );
    emit sigColWidthChanged();
}

void DateBookDayView::keyPressEvent( QKeyEvent *e )
{
    QString txt = e->text();
    if ( !txt.isNull() && txt[0] > ' ' && e->key() < 0x1000 ) {
        // we this is some sort of thing we know about...
        e->accept();
        emit sigCapturedKey( txt );
    } else {
        // I don't know what this key is, do you?
        e->ignore();
    }
}

void DateBookDayView::setRowStyle( int style )
{
    if (style<0) style = 0;

    for (int i=0; i<numRows(); i++)
        setRowHeight(i, style*10+20);
}

void DateBookDayView::contentsMouseReleaseEvent( QMouseEvent* /* e */ )
{
    int sh=99,eh=-1;

    for(int i=0;i<this->numSelections();i++) {
        QTableSelection sel = this->selection( i );
        sh = QMIN(sh,sel.topRow());
        eh = QMAX(sh,sel.bottomRow()+1);
    }
    if (sh > 23 || eh < 1) {
        sh=8;
        eh=9;
    }

    quickLineEdit=new DateBookDayViewQuickLineEdit(QDateTime(currDate,QTime(sh,0,0,0)),QDateTime(currDate,QTime(eh,0,0,0)),this->viewport(),"quickedit");
    quickLineEdit->setGeometry(0,0,this->columnWidth(0)-1,this->rowHeight(0));
    this->moveChild(quickLineEdit,0,sh*this->rowHeight(0));
    quickLineEdit->setFocus();
    quickLineEdit->show();
}

//===========================================================================

DateBookDayViewQuickLineEdit::DateBookDayViewQuickLineEdit(const QDateTime &start, const QDateTime &end,QWidget * parent, const char *name) : QLineEdit(parent,name)
{
    active=1;
    quickEvent.setStart(start);
    quickEvent.setEnd(end);
    connect(this,SIGNAL(returnPressed()),this,SLOT(slotReturnPressed()));
}

void DateBookDayViewQuickLineEdit::slotReturnPressed()
{
    if(active && (!this->text().isEmpty())) {   // Fix to avoid having this event beeing added multiple times.
        quickEvent.setDescription(this->text());
        connect(this,SIGNAL(insertEvent(const Event&)),this->topLevelWidget(),SLOT(insertEvent(const Event&)));
        emit(insertEvent(quickEvent));
        active=0;
    }
        /* we need to return to this object.. */
    QTimer::singleShot(500, this, SLOT(finallyCallClose())  );  // Close and also delete this widget
}
void DateBookDayViewQuickLineEdit::finallyCallClose() {
    close(true); // also deletes this widget...
}

void DateBookDayViewQuickLineEdit::focusOutEvent ( QFocusEvent* /* e */)
{
    slotReturnPressed(); // Reuse code to add event and close this widget.
}

//===========================================================================

DateBookDay::DateBookDay( bool ampm, bool startOnMonday, DateBookDBHoliday *newDb, DateBookHoliday*newHdb, QWidget *parent, const char *name )
    : QVBox( parent, name ), currDate( QDate::currentDate() ), db( newDb ), startTime( 0 )
{
    widgetList.setAutoDelete( true );
    _holiday_db = newHdb;
    header = new DateBookDayHeader( startOnMonday, this, "day header" );
    header->setDate( currDate.year(), currDate.month(), currDate.day() );

    m_allDays = new DatebookdayAllday(newDb, this, "all day event list" );
    m_allDays->hide();

    view = new DateBookDayView( ampm, this, "day view" );

    connect( header, SIGNAL( dateChanged(int,int,int) ), this, SLOT( dateChanged(int,int,int) ) );
    connect( header, SIGNAL( dateChanged(int,int,int) ), view, SLOT( slotDateChanged(int,int,int) ) );
    connect( view, SIGNAL( sigColWidthChanged() ), this, SLOT( slotColWidthChanged() ) );
    connect( qApp, SIGNAL(weekChanged(bool)), this, SLOT(slotWeekChanged(bool)) );
    connect( view, SIGNAL(sigCapturedKey(const QString&)), this, SIGNAL(sigNewEvent(const QString&)) );

    QTimer *timer = new QTimer( this );

    connect( timer, SIGNAL(timeout()), this, SLOT(updateView()) );  //connect timer for updating timeMarker & daywidgetcolors
    timer->start( 1000*60*5, FALSE ); //update every 5min

    selectedWidget = 0;

    timeMarker =  new DateBookDayTimeMarker( this );
    timeMarker->setTime( QTime::currentTime() );
    rowStyle = -1; // initialize with bogus values
        jumpToCurTime = false;
}

void DateBookDay::setJumpToCurTime( bool bJump )
{
    jumpToCurTime = bJump;
}

void DateBookDay::setRowStyle( int style )
{
    if (rowStyle != style) view->setRowStyle( style );
    rowStyle = style;
}

void DateBookDay::updateView( void )
{
    timeMarker->setTime( QTime::currentTime() );
    //need to find a way to update all DateBookDayWidgets
}

void DateBookDay::setSelectedWidget( DateBookDayWidget *w )
{
    selectedWidget = w;
}

DateBookDayWidget * DateBookDay::getSelectedWidget( void )
{
    return selectedWidget;
}

void DateBookDay::selectedDates( QDateTime &start, QDateTime &end )
{
    start.setDate( currDate );
    end.setDate( currDate );

    int sh=99,eh=-1;

    int n = dayView()->numSelections();

    for (int i=0; i<n; i++) {
        QTableSelection sel = dayView()->selection( i );
        sh = QMIN(sh,sel.topRow());
        eh = QMAX(sh,sel.bottomRow()+1);
    }

    if (sh > 23 || eh < 1) {
        sh=8;
        eh=9;
    }

    start.setTime( QTime( sh, 0, 0 ) );
    end.setTime( QTime( eh, 0, 0 ) );
}

void DateBookDay::setDate( int y, int m, int d )
{
    header->setDate( y, m, d );
    selectedWidget = 0;
}

void DateBookDay::setDate( QDate d)
{
    header->setDate( d.year(), d.month(), d.day() );
    selectedWidget = 0;
}

void DateBookDay::dateChanged( int y, int m, int d )
{
    QDate date( y, m, d );
    if ( currDate == date )
        return;
    currDate.setYMD( y, m, d );
    relayoutPage();
    dayView()->clearSelection();
    QTableSelection ts;

    if (jumpToCurTime && this->date() == QDate::currentDate())
    {
        ts.init( QTime::currentTime().hour(), 0);
        ts.expandTo( QTime::currentTime().hour(), 0);
    } else {
        ts.init( startTime, 0 );
        ts.expandTo( startTime, 0 );
    }

    dayView()->addSelection( ts );
    selectedWidget = 0;
}

void DateBookDay::redraw()
{
    if ( isUpdatesEnabled() )
        relayoutPage();
}

void DateBookDay::getEvents()
{
    widgetList.clear();

        /* clear the AllDay List */
        m_allDays->hide(); // just in case
        m_allDays->removeAllEvents();

    QStringList hdays = _holiday_db->holidaylist(currDate);
    QStringList::Iterator sit;
    QObject* object = 0;
    for (sit=hdays.begin();sit!=hdays.end();++sit) {
        object = m_allDays->addHoliday(*sit);
        if (!object) continue;
        /* not to do something with it */
    }
    QValueList<EffectiveEvent> eventList = db->getEffectiveEventsNoHoliday( currDate, currDate );
    QValueListIterator<EffectiveEvent> it;

    for ( it = eventList.begin(); it != eventList.end(); ++it ) {
        EffectiveEvent ev=*it;
        if(!((ev.end().hour()==0) && (ev.end().minute()==0) && (ev.startDate()!=ev.date()))) {  // Skip events ending at 00:00 starting at another day.
                    if (ev.event().type() == Event::AllDay ) {
                        object = m_allDays->addEvent( ev );
                        if (!object)
                            continue;
                    }else {
            DateBookDayWidget* w = new DateBookDayWidget( *it, this );
                        widgetList.append( w );
                        object = w;
                    }

                    connect( object, SIGNAL( deleteMe(const Event&) ), this, SIGNAL( removeEvent(const Event&) ) );
                    connect( object, SIGNAL( duplicateMe(const Event&) ), this, SIGNAL( duplicateEvent(const Event&) ) );
                    connect( object, SIGNAL( editMe(const Event&) ), this, SIGNAL( editEvent(const Event&) ) );
                    connect( object, SIGNAL( beamMe(const Event&) ), this, SIGNAL( beamEvent(const Event&) ) );

        }
    }
}

static int place( const DateBookDayWidget *item, bool *used, int maxn )
{
    int place = 0;
    int start = item->event().start().hour();
    QTime e = item->event().end();
    int end = e.hour();
    if ( e.minute() < 5 )
        end--;
    if ( end < start )
        end = start;
    while ( place < maxn ) {
        bool free = TRUE;
        int s = start;
        while( s <= end ) {
            if ( used[10*s+place] ) {
                free = FALSE;
                break;
            }
            s++;
        }
        if ( free )
            break;
        place++;
    }
    if ( place == maxn ) {
        return -1;
    }
    while( start <= end ) {
        used[10*start+place] = TRUE;
        start++;
    }
    return place;
}


void DateBookDay::relayoutPage( bool fromResize )
{
    setUpdatesEnabled( FALSE );
    if ( !fromResize ) {
        getEvents();    // no need we already have them!

                if (m_allDays->items() > 0 )
                    m_allDays->show();
                /*
                 * else if ( m_allDays->items() ==  0 ) already hide in getEvents
                 */
        }

    widgetList.sort();
    //sorts the widgetList by the heights of the widget so that the tallest widgets are at the beginning
    //this is needed for the simple algo below to work correctly, otherwise some widgets would be drawn outside the view

    int wCount = widgetList.count();
    int wid = view->columnWidth(0)-1;
    int wd;
    int n = 1;

    QArray<int> anzIntersect(wCount); //this stores the number of maximal intersections of each widget

    for (int i = 0; i<wCount; anzIntersect[i] = 1, i++);

    if ( wCount < 20 ) {

        QArray<QRect> geometries(wCount);
        for (int i = 0; i < wCount; geometries[i] = widgetList.at(i)->geometry(), i++); //stores geometry for each widget in vector

        for ( int i = 0; i < wCount; i++) {
            QValueList<int> intersectedWidgets;

            //find all widgets intersecting with widgetList.at(i)
            for ( int j = 0; j < wCount; j++) {
                if (i != j)
                    if (geometries[j].intersects(geometries[i]))
                        intersectedWidgets.append(j);
            }

            //for each of these intersecting widgets find out how many widgets are they intersecting with
            for ( uint j = 0; j < intersectedWidgets.count(); j++)
            {
                QArray<int> inter(wCount);
                inter[j]=1;

                if (intersectedWidgets[j] != -1)
                    for ( uint k = j; k < intersectedWidgets.count(); k++) {
                        if (j != k && intersectedWidgets[k] != -1)
                            if (geometries[intersectedWidgets[k]].intersects(geometries[intersectedWidgets[j]])) {
                                inter[j]++;
                                intersectedWidgets[k] = -1;
                            }
                        if (inter[j] > anzIntersect[i]) anzIntersect[i] = inter[j] + 1;
                    }
                }
            if (anzIntersect[i] == 1 && intersectedWidgets.count()) anzIntersect[i]++;
        }


        for ( int i = 0; i < wCount; i++) {
            DateBookDayWidget *w = widgetList.at(i);
            QRect geom = w->geometry();
            geom.setX( 0 );
            wd = (view->columnWidth(0)-1) / anzIntersect[i] - (anzIntersect[i]>1?2:0);
            geom.setWidth( wd );
            while ( intersects( w, geom ) ) {
                geom.moveBy( wd + 2 + 1, 0 );
            }
            w->setGeometry( geom );
        }

        if (jumpToCurTime && this->date() == QDate::currentDate()) {
            view->setContentsPos( 0, QTime::currentTime().hour() * view->rowHeight(0) ); //set listview to current hour
        } else {
            view->setContentsPos( 0, startTime * view->rowHeight(0) );
        }
    } else {
        int hours[24];
        memset( hours, 0, 24*sizeof( int ) );
        bool overFlow = FALSE;
        for ( int i = 0; i < wCount; i++ ) {
            DateBookDayWidget *w = widgetList.at(i);
            int start = w->event().start().hour();
            QTime e = w->event().end();
            int end = e.hour();
            if ( e.minute() < 5 )
                end--;
            if ( end < start )
                end = start;
            while( start <= end ) {
                hours[start]++;
                if ( hours[start] >= 10 )
                    overFlow = TRUE;
                ++start;
            }
            if ( overFlow )
                break;
        }
        for ( int i = 0; i < 24; i++ ) {
            n = QMAX( n, hours[i] );
        }
        wid = ( view->columnWidth(0)-1 ) / n;

        bool used[24*10];
        memset( used, FALSE, 24*10*sizeof( bool ) );

        for ( int i = 0; i < wCount; i++ ) {
            DateBookDayWidget *w = widgetList.at(i);
            int xp = place( w, used, n );
            if ( xp != -1 ) {
                QRect geom = w->geometry();
                geom.setX( xp*(wid+2) );
                geom.setWidth( wid );
                w->setGeometry( geom );
            }
        }

        if (jumpToCurTime && this->date() == QDate::currentDate()) {
            view->setContentsPos( 0, QTime::currentTime().hour() * view->rowHeight(0) ); //set listview to current hour
        } else {
            view->setContentsPos( 0, startTime * view->rowHeight(0) );
        }
    }

    timeMarker->setTime( QTime::currentTime() );    //display timeMarker
    timeMarker->raise();                //on top of all widgets
    if (this->date() == QDate::currentDate()) {     //only show timeMarker on current day
        timeMarker->show();
    } else {
        timeMarker->hide();
    }
    setUpdatesEnabled( TRUE );
    return;
}

DateBookDayWidget *DateBookDay::intersects( const DateBookDayWidget *item, const QRect &geom )
{
    int i = 0;
    DateBookDayWidget *w = widgetList.at(i);
    int wCount = widgetList.count();
    while ( i < wCount && w != item ) {
        if ( w->geometry().intersects( geom ) ) {
            return w;
        }
        w = widgetList.at(++i);
    }

    return 0;
}


QDate DateBookDay::date() const
{
    return currDate;
}

void DateBookDay::setStartViewTime( int startHere )
{
    startTime = startHere;
    dayView()->clearSelection();
    QTableSelection ts;

    if (jumpToCurTime && this->date() == QDate::currentDate()) {    //this should probably be in datebook.cpp where it's called?
        ts.init( QTime::currentTime().hour(), 0);
        ts.expandTo( QTime::currentTime().hour(), 0);
    } else {
        ts.init( startTime, 0 );
        ts.expandTo( startTime, 0 );
    }

    dayView()->addSelection( ts );
}

int DateBookDay::startViewTime() const
{
    return startTime;
}

void DateBookDay::slotWeekChanged( bool bStartOnMonday )
{
    header->setStartOfWeek( bStartOnMonday );
//  redraw();
}

void DateBookDay::keyPressEvent(QKeyEvent *e)
{
    switch(e->key()) {
        case Key_Up:
            view->moveUp();
            break;
        case Key_Down:
            view->moveDown();
            break;
        case Key_Left:
            setDate(QDate(currDate).addDays(-1));
            break;
        case Key_Right:
            setDate(QDate(currDate).addDays(1));
            break;
        default:
            e->ignore();
    }
}

//===========================================================================

DateBookDayWidget::DateBookDayWidget( const EffectiveEvent &e, DateBookDay *db )
    : QWidget( db->dayView()->viewport() ), ev( e ), dateBook( db )
{
    // why would someone use "<"?  Oh well, fix it up...
    // I wonder what other things may be messed up...
    QString strDesc = ev.description();
    int where = strDesc.find( "<" );
    while ( where != -1 ) {
        strDesc.remove( where, 1 );
        strDesc.insert( where, "&#60;" );
        where = strDesc.find( "<", where );
    }

    QString strCat;
// ### Fix later...
//     QString strCat = ev.category();
//     where = strCat.find( "<" );
//     while ( where != -1 ) {
//  strCat.remove( where, 1 );
//  strCat.insert( where, "&#60;" );
//  where = strCat.find( "<", where );
//     }

    QString strNote = ev.notes();
    where = strNote.find( "<" );
    while ( where != -1 ) {
        strNote.remove( where, 1 );
        strNote.insert( where, "&#60;" );
        where = strNote.find( "<", where );
    }

    text = "<b>" + strDesc + "</b><br>" + "<i>";
    if ( !strCat.isEmpty() )  {
        text += strCat + "</i><br>";
    }
    if (ev.event().type() == Event::Normal ) {
        setEventText( text );
    } else {
        setAllDayText( text );
    }

    text += "<br><br>" + strNote;

    setBackgroundMode( PaletteBase );

    QTime start = ev.start();
    QTime end = ev.end();
    int y = start.hour()*60+start.minute();
    int h = end.hour()*60+end.minute()-y;
    int rh = dateBook->dayView()->rowHeight(0);
    y = y*rh/60;
    h = h*rh/60;

    if ( h < 12 ) h = 12;   // Make sure the widget is no smaller than 12 pixels high, so that it's possible to read atleast the first line.
    if ( y > ((24*rh)-12) ) y=(24*rh)-12;   // Make sure the widget fits inside the dayview.
    geom.setY( y );
    geom.setHeight( h );
    geom.setX( 0 );
    geom.setWidth(dateBook->dayView()->columnWidth(0)-1);

}

void DateBookDayWidget::setAllDayText( QString &text ) {
    text += "<b>" + tr("This is an all day event.") + "</b>";
}

void DateBookDayWidget::setEventText( QString& text ) {
    bool whichClock = dateBook->dayView()->whichClock();
    if ( ev.startDate() != ev.endDate() ) {
        text += "<b>" + tr("Start") + "</b>: ";
        text += TimeString::timeString( ev.event().start().time(), whichClock, FALSE );
        text += " - " + TimeString::longDateString( ev.startDate() ) + "<br>";
        text += "<b>" + tr("End") + "</b>: ";
        text += TimeString::timeString( ev.event().end().time(), whichClock, FALSE );
        text += " - " + TimeString::longDateString( ev.endDate() );
    } else {
        text += "<b>" + tr("Time") + "</b>: ";
        text += TimeString::timeString( ev.start(), whichClock, FALSE );
        text += "<b>" + tr(" - ") + "</b>";
        text += TimeString::timeString( ev.end(), whichClock, FALSE );
    }
}

DateBookDayWidget::~DateBookDayWidget()
{
}

void DateBookDayWidget::paintEvent( QPaintEvent *e )
{
    QPainter p( this );

    if (dateBook->getSelectedWidget() == this) {
        p.setBrush( QColor( 155, 240, 230 ) ); // selected item
    } else {
        if (dateBook->date() == QDate::currentDate()) {
            QTime curTime = QTime::currentTime();
            if (ev.end() < curTime) {
                p.setBrush( QColor( 180, 180, 180 ) ); // grey, inactive
            } else {
                //change color in dependence of the time till the event starts
                int duration = curTime.secsTo(ev.start());
                if (duration < 0) duration = 0;
                int colChange = duration*160/86400; //86400: secs per day, 160: max color shift
                p.setBrush( QColor( 200-colChange, 200-colChange, 255 ) ); //blue
            }
        } else {
            p.setBrush( QColor( 220, 220, 220 ) ); //light grey, inactive (not current date)
            //perhaps make a distinction between future/past dates
        }
    }

    p.setPen( QColor(100, 100, 100) );
    p.drawRect(rect());

 //   p.drawRect(0,0, 5, height());

    int y = 0;
    int d = 0;

    if ( ev.event().hasAlarm() ) {
        p.drawPixmap( width() - 16, 0, Resource::loadPixmap( "bell" ) );
        y = 20;
        d = 20;
    }

    if ( ev.event().hasRepeat() ) {
        p.drawPixmap( width() - 16, y, Resource::loadPixmap( "repeat" ) );
        d = 20;
        y += 20;
    }

    QSimpleRichText rt( text, font() );
    rt.setWidth( geom.width() - d - 6 );
    rt.draw( &p, 7, 0, e->region(), colorGroup() );
}

/*
 * we need to find the real start date for a uid
 * we need to check from one day to another...
 */
QDate DateBookDay::findRealStart( int uid, const QDate& isIncluded ,  DateBookDB* db) {
    QDate dt( isIncluded );
    QDate fnd = dt;

    bool doAgain = true;
    do{
        dt = dt.addDays( -1 );
        QValueList<EffectiveEvent> events = db->getEffectiveEvents( dt, dt );
        for (QValueList<EffectiveEvent>::Iterator it = events.begin(); it != events.end(); ++it ) {
            EffectiveEvent ev = (*it);
            if ( uid == ev.event().uid() && ev.start() != QTime(0, 0, 0 ) )
                return ev.date();
        }
    }while (doAgain );

    return fnd;
}

void DateBookDayWidget::mousePressEvent( QMouseEvent *e )
{
    DateBookDayWidget *item;

    item = dateBook->getSelectedWidget();
    if (item)
        item->update();

    dateBook->setSelectedWidget(this);
    update();
    dateBook->repaint();

        Event eve = ev.event();

    QPopupMenu m;
    m.insertItem( tr( "Edit" ), 1 );
    m.insertItem( tr( "Duplicate" ), 4 );
    m.insertItem( tr( "Delete" ), 2 );
    if(Ir::supported()) m.insertItem( tr( "Beam" ), 3 );
        if(Ir::supported() && ev.event().doRepeat() ) m.insertItem( tr( "Beam this occurence"), 5 );
    int r = m.exec( e->globalPos() );
    if ( r == 1 ) {
        emit editMe( eve );
    } else if ( r == 2 ) {
        emit deleteMe( eve );
    } else if ( r == 3 ) {
        emit beamMe( eve );
    } else if ( r == 4 ) {
        emit duplicateMe( eve );
    } else if ( r == 5 ) {
            // create an Event and beam it...
            /*
             * Start with the easy stuff. If start and  end date is the same we can just use
             * the values of effective events
             * If it is a multi day event we need to find the real start and end date...
             */
            if ( ev.event().start().date() == ev.event().end().date() ) {
                Event event( ev.event() );

                QDateTime dt( ev.date(), ev.start() );
                event.setStart( dt );

                dt.setTime( ev.end() );
                event.setEnd( dt );
                emit beamMe( event );
            }else {
                /*
                 * at least the the Times are right now
                 */
                QDateTime start( ev.event().start() );
                QDateTime end  ( ev.event().end  () );


                /*
                 * ok we know the start date or we need to find it
                 */
                if ( ev.start() != QTime( 0, 0, 0 ) ) {
                    start.setDate( ev.date() );
                }else {
                    QDate dt = DateBookDay::findRealStart( ev.event().uid(), ev.date(), dateBook->db );
                    start.setDate( dt );
                }


                /*
                 * ok we know now the end date...
                 * else
                 *   get to know the offset btw the real start and real end
                 *   and then add it to the new start date...
                 */
                if ( ev.end() != QTime(23, 59, 59 ) ) {
                    end.setDate( ev.date() );
                }else{
                    int days = ev.event().start().date().daysTo( ev.event().end().date() );
                    end.setDate( start.date().addDays( days ) );
                }



                Event event( ev.event() );
                event.setStart( start );
                event.setEnd  ( end   );


                emit beamMe( event );
            }
        }
}

void DateBookDayWidget::setGeometry( const QRect &r )
{
    geom = r;
    setFixedSize( r.width()+1, r.height()+1 );
    dateBook->dayView()->moveChild( this, r.x(), r.y()-1 );
    show();
}


//---------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------


DateBookDayTimeMarker::DateBookDayTimeMarker( DateBookDay *db )
    : QWidget( db->dayView()->viewport() ), dateBook( db )
{
    setBackgroundMode( PaletteBase );
}

DateBookDayTimeMarker::~DateBookDayTimeMarker()
{
}

void DateBookDayTimeMarker::paintEvent( QPaintEvent */*e*/ )
{
    QPainter p( this );
    p.setBrush( QColor( 255, 0, 0 ) );

    QPen pen;
    pen.setStyle(NoPen);

    p.setPen( pen );
    p.drawRect(rect());
}

void DateBookDayTimeMarker::setTime( const QTime &t )
{
    int y = t.hour()*60+t.minute();
    int rh = dateBook->dayView()->rowHeight(0);
    y = y*rh/60;

    geom.setX( 0 );

    int x = dateBook->dayView()->columnWidth(0)-1;
    geom.setWidth( x );

    geom.setY( y );
    geom.setHeight( 1 );

    setGeometry( geom );

    time = t;
}

void DateBookDayTimeMarker::setGeometry( const QRect &r )
{
    geom = r;
    setFixedSize( r.width()+1, r.height()+1 );
    dateBook->dayView()->moveChild( this, r.x(), r.y()-1 );
    show();
}