summaryrefslogtreecommitdiffstats
path: root/widget/gtk/nsMenuObject.cpp
blob: 58d1716fd26d6b1672f04a23d12969780e3aeb1c (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
/* This Source Code Form is subject to the terms of the Mozilla Public
 *  License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "ImageOps.h"
#include "imgIContainer.h"
#include "imgINotificationObserver.h"
#include "imgLoader.h"
#include "imgRequestProxy.h"
#include "mozilla/ArrayUtils.h"
#include "mozilla/Assertions.h"
#include "mozilla/dom/Element.h"
#include "mozilla/Preferences.h"
#include "nsAttrValue.h"
#include "nsComputedDOMStyle.h"
#include "nsContentUtils.h"
#include "nsGkAtoms.h"
#include "nsIContent.h"
#include "nsIContentPolicy.h"
#include "nsIDocument.h"
#include "nsILoadGroup.h"
#include "nsImageToPixbuf.h"
#include "nsIPresShell.h"
#include "nsIURI.h"
#include "nsNetUtil.h"
#include "nsPresContext.h"
#include "nsRect.h"
#include "nsServiceManagerUtils.h"
#include "nsString.h"
#include "nsStyleConsts.h"
#include "nsStyleContext.h"
#include "nsStyleStruct.h"
#include "nsUnicharUtils.h"

#include "nsMenuContainer.h"
#include "nsNativeMenuAtoms.h"
#include "nsNativeMenuDocListener.h"

#include <gdk/gdk.h>
#include <glib-object.h>
#include <pango/pango.h>

#include "nsMenuObject.h"

// X11's None clashes with StyleDisplay::None
#include "X11UndefineNone.h"

#undef None

using namespace mozilla;
using mozilla::image::ImageOps;

#define MAX_WIDTH 350000

const char* gPropertyStrings[] = {
#define DBUSMENU_PROPERTY(e, s, b) s,
    DBUSMENU_PROPERTIES
#undef DBUSMENU_PROPERTY
    nullptr
};

nsWeakMenuObject* nsWeakMenuObject::sHead;
PangoLayout* gPangoLayout = nullptr;

class nsMenuObjectIconLoader final : public imgINotificationObserver {
public:
    NS_DECL_ISUPPORTS
    NS_DECL_IMGINOTIFICATIONOBSERVER

    nsMenuObjectIconLoader(nsMenuObject* aOwner) : mOwner(aOwner) { };

    void LoadIcon(nsStyleContext* aStyleContext);
    void Destroy();

private:
    ~nsMenuObjectIconLoader() { };

    nsMenuObject* mOwner;
    RefPtr<imgRequestProxy> mImageRequest;
    nsCOMPtr<nsIURI> mURI;
    nsIntRect mImageRect;
};

NS_IMPL_ISUPPORTS(nsMenuObjectIconLoader, imgINotificationObserver)

NS_IMETHODIMP
nsMenuObjectIconLoader::Notify(imgIRequest* aProxy,
                               int32_t aType, const nsIntRect* aRect) {
    if (!mOwner) {
        return NS_OK;
    }

    if (aProxy != mImageRequest) {
        return NS_ERROR_FAILURE;
    }

    if (aType == imgINotificationObserver::LOAD_COMPLETE) {
        uint32_t status = imgIRequest::STATUS_ERROR;
        if (NS_FAILED(mImageRequest->GetImageStatus(&status)) ||
            (status & imgIRequest::STATUS_ERROR)) {
            mImageRequest->Cancel(NS_BINDING_ABORTED);
            mImageRequest = nullptr;
            return NS_ERROR_FAILURE;
        }

        nsCOMPtr<imgIContainer> image;
        mImageRequest->GetImage(getter_AddRefs(image));
        MOZ_ASSERT(image);

        // Ask the image to decode at its intrinsic size.
        int32_t width = 0, height = 0;
        image->GetWidth(&width);
        image->GetHeight(&height);
        image->RequestDecodeForSize(nsIntSize(width, height), imgIContainer::FLAG_NONE);
        return NS_OK;
    }

    if (aType == imgINotificationObserver::DECODE_COMPLETE) {
        mImageRequest->Cancel(NS_BINDING_ABORTED);
        mImageRequest = nullptr;
        return NS_OK;
    }

    if (aType != imgINotificationObserver::FRAME_COMPLETE) {
        return NS_OK;
    }

    nsCOMPtr<imgIContainer> img;
    mImageRequest->GetImage(getter_AddRefs(img));
    if (!img) {
        return NS_ERROR_FAILURE;
    }

    if (!mImageRect.IsEmpty()) {
        img = ImageOps::Clip(img, mImageRect);
    }

    int32_t width, height;
    img->GetWidth(&width);
    img->GetHeight(&height);

    if (width <= 0 || height <= 0) {
        mOwner->ClearIcon();
        return NS_OK;
    }

    if (width > 100 || height > 100) {
        // The icon data needs to go across DBus. Make sure the icon
        // data isn't too large, else our connection gets terminated and
        // GDbus helpfully aborts the application. Thank you :)
        NS_WARNING("Icon data too large");
        mOwner->ClearIcon();
        return NS_OK;
    }

    GdkPixbuf* pixbuf = nsImageToPixbuf::ImageToPixbuf(img);
    if (pixbuf) {
        dbusmenu_menuitem_property_set_image(mOwner->GetNativeData(),
                                             DBUSMENU_MENUITEM_PROP_ICON_DATA,
                                             pixbuf);
        g_object_unref(pixbuf);
    }

    return NS_OK;
}

void
nsMenuObjectIconLoader::LoadIcon(nsStyleContext* aStyleContext) {
    nsIDocument* doc = mOwner->ContentNode()->OwnerDoc();

    nsCOMPtr<nsIURI> uri;
    nsIntRect imageRect;
    imgRequestProxy* imageRequest = nullptr;

    nsAutoString uriString;
    if (mOwner->ContentNode()->GetAttr(kNameSpaceID_None, nsGkAtoms::image,
                                       uriString)) {
        NS_NewURI(getter_AddRefs(uri), uriString);
    } else {
        nsIPresShell* shell = doc->GetShell();
        if (!shell) {
            return;
        }

        nsPresContext* pc = shell->GetPresContext();
        if (!pc || !aStyleContext) {
            return;
        }

        const nsStyleList* list = aStyleContext->StyleList();
        imageRequest = list->GetListStyleImage();
        if (imageRequest) {
            imageRequest->GetURI(getter_AddRefs(uri));
            imageRect = list->mImageRegion.ToNearestPixels(
                            pc->AppUnitsPerDevPixel());
        }
    }

    if (!uri) {
        mOwner->ClearIcon();
        mURI = nullptr;

        if (mImageRequest) {
            mImageRequest->Cancel(NS_BINDING_ABORTED);
            mImageRequest = nullptr;
        }

        return;
    }

    bool same;
    if (mURI && NS_SUCCEEDED(mURI->Equals(uri, &same)) && same && 
        (!imageRequest || imageRect == mImageRect)) {
        return;
    }

    if (mImageRequest) {
        mImageRequest->Cancel(NS_BINDING_ABORTED);
        mImageRequest = nullptr;
    }

    mURI = uri;

    if (imageRequest) {
        mImageRect = imageRect;
        imageRequest->Clone(this, getter_AddRefs(mImageRequest));
    } else {
        mImageRect.SetEmpty();
        nsCOMPtr<nsILoadGroup> loadGroup = doc->GetDocumentLoadGroup();
        RefPtr<imgLoader> loader =
            nsContentUtils::GetImgLoaderForDocument(doc);
        if (!loader || !loadGroup) {
            NS_WARNING("Failed to get loader or load group for image load");
            return;
        }

        loader->LoadImage(uri, nullptr, nullptr, mozilla::net::RP_Unset,
                          nullptr, loadGroup, this, nullptr, nullptr,
                          nsIRequest::LOAD_NORMAL, nullptr,
                          nsIContentPolicy::TYPE_IMAGE, EmptyString(),
                          getter_AddRefs(mImageRequest));
    }
}

void
nsMenuObjectIconLoader::Destroy() {
    if (mImageRequest) {
        mImageRequest->CancelAndForgetObserver(NS_BINDING_ABORTED);
        mImageRequest = nullptr;
    }

    mOwner = nullptr;
}

static int
CalculateTextWidth(const nsAString& aText) {
    if (!gPangoLayout) {
        PangoFontMap* fontmap = pango_cairo_font_map_get_default();
        PangoContext* ctx = pango_font_map_create_context(fontmap);
        gPangoLayout = pango_layout_new(ctx);
        g_object_unref(ctx);
    }

    pango_layout_set_text(gPangoLayout, NS_ConvertUTF16toUTF8(aText).get(), -1);

    int width, dummy;
    pango_layout_get_size(gPangoLayout, &width, &dummy);

    return width;
}

static const nsDependentString
GetEllipsis() {
    static char16_t sBuf[4] = { 0, 0, 0, 0 };
    if (!sBuf[0]) {
        nsAdoptingString ellipsis = Preferences::GetLocalizedString("intl.ellipsis");
        if (!ellipsis.IsEmpty()) {
            uint32_t l = ellipsis.Length();
            const nsAdoptingString::char_type* c = ellipsis.BeginReading();
            uint32_t i = 0;
            while (i < 3 && i < l) {
                sBuf[i++] =* (c++);
            }
        } else {
            sBuf[0] = '.';
            sBuf[1] = '.';
            sBuf[2] = '.';
        }
    }

    return nsDependentString(sBuf);
}

static int
GetEllipsisWidth() {
    static int sEllipsisWidth = -1;

    if (sEllipsisWidth == -1) {
        sEllipsisWidth = CalculateTextWidth(GetEllipsis());
    }

    return sEllipsisWidth;
}

nsMenuObject::nsMenuObject(nsMenuContainer* aParent, nsIContent* aContent) :
    mContent(aContent),
    mListener(aParent->DocListener()),
    mParent(aParent),
    mNativeData(nullptr) {
    MOZ_ASSERT(mContent);
    MOZ_ASSERT(mListener);
    MOZ_ASSERT(mParent);
}

nsMenuObject::nsMenuObject(nsNativeMenuDocListener* aListener,
                           nsIContent* aContent) :
    mContent(aContent),
    mListener(aListener),
    mParent(nullptr),
    mNativeData(nullptr) {
    MOZ_ASSERT(mContent);
    MOZ_ASSERT(mListener);
}

void
nsMenuObject::UpdateLabel() {
    // Goanna stores the label and access key in separate attributes
    // so we need to convert label="Foo_Bar"/accesskey="F" in to
    // label="_Foo__Bar" for dbusmenu

    nsAutoString label;
    mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::label, label);

    nsAutoString accesskey;
    mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::accesskey, accesskey);

    const nsAutoString::char_type* akey = accesskey.BeginReading();
    char16_t keyLower = ToLowerCase(*akey);
    char16_t keyUpper = ToUpperCase(*akey);

    const nsAutoString::char_type* iter = label.BeginReading();
    const nsAutoString::char_type* end = label.EndReading();
    uint32_t length = label.Length();
    uint32_t pos = 0;
    bool foundAccessKey = false;

    while (iter != end) {
        if (*iter != char16_t('_')) {
            if ((*iter != keyLower &&* iter != keyUpper) || foundAccessKey) {
                ++iter;
                ++pos;
                continue;
            }
            foundAccessKey = true;
        }

        label.SetLength(++length);

        iter = label.BeginReading() + pos;
        end = label.EndReading();
        nsAutoString::char_type* cur = label.BeginWriting() + pos;

        memmove(cur + 1, cur, (length - 1 - pos)*  sizeof(nsAutoString::char_type));
       * cur = nsAutoString::char_type('_');

        iter += 2;
        pos += 2;
    }

    if (CalculateTextWidth(label) <= MAX_WIDTH) {
        dbusmenu_menuitem_property_set(mNativeData,
                                       DBUSMENU_MENUITEM_PROP_LABEL,
                                       NS_ConvertUTF16toUTF8(label).get());
        return;
    }

    // This sucks.
    // This should be done at the point where the menu is drawn (hello Unity),
    // but unfortunately it doesn't do that and will happily fill your entire
    // screen width with a menu if you have a bookmark with a really long title.
    // This leaves us with no other option but to ellipsize here, with no proper
    // knowledge of Unity's render path, font size etc. This is better than nothing
    nsAutoString truncated;
    int target = MAX_WIDTH - GetEllipsisWidth();
    length = label.Length();

    static nsIContent::AttrValuesArray strings[] = {
        &nsGkAtoms::left, &nsGkAtoms::start,
        &nsGkAtoms::center, &nsGkAtoms::right,
        &nsGkAtoms::end, nullptr
    };

    int32_t type = mContent->FindAttrValueIn(kNameSpaceID_None,
                                             nsGkAtoms::crop,
                                             strings, eCaseMatters);

    switch (type) {
        case 0:
        case 1:
            // FIXME: Implement left cropping
        case 2:
            // FIXME: Implement center cropping
        case 3:
        case 4:
        default:
            for (uint32_t i = 0; i < length; i++) {
                truncated.Append(label.CharAt(i));
                if (CalculateTextWidth(truncated) > target) {
                    break;
                }
            }

            truncated.Append(GetEllipsis());
    }

    dbusmenu_menuitem_property_set(mNativeData,
                                   DBUSMENU_MENUITEM_PROP_LABEL,
                                   NS_ConvertUTF16toUTF8(truncated).get());
}

void
nsMenuObject::UpdateVisibility(nsStyleContext* aStyleContext) {
    bool vis = true;

    if (aStyleContext &&
        (aStyleContext->StyleDisplay()->mDisplay == StyleDisplay::None ||
         aStyleContext->StyleVisibility()->mVisible ==
            NS_STYLE_VISIBILITY_COLLAPSE)) {
        vis = false;
    }

    dbusmenu_menuitem_property_set_bool(mNativeData,
                                        DBUSMENU_MENUITEM_PROP_VISIBLE,
                                        vis);
}

void
nsMenuObject::UpdateSensitivity() {
    bool disabled = mContent->AttrValueIs(kNameSpaceID_None,
                                          nsGkAtoms::disabled,
                                          nsGkAtoms::_true, eCaseMatters);

    dbusmenu_menuitem_property_set_bool(mNativeData,
                                        DBUSMENU_MENUITEM_PROP_ENABLED,
                                        !disabled);

}

void
nsMenuObject::UpdateIcon(nsStyleContext* aStyleContext) {
    if (ShouldShowIcon()) {
        if (!mIconLoader) {
            mIconLoader = new nsMenuObjectIconLoader(this);
        }

        mIconLoader->LoadIcon(aStyleContext);
    } else {
        if (mIconLoader) {
            mIconLoader->Destroy();
            mIconLoader = nullptr;
        }

        ClearIcon();
    }
}

already_AddRefed<nsStyleContext>
nsMenuObject::GetStyleContext() {
    nsIPresShell* shell = mContent->OwnerDoc()->GetShell();
    if (!shell) {
        return nullptr;
    }

    RefPtr<nsStyleContext> sc =
        nsComputedDOMStyle::GetStyleContextForElementNoFlush(
            mContent->AsElement(), nullptr, shell);

    return sc.forget();
}

void
nsMenuObject::InitializeNativeData() {
}

nsMenuObject::PropertyFlags
nsMenuObject::SupportedProperties() const {
    return static_cast<nsMenuObject::PropertyFlags>(0);
}

bool
nsMenuObject::IsCompatibleWithNativeData(DbusmenuMenuitem* aNativeData) const {
    return true;
}

void
nsMenuObject::UpdateContentAttributes() {
}

void
nsMenuObject::Update(nsStyleContext* aStyleContext) {
}

bool
nsMenuObject::ShouldShowIcon() const {
    // Ideally we want to know the visibility of the anonymous XUL image in
    // our menuitem, but this isn't created because we don't have a frame.
    // The following works by default (because xul.css hides images in menuitems
    // that don't have the "menuitem-with-favicon" class). It's possible a third
    // party theme could override this, but, oh well...
    const nsAttrValue* classes = mContent->AsElement()->GetClasses();
    if (!classes) {
        return false;
    }

    for (uint32_t i = 0; i < classes->GetAtomCount(); ++i) {
        if (classes->AtomAt(i) == nsNativeMenuAtoms::menuitem_with_favicon) {
            return true;
        }
    }

    return false;
}

void
nsMenuObject::ClearIcon() {
    dbusmenu_menuitem_property_remove(mNativeData,
                                      DBUSMENU_MENUITEM_PROP_ICON_DATA);
}

nsMenuObject::~nsMenuObject() {
    nsWeakMenuObject::NotifyDestroyed(this);

    if (mIconLoader) {
        mIconLoader->Destroy();
    }

    if (mListener) {
        mListener->UnregisterForContentChanges(mContent);
    }

    if (mNativeData) {
        g_object_unref(mNativeData);
        mNativeData = nullptr;
    }
}

void
nsMenuObject::CreateNativeData() {
    MOZ_ASSERT(mNativeData == nullptr, "This node already has a DbusmenuMenuitem. The old one will be leaked");

    mNativeData = dbusmenu_menuitem_new();
    InitializeNativeData();
    if (mParent && mParent->IsBeingDisplayed()) {
        ContainerIsOpening();
    }

    mListener->RegisterForContentChanges(mContent, this);
}

nsresult
nsMenuObject::AdoptNativeData(DbusmenuMenuitem* aNativeData) {
    MOZ_ASSERT(mNativeData == nullptr, "This node already has a DbusmenuMenuitem. The old one will be leaked");

    if (!IsCompatibleWithNativeData(aNativeData)) {
        return NS_ERROR_FAILURE;
    }

    mNativeData = aNativeData;
    g_object_ref(mNativeData);

    PropertyFlags supported = SupportedProperties();
    PropertyFlags mask = static_cast<PropertyFlags>(1);

    for (uint32_t i = 0; gPropertyStrings[i]; ++i) {
        if (!(mask & supported)) {
            dbusmenu_menuitem_property_remove(mNativeData, gPropertyStrings[i]);
        }
        mask = static_cast<PropertyFlags>(mask << 1);
    }

    InitializeNativeData();
    if (mParent && mParent->IsBeingDisplayed()) {
        ContainerIsOpening();
    }

    mListener->RegisterForContentChanges(mContent, this);

    return NS_OK;
}

void
nsMenuObject::ContainerIsOpening() {
    MOZ_ASSERT(nsContentUtils::IsSafeToRunScript());

    UpdateContentAttributes();

    RefPtr<nsStyleContext> sc = GetStyleContext();
    Update(sc);
}

/* static */ void
nsWeakMenuObject::AddWeakReference(nsWeakMenuObject* aWeak) {
    aWeak->mPrev = sHead;
    sHead = aWeak;
}

/* static */ void
nsWeakMenuObject::RemoveWeakReference(nsWeakMenuObject* aWeak) {
    if (aWeak == sHead) {
        sHead = aWeak->mPrev;
        return;
    }

    nsWeakMenuObject* weak = sHead;
    while (weak && weak->mPrev != aWeak) {
        weak = weak->mPrev;
    }

    if (weak) {
        weak->mPrev = aWeak->mPrev;
    }
}

/* static */ void
nsWeakMenuObject::NotifyDestroyed(nsMenuObject* aMenuObject) {
    nsWeakMenuObject* weak = sHead;
    while (weak) {
        if (weak->mMenuObject == aMenuObject) {
            weak->mMenuObject = nullptr;
        }

        weak = weak->mPrev;
    }
}