1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/osx/webview_webkit.mm
3 // Purpose: wxWebViewWebKit - embeddable web kit control,
4 // OS X implementation of web view component
5 // Author: Jethro Grassie / Kevin Ollivier / Marianne Gagnon
9 // Copyright: (c) Jethro Grassie / Kevin Ollivier / Marianne Gagnon
10 // Licence: wxWindows licence
11 /////////////////////////////////////////////////////////////////////////////
13 // http://developer.apple.com/mac/library/documentation/Cocoa/Reference/WebKit/Classes/WebView_Class/Reference/Reference.html
15 #include "wx/osx/webview_webkit.h"
17 #if wxUSE_WEBVIEW_WEBKIT && (defined(__WXOSX_COCOA__) \
18 || defined(__WXOSX_CARBON__))
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
27 #include "wx/osx/private.h"
28 #include "wx/cocoa/string.h"
30 #include <WebKit/WebKit.h>
31 #include <WebKit/HIWebView.h>
32 #include <WebKit/CarbonUtils.h>
34 #include <Foundation/NSURLError.h>
36 #define DEBUG_WEBKIT_SIZING 0
38 // ----------------------------------------------------------------------------
40 // ----------------------------------------------------------------------------
42 wxIMPLEMENT_DYNAMIC_CLASS(wxWebViewWebKit, wxWebView);
44 BEGIN_EVENT_TABLE(wxWebViewWebKit, wxControl)
45 #if defined(__WXMAC__) && wxOSX_USE_CARBON
46 EVT_SIZE(wxWebViewWebKit::OnSize)
50 #if defined(__WXOSX__) && wxOSX_USE_CARBON
52 // ----------------------------------------------------------------------------
53 // Carbon Events handlers
54 // ----------------------------------------------------------------------------
56 // prototype for function in src/osx/carbon/nonownedwnd.cpp
57 void SetupMouseEvent( wxMouseEvent &wxevent , wxMacCarbonEvent &cEvent );
59 static const EventTypeSpec eventList[] =
61 //{ kEventClassControl, kEventControlTrack } ,
62 { kEventClassMouse, kEventMouseUp },
63 { kEventClassMouse, kEventMouseDown },
64 { kEventClassMouse, kEventMouseMoved },
65 { kEventClassMouse, kEventMouseDragged },
67 { kEventClassKeyboard, kEventRawKeyDown } ,
68 { kEventClassKeyboard, kEventRawKeyRepeat } ,
69 { kEventClassKeyboard, kEventRawKeyUp } ,
70 { kEventClassKeyboard, kEventRawKeyModifiersChanged } ,
72 { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent } ,
73 { kEventClassTextInput, kEventTextInputUpdateActiveInputArea } ,
75 #if DEBUG_WEBKIT_SIZING == 1
76 { kEventClassControl, kEventControlBoundsChanged } ,
80 // mix this in from window.cpp
81 pascal OSStatus wxMacUnicodeTextEventHandler(EventHandlerCallRef handler,
82 EventRef event, void *data) ;
84 // NOTE: This is mostly taken from KeyboardEventHandler in toplevel.cpp, but
85 // that expects the data pointer is a top-level window, so I needed to change
86 // that in this case. However, once 2.8 is out, we should factor out the common
87 // logic among the two functions and merge them.
88 static pascal OSStatus wxWebKitKeyEventHandler(EventHandlerCallRef handler,
89 EventRef event, void *data)
91 OSStatus result = eventNotHandledErr ;
92 wxMacCarbonEvent cEvent( event ) ;
94 wxWebViewWebKit* thisWindow = (wxWebViewWebKit*) data ;
95 wxWindow* focus = thisWindow ;
97 unsigned char charCode ;
105 UInt32 when = EventTimeToTicks( GetEventTime( event ) ) ;
108 ByteCount dataSize = 0 ;
109 if ( GetEventParameter(event, kEventParamKeyUnicodes, typeUnicodeText,
110 NULL, 0 , &dataSize, NULL ) == noErr)
113 int numChars = dataSize / sizeof( UniChar) + 1;
115 UniChar* charBuf = buf ;
117 if ( numChars * 2 > 4 )
118 charBuf = new UniChar[ numChars ] ;
119 GetEventParameter(event, kEventParamKeyUnicodes, typeUnicodeText, NULL,
120 dataSize , NULL , charBuf) ;
121 charBuf[ numChars - 1 ] = 0;
123 #if SIZEOF_WCHAR_T == 2
124 uniChar = charBuf[0] ;
126 wxMBConvUTF16 converter ;
127 converter.MB2WC( uniChar , (const char*)charBuf , 2 ) ;
130 if ( numChars * 2 > 4 )
135 GetEventParameter(event, kEventParamKeyMacCharCodes, typeChar, NULL,
136 sizeof(char), NULL, &charCode );
137 GetEventParameter(event, kEventParamKeyCode, typeUInt32, NULL,
138 sizeof(UInt32), NULL, &keyCode );
139 GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, NULL,
140 sizeof(UInt32), NULL, &modifiers );
141 GetEventParameter(event, kEventParamMouseLocation, typeQDPoint, NULL,
142 sizeof(Point), NULL, &point );
144 UInt32 message = (keyCode << 8) + charCode;
145 switch ( GetEventKind( event ) )
147 case kEventRawKeyRepeat :
148 case kEventRawKeyDown :
150 WXEVENTREF formerEvent = wxTheApp->MacGetCurrentEvent() ;
151 WXEVENTHANDLERCALLREF formerHandler =
152 wxTheApp->MacGetCurrentEventHandlerCallRef() ;
154 wxTheApp->MacSetCurrentEvent( event , handler ) ;
155 if ( /* focus && */ wxTheApp->MacSendKeyDownEvent(
156 focus, message, modifiers, when, point.h, point.v, uniChar[0]))
160 wxTheApp->MacSetCurrentEvent( formerEvent , formerHandler ) ;
164 case kEventRawKeyUp :
165 if ( /* focus && */ wxTheApp->MacSendKeyUpEvent(
166 focus , message , modifiers , when , point.h , point.v , uniChar[0] ) )
172 case kEventRawKeyModifiersChanged :
174 wxKeyEvent event(wxEVT_KEY_DOWN);
176 event.m_shiftDown = modifiers & shiftKey;
177 event.m_controlDown = modifiers & controlKey;
178 event.m_altDown = modifiers & optionKey;
179 event.m_metaDown = modifiers & cmdKey;
184 event.m_uniChar = uniChar[0] ;
187 event.SetTimestamp(when);
188 event.SetEventObject(focus);
190 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & controlKey )
192 event.m_keyCode = WXK_CONTROL ;
193 event.SetEventType( ( modifiers & controlKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
194 focus->GetEventHandler()->ProcessEvent( event ) ;
196 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & shiftKey )
198 event.m_keyCode = WXK_SHIFT ;
199 event.SetEventType( ( modifiers & shiftKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
200 focus->GetEventHandler()->ProcessEvent( event ) ;
202 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & optionKey )
204 event.m_keyCode = WXK_ALT ;
205 event.SetEventType( ( modifiers & optionKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
206 focus->GetEventHandler()->ProcessEvent( event ) ;
208 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & cmdKey )
210 event.m_keyCode = WXK_COMMAND ;
211 event.SetEventType( ( modifiers & cmdKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
212 focus->GetEventHandler()->ProcessEvent( event ) ;
215 wxApp::s_lastModifiers = modifiers ;
226 static pascal OSStatus wxWebViewWebKitEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
228 OSStatus result = eventNotHandledErr ;
230 wxMacCarbonEvent cEvent( event ) ;
232 ControlRef controlRef ;
233 wxWebViewWebKit* thisWindow = (wxWebViewWebKit*) data ;
234 wxNonOwnedWindow* tlw = NULL;
236 tlw = thisWindow->MacGetTopLevelWindow();
238 cEvent.GetParameter( kEventParamDirectObject , &controlRef ) ;
240 wxWindow* currentMouseWindow = thisWindow ;
242 if ( wxApp::s_captureWindow )
243 currentMouseWindow = wxApp::s_captureWindow;
245 switch ( GetEventClass( event ) )
247 case kEventClassKeyboard:
249 result = wxWebKitKeyEventHandler(handler, event, data);
253 case kEventClassTextInput:
255 result = wxMacUnicodeTextEventHandler(handler, event, data);
259 case kEventClassMouse:
261 switch ( GetEventKind( event ) )
263 case kEventMouseDragged :
264 case kEventMouseMoved :
265 case kEventMouseDown :
268 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
269 SetupMouseEvent( wxevent , cEvent ) ;
271 currentMouseWindow->ScreenToClient( &wxevent.m_x , &wxevent.m_y ) ;
272 wxevent.SetEventObject( currentMouseWindow ) ;
273 wxevent.SetId( currentMouseWindow->GetId() ) ;
275 if ( currentMouseWindow->GetEventHandler()->ProcessEvent(wxevent) )
280 break; // this should enable WebKit to fire mouse dragged and mouse up events...
290 result = CallNextEventHandler(handler, event);
294 DEFINE_ONE_SHOT_HANDLER_GETTER( wxWebViewWebKitEventHandler )
298 @interface MyFrameLoadMonitor : NSObject
300 wxWebViewWebKit* webKitWindow;
303 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
307 @interface MyPolicyDelegate : NSObject
309 wxWebViewWebKit* webKitWindow;
312 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
316 // ----------------------------------------------------------------------------
317 // creation/destruction
318 // ----------------------------------------------------------------------------
320 bool wxWebViewWebKit::Create(wxWindow *parent,
322 const wxString& strURL,
324 const wxSize& size, long style,
325 const wxString& name)
330 wxControl::Create(parent, winID, pos, size, style, wxDefaultValidator, name);
333 m_peer = new wxMacControl(this);
335 HIWebViewCreate( m_peer->GetControlRefAddr() );
337 m_webView = (WebView*) HIWebViewGetWebView( m_peer->GetControlRef() );
339 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_3
340 if ( UMAGetSystemVersion() >= 0x1030 )
341 HIViewChangeFeatures( m_peer->GetControlRef() , kHIViewIsOpaque , 0 ) ;
343 InstallControlEventHandler(m_peer->GetControlRef(),
344 GetwxWebViewWebKitEventHandlerUPP(),
345 GetEventTypeCount(eventList), eventList, this,
346 (EventHandlerRef *)&m_webKitCtrlEventHandler);
348 NSRect r = wxOSXGetFrameForControl( this, pos , size ) ;
349 m_webView = [[WebView alloc] initWithFrame:r
350 frameName:@"webkitFrame"
351 groupName:@"webkitGroup"];
352 SetPeer(new wxWidgetCocoaImpl( this, m_webView ));
355 MacPostControlCreate(pos, size);
358 HIViewSetVisible( m_peer->GetControlRef(), true );
360 [m_webView setHidden:false];
364 // Register event listener interfaces
365 MyFrameLoadMonitor* myFrameLoadMonitor =
366 [[MyFrameLoadMonitor alloc] initWithWxWindow: this];
368 [m_webView setFrameLoadDelegate:myFrameLoadMonitor];
370 // this is used to veto page loads, etc.
371 MyPolicyDelegate* myPolicyDelegate =
372 [[MyPolicyDelegate alloc] initWithWxWindow: this];
374 [m_webView setPolicyDelegate:myPolicyDelegate];
380 wxWebViewWebKit::~wxWebViewWebKit()
382 MyFrameLoadMonitor* myFrameLoadMonitor = [m_webView frameLoadDelegate];
383 MyPolicyDelegate* myPolicyDelegate = [m_webView policyDelegate];
384 [m_webView setFrameLoadDelegate: nil];
385 [m_webView setPolicyDelegate: nil];
387 if (myFrameLoadMonitor)
388 [myFrameLoadMonitor release];
390 if (myPolicyDelegate)
391 [myPolicyDelegate release];
394 // ----------------------------------------------------------------------------
396 // ----------------------------------------------------------------------------
398 bool wxWebViewWebKit::CanGoBack()
403 return [m_webView canGoBack];
406 bool wxWebViewWebKit::CanGoForward()
411 return [m_webView canGoForward];
414 void wxWebViewWebKit::GoBack()
419 [(WebView*)m_webView goBack];
422 void wxWebViewWebKit::GoForward()
427 [(WebView*)m_webView goForward];
430 void wxWebViewWebKit::Reload(wxWebViewReloadFlags flags)
435 if (flags & wxWEB_VIEW_RELOAD_NO_CACHE)
437 // TODO: test this indeed bypasses the cache
438 [[m_webView preferences] setUsesPageCache:NO];
439 [[m_webView mainFrame] reload];
440 [[m_webView preferences] setUsesPageCache:YES];
444 [[m_webView mainFrame] reload];
448 void wxWebViewWebKit::Stop()
453 [[m_webView mainFrame] stopLoading];
456 bool wxWebViewWebKit::CanGetPageSource()
461 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
462 return ( [[dataSource representation] canProvideDocumentSource] );
465 wxString wxWebViewWebKit::GetPageSource()
468 if (CanGetPageSource())
470 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
471 wxASSERT (dataSource != nil);
473 id<WebDocumentRepresentation> representation = [dataSource representation];
474 wxASSERT (representation != nil);
476 NSString* source = [representation documentSource];
479 return wxEmptyString;
482 return wxStringWithNSString( source );
485 return wxEmptyString;
488 bool wxWebViewWebKit::CanIncreaseTextSize()
493 if ([m_webView canMakeTextLarger])
499 void wxWebViewWebKit::IncreaseTextSize()
504 if (CanIncreaseTextSize())
505 [m_webView makeTextLarger:(WebView*)m_webView];
508 bool wxWebViewWebKit::CanDecreaseTextSize()
513 if ([m_webView canMakeTextSmaller])
519 void wxWebViewWebKit::DecreaseTextSize()
524 if (CanDecreaseTextSize())
525 [m_webView makeTextSmaller:(WebView*)m_webView];
528 void wxWebViewWebKit::Print()
531 // TODO: allow specifying the "show prompt" parameter in Print() ?
532 bool showPrompt = true;
537 id view = [[[m_webView mainFrame] frameView] documentView];
538 NSPrintOperation *op = [NSPrintOperation printOperationWithView:view
539 printInfo: [NSPrintInfo sharedPrintInfo]];
542 [op setShowsPrintPanel: showPrompt];
543 // in my tests, the progress bar always freezes and it stops the whole
544 // print operation. do not turn this to true unless there is a
545 // workaround for the bug.
546 [op setShowsProgressPanel: false];
552 void wxWebViewWebKit::SetEditable(bool enable)
557 [m_webView setEditable:enable ];
560 bool wxWebViewWebKit::IsEditable()
565 return [m_webView isEditable];
568 void wxWebViewWebKit::SetZoomType(wxWebViewZoomType zoomType)
570 // there is only one supported zoom type at the moment so this setter
571 // does nothing beyond checking sanity
572 wxASSERT(zoomType == wxWEB_VIEW_ZOOM_TYPE_TEXT);
575 wxWebViewZoomType wxWebViewWebKit::GetZoomType() const
577 // for now that's the only one that is supported
578 // FIXME: does the default zoom type change depending on webkit versions? :S
579 // Then this will be wrong
580 return wxWEB_VIEW_ZOOM_TYPE_TEXT;
583 bool wxWebViewWebKit::CanSetZoomType(wxWebViewZoomType type) const
587 // for now that's the only one that is supported
588 // TODO: I know recent versions of webkit support layout zoom too,
589 // check if we can support it
590 case wxWEB_VIEW_ZOOM_TYPE_TEXT:
598 int wxWebViewWebKit::GetScrollPos()
600 id result = [[m_webView windowScriptObject]
601 evaluateWebScript:@"document.body.scrollTop"];
602 return [result intValue];
605 void wxWebViewWebKit::SetScrollPos(int pos)
611 javascript.Printf(wxT("document.body.scrollTop = %d;"), pos);
612 [[m_webView windowScriptObject] evaluateWebScript:
613 (NSString*)wxNSStringWithWxString( javascript )];
616 wxString wxWebViewWebKit::GetSelectedText()
618 NSString* selection = [[m_webView selectedDOMRange] markupString];
619 if (!selection) return wxEmptyString;
621 return wxStringWithNSString(selection);
624 void wxWebViewWebKit::RunScript(const wxString& javascript)
629 [[m_webView windowScriptObject] evaluateWebScript:
630 (NSString*)wxNSStringWithWxString( javascript )];
633 void wxWebViewWebKit::OnSize(wxSizeEvent &event)
635 #if defined(__WXMAC_) && wxOSX_USE_CARBON
636 // This is a nasty hack because WebKit seems to lose its position when it is
637 // embedded in a control that is not itself the content view for a TLW.
638 // I put it in OnSize because these calcs are not perfect, and in fact are
639 // basically guesses based on reverse engineering, so it's best to give
640 // people the option of overriding OnSize with their own calcs if need be.
641 // I also left some test debugging print statements as a convenience if
642 // a(nother) problem crops up.
644 wxWindow* tlw = MacGetTopLevelWindow();
646 NSRect frame = [(WebView*)m_webView frame];
647 NSRect bounds = [(WebView*)m_webView bounds];
649 #if DEBUG_WEBKIT_SIZING
650 fprintf(stderr,"Carbon window x=%d, y=%d, width=%d, height=%d\n",
651 GetPosition().x, GetPosition().y, GetSize().x, GetSize().y);
652 fprintf(stderr, "Cocoa window frame x=%G, y=%G, width=%G, height=%G\n",
653 frame.origin.x, frame.origin.y,
654 frame.size.width, frame.size.height);
655 fprintf(stderr, "Cocoa window bounds x=%G, y=%G, width=%G, height=%G\n",
656 bounds.origin.x, bounds.origin.y,
657 bounds.size.width, bounds.size.height);
660 // This must be the case that Apple tested with, because well, in this one case
661 // we don't need to do anything! It just works. ;)
662 if (GetParent() == tlw) return;
664 // since we no longer use parent coordinates, we always want 0,0.
672 #if DEBUG_WEBKIT_SIZING
673 printf("Before conversion, origin is: x = %d, y = %d\n", x, y);
676 // NB: In most cases, when calling HIViewConvertRect, what people want is to
677 // use GetRootControl(), and this tripped me up at first. But in fact, what
678 // we want is the root view, because we need to make the y origin relative
679 // to the very top of the window, not its contents, since we later flip
680 // the y coordinate for Cocoa.
681 HIViewConvertRect (&rect, m_peer->GetControlRef(),
683 (WindowRef) MacGetTopLevelWindowRef()
686 x = (int)rect.origin.x;
687 y = (int)rect.origin.y;
689 #if DEBUG_WEBKIT_SIZING
690 printf("Moving Cocoa frame origin to: x = %d, y = %d\n", x, y);
694 //flip the y coordinate to convert to Cocoa coordinates
695 y = tlw->GetSize().y - ((GetSize().y) + y);
698 #if DEBUG_WEBKIT_SIZING
699 printf("y = %d after flipping value\n", y);
704 [(WebView*)m_webView setFrame:frame];
707 [(WebView*)m_webView display];
712 void wxWebViewWebKit::MacVisibilityChanged(){
713 #if defined(__WXMAC__) && wxOSX_USE_CARBON
714 bool isHidden = !IsControlVisible( m_peer->GetControlRef());
716 [(WebView*)m_webView display];
718 [m_webView setHidden:isHidden];
722 void wxWebViewWebKit::LoadUrl(const wxString& url)
724 [[m_webView mainFrame] loadRequest:[NSURLRequest requestWithURL:
725 [NSURL URLWithString:wxNSStringWithWxString(url)]]];
728 wxString wxWebViewWebKit::GetCurrentURL()
730 return wxStringWithNSString([m_webView mainFrameURL]);
733 wxString wxWebViewWebKit::GetCurrentTitle()
735 return wxStringWithNSString([m_webView mainFrameTitle]);
738 float wxWebViewWebKit::GetWebkitZoom()
740 return [m_webView textSizeMultiplier];
743 void wxWebViewWebKit::SetWebkitZoom(float zoom)
745 [m_webView setTextSizeMultiplier:zoom];
748 wxWebViewZoom wxWebViewWebKit::GetZoom()
750 float zoom = GetWebkitZoom();
752 // arbitrary way to map float zoom to our common zoom enum
755 return wxWEB_VIEW_ZOOM_TINY;
757 else if (zoom > 0.55 && zoom <= 0.85)
759 return wxWEB_VIEW_ZOOM_SMALL;
761 else if (zoom > 0.85 && zoom <= 1.15)
763 return wxWEB_VIEW_ZOOM_MEDIUM;
765 else if (zoom > 1.15 && zoom <= 1.45)
767 return wxWEB_VIEW_ZOOM_LARGE;
769 else if (zoom > 1.45)
771 return wxWEB_VIEW_ZOOM_LARGEST;
774 // to shut up compilers, this can never be reached logically
776 return wxWEB_VIEW_ZOOM_MEDIUM;
779 void wxWebViewWebKit::SetZoom(wxWebViewZoom zoom)
781 // arbitrary way to map our common zoom enum to float zoom
784 case wxWEB_VIEW_ZOOM_TINY:
788 case wxWEB_VIEW_ZOOM_SMALL:
792 case wxWEB_VIEW_ZOOM_MEDIUM:
796 case wxWEB_VIEW_ZOOM_LARGE:
800 case wxWEB_VIEW_ZOOM_LARGEST:
810 void wxWebViewWebKit::SetPage(const wxString& src, const wxString& baseUrl)
815 [[m_webView mainFrame] loadHTMLString:(NSString*)wxNSStringWithWxString(src)
816 baseURL:[NSURL URLWithString:
817 wxNSStringWithWxString( baseUrl )]];
820 void wxWebViewWebKit::Cut()
825 [(WebView*)m_webView cut:m_webView];
828 void wxWebViewWebKit::Copy()
833 [(WebView*)m_webView copy:m_webView];
836 void wxWebViewWebKit::Paste()
841 [(WebView*)m_webView paste:m_webView];
844 void wxWebViewWebKit::DeleteSelection()
849 [(WebView*)m_webView deleteSelection];
852 bool wxWebViewWebKit::HasSelection()
854 DOMRange* range = [m_webView selectedDOMRange];
865 void wxWebViewWebKit::ClearSelection()
867 //We use javascript as selection isn't exposed at the moment in webkit
868 RunScript("window.getSelection().removeAllRanges();");
871 void wxWebViewWebKit::SelectAll()
873 RunScript("window.getSelection().selectAllChildren(document.body);");
876 wxString wxWebViewWebKit::GetSelectedSource()
878 wxString script = ("var range = window.getSelection().getRangeAt(0);"
879 "var element = document.createElement('div');"
880 "element.appendChild(range.cloneContents());"
881 "return element.innerHTML;");
882 id result = [[m_webView windowScriptObject]
883 evaluateWebScript:wxNSStringWithWxString(script)];
884 return wxStringWithNSString([result stringValue]);
887 wxString wxWebViewWebKit::GetPageText()
889 id result = [[m_webView windowScriptObject]
890 evaluateWebScript:@"document.body.textContent"];
891 return wxStringWithNSString([result stringValue]);
894 void wxWebViewWebKit::EnableHistory(bool enable)
899 [m_webView setMaintainsBackForwardList:enable];
902 void wxWebViewWebKit::ClearHistory()
904 [m_webView setMaintainsBackForwardList:NO];
905 [m_webView setMaintainsBackForwardList:YES];
908 wxVector<wxSharedPtr<wxWebHistoryItem> > wxWebViewWebKit::GetBackwardHistory()
910 wxVector<wxSharedPtr<wxWebHistoryItem> > backhist;
911 WebBackForwardList* history = [m_webView backForwardList];
912 int count = [history backListCount];
913 for(int i = -count; i < 0; i++)
915 WebHistoryItem* item = [history itemAtIndex:i];
916 wxString url = wxStringWithNSString([item URLString]);
917 wxString title = wxStringWithNSString([item title]);
918 wxWebHistoryItem* wxitem = new wxWebHistoryItem(url, title);
919 wxitem->m_histItem = item;
920 wxSharedPtr<wxWebHistoryItem> itemptr(wxitem);
921 backhist.push_back(itemptr);
926 wxVector<wxSharedPtr<wxWebHistoryItem> > wxWebViewWebKit::GetForwardHistory()
928 wxVector<wxSharedPtr<wxWebHistoryItem> > forwardhist;
929 WebBackForwardList* history = [m_webView backForwardList];
930 int count = [history forwardListCount];
931 for(int i = 1; i <= count; i++)
933 WebHistoryItem* item = [history itemAtIndex:i];
934 wxString url = wxStringWithNSString([item URLString]);
935 wxString title = wxStringWithNSString([item title]);
936 wxWebHistoryItem* wxitem = new wxWebHistoryItem(url, title);
937 wxitem->m_histItem = item;
938 wxSharedPtr<wxWebHistoryItem> itemptr(wxitem);
939 forwardhist.push_back(itemptr);
944 void wxWebViewWebKit::LoadHistoryItem(wxSharedPtr<wxWebHistoryItem> item)
946 [m_webView goToBackForwardItem:item->m_histItem];
949 bool wxWebViewWebKit::CanUndo()
951 return [[m_webView undoManager] canUndo];
954 bool wxWebViewWebKit::CanRedo()
956 return [[m_webView undoManager] canRedo];
959 void wxWebViewWebKit::Undo()
961 [[m_webView undoManager] undo];
964 void wxWebViewWebKit::Redo()
966 [[m_webView undoManager] redo];
969 //------------------------------------------------------------
970 // Listener interfaces
971 //------------------------------------------------------------
973 // NB: I'm still tracking this down, but it appears the Cocoa window
974 // still has these events fired on it while the Carbon control is being
975 // destroyed. Therefore, we must be careful to check both the existence
976 // of the Carbon control and the event handler before firing events.
978 @implementation MyFrameLoadMonitor
980 - initWithWxWindow: (wxWebViewWebKit*)inWindow
983 webKitWindow = inWindow; // non retained
987 - (void)webView:(WebView *)sender
988 didStartProvisionalLoadForFrame:(WebFrame *)frame
990 webKitWindow->m_busy = true;
993 - (void)webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame
995 webKitWindow->m_busy = true;
997 if (webKitWindow && frame == [sender mainFrame]){
998 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
999 wxString target = wxStringWithNSString([frame name]);
1000 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATED,
1001 webKitWindow->GetId(),
1002 wxStringWithNSString( url ),
1005 if (webKitWindow && webKitWindow->GetEventHandler())
1006 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1010 - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
1012 webKitWindow->m_busy = false;
1014 if (webKitWindow && frame == [sender mainFrame]){
1015 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1017 wxString target = wxStringWithNSString([frame name]);
1018 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_LOADED,
1019 webKitWindow->GetId(),
1020 wxStringWithNSString( url ),
1023 if (webKitWindow && webKitWindow->GetEventHandler())
1024 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1028 wxString nsErrorToWxHtmlError(NSError* error, wxWebNavigationError* out)
1030 *out = wxWEB_NAV_ERR_OTHER;
1032 if ([[error domain] isEqualToString:NSURLErrorDomain])
1034 switch ([error code])
1036 case NSURLErrorCannotFindHost:
1037 case NSURLErrorFileDoesNotExist:
1038 case NSURLErrorRedirectToNonExistentLocation:
1039 *out = wxWEB_NAV_ERR_NOT_FOUND;
1042 case NSURLErrorResourceUnavailable:
1043 case NSURLErrorHTTPTooManyRedirects:
1044 case NSURLErrorDataLengthExceedsMaximum:
1045 case NSURLErrorBadURL:
1046 case NSURLErrorFileIsDirectory:
1047 *out = wxWEB_NAV_ERR_REQUEST;
1050 case NSURLErrorTimedOut:
1051 case NSURLErrorDNSLookupFailed:
1052 case NSURLErrorNetworkConnectionLost:
1053 case NSURLErrorCannotConnectToHost:
1054 case NSURLErrorNotConnectedToInternet:
1055 //case NSURLErrorInternationalRoamingOff:
1056 //case NSURLErrorCallIsActive:
1057 //case NSURLErrorDataNotAllowed:
1058 *out = wxWEB_NAV_ERR_CONNECTION;
1061 case NSURLErrorCancelled:
1062 case NSURLErrorUserCancelledAuthentication:
1063 *out = wxWEB_NAV_ERR_USER_CANCELLED;
1066 case NSURLErrorCannotDecodeRawData:
1067 case NSURLErrorCannotDecodeContentData:
1068 case NSURLErrorBadServerResponse:
1069 case NSURLErrorCannotParseResponse:
1070 *out = wxWEB_NAV_ERR_REQUEST;
1073 case NSURLErrorUserAuthenticationRequired:
1074 case NSURLErrorSecureConnectionFailed:
1075 case NSURLErrorClientCertificateRequired:
1076 *out = wxWEB_NAV_ERR_AUTH;
1079 case NSURLErrorNoPermissionsToReadFile:
1080 *out = wxWEB_NAV_ERR_SECURITY;
1083 case NSURLErrorServerCertificateHasBadDate:
1084 case NSURLErrorServerCertificateUntrusted:
1085 case NSURLErrorServerCertificateHasUnknownRoot:
1086 case NSURLErrorServerCertificateNotYetValid:
1087 case NSURLErrorClientCertificateRejected:
1088 *out = wxWEB_NAV_ERR_CERTIFICATE;
1093 wxString message = wxStringWithNSString([error localizedDescription]);
1094 NSString* detail = [error localizedFailureReason];
1097 message = message + " (" + wxStringWithNSString(detail) + ")";
1102 - (void)webView:(WebView *)sender didFailLoadWithError:(NSError*) error
1103 forFrame:(WebFrame *)frame
1105 webKitWindow->m_busy = false;
1107 if (webKitWindow && frame == [sender mainFrame]){
1108 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1110 wxWebNavigationError type;
1111 wxString description = nsErrorToWxHtmlError(error, &type);
1112 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1113 webKitWindow->GetId(),
1114 wxStringWithNSString( url ),
1115 wxEmptyString, false);
1116 thisEvent.SetString(description);
1117 thisEvent.SetInt(type);
1119 if (webKitWindow && webKitWindow->GetEventHandler())
1121 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1126 - (void)webView:(WebView *)sender
1127 didFailProvisionalLoadWithError:(NSError*)error
1128 forFrame:(WebFrame *)frame
1130 webKitWindow->m_busy = false;
1132 if (webKitWindow && frame == [sender mainFrame]){
1133 NSString *url = [[[[frame provisionalDataSource] request] URL]
1136 wxWebNavigationError type;
1137 wxString description = nsErrorToWxHtmlError(error, &type);
1138 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1139 webKitWindow->GetId(),
1140 wxStringWithNSString( url ),
1141 wxEmptyString, false);
1142 thisEvent.SetString(description);
1143 thisEvent.SetInt(type);
1145 if (webKitWindow && webKitWindow->GetEventHandler())
1146 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1150 - (void)webView:(WebView *)sender didReceiveTitle:(NSString *)title
1151 forFrame:(WebFrame *)frame
1153 wxString target = wxStringWithNSString([frame name]);
1154 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_TITLE_CHANGED,
1155 webKitWindow->GetId(),
1156 webKitWindow->GetCurrentURL(),
1159 thisEvent.SetString(wxStringWithNSString(title));
1161 if (webKitWindow && webKitWindow->GetEventHandler())
1162 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1166 @implementation MyPolicyDelegate
1168 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1171 webKitWindow = inWindow; // non retained
1175 - (void)webView:(WebView *)sender
1176 decidePolicyForNavigationAction:(NSDictionary *)actionInformation
1177 request:(NSURLRequest *)request
1178 frame:(WebFrame *)frame
1179 decisionListener:(id<WebPolicyDecisionListener>)listener
1183 webKitWindow->m_busy = true;
1184 NSString *url = [[request URL] absoluteString];
1185 wxString target = wxStringWithNSString([frame name]);
1186 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATING,
1187 webKitWindow->GetId(),
1188 wxStringWithNSString( url ), target, true);
1190 if (webKitWindow && webKitWindow->GetEventHandler())
1191 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1193 if (thisEvent.IsVetoed())
1195 webKitWindow->m_busy = false;
1204 - (void)webView:(WebView *)sender
1205 decidePolicyForNewWindowAction:(NSDictionary *)actionInformation
1206 request:(NSURLRequest *)request
1207 newFrameName:(NSString *)frameName
1208 decisionListener:(id < WebPolicyDecisionListener >)listener
1210 wxUnusedVar(actionInformation);
1212 NSString *url = [[request URL] absoluteString];
1213 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NEWWINDOW,
1214 webKitWindow->GetId(),
1215 wxStringWithNSString( url ), "", true);
1217 if (webKitWindow && webKitWindow->GetEventHandler())
1218 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1224 #endif //wxUSE_WEBVIEW_WEBKIT