summaryrefslogtreecommitdiffstats
path: root/kicker/taskbar/taskbar.cpp
blob: ddeef37a5259571afd8285fb5bacd41b21a0e4e4 (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
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
/*****************************************************************

Copyright (c) 2001 Matthias Elter <elter@kde.org>
Copyright (c) 2004 Sebastian Wolff
Copyright (c) 2005 Aaron Seigo <aseigo@kde.org>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

******************************************************************/

#include <math.h>

#include <tqapplication.h>
#include <tqbitmap.h>
#include <tqdesktopwidget.h>
#include <tqlayout.h>
#include <tqpainter.h>
#include <tqstringlist.h>

#include <dcopclient.h>
#include <kapplication.h>
#include <kdebug.h>
#include <kglobal.h>
#include <kglobalaccel.h>
#include <kimageeffect.h>
#include <klocale.h>
#include <kstandarddirs.h>

#include "kickerSettings.h"
#include "taskbarsettings.h"
#include "taskcontainer.h"
#include "taskmanager.h"

#include "taskbar.h"
#include "taskbar.moc"


TaskBar::TaskBar( TaskBarSettings* settingsObject, TQWidget *parent, const char *name )
    : Panner( parent, name ),
      m_showAllWindows(false),
      m_cycleWheel(false),
      m_currentScreen(-1),
      m_showOnlyCurrentScreen(false),
      m_sortByDesktop(false),
      m_showIcon(false),
      m_showOnlyIconified(false),
      m_showTaskStates(0),
      m_textShadowEngine(0),
      m_ignoreUpdates(false),
      m_relayoutTimer(0, "TaskBar::m_relayoutTimer")
{
    arrowType = LeftArrow;
    blocklayout = true;

    m_settingsObject = settingsObject;
    if (m_settingsObject)
    {
        m_settingsObject->readConfig();
    }

    // init
    setSizePolicy( TQSizePolicy( TQSizePolicy::Expanding, TQSizePolicy::Expanding ) );

    // setup animation frames
    for (int i = 1; i < 11; i++)
    {
        frames.append(new TQPixmap(locate("data", "kicker/pics/disk" + TQString::number(i) + ".png")));
    }

    // configure
    configure();

    connect(&m_relayoutTimer, TQT_SIGNAL(timeout()),
            this, TQT_SLOT(reLayout()));

		connect(this, TQT_SIGNAL(contentsMoving(int, int)), TQT_SLOT(setBackground()));

    // connect manager
    connect(TaskManager::the(), TQT_SIGNAL(taskAdded(Task::Ptr)),
            this, TQT_SLOT(add(Task::Ptr)));
    connect(TaskManager::the(), TQT_SIGNAL(taskRemoved(Task::Ptr)),
            this, TQT_SLOT(remove(Task::Ptr)));
    connect(TaskManager::the(), TQT_SIGNAL(startupAdded(Startup::Ptr)),
            this, TQT_SLOT(add(Startup::Ptr)));
    connect(TaskManager::the(), TQT_SIGNAL(startupRemoved(Startup::Ptr)),
            this, TQT_SLOT(remove(Startup::Ptr)));
    connect(TaskManager::the(), TQT_SIGNAL(desktopChanged(int)),
            this, TQT_SLOT(desktopChanged(int)));
    connect(TaskManager::the(), TQT_SIGNAL(windowChanged(Task::Ptr)),
            this, TQT_SLOT(windowChanged(Task::Ptr)));

    isGrouping = shouldGroup();

    // register existant tasks
    Task::Dict tasks = TaskManager::the()->tasks();
    Task::Dict::iterator taskEnd = tasks.end();
    for (Task::Dict::iterator it = tasks.begin(); it != taskEnd; ++it)
    {
        add(it.data());
    }

    // register existant startups
    Startup::List startups = TaskManager::the()->startups();
    Startup::List::iterator startupEnd = startups.end();
    for (Startup::List::iterator sIt = startups.begin(); sIt != startupEnd; ++sIt)
    {
        add((*sIt));
    }

    blocklayout = false;

    connect(kapp, TQT_SIGNAL(settingsChanged(int)), TQT_SLOT(slotSettingsChanged(int)));
    keys = new TDEGlobalAccel( TQT_TQOBJECT(this) );
#include "taskbarbindings.cpp"
    keys->readSettings();
    keys->updateConnections();

    reLayout();
}

TaskBar::~TaskBar()
{
    for (TaskContainer::Iterator it = m_hiddenContainers.begin();
         it != m_hiddenContainers.end();
         ++it)
    {
        (*it)->deleteLater();
    }

    for (TaskContainer::List::const_iterator it = containers.constBegin();
         it != containers.constEnd();
         ++it)
    {
        (*it)->deleteLater();
    }

    for (PixmapList::const_iterator it = frames.constBegin();
         it != frames.constEnd();
         ++it)
    {
        delete *it;
    }

    delete m_textShadowEngine;
}

KTextShadowEngine *TaskBar::textShadowEngine()
{
    if (!m_textShadowEngine)
        m_textShadowEngine = new KTextShadowEngine();

    return m_textShadowEngine;
}


TQSize TaskBar::sizeHint() const
{
    // get our minimum height based on the minimum button height or the
    // height of the font in use, which is largest
    TQFontMetrics fm(TDEGlobalSettings::taskbarFont());
    int minButtonHeight = fm.height() > m_settingsObject->minimumButtonHeight() ?
                          fm.height() : m_settingsObject->minimumButtonHeight();

    return TQSize(BUTTON_MIN_WIDTH, minButtonHeight);
}

TQSize TaskBar::sizeHint( KPanelExtension::Position p, TQSize maxSize) const
{
    // get our minimum height based on the minimum button height or the
    // height of the font in use, which is largest
    TQFontMetrics fm(TDEGlobalSettings::taskbarFont());
    int minButtonHeight = fm.height() > m_settingsObject->minimumButtonHeight() ?
                          fm.height() : m_settingsObject->minimumButtonHeight();

    if ( p == KPanelExtension::Left || p == KPanelExtension::Right )
    {
        int actualMax = minButtonHeight * containerCount();

        if (containerCount() == 0)
        {
            actualMax = minButtonHeight;
        }

        if (actualMax > maxSize.height())
        {
            return maxSize;
        }
        return TQSize( maxSize.width(), actualMax );
    }
    else
    {
        int rows = KickerSettings::conserveSpace() ?
                   contentsRect().height() / minButtonHeight :
                   1;
        if ( rows < 1 )
        {
            rows = 1;
        }

        int maxWidth = m_settingsObject->maximumButtonWidth();
        if (maxWidth == 0)
        {
            maxWidth = BUTTON_MAX_WIDTH;
        }

        int actualMax = maxWidth * (containerCount() / rows);

        if (containerCount() % rows > 0)
        {
            actualMax += maxWidth;
        }
        if (containerCount() == 0)
        {
            actualMax = maxWidth;
        }

        if (actualMax > maxSize.width())
        {
           return maxSize;
        }
        return TQSize( actualMax, maxSize.height() );
    }
}

void TaskBar::configure()
{
    bool wasShowWindows = m_showAllWindows;
    bool wasSortByDesktop = m_sortByDesktop;
    bool wasCycleWheel = m_cycleWheel;
    bool wasShowIcon = m_showIcon;
    bool wasShowOnlyIconified = m_showOnlyIconified;
    int  wasShowTaskStates = m_showTaskStates;

    m_showAllWindows = m_settingsObject->showAllWindows();
    m_sortByDesktop = m_showAllWindows && m_settingsObject->sortByDesktop();
    m_showIcon = m_settingsObject->showIcon();
    m_showOnlyIconified = m_settingsObject->showOnlyIconified();
    m_cycleWheel = m_settingsObject->cycleWheel();
    m_showTaskStates = m_settingsObject->showTaskStates();

    m_currentScreen = -1;    // Show all screens or re-get our screen
    m_showOnlyCurrentScreen = (m_settingsObject->showCurrentScreenOnly() &&
                              TQApplication::desktop()->isVirtualDesktop() &&
                              TQApplication::desktop()->numScreens() > 1) || (TQApplication::desktop()->numScreens() < 2);

    // we need to watch geometry issues if we aren't showing windows when we
    // are paying attention to the current Xinerama screen
    if (m_showOnlyCurrentScreen)
    {
        // disconnect first in case we've been here before
        // to avoid multiple connections
        disconnect(TaskManager::the(), TQT_SIGNAL(windowChangedGeometry(Task::Ptr)),
                    this, TQT_SLOT(windowChangedGeometry(Task::Ptr)));
        connect(TaskManager::the(), TQT_SIGNAL(windowChangedGeometry(Task::Ptr)),
                 this, TQT_SLOT(windowChangedGeometry(Task::Ptr)));
    }
    TaskManager::the()->trackGeometry(m_showOnlyCurrentScreen);

    if (wasShowWindows != m_showAllWindows ||
        wasSortByDesktop != m_sortByDesktop ||
        wasShowIcon != m_showIcon ||
        wasCycleWheel != m_cycleWheel ||
        wasShowOnlyIconified != m_showOnlyIconified ||
        wasShowTaskStates != m_showTaskStates)
    {
        // relevant settings changed, update our task containers
        for (TaskContainer::Iterator it = containers.begin();
             it != containers.end();
             ++it)
        {
            (*it)->settingsChanged();
        }
    }

    TaskManager::the()->setXCompositeEnabled(m_settingsObject->showThumbnails());

    reLayoutEventually();
}

void TaskBar::setOrientation( Orientation o )
{
    Panner::setOrientation( o );
    reLayoutEventually();
}

void TaskBar::moveEvent( TQMoveEvent* e )
{
    Panner::moveEvent(e);
    setViewportBackground();
}

void TaskBar::resizeEvent( TQResizeEvent* e )
{
    if (m_showOnlyCurrentScreen)
    {
        TQPoint topLeft = mapToGlobal(this->geometry().topLeft());
        if (m_currentScreen != TQApplication::desktop()->screenNumber(topLeft))
        {
            // we have been moved to another screen!
            m_currentScreen = -1;
            reGroup();
        }
    }

    Panner::resizeEvent(e);
    reLayoutEventually();
    setViewportBackground();
}

void TaskBar::add(Task::Ptr task)
{
    if (!task ||
        (m_showOnlyCurrentScreen &&
         !TaskManager::isOnScreen(showScreen(), task->window())))
    {
        return;
    }

    // try to group
    if (isGrouping)
    {
        for (TaskContainer::Iterator it = containers.begin();
             it != containers.end();
             ++it)
        {
            TaskContainer* c = *it;

            if (idMatch(task->classClass(), c->id()))
            {
                c->add(task);
                reLayoutEventually();
                return;
            }
        }
    }

    // create new container
    TaskContainer *container = new TaskContainer(task, this, m_settingsObject, viewport());
    m_hiddenContainers.append(container);

    // even though there is a signal to listen to, we have to add this
    // immediately to ensure grouping doesn't break (primarily on startup)
    // we still add the container to m_hiddenContainers in case the event
    // loop gets re-entered here and something bizarre happens. call it
    // insurance =)
    showTaskContainer(container);
}

void TaskBar::add(Startup::Ptr startup)
{
    if (!startup)
    {
        return;
    }

    for (TaskContainer::Iterator it = containers.begin();
         it != containers.end();
         ++it)
    {
        if ((*it)->contains(startup))
        {
            return;
        }
    }

    // create new container
    TaskContainer *container = new TaskContainer(startup, frames, this, m_settingsObject, viewport());
    m_hiddenContainers.append(container);
    connect(container, TQT_SIGNAL(showMe(TaskContainer*)), this, TQT_SLOT(showTaskContainer(TaskContainer*)));
}

void TaskBar::showTaskContainer(TaskContainer* container)
{
    TaskContainer::List::iterator it = m_hiddenContainers.find(container);
    if (it != m_hiddenContainers.end())
    {
        m_hiddenContainers.erase(it);
    }

    if (container->isEmpty())
    {
        return;
    }

    // try to place the container after one of the same app
    if (m_settingsObject->sortByApp())
    {
        TaskContainer::Iterator it = containers.begin();
        for (; it != containers.end(); ++it)
        {
            TaskContainer* c = *it;

            if (container->id().lower() == c->id().lower())
            {
                // search for the last occurrence of this app
                for (; it != containers.end(); ++it)
                {
                    c = *it;

                    if (container->id().lower() != c->id().lower())
                    {
                        break;
                    }
                }
                break;
            }
        }

        if (it != containers.end())
        {
            containers.insert(it, container);
        }
        else
        {
            containers.append(container);
        }
    }
    else
    {
        containers.append(container);
    }

    addChild(container);
    reLayoutEventually();
    emit containerCountChanged();
}

void TaskBar::remove(Task::Ptr task, TaskContainer* container)
{
    for (TaskContainer::Iterator it = m_hiddenContainers.begin();
         it != m_hiddenContainers.end();
         ++it)
    {
        if ((*it)->contains(task))
        {
            (*it)->finish();
            m_deletableContainers.append(*it);
            m_hiddenContainers.erase(it);
            break;
        }
    }

    if (!container)
    {
        for (TaskContainer::Iterator it = containers.begin();
             it != containers.end();
             ++it)
        {
            if ((*it)->contains(task))
            {
                container = *it;
                break;
            }
        }

        if (!container)
        {
            return;
        }
    }

    container->remove(task);

    if (container->isEmpty())
    {
        TaskContainer::List::iterator it = containers.find(container);
        if (it != containers.end())
        {
            containers.erase(it);
        }

        removeChild(container);
        container->finish();
        m_deletableContainers.append(container);

        reLayoutEventually();
        emit containerCountChanged();
    }
    else if (container->filteredTaskCount() < 1)
    {
        reLayoutEventually();
        emit containerCountChanged();
    }
}

void TaskBar::remove(Startup::Ptr startup, TaskContainer* container)
{
    for (TaskContainer::Iterator it = m_hiddenContainers.begin();
         it != m_hiddenContainers.end();
         ++it)
    {
        if ((*it)->contains(startup))
        {
            (*it)->remove(startup);

            if ((*it)->isEmpty())
            {
                (*it)->finish();
                m_deletableContainers.append(*it);
                m_hiddenContainers.erase(it);
            }

            break;
        }
    }

    if (!container)
    {
        for (TaskContainer::Iterator it = containers.begin();
             it != containers.end();
             ++it)
        {
            if ((*it)->contains(startup))
            {
                container = *it;
                break;
            }
        }

        if (!container)
        {
            return;
        }
    }

    container->remove(startup);
    if (!container->isEmpty())
    {
        return;
    }

    TaskContainer::List::iterator it = containers.find(container);
    if (it != containers.end())
    {
        containers.erase(it);
    }

    // startup containers only ever contain that one item. so
    // just delete the poor bastard.
    container->finish();
    m_deletableContainers.append(container);
    reLayoutEventually();
    emit containerCountChanged();
}

void TaskBar::desktopChanged(int desktop)
{
    if (m_showAllWindows)
    {
        return;
    }

    m_relayoutTimer.stop();
    m_ignoreUpdates = true;
    for (TaskContainer::Iterator it = containers.begin();
         it != containers.end();
         ++it)
    {
        (*it)->desktopChanged(desktop);
    }

    m_ignoreUpdates = false;
    reLayout();
    emit containerCountChanged();
}

void TaskBar::windowChanged(Task::Ptr task)
{
    if (m_showOnlyCurrentScreen &&
        !TaskManager::isOnScreen(showScreen(), task->window()))
    {
        return; // we don't care about this window
    }

    TaskContainer* container = 0;
    for (TaskContainer::List::const_iterator it = containers.constBegin();
         it != containers.constEnd();
         ++it)
    {
        TaskContainer* c = *it;

        if (c->contains(task))
        {
            container = c;
            break;
        }
    }

    // if we don't have a container or we're showing only windows on this
    // desktop and the container is neither on the desktop nor currently visible
    // just skip it
    if (!container ||
        (!m_showAllWindows &&
         !container->onCurrentDesktop() &&
         !container->isVisibleTo(this)))
    {
        return;
    }

    container->windowChanged(task);

    if (!m_showAllWindows || m_showOnlyIconified)
    {
        emit containerCountChanged();
    }

    reLayoutEventually();
}

void TaskBar::windowChangedGeometry(Task::Ptr task)
{
    //TODO: this gets called every time a window's geom changes
    //      when we are in "show only on the same Xinerama screen"
    //      mode it would be Good(tm) to compress these events so this
    //      gets run less often, but always when needed
    TaskContainer* container = 0;
    for (TaskContainer::Iterator it = containers.begin();
         it != containers.end();
         ++it)
    {
        TaskContainer* c = *it;
        if (c->contains(task))
        {
            container = c;
            break;
        }
    }

    if ((!!container) == TaskManager::isOnScreen(showScreen(), task->window()))
    {
        // we have this window covered, so we don't need to do anything
        return;
    }

    if (container)
    {
        remove(task, container);
    }
    else
    {
        add(task);
    }
}

void TaskBar::reLayoutEventually()
{
    m_relayoutTimer.stop();

    if (!blocklayout && !m_ignoreUpdates)
    {
        m_relayoutTimer.start(25, true);
    }
}

void TaskBar::reLayout()
{
    // Because TQPopupMenu::exec() creates its own event loop, deferred deletes
    // via TQObject::deleteLater() may be prematurely executed when a container's
    // popup menu is visible.
    //
    // To get around this, we collect the containers and delete them manually
    // when doing a relayout. (kling)
    if (!m_deletableContainers.isEmpty()) {
        TaskContainer::List::iterator it = m_deletableContainers.begin();
        for (; it != m_deletableContainers.end(); ++it)
            delete *it;
        m_deletableContainers.clear();
    }

    // filter task container list
    TaskContainer::List list = filteredContainers();

    if (list.count() < 1)
    {
        resizeContents(contentsRect().width(), contentsRect().height());
        return;
    }

    if (isGrouping != shouldGroup())
    {
        reGroup();
        return;
    }

    // sort container list by desktop
    if (m_sortByDesktop)
    {
        sortContainersByDesktop(list);
    }

    // needed because Panner doesn't know how big it's contents are so it's
    // up to us to initialize it. =(
    resizeContents(contentsRect().width(), contentsRect().height());

    // number of rows simply depends on our height which is either the
    // minimum button height or the height of the font in use, whichever is
    // largest
    TQFontMetrics fm(TDEGlobalSettings::taskbarFont());
    int minButtonHeight = fm.height() > m_settingsObject->minimumButtonHeight() ?
                          fm.height() : m_settingsObject->minimumButtonHeight();

    // horizontal layout
    if (orientation() == Qt::Horizontal)
    {
        int bwidth = BUTTON_MIN_WIDTH;
        int rows = contentsRect().height() / minButtonHeight;

        if ( rows < 1 )
        {
            rows = 1;
        }

        // actual button height
        int bheight = contentsRect().height() / rows;

        // avoid zero devision later
        if (bheight < 1)
        {
            bheight = 1;
        }

        // buttons per row
        int bpr = (int)ceil( (double)list.count() / rows);

        // adjust content size
        if ( contentsRect().width() < bpr * BUTTON_MIN_WIDTH )
        {
            resizeContents( bpr * BUTTON_MIN_WIDTH, contentsRect().height() );
        }

        // maximum number of buttons per row
        int mbpr = contentsRect().width() / BUTTON_MIN_WIDTH;

        // expand button width if space permits
        if (mbpr > bpr)
        {
            bwidth = contentsRect().width() / bpr;
            int maxWidth = m_settingsObject->maximumButtonWidth();
            if (maxWidth > 0 && bwidth > maxWidth)
            {
                bwidth = maxWidth;
            }
        }

        // layout containers

        // for taskbars at the bottom, we need to ensure that the bottom
        // buttons touch the bottom of the screen. since we layout from
        // top to bottom this means seeing if we have any padding and
        // popping it on the top. this preserves Fitt's Law behaviour
        // for taskbars on the bottom
        int topPadding = 0;
        if (arrowType == UpArrow)
        {
            topPadding = contentsRect().height() % (rows * bheight);
        }

        int i = 0;
        bool reverseLayout = TQApplication::reverseLayout();
        for (TaskContainer::Iterator it = list.begin();
             it != list.end();
             ++it, i++)
        {
            TaskContainer* c = *it;

            int row = i % rows;

            int x = ( i / rows ) * bwidth;
            if (reverseLayout)
            {
                x = contentsRect().width() - x - bwidth;
            }
            int y = (row * bheight) + topPadding;

            c->setArrowType(arrowType);
            
            if (childX(c) != x || childY(c) != y)
                moveChild(c, x, y);
                
            if (c->width() != bwidth || c->height() != bheight)
                c->resize( bwidth, bheight );
                
            c->setBackground();
        }
    }
    else // vertical layout
    {
        // adjust content size
        if (contentsRect().height() < (int)list.count() * minButtonHeight)
        {
            resizeContents(contentsRect().width(), list.count() * minButtonHeight);
        }

        // layout containers
        int i = 0;
        for (TaskContainer::Iterator it = list.begin();
             it != list.end();
             ++it)
        {
            TaskContainer* c = *it;

            c->setArrowType(arrowType);
            
            if (c->width() != contentsRect().width() || c->height() != minButtonHeight)
                c->resize(contentsRect().width(), minButtonHeight);

            if (childX(c) != 0 || childY(c) != (i * minButtonHeight))
                moveChild(c, 0, i * minButtonHeight);
            
            c->setBackground();
            i++;
        }
    }
    
    TQTimer::singleShot(100, this, TQT_SLOT(publishIconGeometry()));
}

void TaskBar::setViewportBackground()
{
    const TQPixmap *bg = parentWidget()->backgroundPixmap();
    
    if (bg)
    {
        TQPixmap pm(parentWidget()->size());
        pm.fill(parentWidget(), pos() + viewport()->pos());
        viewport()->setPaletteBackgroundPixmap(pm);
        viewport()->setBackgroundOrigin(WidgetOrigin);
    }
    else
        viewport()->setPaletteBackgroundColor(paletteBackgroundColor());
}

void TaskBar::setBackground()
{
    setViewportBackground();
    
    TaskContainer::List list = filteredContainers();
    
    for (TaskContainer::Iterator it = list.begin();
            it != list.end();
            ++it)
    {
        TaskContainer* c = *it;
        c->setBackground();
    }
}

void TaskBar::setArrowType(TQt::ArrowType at)
{
    if (arrowType == at)
    {
        return;
    }

    arrowType = at;
    for (TaskContainer::Iterator it = containers.begin();
         it != containers.end();
         ++it)
    {
        (*it)->setArrowType(arrowType);
    }
}

void TaskBar::publishIconGeometry()
{
    TQPoint p = mapToGlobal(TQPoint(0,0)); // roundtrip, don't do that too often

    for (TaskContainer::Iterator it = containers.begin();
         it != containers.end();
         ++it)
    {
        (*it)->publishIconGeometry(p);
    }
}

void TaskBar::viewportMousePressEvent( TQMouseEvent* e )
{
    propagateMouseEvent( e );
}

void TaskBar::viewportMouseReleaseEvent( TQMouseEvent* e )
{
    propagateMouseEvent( e );
}

void TaskBar::viewportMouseDoubleClickEvent( TQMouseEvent* e )
{
    propagateMouseEvent( e );
}

void TaskBar::viewportMouseMoveEvent( TQMouseEvent* e )
{
    propagateMouseEvent( e );
}

void TaskBar::propagateMouseEvent( TQMouseEvent* e )
{
    if ( !isTopLevel()  )
    {
        TQMouseEvent me( e->type(), mapTo( topLevelWidget(), e->pos() ),
                        e->globalPos(), e->button(), e->state() );
        TQApplication::sendEvent( topLevelWidget(), &me );
    }
}

bool TaskBar::idMatch( const TQString& id1, const TQString& id2 )
{
    if ( id1.isEmpty() || id2.isEmpty() )
        return false;

    return id1.lower() == id2.lower();
}

int TaskBar::containerCount() const
{
    int i = 0;

    for (TaskContainer::List::const_iterator it = containers.constBegin();
         it != containers.constEnd();
         ++it)
    {
        if ((m_showAllWindows || (*it)->onCurrentDesktop()) &&
            ((showScreen() == -1) || ((*it)->isOnScreen())))
        {
            if (!(*it)->isHidden())
            {
                i++;
            }
        }
    }

    return i;
}

int TaskBar::taskCount() const
{
    int i = 0;

    for (TaskContainer::List::const_iterator it = containers.constBegin();
         it != containers.constEnd();
         ++it)
    {
        if ((m_showAllWindows || (*it)->onCurrentDesktop()) &&
            ((showScreen() == -1) || ((*it)->isOnScreen())))
        {
            if (!(*it)->isHidden())
            {
                i += (*it)->filteredTaskCount();
            }
        }
    }

    return i;
}

int TaskBar::maximumButtonsWithoutShrinking() const
{
    TQFontMetrics fm(TDEGlobalSettings::taskbarFont());
    int minButtonHeight = fm.height() > m_settingsObject->minimumButtonHeight() ?
                          fm.height() : m_settingsObject->minimumButtonHeight();
    int rows = contentsRect().height() / minButtonHeight;

    if (rows < 1)
    {
        rows = 1;
    }

    if ( orientation() == Qt::Horizontal ) {
        // maxWidth of 0 means no max width, drop back to default
        int maxWidth = m_settingsObject->maximumButtonWidth();
        if (maxWidth == 0)
        {
            maxWidth = BUTTON_MAX_WIDTH;
        }

        // They squash a bit before they pop, hence the 2
        return rows * (contentsRect().width() / maxWidth) + 2;
    }
    else
    {
        // Overlap slightly and ugly arrows appear, hence -1
        return rows - 1;
    }
}

bool TaskBar::shouldGroup() const
{
    return m_settingsObject->groupTasks() == m_settingsObject->GroupAlways ||
           (m_settingsObject->groupTasks() == m_settingsObject->GroupWhenFull &&
            taskCount() > maximumButtonsWithoutShrinking());
}

void TaskBar::reGroup()
{
    isGrouping = shouldGroup();
    blocklayout = true;

    TaskContainer::Iterator lastContainer = m_hiddenContainers.end();
    for (TaskContainer::Iterator it = m_hiddenContainers.begin();
         it != lastContainer;
         ++it)
    {
        (*it)->finish();
        m_deletableContainers.append(*it);
    }
    m_hiddenContainers.clear();

    for (TaskContainer::List::const_iterator it = containers.constBegin();
         it != containers.constEnd();
         ++it)
    {
        (*it)->finish();
        m_deletableContainers.append(*it);
    }
    containers.clear();

    Task::Dict tasks = TaskManager::the()->tasks();
    Task::Dict::iterator lastTask = tasks.end();
    for (Task::Dict::iterator it = tasks.begin(); it != lastTask; ++it)
    {
        Task::Ptr task = it.data();
        if (showScreen() == -1 || task->isOnScreen(showScreen()))
        {
            add(task);
        }
    }

    Startup::List startups = TaskManager::the()->startups();
    Startup::List::iterator itEnd = startups.end();
    for (Startup::List::iterator sIt = startups.begin(); sIt != itEnd; ++sIt)
    {
        add(*sIt);
    }

    blocklayout = false;
    reLayoutEventually();
}


TaskContainer::List TaskBar::filteredContainers()
{
    // filter task container list
    TaskContainer::List list;

    for (TaskContainer::List::const_iterator it = containers.constBegin();
        it != containers.constEnd();
        ++it)
    {
        TaskContainer* c = *it;
        if ((m_showAllWindows || c->onCurrentDesktop()) &&
            (!m_showOnlyIconified || c->isIconified()) &&
            ((showScreen() == -1) || c->isOnScreen()) &&
            (!c->isHidden()))
        {
            list.append(c);
            c->show();
        }
        else
        {
            c->hide();
        }
    }
        
    return list;
}

void TaskBar::activateNextTask(bool forward)
{
    bool forcenext = false;
    TaskContainer::List list = filteredContainers();

    // this is necessary here, because 'containers' is unsorted and
    // we want to iterate over the _shown_ task containers in a linear way
    if (m_sortByDesktop)
    {
        sortContainersByDesktop(list);
    }

    int numContainers = list.count();
    TaskContainer::List::iterator it;
    for (int i = 0; i < numContainers; ++i)
    {
        it = forward ? list.at(i) : list.at(numContainers - i - 1);

        if (it != list.end() && (*it)->activateNextTask(forward, forcenext))
        {
            return;
        }
    }

    if (forcenext)
    {
        // moving forward from the last, or backward from the first, loop around
        for (int i = 0; i < numContainers; ++i)
        {
            it = forward ? list.at(i) : list.at(numContainers - i - 1);

            if (it != list.end() && (*it)->activateNextTask(forward, forcenext))
            {
                return;
            }
        }

        return;
    }

    forcenext = true; // select first
    for (int i = 0; i < numContainers; ++i)
    {
        it = forward ? list.at(i) : list.at(numContainers - i - 1);

        if (it == list.end())
        {
            break;
        }

        TaskContainer* c = *it;
        if (m_sortByDesktop)
        {
            if (forward ? c->desktop() < TaskManager::the()->currentDesktop()
                        : c->desktop() > TaskManager::the()->currentDesktop())
            {
                continue;
            }
        }

        if (c->activateNextTask(forward, forcenext))
        {
            return;
        }
    }
}

void TaskBar::wheelEvent(TQWheelEvent* e)
{

    if(m_settingsObject->cycleWheel()) {

        if (e->delta() > 0)
        {
            // scroll away from user, previous task
            activateNextTask(false);
        }
        else
        {
            // scroll towards user, next task
            activateNextTask(true);
        }
    }
}

void TaskBar::slotActivateNextTask()
{
    activateNextTask( true );
}

void TaskBar::slotActivatePreviousTask()
{
    activateNextTask( false );
}

void TaskBar::slotSettingsChanged( int category )
{
    if( category == (int) TDEApplication::SETTINGS_SHORTCUTS )
    {
        keys->readSettings();
        keys->updateConnections();
    }
}

int TaskBar::showScreen() const
{
    if (m_showOnlyCurrentScreen && m_currentScreen == -1)
    {
        const_cast<TaskBar*>(this)->m_currentScreen =
            TQApplication::desktop()->screenNumber(mapToGlobal(this->geometry().topLeft()));
    }

    return m_currentScreen;
}

TQImage* TaskBar::blendGradient(const TQSize& size)
{
    if (m_blendGradient.isNull() || m_blendGradient.size() != size)
    {
        TQPixmap bgpm(size);
        TQPainter bgp(&bgpm);
        bgpm.fill(black);

        if (TQApplication::reverseLayout())
        {
            TQImage gradient = KImageEffect::gradient(
                    TQSize(30, size.height()),
                    TQColor(255,255,255),
                    TQColor(0,0,0),
                    KImageEffect::HorizontalGradient);
            bgp.drawImage(0, 0, gradient);
        }
        else
        {
            TQImage gradient = KImageEffect::gradient(
                    TQSize(30, size.height()),
                    TQColor(0,0,0),
                    TQColor(255,255,255),
                    KImageEffect::HorizontalGradient);
            bgp.drawImage(size.width() - 30, 0, gradient);
        }

        m_blendGradient = bgpm.convertToImage();
    }

    return &m_blendGradient;
}

void TaskBar::sortContainersByDesktop(TaskContainer::List& list)
{
    typedef TQValueVector<QPair<int, QPair<int, TaskContainer*> > > SortVector;
    SortVector sorted;
    sorted.resize(list.count());
    int i = 0;

    TaskContainer::List::ConstIterator lastUnsorted(list.constEnd());
    for (TaskContainer::List::ConstIterator it = list.constBegin();
            it != lastUnsorted;
            ++it)
    {
        sorted[i] = qMakePair((*it)->desktop(), qMakePair(i, *it));
        ++i;
    }

    qHeapSort(sorted);

    list.clear();
    SortVector::const_iterator lastSorted(sorted.constEnd());
    for (SortVector::const_iterator it = sorted.constBegin();
         it != lastSorted;
         ++it)
    {
        list.append((*it).second.second);
    }
}