File: kpopupmenu.cpp

package info (click to toggle)
kdelibs 4%3A3.5.10.dfsg.1-5%2Bdeb6u1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze-lts
  • size: 98,764 kB
  • ctags: 76,783
  • sloc: cpp: 578,944; xml: 117,726; ansic: 28,321; sh: 11,188; perl: 6,290; java: 4,069; makefile: 3,795; yacc: 2,437; lex: 643; ruby: 329; asm: 166; jsp: 128; haskell: 116; f90: 99; ml: 75; awk: 71; tcl: 29; lisp: 24; php: 9
file content (689 lines) | stat: -rw-r--r-- 17,873 bytes parent folder | download | duplicates (5)
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
/* This file is part of the KDE libraries
   Copyright (C) 2000 Daniel M. Duley <mosfet@kde.org>
   Copyright (C) 2002 Hamish Rodda <rodda@kde.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 as published by the Free Software Foundation.

   This library 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/
#include <qcursor.h>
#include <qpainter.h>
#include <qtimer.h>
#include <qfontmetrics.h>
#include <qstyle.h>

#include "kpopupmenu.h"

#include <kdebug.h>
#include <kapplication.h>

KPopupTitle::KPopupTitle(QWidget *parent, const char *name)
    : QWidget(parent, name)
{
    setMinimumSize(16, fontMetrics().height()+8);
}

KPopupTitle::KPopupTitle(KPixmapEffect::GradientType /* gradient */,
                         const QColor &/* color */, const QColor &/* textColor */,
                         QWidget *parent, const char *name)
   : QWidget(parent, name)
{
    calcSize();
}

KPopupTitle::KPopupTitle(const KPixmap & /* background */, const QColor &/* color */,
                         const QColor &/* textColor */, QWidget *parent,
                         const char *name)
    : QWidget(parent, name)
{
    calcSize();
}

void KPopupTitle::setTitle(const QString &text, const QPixmap *icon)
{
    titleStr = text;
    if (icon)
        miniicon = *icon;
    else
        miniicon.resize(0, 0);

    calcSize();
}

void KPopupTitle::setText( const QString &text )
{
    titleStr = text;
    calcSize();
}

void KPopupTitle::setIcon( const QPixmap &pix )
{
    miniicon = pix;
    calcSize();
}

void KPopupTitle::calcSize()
{
    QFont f = font();
    f.setBold(true);
    int w = miniicon.width()+QFontMetrics(f).width(titleStr);
    int h = QMAX( fontMetrics().height(), miniicon.height() );
    setMinimumSize( w+16, h+8 );
}

void KPopupTitle::paintEvent(QPaintEvent *)
{
    QRect r(rect());
    QPainter p(this);
    kapp->style().drawPrimitive(QStyle::PE_HeaderSection, &p, r, palette().active());

    if (!miniicon.isNull())
        p.drawPixmap(4, (r.height()-miniicon.height())/2, miniicon);

    if (!titleStr.isNull())
    {
        p.setPen(palette().active().text());
        QFont f = p.font();
        f.setBold(true);
        p.setFont(f);
        if(!miniicon.isNull())
        {
            p.drawText(miniicon.width()+8, 0, width()-(miniicon.width()+8),
                       height(), AlignLeft | AlignVCenter | SingleLine,
                       titleStr);
        }
        else
        {
            p.drawText(0, 0, width(), height(),
                       AlignCenter | SingleLine, titleStr);
        }
    }
}

QSize KPopupTitle::sizeHint() const
{
    return minimumSize();
}

class KPopupMenu::KPopupMenuPrivate
{
public:
    KPopupMenuPrivate ()
        : noMatches(false)
        , shortcuts(false)
        , autoExec(false)
        , lastHitIndex(-1)
        , state(Qt::NoButton)
        , m_ctxMenu(0)
    {}

    ~KPopupMenuPrivate ()
    {
        delete m_ctxMenu;
    }

    QString m_lastTitle;

    // variables for keyboard navigation
    QTimer clearTimer;

    bool noMatches : 1;
    bool shortcuts : 1;
    bool autoExec : 1;

    QString keySeq;
    QString originalText;

    int lastHitIndex;
    Qt::ButtonState state;

    // support for RMB menus on menus
    QPopupMenu* m_ctxMenu;
    static bool s_continueCtxMenuShow;
    static int s_highlightedItem;
    static KPopupMenu* s_contextedMenu;
};

int KPopupMenu::KPopupMenuPrivate::s_highlightedItem(-1);
KPopupMenu* KPopupMenu::KPopupMenuPrivate::s_contextedMenu(0);
bool KPopupMenu::KPopupMenuPrivate::s_continueCtxMenuShow(true);

KPopupMenu::KPopupMenu(QWidget *parent, const char *name)
    : QPopupMenu(parent, name)
{
    d = new KPopupMenuPrivate;
    resetKeyboardVars();
    connect(&(d->clearTimer), SIGNAL(timeout()), SLOT(resetKeyboardVars()));
}

KPopupMenu::~KPopupMenu()
{
    if (KPopupMenuPrivate::s_contextedMenu == this)
    {
        KPopupMenuPrivate::s_contextedMenu = 0;
        KPopupMenuPrivate::s_highlightedItem = -1;
    }

    delete d;
}

int KPopupMenu::insertTitle(const QString &text, int id, int index)
{
    KPopupTitle *titleItem = new KPopupTitle();
    titleItem->setTitle(text);
    int ret = insertItem(titleItem, id, index);
    setItemEnabled(ret, false);
    return ret;
}

int KPopupMenu::insertTitle(const QPixmap &icon, const QString &text, int id,
                            int index)
{
    KPopupTitle *titleItem = new KPopupTitle();
    titleItem->setTitle(text, &icon);
    int ret = insertItem(titleItem, id, index);
    setItemEnabled(ret, false);
    return ret;
}

void KPopupMenu::changeTitle(int id, const QString &text)
{
    QMenuItem *item = findItem(id);
    if(item){
        if(item->widget())
            ((KPopupTitle *)item->widget())->setTitle(text);
#ifndef NDEBUG
        else
            kdWarning() << "KPopupMenu: changeTitle() called with non-title id "<< id << endl;
#endif
    }
#ifndef NDEBUG
    else
        kdWarning() << "KPopupMenu: changeTitle() called with invalid id " << id << endl;
#endif
}

void KPopupMenu::changeTitle(int id, const QPixmap &icon, const QString &text)
{
    QMenuItem *item = findItem(id);
    if(item){
        if(item->widget())
            ((KPopupTitle *)item->widget())->setTitle(text, &icon);
#ifndef NDEBUG
        else
            kdWarning() << "KPopupMenu: changeTitle() called with non-title id "<< id << endl;
#endif
    }
#ifndef NDEBUG
    else
        kdWarning() << "KPopupMenu: changeTitle() called with invalid id " << id << endl;
#endif
}

QString KPopupMenu::title(int id) const
{
    if(id == -1) // obsolete
        return d->m_lastTitle;
    QMenuItem *item = findItem(id);
    if(item){
        if(item->widget())
            return ((KPopupTitle *)item->widget())->title();
        else
            qWarning("KPopupMenu: title() called with non-title id %d.", id);
    }
    else
        qWarning("KPopupMenu: title() called with invalid id %d.", id);
    return QString::null;
}

QPixmap KPopupMenu::titlePixmap(int id) const
{
    QMenuItem *item = findItem(id);
    if(item){
        if(item->widget())
            return ((KPopupTitle *)item->widget())->icon();
        else
            qWarning("KPopupMenu: titlePixmap() called with non-title id %d.", id);
    }
    else
        qWarning("KPopupMenu: titlePixmap() called with invalid id %d.", id);
    QPixmap tmp;
    return tmp;
}

/**
 * This is re-implemented for keyboard navigation.
 */
void KPopupMenu::closeEvent(QCloseEvent*e)
{
    if (d->shortcuts)
        resetKeyboardVars();
    QPopupMenu::closeEvent(e);
}

void KPopupMenu::activateItemAt(int index)
{
    d->state = Qt::NoButton;
    QPopupMenu::activateItemAt(index);
}

Qt::ButtonState KPopupMenu::state() const
{
    return d->state;
}

void KPopupMenu::keyPressEvent(QKeyEvent* e)
{
    d->state = Qt::NoButton;
    if (!d->shortcuts) {
        // continue event processing by Qpopup
        //e->ignore();
        d->state = e->state();
        QPopupMenu::keyPressEvent(e);
        return;
    }

    int i = 0;
    bool firstpass = true;
    QString keyString = e->text();

    // check for common commands dealt with by QPopup
    int key = e->key();
    if (key == Key_Escape || key == Key_Return || key == Key_Enter
            || key == Key_Up || key == Key_Down || key == Key_Left
            || key == Key_Right || key == Key_F1) {

        resetKeyboardVars();
        // continue event processing by Qpopup
        //e->ignore();
        d->state = e->state();
        QPopupMenu::keyPressEvent(e);
        return;
    } else if ( key == Key_Shift || key == Key_Control || key == Key_Alt || key == Key_Meta )
	return QPopupMenu::keyPressEvent(e);

    // check to see if the user wants to remove a key from the sequence (backspace)
    // or clear the sequence (delete)
    if (!d->keySeq.isNull()) {

        if (key == Key_Backspace) {

            if (d->keySeq.length() == 1) {
                resetKeyboardVars();
                return;
            }

            // keep the last sequence in keyString
            keyString = d->keySeq.left(d->keySeq.length() - 1);

            // allow sequence matching to be tried again
            resetKeyboardVars();

        } else if (key == Key_Delete) {
            resetKeyboardVars();

            // clear active item
            setActiveItem(0);
            return;

        } else if (d->noMatches) {
            // clear if there are no matches
            resetKeyboardVars();

            // clear active item
            setActiveItem(0);

        } else {
            // the key sequence is not a null string
            // therefore the lastHitIndex is valid
            i = d->lastHitIndex;
        }
    } else if (key == Key_Backspace && parentMenu) {
        // backspace with no chars in the buffer... go back a menu.
        hide();
        resetKeyboardVars();
        return;
    }

    d->keySeq += keyString;
    int seqLen = d->keySeq.length();

    for (; i < (int)count(); i++) {
        // compare typed text with text of this entry
        int j = idAt(i);

        // don't search disabled entries
        if (!isItemEnabled(j))
            continue;

        QString thisText;

        // retrieve the right text
        // (the last selected item one may have additional ampersands)
        if (i == d->lastHitIndex)
            thisText = d->originalText;
        else
            thisText = text(j);

        // if there is an accelerator present, remove it
        if ((int)accel(j) != 0)
            thisText = thisText.replace("&", QString::null);

        // chop text to the search length
        thisText = thisText.left(seqLen);

        // do the search
        if (!thisText.find(d->keySeq, 0, false)) {

            if (firstpass) {
                // match
                setActiveItem(i);

                // check to see if we're underlining a different item
                if (d->lastHitIndex != i)
                    // yes; revert the underlining
                    changeItem(idAt(d->lastHitIndex), d->originalText);

                // set the original text if it's a different item
                if (d->lastHitIndex != i || d->lastHitIndex == -1)
                    d->originalText = text(j);

                // underline the currently selected item
                changeItem(j, underlineText(d->originalText, d->keySeq.length()));

                // remember what's going on
                d->lastHitIndex = i;

                // start/restart the clear timer
                d->clearTimer.start(5000, true);

                // go around for another try, to see if we can execute
                firstpass = false;
            } else {
                // don't allow execution
                return;
            }
        }

        // fall through to allow execution
    }

    if (!firstpass) {
        if (d->autoExec) {
            // activate anything
            activateItemAt(d->lastHitIndex);
            resetKeyboardVars();

        } else if (findItem(idAt(d->lastHitIndex)) &&
                 findItem(idAt(d->lastHitIndex))->popup()) {
            // only activate sub-menus
            activateItemAt(d->lastHitIndex);
            resetKeyboardVars();
        }

        return;
    }

    // no matches whatsoever, clean up
    resetKeyboardVars(true);
    //e->ignore();
    QPopupMenu::keyPressEvent(e);
}

bool KPopupMenu::focusNextPrevChild( bool next )
{
    resetKeyboardVars();
    return QPopupMenu::focusNextPrevChild( next );
}

QString KPopupMenu::underlineText(const QString& text, uint length)
{
    QString ret = text;
    for (uint i = 0; i < length; i++) {
        if (ret[2*i] != '&')
            ret.insert(2*i, "&");
    }
    return ret;
}

void KPopupMenu::resetKeyboardVars(bool noMatches /* = false */)
{
    // Clean up keyboard variables
    if (d->lastHitIndex != -1) {
        changeItem(idAt(d->lastHitIndex), d->originalText);
        d->lastHitIndex = -1;
    }

    if (!noMatches) {
        d->keySeq = QString::null;
    }

    d->noMatches = noMatches;
}

void KPopupMenu::setKeyboardShortcutsEnabled(bool enable)
{
    d->shortcuts = enable;
}

void KPopupMenu::setKeyboardShortcutsExecute(bool enable)
{
    d->autoExec = enable;
}
/**
 * End keyboard navigation.
 */

/**
 * RMB menus on menus
 */

void KPopupMenu::mousePressEvent(QMouseEvent* e)
{
    if (d->m_ctxMenu && d->m_ctxMenu->isVisible())
    {
        // hide on a second context menu event
        d->m_ctxMenu->hide();
    }

    QPopupMenu::mousePressEvent(e);
}

void KPopupMenu::mouseReleaseEvent(QMouseEvent* e)
{
    // Save the button, and the modifiers from state()
    d->state = Qt::ButtonState(e->button() | (e->state() & KeyButtonMask));
    
    if ( !d->m_ctxMenu || !d->m_ctxMenu->isVisible() )
	QPopupMenu::mouseReleaseEvent(e);
}

QPopupMenu* KPopupMenu::contextMenu()
{
    if (!d->m_ctxMenu)
    {
        d->m_ctxMenu = new QPopupMenu(this);
        connect(d->m_ctxMenu, SIGNAL(aboutToHide()), this, SLOT(ctxMenuHiding()));
    }

    return d->m_ctxMenu;
}

const QPopupMenu* KPopupMenu::contextMenu() const
{
    return const_cast< KPopupMenu* >( this )->contextMenu();
}

void KPopupMenu::hideContextMenu()
{
    KPopupMenuPrivate::s_continueCtxMenuShow = false;
}

int KPopupMenu::contextMenuFocusItem()
{
    return KPopupMenuPrivate::s_highlightedItem;
}

KPopupMenu* KPopupMenu::contextMenuFocus()
{
    return KPopupMenuPrivate::s_contextedMenu;
}

void KPopupMenu::itemHighlighted(int /* whichItem */)
{
    if (!d->m_ctxMenu || !d->m_ctxMenu->isVisible())
    {
        return;
    }

    d->m_ctxMenu->hide();
    showCtxMenu(mapFromGlobal(QCursor::pos()));
}

void KPopupMenu::showCtxMenu(QPoint pos)
{
    QMenuItem* item = findItem(KPopupMenuPrivate::s_highlightedItem);
    if (item)
    {
        QPopupMenu* subMenu = item->popup();
        if (subMenu)
        {
            disconnect(subMenu, SIGNAL(aboutToShow()), this, SLOT(ctxMenuHideShowingMenu()));
        }
    }

    KPopupMenuPrivate::s_highlightedItem = idAt(pos);

    if (KPopupMenuPrivate::s_highlightedItem == -1)
    {
        KPopupMenuPrivate::s_contextedMenu = 0;
        return;
    }

    emit aboutToShowContextMenu(this, KPopupMenuPrivate::s_highlightedItem, d->m_ctxMenu);

    QPopupMenu* subMenu = findItem(KPopupMenuPrivate::s_highlightedItem)->popup();
    if (subMenu)
    {
        connect(subMenu, SIGNAL(aboutToShow()), SLOT(ctxMenuHideShowingMenu()));
        QTimer::singleShot(100, subMenu, SLOT(hide()));
    }

    if (!KPopupMenuPrivate::s_continueCtxMenuShow)
    {
        KPopupMenuPrivate::s_continueCtxMenuShow = true;
        return;
    }

    KPopupMenuPrivate::s_contextedMenu = this;
    d->m_ctxMenu->popup(this->mapToGlobal(pos));
    connect(this, SIGNAL(highlighted(int)), this, SLOT(itemHighlighted(int)));
}

/*
 * this method helps prevent submenus popping up while we have a context menu
 * showing
 */
void KPopupMenu::ctxMenuHideShowingMenu()
{
    QMenuItem* item = findItem(KPopupMenuPrivate::s_highlightedItem);
    if (item)
    {
        QPopupMenu* subMenu = item->popup();
        if (subMenu)
        {
            QTimer::singleShot(0, subMenu, SLOT(hide()));
        }
    }
}

void KPopupMenu::ctxMenuHiding()
{
    if (KPopupMenuPrivate::s_highlightedItem)
    {
        QPopupMenu* subMenu = findItem(KPopupMenuPrivate::s_highlightedItem)->popup();
        if (subMenu)
        {
            disconnect(subMenu, SIGNAL(aboutToShow()), this, SLOT(ctxMenuHideShowingMenu()));
        }
    }

    disconnect(this, SIGNAL(highlighted(int)), this, SLOT(itemHighlighted(int)));
    KPopupMenuPrivate::s_continueCtxMenuShow = true;
}

void KPopupMenu::contextMenuEvent(QContextMenuEvent* e)
{
    if (d->m_ctxMenu)
    {
        if (e->reason() == QContextMenuEvent::Mouse)
        {
            showCtxMenu(e->pos());
        }
        else if (actItem != -1)
        {
            showCtxMenu(itemGeometry(actItem).center());
        }

        e->accept();
        return;
    }

    QPopupMenu::contextMenuEvent(e);
}

void KPopupMenu::hideEvent(QHideEvent*)
{
    if (d->m_ctxMenu && d->m_ctxMenu->isVisible())
    {
        // we need to block signals here when the ctxMenu is showing
        // to prevent the QPopupMenu::activated(int) signal from emitting
        // when hiding with a context menu, the user doesn't expect the
        // menu to actually do anything.
        // since hideEvent gets called very late in the process of hiding
        // (deep within QWidget::hide) the activated(int) signal is the
        // last signal to be emitted, even after things like aboutToHide()
        // AJS
        blockSignals(true);
        d->m_ctxMenu->hide();
        blockSignals(false);
    }
}
/**
 * end of RMB menus on menus support
 */

// Obsolete
KPopupMenu::KPopupMenu(const QString& title, QWidget *parent, const char *name)
    : QPopupMenu(parent, name)
{
    d = new KPopupMenuPrivate;
    insertTitle(title);
}

// Obsolete
void KPopupMenu::setTitle(const QString &title)
{
    KPopupTitle *titleItem = new KPopupTitle();
    titleItem->setTitle(title);
    insertItem(titleItem);
    d->m_lastTitle = title;
}

void KPopupTitle::virtual_hook( int, void* )
{ /*BASE::virtual_hook( id, data );*/ }

void KPopupMenu::virtual_hook( int, void* )
{ /*BASE::virtual_hook( id, data );*/ }

#include "kpopupmenu.moc"