aboutsummaryrefslogtreecommitdiff
path: root/src/views/mtoolbarview.cpp
blob: c0132e3e6add044b35a714f4bc5a39148e273d4a (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
/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include <QGraphicsLinearLayout>

#include "mtoolbar.h"
#include "mtoolbar_p.h"

#include "mtheme.h"
#include "mbutton.h"
#include "mbuttongroup.h"
#include "mwidgetaction.h"
#include "private/mwidgetview_p.h"

#include "mlayout.h"
#include "mlinearlayoutpolicy.h"
#include "mtextedit.h"
#include "mtoolbarview.h"
#include "mtoolbarview_p.h"

const int maxSlots = 4;

/* Make a layout policy for aligning widgets nicely by
 * adding spacers.
 * This is a very crude policy, and doesn't support most
 * of the functions of MLinearLayoutPolicy */
class ToolBarLayoutPolicy : public MLinearLayoutPolicy
{
public:
    explicit ToolBarLayoutPolicy(MLayout *layout) :
        MLinearLayoutPolicy(layout, Qt::Horizontal) {
            textEditIndex = -1;
            insertSpacer(0);
            setSpacing(0);
        }
    ~ToolBarLayoutPolicy() {
        for(int i = widgetCount()-1; i >= 0; i--)
            removeWidgetAt(i);
        QGraphicsLayoutItem *item = MLinearLayoutPolicy::itemAt(0);
        MLinearLayoutPolicy::removeAt(0);
        delete item;
    }
    void insertWidgetAndRemoveOverflow(int index, QGraphicsLayoutItem *item)
    {
        index = qMin((uint)index, (uint)widgetCount());
        //A ugly hack to try to cope with QTBUG-11134
        item->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
        Q_ASSERT(item);
        Q_ASSERT(MLinearLayoutPolicy::count() % 2);
        Q_ASSERT(MLinearLayoutPolicy::count() > index*2);

        if(dynamic_cast<MTextEdit *>(item->graphicsItem())) {
            if(textEditIndex != -1)  //Remove any previous text edit
                removeWidgetAt(textEditIndex);
            textEditIndex = index;
        } else if(index <= textEditIndex)
            textEditIndex++;

        //Add an item and a spacer after the item
        MLinearLayoutPolicy::insertItem(1 + index*2, item);

        insertSpacer(2+index*2);
        Q_ASSERT(MLinearLayoutPolicy::count() % 2);

        //Prevent overflow - remove any that we've pushed off the end
        while(takenSlots() > maxSlots) {
            removeWidgetAt(widgetCount()-1);
        }
    }
    bool roomForWidget(int index, bool textEdit) const {
        index = qMin((uint)index, (uint)widgetCount());

        if(textEdit) {
            if(textEditIndex != -1 && index > textEditIndex) {
                //If we come first, we push the old textedit out of the way
                return false; //No room for us
            } else if(index + 1 >= maxSlots) {
                return false; //No room to add
            }
        }
        else if(index >= maxSlots)
            return false; //No room to add
        else if(textEditIndex != -1 && index >= maxSlots -1)
            return false; //No room to add because textedit takes up two spaces
        return true;
    }
    void removeWidgetAt(int index)
    {
        if(index < 0 || index >= widgetCount())
            return;
        Q_ASSERT(MLinearLayoutPolicy::count() % 2);
        Q_ASSERT(MLinearLayoutPolicy::count() > 2+index*2);

        //Remove the item first
        if(index == textEditIndex)
            textEditIndex = -1;
        else if(textEditIndex != -1 && index < textEditIndex)
            textEditIndex--;
        MLinearLayoutPolicy::removeAt(2+index*2);
        MLinearLayoutPolicy::removeAt(1+index*2);
    }

    int widgetCount() const
    {
        return (MLinearLayoutPolicy::count()-1)/2;
    }
    int takenSlots() const
    {
        if(textEditIndex != -1)
            return widgetCount() + 1;  //textedit counts for two slots
        else
            return widgetCount();
    }
    int widgetIndexOf(const QGraphicsLayoutItem *item) const {
        for(int i = widgetCount() -1; i >= 0; i--) {
            if(MLinearLayoutPolicy::itemAt(1+i*2) == item)
                return i;
        }
        return -1;
    }
    void removeWidget(const QGraphicsLayoutItem *item)
    {
        removeWidgetAt(widgetIndexOf(item));
    }

protected:
    /** Hide the normal functions since these include the spacers
     *  and we want to encourage the user to only use our functions */
    virtual int count() const { return MLinearLayoutPolicy::count(); }
    virtual QGraphicsLayoutItem *itemAt(int index) const { return MLinearLayoutPolicy::itemAt(index); }
    virtual void insertItem(int index, QGraphicsLayoutItem *item) { return MLinearLayoutPolicy::insertItem(index, item); }
    void indexOf(const QGraphicsLayoutItem *item) const;
    virtual void removeAt(int index) {
        //This can be called by the layout, and we need to make sure that we delete the spacer as well
        removeWidgetAt((index-1)/2);
    }

private:
    int textEditIndex;

    void insertSpacer(int position) {
        //Create an item that will expand if necessary
        QGraphicsWidget *item =  new QGraphicsWidget;
        item->setPreferredSize(1,1); //Ugly hack around QTBUG-11134
        item->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
        MLinearLayoutPolicy::insertItem(position, item);
    }
};

MToolBarViewPrivate::MToolBarViewPrivate(MToolBar *controller)
    : QObject(),
      q_ptr(0),
      layout(0),
      buttonGroup(0)
{
    this->controller = controller;
    controller->installEventFilter(this);
}


MToolBarViewPrivate::~MToolBarViewPrivate()
{
    removeEventFilter(controller);
    if(buttonGroup) {
        foreach(MButton *button, buttonGroup->buttons())
            buttonGroup->removeButton(button);
        delete buttonGroup;
        buttonGroup = NULL;
    }
    QHashIterator<QAction *, MWidget *> iterator(leasedWidgets);
    while (iterator.hasNext()) {
        iterator.next();

        if (!releaseWidget(iterator.key(), iterator.value()))
            delete iterator.value(); //Is this the right thing to do ?
    }
    qDeleteAll(buttons);
    delete layout;
    layout = NULL;
}

void MToolBarViewPrivate::init()
{
    layout = new MLayout;
    layout->setAnimation(NULL);
    layout->setContentsMargins(0, 0, 0, 0);

    landscapePolicy = new ToolBarLayoutPolicy(layout);
    layout->setLandscapePolicy(landscapePolicy);

    portraitPolicy = new ToolBarLayoutPolicy(layout);
    layout->setPortraitPolicy(portraitPolicy);

    QGraphicsLinearLayout *controllerlayout = (QGraphicsLinearLayout *)(controller->layout());
    controllerlayout->addItem(layout);

    //Add any existing actions now
    foreach(QAction *action, controller->actions()) {
        add(action);
    }
}

int MToolBarViewPrivate::policyIndexForAddingAction(QAction *action, ToolBarLayoutPolicy *policy) const {
    Q_Q(const MToolBarView);
    //We need to add the action's given widget to the policy
    //This is a bit complicated because we ideally want to add it in the right place,
    //preserving the same order as in the controller->actions()
    QList< QAction *> actions = controller->actions();
    int parentIndex = actions.indexOf(action)+1;
    int index = policy->widgetCount();
    while(parentIndex < actions.size()) {
        MWidget *w = q->getWidget(actions.at(parentIndex));
        if(w) {
            int policyIndex = policy->widgetIndexOf(w);
            if(policyIndex >= 0) {
                index = policyIndex;
                break;
            }
        }
        parentIndex++;
    }
    if(policy->roomForWidget(index, hasTextEditWidget(action)))
        return index;
    return -1;
}

void MToolBarViewPrivate::add(QAction *action)
{
    if (!action || !action->isVisible() || hasUnusableWidget(action))
        return; //Cancel adding action

    // add to policies only if the action is visible
    int landscapeIndex = -1;
    int portraitIndex = -1;
    if (isLocationValid(action, MAction::ToolBarLandscapeLocation))
        landscapeIndex = policyIndexForAddingAction(action, landscapePolicy);
    if (isLocationValid(action, MAction::ToolBarPortraitLocation))
        portraitIndex = policyIndexForAddingAction(action, portraitPolicy);

    if (landscapeIndex == -1 && portraitIndex == -1)
        return; //Cancel adding action
    MWidget *widget = createWidget(action);
    Q_ASSERT(widget);
    if (landscapeIndex != -1)
        landscapePolicy->insertWidgetAndRemoveOverflow( landscapeIndex, widget );
    if (portraitIndex != -1)
        portraitPolicy->insertWidgetAndRemoveOverflow( portraitIndex, widget );
    updateWidgetFromAction(widget, action);
}

void MToolBarViewPrivate::remove(QAction *action, bool hideOnly)
{
    MButton *button = buttons.value(action);
    MWidget *leased = leasedWidgets.value(action);
    MWidget *widget = (button != 0) ? button : leased;
    if(!widget)
        return;

    if (button && buttonGroup)
        buttonGroup->removeButton(button);
    if(hideOnly) {
        landscapePolicy->removeWidget(widget);
        portraitPolicy->removeWidget(widget);
        if (button)
            button->setChecked(false);
    } else {
        //Need to fully remove the action
        layout->removeItem(widget);

        if (button) {
            buttons.remove(action);
            delete button;
        } else {
            releaseWidget(action, leased);
            leasedWidgets.remove(action);
        }
    }

    //There might be space now any actions not already added.  Signal a change action which
    //will check if an item now has room to be shown
    foreach(QAction *action2, controller->actions()) {
        if(action2 != action && action2->isVisible() &&
                (isLocationValid(action2, MAction::ToolBarLandscapeLocation) ||
                 isLocationValid(action2, MAction::ToolBarPortraitLocation)))
            change(action2);
    }
}

void MToolBarViewPrivate::change(QAction *action)
{
    Q_Q(MToolBarView);
    if(hasUnusableWidget(action))
        return;
    if(!action->isVisible()) {
        remove(action, true); //Remove action, but only hiding the widget, not deleting/releasing it
        return;
    }
    bool validInLandscape = isLocationValid(action, MAction::ToolBarLandscapeLocation);
    bool validInPortrait = isLocationValid(action, MAction::ToolBarPortraitLocation);
    if (!validInLandscape && !validInPortrait) {
        remove(action, true);
        return;
    }

    //Check that the widget is in the controller actions
    QList< QAction *> actions = controller->actions();
    int indexOfAction = actions.indexOf(action);
    if(indexOfAction == -1) {
        remove(action, false); // I don't think this is possible
        return;
    }
        
    MWidget *widget = q->getWidget(action);
    if (!widget) {
        //We need to add the action
        add(action);
        return;
    }
    if(buttonGroup) {
        MButton *button = buttons.value(action);
        if(button)
            buttonGroup->addButton(button);
    }

    //We have now an action and a widget for it
    int landscapeIndex = landscapePolicy->widgetIndexOf(widget);
    int portraitIndex = portraitPolicy->widgetIndexOf(widget);
    if(!validInLandscape && landscapeIndex >= 0) {
        //We are showing it in landscape view but should not be
        landscapePolicy->removeWidgetAt(landscapeIndex);
    }
    if(!validInPortrait && portraitIndex >= 0) {
        //We are showing it in portrait view but should not be
        portraitPolicy->removeWidgetAt(portraitIndex);
    }
    if(validInLandscape && landscapeIndex == -1) {
        int index = policyIndexForAddingAction(action, landscapePolicy);
        if(index != -1)
            landscapePolicy->insertWidgetAndRemoveOverflow( index, widget );
    }
    if(validInPortrait && portraitIndex == -1) {
        int index = policyIndexForAddingAction(action, portraitPolicy);
        if(index != -1)
            portraitPolicy->insertWidgetAndRemoveOverflow( index, widget );
    }

    updateWidgetFromAction(widget, action);
}

void MToolBarViewPrivate::updateWidgetFromAction(MWidget *widget, QAction *action) const
{
    widget->setEnabled(action->isEnabled());
    MButton *button = qobject_cast<MButton *>(widget);
    if (button) {
        // Update button data accordingly
        button->setCheckable(action->isCheckable());
        button->setChecked(action->isChecked());

        // Only update the text and icon if we created the button
        if(buttons.contains(action)) {
            button->setText(action->text());
            MAction *mAction = qobject_cast<MAction *>(action);
            if (mAction)
                button->setIconID(mAction->iconID());
        }
    }
}

bool MToolBarViewPrivate::eventFilter(QObject *obj, QEvent *e)
{
    switch (e->type()) {
        case QEvent::ActionRemoved:
            remove(static_cast<QActionEvent *>(e)->action(), false);
            break;
        case QEvent::ActionAdded:
            add(static_cast<QActionEvent *>(e)->action());
            break;
        case QEvent::ActionChanged:
            change(static_cast<QActionEvent *>(e)->action());
            break;

        case QEvent::DynamicPropertyChange:
            {
                QDynamicPropertyChangeEvent *propertyEvent = static_cast<QDynamicPropertyChangeEvent*>(e);
                if (propertyEvent->propertyName() == _M_IsEnabledPreservingSelection) {
                    bool enabledPreservingSelection = obj->property(_M_IsEnabledPreservingSelection).toBool();
                    setEnabledPreservingSelection(enabledPreservingSelection);
                }
            }
            break;

        default:
            break;
    }
    return QObject::eventFilter(obj, e);
}

MWidget *MToolBarViewPrivate::createWidget(QAction *action)
{
    Q_Q(MToolBarView);
    // If widget is not already created then create it
    MWidget *widget = buttons.value(action);
    if (!widget)
        widget = leasedWidgets.value(action);
    if (!widget) {
        MWidgetAction *widgetAction = qobject_cast<MWidgetAction *>(action);
        if (widgetAction) {
            widget = widgetAction->requestWidget(NULL);
            leasedWidgets.insert(action, widget);
            widget->show();
        } else {
            MButton *button = new MButton;
            button->setMinimumSize(0,0);

            button->setObjectName("toolbaractioncommand");
            if (action && !action->objectName().isEmpty())
                button->setObjectName(button->objectName() + "_" + action->objectName());

            if(buttonGroup) {
                button->setViewType("toolbartab");
                button->setCheckable(action->isCheckable());
                //We can't set button->checked until we've added it to the scene
                buttonGroup->addButton(button);
                connect(button, SIGNAL(toggled(bool)), q, SLOT(_q_groupButtonClicked(bool)));
                connect(action, SIGNAL(toggled(bool)), q, SLOT(_q_groupActionToggled(bool)));
            } else {
                button->setViewType("toolbar");
            }
            connect(button, SIGNAL(clicked(bool)), action, SIGNAL(triggered()));

            buttons.insert(action, button);
            widget = button;
        }
    }
    Q_ASSERT(widget);
    return widget;
}
bool MToolBarViewPrivate::isLocationValid(QAction *action, MAction::Location loc) const
{
    MAction *mAction = qobject_cast<MAction *>(action);
    if(!mAction)
        return true; //A normal QAction is valid to place on toolbar
    return mAction->location().testFlag(loc);
}

bool MToolBarViewPrivate::releaseWidget(QAction *action, MWidget *widget) const
{
    MWidgetAction *widgetAction = qobject_cast<MWidgetAction *>(action);
    if (widgetAction) {
        widgetAction->releaseWidget(widget);
    }
    return (widgetAction != 0);
}

bool MToolBarViewPrivate::hasTextEditWidget(QAction *action) const
{
    MTextEdit *textEditWidget = 0;
    MWidgetAction *widgetAction = qobject_cast<MWidgetAction *>(action);
    if (widgetAction) {
        textEditWidget = qobject_cast<MTextEdit *>(widgetAction->widget());
    }
    return (textEditWidget != 0);
}

bool MToolBarViewPrivate::hasUnusableWidget(QAction *action) const
{
    if( buttons.contains(action) || leasedWidgets.contains(action) )
        return false; //If we are already using it, it must be usable
    MWidgetAction *widgetAction = qobject_cast<MWidgetAction *>(action);
    if(!widgetAction || !widgetAction->widget())
        return false; //We can create a button for it
    return widgetAction->isWidgetInUse();
}

MWidget *MToolBarView::getWidget(QAction *action) const
{
    Q_D(const MToolBarView);
    MWidget *button = d->buttons.value(action);
    if( button )
        return button;
    return d->leasedWidgets.value(action);
}

void MToolBarViewPrivate::setEnabledPreservingSelection(bool enabled)
{
    foreach(MButton *button, buttons) {
        if (!button->isChecked())
            button->setEnabled(enabled);
    }

    foreach(MWidget *leasedWidget, leasedWidgets) {
        MButton *button = qobject_cast<MButton *>(leasedWidget);
        if (!button || !button->isChecked())
            leasedWidget->setEnabled(enabled);
    }
}

void MToolBarViewPrivate::_q_groupButtonClicked(bool checked)
{
    Q_Q(MToolBarView);
    MButton *button = qobject_cast<MButton *>(q->sender());
    if(!button)
        return; //impossible?

    button->setChecked(checked);

    QAction *action = buttons.key(button);
    if(action->isChecked() != checked)
        action->setChecked(checked);
}

void MToolBarViewPrivate::_q_groupActionToggled(bool checked)
{
    Q_Q(MToolBarView);
    QAction* action = qobject_cast<QAction *>(q->sender());
    Q_ASSERT(action);
    MButton *button = buttons.value(action);
    if (button) {
        button->setChecked(checked);
    }
}

MToolBarView::MToolBarView(MToolBar *controller) :
    MWidgetView(controller),
    d_ptr(new MToolBarViewPrivate(controller))
{
    Q_D(MToolBarView);
    d->q_ptr = this;
    d->init();
}

MToolBarView::MToolBarView(MToolBarViewPrivate &dd, MToolBar *controller) :
    MWidgetView(controller),
    d_ptr(&dd)
{
    Q_D(MToolBarView);
    d->q_ptr = this;
    d->controller = controller;
    d->init();
}

MToolBarView::~MToolBarView()
{
    delete d_ptr;
}

// bind view and controller together
M_REGISTER_VIEW_NEW(MToolBarView, MToolBar)

#include "moc_mtoolbarview.cpp"