summaryrefslogtreecommitdiff
path: root/src/plugins/help/macwebkithelpviewer.mm
blob: 6cd509e8044279c7eec92f359e542fe9b0ca87cd (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
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/

#include "macwebkithelpviewer.h"

#include "localhelpmanager.h"
#include "openpagesmanager.h"

#include <coreplugin/icore.h>
#include <utils/qtcassert.h>

#include <QApplication>
#include <QClipboard>
#include <QHelpEngine>
#include <QStyle>
#include <QTimer>
#include <QtMac>
#include <QToolTip>
#include <QUrl>
#include <QVBoxLayout>

#include <QDebug>

#import <AppKit/NSMenuItem.h>
#import <Foundation/NSURLProtocol.h>
#import <Foundation/NSURLResponse.h>
#import <WebKit/DOMDocument.h>
#import <WebKit/DOMElement.h>
#import <WebKit/DOMHTMLElement.h>
#import <WebKit/DOMNodeFilter.h>
#import <WebKit/DOMNodeIterator.h>
#import <WebKit/DOMRange.h>
#import <WebKit/WebBackForwardList.h>
#import <WebKit/WebDataSource.h>
#import <WebKit/WebDocument.h>
#import <WebKit/WebFrame.h>
#import <WebKit/WebFrameLoadDelegate.h>
#import <WebKit/WebFrameView.h>
#import <WebKit/WebHistoryItem.h>
#import <WebKit/WebPreferences.h>
#import <WebKit/WebUIDelegate.h>
#import <WebKit/WebView.h>

using namespace Utils;

// #pragma mark -- mac helpers

// copy from qcocoahelpers.mm
static int mainScreenHeight()
{
    // The first screen in the screens array is documented
    // to have the (0,0) origin.
    NSRect screenFrame = [[[NSScreen screens] firstObject] frame];
    return screenFrame.size.height;
}

static QPoint flipPoint(const NSPoint &p)
{
    return QPoint(p.x, mainScreenHeight() - p.y);
}

// #pragma mark -- DOMNodeIterator (PrivateExtensions)

@interface DOMNodeIterator (PrivateExtensions)

- (BOOL)findNode:(DOMNode *)node;
- (DOMNode *)nextTextNode;
- (DOMNode *)previousTextNode;
- (DOMNode *)gotoEnd;

@end

@implementation DOMNodeIterator (PrivateExtensions)

- (BOOL)findNode:(DOMNode *)node
{
    while (DOMNode *next = [self nextNode]) {
        if (next == node)
            return YES;
    }
    return NO;
}

- (DOMNode *)nextTextNode
{
    DOMNode *node = nil;
    do {
        node = [self nextNode];
    } while (node && node.nodeType != DOM_TEXT_NODE);
    return node;
}

- (DOMNode *)previousTextNode
{
    DOMNode *node = nil;
    do {
        node = [self previousNode];
    } while (node && node.nodeType != DOM_TEXT_NODE);
    return node;
}

- (DOMNode *)gotoEnd
{
    DOMNode *previous = nil;
    DOMNode *node = nil;
    do {
        previous = node;
        node = [self nextNode];
    } while (node);
    return previous;
}

@end

// #pragma mark -- QtHelpURLProtocol

@interface QtHelpURLProtocol : NSURLProtocol
{
}

+ (BOOL)canInitWithRequest:(NSURLRequest *)request;

@end

@implementation QtHelpURLProtocol

+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
    return [[[request URL] scheme] isEqualToString:@"qthelp"];
}

+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
{
    return request;
}

- (void)startLoading
{
    const QUrl &url = QUrl::fromNSURL(self.request.URL);
    Help::Internal::LocalHelpManager::HelpData data;
    Help::Internal::LocalHelpManager *helpManager = Help::Internal::LocalHelpManager::instance();

    QMetaObject::invokeMethod(helpManager, "helpData", Qt::BlockingQueuedConnection,
                              Q_RETURN_ARG(Help::Internal::LocalHelpManager::HelpData, data),
                              Q_ARG(QUrl, url));

    NSURL *resolvedURL = data.resolvedUrl.toNSURL();
    NSString *mimeType = data.mimeType.toNSString();
    NSData *nsdata = QtMac::toNSData(data.data); // Qt 5.3 has this in QByteArray
    NSURLResponse *response = [[NSURLResponse alloc] initWithURL:resolvedURL
                                                        MIMEType:mimeType
                                           expectedContentLength:data.data.length()
                                                textEncodingName:@"UTF8"];
    [self.client URLProtocol:self didReceiveResponse:response
                                  cacheStoragePolicy:NSURLCacheStorageNotAllowed];
    [self.client URLProtocol:self didLoadData:nsdata];
    [self.client URLProtocolDidFinishLoading:self];
    [response release];
}

- (void)stopLoading
{
}

@end

static void ensureProtocolHandler()
{
    static bool registered = false;
    if (!registered) {
        [NSURLProtocol registerClass:[QtHelpURLProtocol class]];
        registered = true;
    }
}

// #pragma mark -- FrameLoadDelegate

@interface FrameLoadDelegate : NSObject
{
    WebFrame *mainFrame;
    Help::Internal::MacWebKitHelpViewer *viewer;
}

- (id)initWithMainFrame:(WebFrame *)frame viewer:(Help::Internal::MacWebKitHelpViewer *)viewer;
- (void)webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame;
- (void)webView:(WebView *)sender didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame;
- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame;
- (void)webView:(WebView *)sender didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame;

@end

@implementation FrameLoadDelegate

- (id)initWithMainFrame:(WebFrame *)frame viewer:(Help::Internal::MacWebKitHelpViewer *)helpViewer
{
    self = [super init];
    if (self) {
        mainFrame = frame;
        viewer = helpViewer;
    }
    return self;
}

- (void)webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame
{
    Q_UNUSED(sender)
    if (frame == mainFrame)
        viewer->slotLoadStarted();
}

- (void)webView:(WebView *)sender didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame
{
    Q_UNUSED(sender)
    Q_UNUSED(title)
    if (frame == mainFrame)
        viewer->titleChanged();
}

- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
{
    Q_UNUSED(sender)
    if (frame == mainFrame)
        viewer->slotLoadFinished();
}

- (void)webView:(WebView *)sender didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
{
    Q_UNUSED(sender)
    Q_UNUSED(error)
    if (frame == mainFrame)
        viewer->slotLoadFinished();
}

@end

// #pragma mark -- UIDelegate

@interface UIDelegate : NSObject
{
    Help::Internal::MacWebKitHelpWidget *widget;
}

@property (assign) BOOL openInNewPageActionVisible;

- (id)initWithWidget:(Help::Internal::MacWebKitHelpWidget *)theWidget;
- (void)webView:(WebView *)sender makeFirstResponder:(NSResponder *)responder;
- (NSArray *)webView:(WebView *)sender contextMenuItemsForElement:(NSDictionary *)element
    defaultMenuItems:(NSArray *)defaultMenuItems;
- (WebView *)webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request;
- (void)webView:(WebView *)sender mouseDidMoveOverElement:(NSDictionary *)elementInformation
    modifierFlags:(NSUInteger)modifierFlags;
@end

@implementation UIDelegate

- (id)initWithWidget:(Help::Internal::MacWebKitHelpWidget *)theWidget
{
    self = [super init];
    if (self) {
        widget = theWidget;
        self.openInNewPageActionVisible = YES;
    }
    return self;
}

- (void)webView:(WebView *)sender makeFirstResponder:(NSResponder *)responder
{
    // make the widget get focus
    if (responder) {
        widget->setFocus();
        [sender.window makeFirstResponder:responder];
    }
}

- (NSArray *)webView:(WebView *)sender contextMenuItemsForElement:(NSDictionary *)element
    defaultMenuItems:(NSArray *)defaultMenuItems
{
    Q_UNUSED(sender)
    Q_UNUSED(element)
    NSMutableArray *ret = [[NSMutableArray alloc] init];
    for (NSMenuItem *item in defaultMenuItems) {
        switch (item.tag) {
        case WebMenuItemTagCopyLinkToClipboard:
        case WebMenuItemTagCopyImageToClipboard:
        case WebMenuItemTagCopy:
        case WebMenuItemTagGoBack:
        case WebMenuItemTagGoForward:
        case WebMenuItemTagStop:
        case WebMenuItemTagReload:
        case WebMenuItemTagOther:
        case WebMenuItemTagSearchInSpotlight:
        case WebMenuItemTagSearchWeb:
        case WebMenuItemTagLookUpInDictionary:
        case WebMenuItemTagOpenWithDefaultApplication:
            [ret addObject:item];
            break;
        case WebMenuItemTagOpenLinkInNewWindow:
        case WebMenuItemTagOpenImageInNewWindow:
            if (self.openInNewPageActionVisible) {
                item.title = QCoreApplication::translate("HelpViewer", "Open Link as New Page").toNSString();
                [ret addObject:item];
            }
        default:
            break;
        }
    }
    return [ret autorelease];
}

- (WebView *)webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request
{
    Q_UNUSED(sender)
    Q_UNUSED(request)
    Help::Internal::MacWebKitHelpViewer* viewer
            = static_cast<Help::Internal::MacWebKitHelpViewer *>(
                Help::Internal::OpenPagesManager::instance().createPage(QUrl()));
    return viewer->widget()->webView();
}

- (void)webView:(WebView *)sender mouseDidMoveOverElement:(NSDictionary *)elementInformation
    modifierFlags:(NSUInteger)modifierFlags
{
    Q_UNUSED(sender)
    if (!elementInformation || (modifierFlags & NSDeviceIndependentModifierFlagsMask) != 0) {
        widget->hideToolTip();
        return;
    }
    NSURL *url = [elementInformation objectForKey:WebElementLinkURLKey];
    if (!url) {
        widget->hideToolTip();
        return;
    }
    widget->startToolTipTimer(flipPoint(NSEvent.mouseLocation),
                       QString::fromNSString(url.absoluteString));
}

@end

// #pragma mark -- MyWebView
@interface MyWebView : WebView
@end

// work around Qt + WebView issue QTBUG-26593, that Qt does not pass mouseMoved: events up the event chain,
// but the Web(HTML)View is only handling mouse moved for hovering etc if the event was passed up
// to the NSWindow (arguably a bug in Web(HTML)View)
@implementation MyWebView

- (void)updateTrackingAreas
{
    [super updateTrackingAreas];
    if (NSArray *trackingArray = [self trackingAreas]) {
        NSUInteger size = [trackingArray count];
        for (NSUInteger i = 0; i < size; ++i) {
            NSTrackingArea *t = [trackingArray objectAtIndex:i];
            [self removeTrackingArea:t];
        }
    }
    NSUInteger trackingOptions = NSTrackingActiveInActiveApp | NSTrackingInVisibleRect
            | NSTrackingMouseMoved;
    NSTrackingArea *ta = [[[NSTrackingArea alloc] initWithRect:[self frame]
                                                      options:trackingOptions
                                                        owner:self
                                                     userInfo:nil]
                                                                autorelease];
    [self addTrackingArea:ta];
}

- (void)mouseMoved:(NSEvent *)theEvent
{
    [self.window mouseMoved:theEvent];
}

@end

namespace Help {
namespace Internal {

// #pragma mark -- MacWebKitHelpWidget

class MacWebKitHelpWidgetPrivate
{
public:
    MacWebKitHelpWidgetPrivate()
        : m_savedResponder(nil)
    {
    }

    ~MacWebKitHelpWidgetPrivate()
    {
        [m_webView release];
        [m_frameLoadDelegate release];
        [m_uiDelegate release];
    }

    WebView *m_webView;
    FrameLoadDelegate *m_frameLoadDelegate;
    UIDelegate *m_uiDelegate;
    NSResponder *m_savedResponder;
    QTimer m_toolTipTimer;
    QPoint m_toolTipPos;
    QString m_toolTipText;
};

// #pragma mark -- MacWebKitHelpWidget

MacWebKitHelpWidget::MacWebKitHelpWidget(MacWebKitHelpViewer *parent)
    : QMacCocoaViewContainer(0, parent),
      d(new MacWebKitHelpWidgetPrivate)
{
    d->m_toolTipTimer.setSingleShot(true);
    connect(&d->m_toolTipTimer, &QTimer::timeout, this, &MacWebKitHelpWidget::showToolTip);
    @autoreleasepool {
        d->m_webView = [[MyWebView alloc] init];
        // Turn layered rendering on.
        // Otherwise the WebView will render empty after any QQuickWidget was shown.
        d->m_webView.wantsLayer = YES;
        d->m_frameLoadDelegate = [[FrameLoadDelegate alloc] initWithMainFrame:d->m_webView.mainFrame
                                                                       viewer:parent];
        [d->m_webView setFrameLoadDelegate:d->m_frameLoadDelegate];
        d->m_uiDelegate = [[UIDelegate alloc] initWithWidget:this];
        [d->m_webView setUIDelegate:d->m_uiDelegate];

        setCocoaView(d->m_webView);
    }
}

MacWebKitHelpWidget::~MacWebKitHelpWidget()
{
    delete d;
}

void MacWebKitHelpWidget::setOpenInNewPageActionVisible(bool visible)
{
    d->m_uiDelegate.openInNewPageActionVisible = visible;
}

WebView *MacWebKitHelpWidget::webView() const
{
    return d->m_webView;
}

void MacWebKitHelpWidget::startToolTipTimer(const QPoint &pos, const QString &text)
{
    int delay = style()->styleHint(QStyle::SH_ToolTip_WakeUpDelay, 0, this, 0);
    d->m_toolTipPos = pos;
    d->m_toolTipText = text;
    d->m_toolTipTimer.start(delay);
}

void MacWebKitHelpWidget::hideToolTip()
{
    d->m_toolTipTimer.stop();
    QToolTip::showText(QPoint(), QString());
}

void MacWebKitHelpWidget::hideEvent(QHideEvent *)
{
    [d->m_webView setHidden:YES];
}

void MacWebKitHelpWidget::showEvent(QShowEvent *)
{
    [d->m_webView setHidden:NO];
}

void MacWebKitHelpWidget::showToolTip()
{
    QToolTip::showText(d->m_toolTipPos, d->m_toolTipText, this);
}

// #pragma mark -- MacWebKitHelpViewer

MacWebKitHelpViewer::MacWebKitHelpViewer(QWidget *parent)
    : HelpViewer(parent),
      m_widget(new MacWebKitHelpWidget(this))
{
    static bool responderHackInstalled = false;
    if (!responderHackInstalled) {
        responderHackInstalled = true;
        new MacResponderHack(qApp);
    }

    @autoreleasepool {
        QVBoxLayout *layout = new QVBoxLayout;
        setLayout(layout);
        layout->setContentsMargins(0, 0, 0, 0);
        layout->addWidget(m_widget, 10);
    }
}

MacWebKitHelpViewer::~MacWebKitHelpViewer()
{

}

QFont MacWebKitHelpViewer::viewerFont() const
{
    @autoreleasepool {
        WebPreferences *preferences = m_widget->webView().preferences;
        QString family = QString::fromNSString([preferences standardFontFamily]);
        int size = [preferences defaultFontSize];
        return QFont(family, size);
    }
}

void MacWebKitHelpViewer::setViewerFont(const QFont &font)
{
    @autoreleasepool {
        WebPreferences *preferences = m_widget->webView().preferences;
        [preferences setStandardFontFamily:font.family().toNSString()];
        [preferences setDefaultFontSize:font.pointSize()];
    }
}

void MacWebKitHelpViewer::scaleUp()
{
    @autoreleasepool {
        m_widget->webView().textSizeMultiplier += 0.1;
    }
}

void MacWebKitHelpViewer::scaleDown()
{
    @autoreleasepool {
        m_widget->webView().textSizeMultiplier = qMax(0.1, m_widget->webView().textSizeMultiplier - 0.1);
    }
}

void MacWebKitHelpViewer::resetScale()
{
    @autoreleasepool {
        m_widget->webView().textSizeMultiplier = 1.0;
    }
}

qreal MacWebKitHelpViewer::scale() const
{
    @autoreleasepool {
        return m_widget->webView().textSizeMultiplier;
    }
}

void MacWebKitHelpViewer::setScale(qreal scale)
{
    m_widget->webView().textSizeMultiplier = (scale <= 0.0 ? 1.0 : scale);
}

QString MacWebKitHelpViewer::title() const
{
    @autoreleasepool {
        return QString::fromNSString(m_widget->webView().mainFrameTitle);
    }
}

QUrl MacWebKitHelpViewer::source() const
{
    @autoreleasepool {
        WebDataSource *dataSource = m_widget->webView().mainFrame.dataSource;
        if (!dataSource)
            dataSource = m_widget->webView().mainFrame.provisionalDataSource;
        return QUrl::fromNSURL(dataSource.request.URL);
    }
}

void MacWebKitHelpViewer::setSource(const QUrl &url)
{
    @autoreleasepool {
        ensureProtocolHandler();
        [m_widget->webView().mainFrame loadRequest:[NSURLRequest requestWithURL:url.toNSURL()]];
    }
}

void MacWebKitHelpViewer::scrollToAnchor(const QString &anchor)
{
    QUrl url = source();
    url.setFragment(anchor);
    setSource(url);
}

void MacWebKitHelpViewer::setHtml(const QString &html)
{
    @autoreleasepool {
        [m_widget->webView().mainFrame
                loadHTMLString:html.toNSString()
                       baseURL:[NSURL fileURLWithPath:Core::ICore::resourcePath().toNSString()]];
    }
}

QString MacWebKitHelpViewer::selectedText() const
{
    @autoreleasepool {
        return QString::fromNSString(m_widget->webView().selectedDOMRange.text);
    }
}

bool MacWebKitHelpViewer::isForwardAvailable() const
{
    @autoreleasepool {
        return m_widget->webView().canGoForward;
    }
}

bool MacWebKitHelpViewer::isBackwardAvailable() const
{
    @autoreleasepool {
        return m_widget->webView().canGoBack;
    }
}

void MacWebKitHelpViewer::addBackHistoryItems(QMenu *backMenu)
{
    @autoreleasepool {
        WebBackForwardList *list = m_widget->webView().backForwardList;
        int backListCount = list.backListCount;
        for (int i = 0; i < backListCount; ++i) {
            int historyIndex = -(i+1);
            QAction *action = new QAction(backMenu);
            action->setText(QString::fromNSString([list itemAtIndex:historyIndex].title));
            action->setData(historyIndex);
            connect(action, SIGNAL(triggered()), this, SLOT(goToHistoryItem()));
            backMenu->addAction(action);
        }
    }
}

void MacWebKitHelpViewer::addForwardHistoryItems(QMenu *forwardMenu)
{
    @autoreleasepool {
        WebBackForwardList *list = m_widget->webView().backForwardList;
        int forwardListCount = list.forwardListCount;
        for (int i = 0; i < forwardListCount; ++i) {
            int historyIndex = i + 1;
            QAction *action = new QAction(forwardMenu);
            action->setText(QString::fromNSString([list itemAtIndex:historyIndex].title));
            action->setData(historyIndex);
            connect(action, SIGNAL(triggered()), this, SLOT(goToHistoryItem()));
            forwardMenu->addAction(action);
        }
    }
}

void MacWebKitHelpViewer::setOpenInNewPageActionVisible(bool visible)
{
    m_widget->setOpenInNewPageActionVisible(visible);
}

DOMRange *MacWebKitHelpViewer::findText(NSString *text, bool forward, bool caseSensitive, DOMNode *startNode, int startOffset)
{
    QTC_ASSERT(text, return nil);
    if (text.length == 0)
        return nil;
    DOMDocument *document = m_widget->webView().mainFrame.DOMDocument;
    // search only the body
    DOMNodeIterator *iterator = [document createNodeIterator:document.body whatToShow:DOM_SHOW_ALL
            filter:nil expandEntityReferences:NO];

    DOMNode *selectionStart = nil;
    int selectionStartOffset = 0;
    DOMNode *currentNode = startNode;
    int currentOffset = startOffset;
    NSString *searchTerm = caseSensitive ? text : [text lowercaseString];
    int searchTermLength = searchTerm.length;
    int indexInSearchTerm = forward ? 0 : searchTerm.length - 1;
    if (!currentNode) { // search whole body from end
        if (forward)
            currentNode = document.body;
        else
            currentNode = [iterator gotoEnd];
    } else { // otherwise find the start node
        QTC_ASSERT([iterator findNode:currentNode], return nil);
    }
    if (!forward) { // findNode leaves iterator behind currentNode, we need to go back
        QTC_ASSERT([iterator previousNode] == currentNode, return nil);
    }
    if (currentNode.nodeType != DOM_TEXT_NODE) { // we only want text nodes
        currentNode = forward ? [iterator nextTextNode] : [iterator previousTextNode];
        currentOffset = -1; // search whole node
    }
    while (currentNode) {
        NSString *currentText = caseSensitive ? currentNode.nodeValue : [currentNode.nodeValue lowercaseString];
        int currentTextLength = currentText.length;
        if (currentOffset < 0) // search whole node
            currentOffset = forward ? 0 : currentTextLength - 1;
        while (currentOffset < currentTextLength/*forward*/ && currentOffset >= 0/*backward*/) {
            if ([currentText characterAtIndex:currentOffset] == [searchTerm characterAtIndex:indexInSearchTerm]) {
                indexInSearchTerm += forward ? 1 : -1;
                if (!selectionStart) {
                    selectionStart = currentNode;
                    selectionStartOffset = currentOffset;
                }
            } else {
                indexInSearchTerm = forward ? 0 : searchTerm.length - 1;
                selectionStart = nil;
            }
            currentOffset += forward ? 1 : -1;
            if (indexInSearchTerm >= searchTermLength/*forward*/ || indexInSearchTerm < 0/*backward*/) {
                // we have found a match!
                DOMRange *range = [document createRange];
                if (forward) {
                    [range setStart:selectionStart offset:selectionStartOffset];
                    [range setEnd:currentNode offset:currentOffset];
                } else {
                    [range setStart:currentNode offset:(currentOffset + 1)]; // was already decreased
                    [range setEnd:selectionStart offset:(selectionStartOffset + 1)];
                }
                return range;
            }
        }
        currentNode = forward ? [iterator nextTextNode] : [iterator previousTextNode];
        currentOffset = -1; // search whole node
    }
    return nil;
}

bool MacWebKitHelpViewer::findText(const QString &text, Core::FindFlags flags, bool incremental,
                                   bool fromSearch, bool *wrapped)
{
    Q_UNUSED(incremental);
    Q_UNUSED(fromSearch);
    @autoreleasepool {
        if (wrapped)
            *wrapped = false;
        bool forward = !(flags & Core::FindBackward);
        bool caseSensitive = (flags & Core::FindCaseSensitively);
        WebView *webView = m_widget->webView();

        // WebView searchFor:.... grabs first responder, and when losing first responder afterwards,
        // it removes the selection and forgets the search state, making it pretty useless for us

        // define the start node and offset for the search
        DOMNode *start = nil; // default is search whole body
        int startOffset = -1;
        DOMRange *selection = webView.selectedDOMRange;
        if (selection) {
            if (QString::fromNSString(selection.text).compare(
                        text, caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive) != 0) {
                // for incremental search we want to search from the beginning of the selection
                start = selection.startContainer;
                startOffset = selection.startOffset;
            } else {
                // search for next occurrence
                if (forward) {
                    start = selection.endContainer;
                    startOffset = selection.endOffset;
                } else {
                    start = selection.startContainer;
                    startOffset = selection.startOffset;
                }
            }
        }
        DOMRange *newSelection = findText(text.toNSString(), forward, caseSensitive,
                                          start, startOffset);
        if (!newSelection && start != nil) { // wrap
            start = nil;
            startOffset = -1;
            newSelection = findText(text.toNSString(), forward, caseSensitive,
                                                  start, startOffset);
            if (newSelection && wrapped)
                *wrapped = true;
        }
        if (newSelection) {
            // found, select and scroll there
            [webView setSelectedDOMRange:newSelection affinity:NSSelectionAffinityDownstream];
            if (forward)
                [newSelection.endContainer.parentElement scrollIntoViewIfNeeded:YES];
            else
                [newSelection.startContainer.parentElement scrollIntoViewIfNeeded:YES];
            return true;
        }
    }
    return false;
}

void MacWebKitHelpViewer::copy()
{
    QApplication::clipboard()->setText(selectedText());
}

void MacWebKitHelpViewer::stop()
{
    [m_widget->webView() stopLoading:nil];
}

void MacWebKitHelpViewer::forward()
{
    @autoreleasepool {
        [m_widget->webView() goForward];
        emit forwardAvailable(isForwardAvailable());
        emit backwardAvailable(isBackwardAvailable());
    }
}

void MacWebKitHelpViewer::backward()
{
    @autoreleasepool {
        [m_widget->webView() goBack];
        emit forwardAvailable(isForwardAvailable());
        emit backwardAvailable(isBackwardAvailable());
    }
}

void MacWebKitHelpViewer::print(QPrinter *printer)
{
    Q_UNUSED(printer)
}

void MacWebKitHelpViewer::slotLoadStarted()
{
    HelpViewer::slotLoadStarted();
}

void MacWebKitHelpViewer::slotLoadFinished()
{
    HelpViewer::slotLoadFinished();
    emit forwardAvailable(isForwardAvailable());
    emit backwardAvailable(isBackwardAvailable());
}

void MacWebKitHelpViewer::goToHistoryItem()
{
    @autoreleasepool {
        QAction *action = qobject_cast<QAction *>(sender());
        QTC_ASSERT(action, return);
        bool ok = false;
        int index = action->data().toInt(&ok);
        QTC_ASSERT(ok, return);
        WebBackForwardList *list = m_widget->webView().backForwardList;
        WebHistoryItem *item = [list itemAtIndex:index];
        QTC_ASSERT(item, return);
        [m_widget->webView() goToBackForwardItem:item];
        emit forwardAvailable(isForwardAvailable());
        emit backwardAvailable(isBackwardAvailable());
    }
}

// #pragma mark -- MacResponderHack

MacResponderHack::MacResponderHack(QObject *parent)
    : QObject(parent)
{
    connect(qApp, SIGNAL(focusChanged(QWidget*,QWidget*)),
            this, SLOT(responderHack(QWidget*,QWidget*)));
}

void MacResponderHack::responderHack(QWidget *old, QWidget *now)
{
    // On focus change, Qt does not make the corresponding QNSView firstResponder.
    // That breaks when embedding native NSView into a Qt hierarchy. When the focus is changed
    // by clicking with the mouse into a widget, everything is fine, because Cocoa automatically
    // adapts firstResponder in that case, but it breaks when setting the Qt focus from code.
    Q_UNUSED(old)
    if (!now)
        return;
    @autoreleasepool {
        NSView *view;
        if (QMacCocoaViewContainer *viewContainer = qobject_cast<QMacCocoaViewContainer *>(now))
            view = viewContainer->cocoaView();
        else
            view = (NSView *)now->effectiveWinId();
        [view.window makeFirstResponder:view];
    }
}

} // Internal
} // Help