summaryrefslogtreecommitdiffstats
path: root/amor/amor.cpp
blob: 2efb89694ddd7fcccb70101fdc4e0e1807912d96 (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
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
/* amor.cpp
**
** Copyright (c) 1999 Martin R. Jones <mjones@kde.org>
**
*/

/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
** MA 02110-1301, USA.
*/

/*
** Bug reports and questions can be sent to kde-devel@kde.org
*/
#include <stdlib.h>
#include <unistd.h>
#include <time.h>

#include <kdebug.h>

#include <kpopupmenu.h>
#include <tqtimer.h>
#include <tqcursor.h>
#include <tqvaluelist.h>

#include <klocale.h>
#include <kmessagebox.h>
#include <kstartupinfo.h>
#include <kwin.h>
#include <kwinmodule.h>
#include <kstandarddirs.h>
#include <khelpmenu.h>
#include <kiconloader.h>

#include "amor.h"
#include "amor.moc"
#include "amorpm.h"
#include "amorbubble.h"
#include "amorwidget.h"
#include "amordialog.h"
#include "version.h"
#include <X11/Xlib.h>
#include <kdebug.h>

// #define DEBUG_AMOR

#define SLEEP_TIMEOUT   180     // Animation sleeps after SLEEP_TIMEOUT seconds
                                // of mouse inactivity.
#define TIPS_FILE       "tips"  // Display tips in TIP_FILE-LANG, e.g "tips-en"
#define TIP_FREQUENCY   20      // Frequency tips are displayed small == more
                                // often.

#define BUBBLE_TIME_STEP 250

// Standard animation groups
#define ANIM_BASE       "Base"
#define ANIM_NORMAL     "Sequences"
#define ANIM_FOCUS      "Focus"
#define ANIM_BLUR       "Blur"
#define ANIM_DESTROY    "Destroy"
#define ANIM_SLEEP      "Sleep"
#define ANIM_WAKE       "Wake"

//---------------------------------------------------------------------------
// QueueItem
// Constructor
//

QueueItem::QueueItem(itemType ty, TQString te, int ti)
{
    // if the time field was not given, calculate one based on the type 
    // and length of the item
    int effectiveLength = 0, nesting = 0;

    // discard html code from the lenght count
    for (unsigned int i = 0; i < te.length(); i++)
    {
	if (te[i] == '<')	nesting++;
	else if (te[i] == '>')	nesting--;
	else if (!nesting)	effectiveLength++;
    }
    if (nesting) // malformed html
    {
#ifdef DEBUG_AMOR
	kdDebug(10000) << "QueueItem::QueueItem(): Malformed HTML!" << endl;
#endif
	effectiveLength = te.length();
    }

    if (ti == -1)
    {
	switch (ty)  {
	    case Talk : // shorter times
			ti = 1500 + 45 * effectiveLength;
			break;
	    case Tip  : // longer times
			ti = 4000 + 30 * effectiveLength;
			break;
	}
    }

    iType = ty;
    iText = te;
    iTime = ti;
}

//---------------------------------------------------------------------------
// AMOR
// Constructor
//
Amor::Amor() : DCOPObject( "AmorIface" ), TQObject()
{
    mAmor = 0;
    mBubble = 0;
    mForceHideAmorWidget = false;
    if (readConfig())
    {
        mTargetWin   = 0;
        mNextTarget  = 0;
        mAmorDialog  = 0;
        mMenu        = 0;
        mCurrAnim    = mBaseAnim;
        mPosition    = mCurrAnim->hotspot().x();
        mState       = Normal;

        mWin = new KWinModule;
        connect(mWin, TQT_SIGNAL(activeWindowChanged(WId)),
                this, TQT_SLOT(slotWindowActivate(WId)));
        connect(mWin, TQT_SIGNAL(windowRemoved(WId)),
                this, TQT_SLOT(slotWindowRemove(WId)));
        connect(mWin, TQT_SIGNAL(stackingOrderChanged()),
                this, TQT_SLOT(slotStackingChanged()));
        connect(mWin, TQT_SIGNAL(windowChanged(WId, const unsigned long *)),
                this, TQT_SLOT(slotWindowChange(WId, const unsigned long *)));
        connect(mWin, TQT_SIGNAL(currentDesktopChanged(int)),
                this, TQT_SLOT(slotDesktopChange(int)));

        mAmor = new AmorWidget();
        connect(mAmor, TQT_SIGNAL(mouseClicked(const TQPoint &)),
                        TQT_SLOT(slotMouseClicked(const TQPoint &)));
        connect(mAmor, TQT_SIGNAL(dragged(const TQPoint &, bool)),
                        TQT_SLOT(slotWidgetDragged(const TQPoint &, bool)));
        mAmor->resize(mTheme.tqmaximumSize());

        mTimer = new TQTimer(this);
        connect(mTimer, TQT_SIGNAL(timeout()), TQT_SLOT(slotTimeout()));

        mStackTimer = new TQTimer(this);
        connect(mStackTimer, TQT_SIGNAL(timeout()), TQT_SLOT(restack()));
    
	mBubbleTimer = new TQTimer(this);
	connect(mBubbleTimer, TQT_SIGNAL(timeout()), TQT_SLOT(slotBubbleTimeout()));

        time(&mActiveTime);
        mCursPos = TQCursor::pos();
        mCursorTimer = new TQTimer(this);
        connect(mCursorTimer, TQT_SIGNAL(timeout()), TQT_SLOT(slotCursorTimeout()));
	mCursorTimer->start( 500 );

        if (mWin->activeWindow())
        {
            mNextTarget = mWin->activeWindow();
            selectAnimation(Focus);
            mTimer->start(0, true);
        }
	if (!connectDCOPSignal(0,0, "KDE_stop_screensaver()", "screenSaverStopped()",false))
		kdDebug(10000) << "Could not attach signal...KDE_stop_screensaver()" << endl;
	else
		kdDebug(10000) << "attached dcop signals..." << endl;

	if (!connectDCOPSignal(0,0, "KDE_start_screensaver()", "screenSaverStarted()",false))
		kdDebug(10000) << "Could not attach signal...KDE_start_screensaver()" << endl;
	else
		kdDebug(10000) << "attached dcop signals..." << endl;

	mTipsQueue.setAutoDelete(true);

	KStartupInfo::appStarted();
    }
    else
    {
        kapp->quit();
    }
}

//---------------------------------------------------------------------------
//
// Destructor
//
Amor::~Amor()
{
    delete mWin;
    delete mAmor;
    delete mBubble;
}

void Amor::screenSaverStopped()
{
#ifdef DEBUG_AMOR
    kdDebug(10000)<<"void Amor::screenSaverStopped() \n";
#endif

    mAmor->show();
    mForceHideAmorWidget = false;

    mTimer->start(0, true);
}

void Amor::screenSaverStarted()
{
#ifdef DEBUG_AMOR
    kdDebug(10000)<<"void Amor::screenSaverStarted() \n";
#endif

    mAmor->hide();
    mTimer->stop();
    mForceHideAmorWidget = true;

    // GP: hide the bubble (if there's any) leaving any current message in the queue
    hideBubble();
}

//---------------------------------------------------------------------------
//
void Amor::showTip( TQString tip )
{
    if (mTipsQueue.count() < 5 && !mForceHideAmorWidget) // start dropping tips if the queue is too long
        mTipsQueue.enqueue(new QueueItem(QueueItem::Tip, tip));

    if (mState == Sleeping)
    {
	selectAnimation(Waking);	// Set waking immediatedly
	mTimer->start(0, true);
    }
}


void Amor::showMessage( TQString message )
{
    showMessage(message, -1);
}

void Amor::showMessage( TQString message , int msec )
{
    // FIXME: What should be done about messages and tips while the screensaver is on?
    if (mForceHideAmorWidget) return; // do not show messages sent while in the screensaver

    mTipsQueue.enqueue(new QueueItem(QueueItem::Talk, message, msec));

    if (mState == Sleeping)
    {
	selectAnimation(Waking);	// Set waking immediatedly
	mTimer->start(0, true);
    }
}


//---------------------------------------------------------------------------
//
// Clear existing theme and reload configuration
//
void Amor::reset()
{
    hideBubble();

    mAmor->setPixmap(0L);	// get rid of your old copy of the pixmap

    AmorPixmapManager::manager()->reset();
    mTips.reset();

//    mTipsQueue.clear();	Why had I chosen to clean the tips queue? insane!

    readConfig();

    mCurrAnim   = mBaseAnim;
    mPosition   = mCurrAnim->hotspot().x();
    mState      = Normal;

    mAmor->resize(mTheme.tqmaximumSize()); 
    mCurrAnim->reset();

    mTimer->start(0, true);
}

//---------------------------------------------------------------------------
//
// Read the selected theme.
//
bool Amor::readConfig()
{
    // Read user preferences
    mConfig.read();

    if (mConfig.mTips)
    {
        mTips.setFile(TIPS_FILE);
    }

    // Select a random theme if user requested it
    if (mConfig.mRandomTheme)
    {
        TQStringList files;
        
        // Store relative paths into files to avoid storing absolute pathnames.
        KGlobal::dirs()->findAllResources("appdata", "*rc", false, false, files);
        int randomTheme = kapp->random() % files.count();
        mConfig.mTheme = (TQString)*files.at(randomTheme);
    }
	
    // read selected theme
    if (!mTheme.setTheme(mConfig.mTheme))
    {
        KMessageBox::error(0, i18n("Error reading theme: ") + mConfig.mTheme);
        return false;
    }

    if ( !mTheme.isStatic() )
    {
	const char *groups[] = { ANIM_BASE, ANIM_NORMAL, ANIM_FOCUS, ANIM_BLUR,
				ANIM_DESTROY, ANIM_SLEEP, ANIM_WAKE, 0 };

	// Read all the standard animation groups
	for (int i = 0; groups[i]; i++)
	{
	    if (mTheme.readGroup(groups[i]) == false)
	    {
		KMessageBox::error(0, i18n("Error reading group: ") + groups[i]);
		return false;
	    }
	}
    }
    else
    {
	if ( mTheme.readGroup( ANIM_BASE ) == false )
	{
	    KMessageBox::error(0, i18n("Error reading group: ") + ANIM_BASE);
	    return false;
	}
    }

    // Get the base animation
    mBaseAnim = mTheme.random(ANIM_BASE);

    return true;
}

//---------------------------------------------------------------------------
//
// Show the bubble text
//
void Amor::showBubble()
{
    if (!mTipsQueue.isEmpty())
    {
#ifdef DEBUG_AMOR
    kdDebug(10000) << "Amor::showBubble(): Displaying tips bubble." << endl;
#endif

        if (!mBubble)
        {
            mBubble = new AmorBubble;
        }

        mBubble->setOrigin(mAmor->x()+mAmor->width()/2,
                           mAmor->y()+mAmor->height()/2);
        mBubble->setMessage(mTipsQueue.head()->text());

//	mBubbleTimer->start(mTipsQueue.head()->time(), true);
	mBubbleTimer->start(BUBBLE_TIME_STEP, true);
    }
}

//---------------------------------------------------------------------------
//
// Hide the bubble text if visible
//
void Amor::hideBubble(bool forceDequeue)
{
    if (mBubble)
    {
#ifdef DEBUG_AMOR
    kdDebug(10000) << "Amor::hideBubble(): Hiding tips bubble" << endl;
#endif

        // GP: stop mBubbleTimer to avoid deleting the first element, just in case we are changing windows
	// or something before the tip was shown long enough
        mBubbleTimer->stop();

	// GP: the first message on the queue should be taken off for a 
	// number of reasons: a) forceDequeue == true, only when called 
	// from slotBubbleTimeout; b) the bubble is not visible ; c) 
	// the bubble is visible, but there's Tip being displayed. The 
	// latter is to keep backwards compatibility and because 
	// carrying around a tip bubble when switching windows quickly is really 
	// annoyying
	if (forceDequeue || !mBubble->isVisible() || 
	    (mTipsQueue.head()->type() == QueueItem::Tip)) /* there's always an item in the queue here */
	    mTipsQueue.dequeue();

        delete mBubble;
        mBubble = 0;
    }
}

//---------------------------------------------------------------------------
//
// Select a new animation appropriate for the current state.
//
void Amor::selectAnimation(State state)
{
    switch (state)
    {
        case Blur:
            hideBubble();
            mCurrAnim = mTheme.random(ANIM_BLUR);
            mState = Focus;
            break;

        case Focus:
            hideBubble();
            mCurrAnim = mTheme.random(ANIM_FOCUS);
            mCurrAnim->reset();
            mTargetWin = mNextTarget;
            if (mTargetWin != None)
            {
                mTargetRect = KWin::windowInfo(mTargetWin).frameGeometry();

		// if the animation falls outside of the working area, 
		// then relocate it so that is inside the desktop again
		TQRect desktopArea = mWin->workArea();
		mInDesktopBottom = false;

		if (mTargetRect.y() - mCurrAnim->hotspot().y() + mConfig.mOffset <
		    desktopArea.y())
		{
		    // relocate the animation at the bottom of the screen
		    mTargetRect = TQRect(desktopArea.x(), 
				  desktopArea.y() + desktopArea.height(),
				  desktopArea.width(), 0);

		    // we'll relocate the animation in the desktop 
		    // frame, so do not add the offset to its vertical position
		    mInDesktopBottom = true;
		}

		if ( mTheme.isStatic() )
		{
		    if ( mConfig.mStaticPos < 0 )
			mPosition = mTargetRect.width() + mConfig.mStaticPos;
		    else
			mPosition = mConfig.mStaticPos;
		    if ( mPosition >= mTargetRect.width() )
			mPosition = mTargetRect.width()-1;
		    else if ( mPosition < 0 )
			mPosition = 0;
		}
		else
		{
		    if (mCurrAnim->frame())
		    {
		        if (mTargetRect.width() == mCurrAnim->frame()->width())
			    mPosition = mCurrAnim->hotspot().x();
			else
			    mPosition = ( kapp->random() %
					  (mTargetRect.width() - mCurrAnim->frame()->width()) )
					 + mCurrAnim->hotspot().x();
		    }
		    else
		    {
			mPosition = mTargetRect.width()/2;
		    }
		}
            }
            else
            {
                // We don't want to do anything until a window comes into
                // focus.
                mTimer->stop();
            }
            mAmor->hide();
	    
            restack();
            mState = Normal;
            break;

        case Destroy:
            hideBubble();
            mCurrAnim = mTheme.random(ANIM_DESTROY);
            mState = Focus;
            break;

        case Sleeping:
            mCurrAnim = mTheme.random(ANIM_SLEEP);
            break;

        case Waking:
            mCurrAnim = mTheme.random(ANIM_WAKE);
            mState = Normal;
            break;

        default:
            // Select a random normal animation if the current animation
            // is not the base, otherwise select the base.  This makes us
            // alternate between the base animation and a random
            // animination.
	    if (mCurrAnim == mBaseAnim && !mBubble)
            {
                mCurrAnim = mTheme.random(ANIM_NORMAL);
            }
            else
            {
                mCurrAnim = mBaseAnim;
            }
            break;
    }

    if (mCurrAnim->totalMovement() + mPosition > mTargetRect.width() ||
        mCurrAnim->totalMovement() + mPosition < 0)
    {
        // The selected animation would end outside of this window's width
        // We could randomly select a different one, but I prefer to just
        // use the default animation.
        mCurrAnim = mBaseAnim;
    }

    mCurrAnim->reset();
}

//---------------------------------------------------------------------------
//
// Set the animation's stacking order to be just above the target window's
// window decoration, or on top.
//
void Amor::restack()
{
    if (mTargetWin == None)
    {
        return;
    }

    if (mConfig.mOnTop)
    {
        // simply raise the widget to the top
        mAmor->raise();
        return;
    }

#ifdef DEBUG_AMOR
    kdDebug(10000) << "restacking" << endl;
#endif

    Window sibling = mTargetWin;
    Window dw, parent = None, *wins;

    do {
        unsigned int nwins = 0;

        // We must use the target window's parent as our sibling.
        // Is there a faster way to get parent window than XQueryTree?
        if (XQueryTree(qt_xdisplay(), sibling, &dw, &parent, &wins, &nwins))
        {
            if (nwins)
            {
                XFree(wins);
            }
        }

        if (parent != None && parent != dw )
            sibling = parent;
    } while ( parent != None && parent != dw );

    // Set animation's stacking order to be above the window manager's
    // decoration of target window.
    XWindowChanges values;
    values.sibling = sibling;
    values.stack_mode = Above;
    XConfigureWindow(qt_xdisplay(), mAmor->winId(), CWSibling | CWStackMode,
                     &values);
}

//---------------------------------------------------------------------------
//
// The user clicked on our animation.
//
void Amor::slotMouseClicked(const TQPoint &pos)
{
    bool restartTimer = mTimer->isActive();

    // Stop the animation while the menu is open.
    if (restartTimer)
    {
        mTimer->stop();
    }

    if (!mMenu)
    {
        KHelpMenu* help = new KHelpMenu(0, KGlobal::instance()->aboutData(), false);
        KPopupMenu* helpMnu = help->menu();
        mMenu = new KPopupMenu();
        mMenu->insertTitle("Amor"); // I really don't want this i18n'ed
        mMenu->insertItem(SmallIcon("configure"), i18n("&Configure..."), this, TQT_SLOT(slotConfigure()));
        mMenu->insertSeparator();
        mMenu->insertItem(SmallIcon("help"), i18n("&Help"), helpMnu);
        mMenu->insertItem(SmallIcon("exit"), i18n("&Quit"), kapp, TQT_SLOT(quit()));
    }

    mMenu->exec(pos);

    if (restartTimer)
    {
        mTimer->start(1000, true);
    }
}

//---------------------------------------------------------------------------
//
// Check cursor position
//
void Amor::slotCursorTimeout()
{
    TQPoint currPos = TQCursor::pos();
    TQPoint diff = currPos - mCursPos;
    time_t now = time(0);

    if (mForceHideAmorWidget) return; // we're hidden, do nothing

    if (abs(diff.x()) > 1 || abs(diff.y()) > 1)
    {
	if (mState == Sleeping)
	{
	    // Set waking immediatedly
	    selectAnimation(Waking);
	}
	mActiveTime = now;
	mCursPos = currPos;
    }
    else if (mState != Sleeping && now - mActiveTime > SLEEP_TIMEOUT)
    {
	// GP: can't go to sleep if there are tips in the queue
	if (mTipsQueue.isEmpty())
	    mState = Sleeping;	// The next animation will become sleeping
    }
}

//---------------------------------------------------------------------------
//
// Display the next frame or a new animation
//
void Amor::slotTimeout()
{
    if ( mForceHideAmorWidget )
        return;

    if (!mTheme.isStatic())
	mPosition += mCurrAnim->movement();
    mAmor->setPixmap(mCurrAnim->frame());
    mAmor->move(mTargetRect.x() + mPosition - mCurrAnim->hotspot().x(),
                 mTargetRect.y() - mCurrAnim->hotspot().y() + (!mInDesktopBottom?mConfig.mOffset:0));
    if (!mAmor->isVisible())
    {
        mAmor->show();
        restack();
    }

    if (mCurrAnim == mBaseAnim && mCurrAnim->validFrame())
    {
	// GP: Application tips/messages can be shown in any frame number; amor tips are 
	// only displayed on the first frame of mBaseAnim (the old way of doing this).
	if ( !mTipsQueue.isEmpty() && !mBubble &&  mConfig.mAppTips)
	    showBubble();
	else if (kapp->random()%TIP_FREQUENCY == 1 && mConfig.mTips && !mBubble && !mCurrAnim->frameNum())
        {
	    mTipsQueue.enqueue(new QueueItem(QueueItem::Tip, mTips.tip())); 
	    showBubble();
        }
    }

    if (mTheme.isStatic())
	mTimer->start((mState == Normal) || (mState == Sleeping) ? 1000 : 100, true);
    else
	mTimer->start(mCurrAnim->delay(), true);

    if (!mCurrAnim->next())
    {
	if ( mBubble )
	    mCurrAnim->reset();
	else
	    selectAnimation(mState);
    }
}

//---------------------------------------------------------------------------
//
// Display configuration dialog
//
void Amor::slotConfigure()
{
    if (!mAmorDialog)
    {
        mAmorDialog = new AmorDialog();
        connect(mAmorDialog, TQT_SIGNAL(changed()), TQT_SLOT(slotConfigChanged()));
        connect(mAmorDialog, TQT_SIGNAL(offsetChanged(int)),
                TQT_SLOT(slotOffsetChanged(int)));
    }

    mAmorDialog->show();
}

//--------------------------------------------------------------------------
//
// Configuration changed.
//
void Amor::slotConfigChanged()
{
    reset();
}

//---------------------------------------------------------------------------
//
// Offset changed
//
void Amor::slotOffsetChanged(int off)
{
    mConfig.mOffset = off;

    if (mCurrAnim->frame())
    {
        mAmor->move(mPosition + mTargetRect.x() - mCurrAnim->hotspot().x(),
                 mTargetRect.y() - mCurrAnim->hotspot().y() + (!mInDesktopBottom?mConfig.mOffset:0));
    }
}

//---------------------------------------------------------------------------
//
// Display About box
//
void Amor::slotAbout()
{
    TQString about = i18n("Amor Version %1\n\n").tqarg(AMOR_VERSION) +
                i18n("Amusing Misuse Of Resources\n\n") +
                i18n("Copyright (c) 1999 Martin R. Jones <mjones@kde.org>\n\n") +
		i18n("Original Author: Martin R. Jones <mjones@kde.org>\n") +
		i18n("Current Maintainer: Gerardo Puga <gpuga@gioia.ing.unlp.edu.ar>\n" ) +
                "\nhttp://www.powerup.com.au/~mjones/amor/";
    KMessageBox::about(0, about, i18n("About Amor"));
}

//---------------------------------------------------------------------------
//
// Widget dragged
//
void Amor::slotWidgetDragged( const TQPoint &delta, bool release )
{
    if (mCurrAnim->frame())
    {
	int newPosition = mPosition + delta.x();
	if (mCurrAnim->totalMovement() + newPosition > mTargetRect.width())
	    newPosition = mTargetRect.width() - mCurrAnim->totalMovement();
	else if (mCurrAnim->totalMovement() + newPosition < 0)
	    newPosition = -mCurrAnim->totalMovement();
	mPosition = newPosition;
        mAmor->move(mTargetRect.x() + mPosition - mCurrAnim->hotspot().x(),
                 mAmor->y());

	if ( mTheme.isStatic() && release ) {
	    // static animations save the new position as preferred.
	    int savePos = mPosition;
	    if ( savePos > mTargetRect.width()/2 )
		savePos -= (mTargetRect.width()+1);

	    mConfig.mStaticPos = savePos;
	    mConfig.write();
	}
    }
}

//---------------------------------------------------------------------------
//
// Focus changed to a different window
//
void Amor::slotWindowActivate(WId win)
{
#ifdef DEBUG_AMOR
    kdDebug(10000) << "Window activated:" << win << endl;
#endif

    mTimer->stop();
    mNextTarget = win;

    // This is an active event that affects the target window
    time(&mActiveTime);

    // A window gaining focus implies that the current window has lost
    // focus.  Initiate a blur event if there is a current active window.
    if (mTargetWin)
    {
        // We are losing focus from the current window
        selectAnimation(Blur);
        mTimer->start(0, true);
    }
    else if (mNextTarget)
    {
        // We are setting focus to a new window
        if (mState != Focus )
	    selectAnimation(Focus);
	mTimer->start(0, true);
    }
    else
    {
        // No action - We can get this when we switch between two empty
        // desktops
        mAmor->hide();
    }
}

//---------------------------------------------------------------------------
//
// Window removed
//
void Amor::slotWindowRemove(WId win)
{
#ifdef DEBUG_AMOR
    kdDebug(10000) << "Window removed" << endl;
#endif

    if (win == mTargetWin)
    {
        // This is an active event that affects the target window
        time(&mActiveTime);

        selectAnimation(Destroy);
        mTimer->stop();
        mTimer->start(0, true);
    }
}

//---------------------------------------------------------------------------
//
// Window stacking changed
//
void Amor::slotStackingChanged()
{
#ifdef DEBUG_AMOR
    kdDebug(10000) << "Stacking changed" << endl;
#endif

    // This is an active event that affects the target window
    time(&mActiveTime);

    // We seem to get this signal before the window has been restacked,
    // so we just schedule a restack.
    mStackTimer->start( 20, TRUE );
}

//---------------------------------------------------------------------------
//
// Properties of a window changed
//
void Amor::slotWindowChange(WId win, const unsigned long * properties)
{

    if (win != mTargetWin)
    {
        return;
    }

    // This is an active event that affects the target window
    time(&mActiveTime);

    KWin::Info info = KWin::info( mTargetWin );

    if (info.isIconified() ||
        info.mappingState == NET::Withdrawn)
    {
#ifdef DEBUG_AMOR
        kdDebug(10000) << "Target window iconified" << endl;
#endif

        // The target window has been iconified
        selectAnimation(Destroy);
        mTargetWin = None;
        mTimer->stop();
        mTimer->start(0, true);

	return;
    }
    
    if (properties[0] & NET::WMGeometry) 
    {
#ifdef DEBUG_AMOR
        kdDebug(10000) << "Target window moved or resized" << endl;
#endif

        TQRect newTargetRect = KWin::windowInfo(mTargetWin).frameGeometry();

	// if the change in the window caused the animation to fall 
	// out of the working area of the desktop, or if the animation 
	// didn't fall in the working area before but it does now, then
	//  refocus on the current window so that the animation is 
	// relocated.
	TQRect desktopArea = mWin->workArea();

	bool fitsInWorkArea = !(newTargetRect.y() - mCurrAnim->hotspot().y() + mConfig.mOffset < desktopArea.y()); 
	if ((!fitsInWorkArea && !mInDesktopBottom) || (fitsInWorkArea && mInDesktopBottom))
	{
	    mNextTarget = mTargetWin;
	    selectAnimation(Blur);
	    mTimer->start(0, true);

	    return;
	}

	if (!mInDesktopBottom)
	    mTargetRect = newTargetRect;

        // make sure the animation is still on the window.
        if (mCurrAnim->frame())
        {
            hideBubble();
	    if (mTheme.isStatic())
	    {
		if ( mConfig.mStaticPos < 0 )
		    mPosition = mTargetRect.width() + mConfig.mStaticPos;
		else
		    mPosition = mConfig.mStaticPos;
		if ( mPosition >= mTargetRect.width() )
		    mPosition = mTargetRect.width()-1;
		else if ( mPosition < 0 )
		    mPosition = 0;
	    }
            else if (mPosition > mTargetRect.width() -
                    (mCurrAnim->frame()->width() - mCurrAnim->hotspot().x()))
            {
                mPosition = mTargetRect.width() - (mCurrAnim->frame()->width() - mCurrAnim->hotspot().x());
            }
            mAmor->move(mTargetRect.x() + mPosition - mCurrAnim->hotspot().x(),
                     mTargetRect.y() - mCurrAnim->hotspot().y() + (!mInDesktopBottom?mConfig.mOffset:0));
        }

	return;
    }
}

//---------------------------------------------------------------------------
//
// Changed to a different desktop
//
void Amor::slotDesktopChange(int desktop)
{
    // GP: signal currentDesktopChanged seems to be emitted even if you 
    // change to the very same desktop you are in.
    if (mWin->currentDesktop() == desktop)
	return;

#ifdef DEBUG_AMOR
    kdDebug(10000) << "Desktop change" << endl;
#endif

    mNextTarget = None;
    mTargetWin = None;
    selectAnimation( Normal );
    mTimer->stop();
    mAmor->hide();
}

// GP ===========================================================================

void Amor::slotBubbleTimeout()
{
    // has the queue item been displayed for long enough?
    QueueItem *first = mTipsQueue.head();
#ifdef DEBUG_AMOR
    if (!first)	kdDebug(10000) << "Amor::slotBubbleTimeout(): empty queue!" << endl;
#endif
    if ((first->time() > BUBBLE_TIME_STEP) && (mBubble->isVisible()))
    {
    	first->setTime(first->time() - BUBBLE_TIME_STEP);
	mBubbleTimer->start(BUBBLE_TIME_STEP, true);
	return;
    }

    // do not do anything if the mouse pointer is in the bubble
    if (mBubble->mouseWithin())
    {
	first->setTime(500);		// show this item for another 500ms
	mBubbleTimer->start(BUBBLE_TIME_STEP, true);
	return;	
    }
    
    // are there any other tips pending?
    if (mTipsQueue.count() > 1)
    {
	mTipsQueue.dequeue();
	showBubble();	// shows the next item in the queue
    } else
	hideBubble(true); // hideBubble calls dequeue() for itself.
}

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

AmorSessionWidget::AmorSessionWidget()
{
    // the only function of this widget is to catch & forward the
    // saveYourself() signal from the session manager
    connect(kapp, TQT_SIGNAL(saveYourself()), TQT_SLOT(wm_saveyourself()));
}

void AmorSessionWidget::wm_saveyourself()
{
    // no action required currently.
}