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 && 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"
29 #include "wx/hashmap.h"
30 #include "wx/filesys.h"
32 #include <WebKit/WebKit.h>
33 #include <WebKit/HIWebView.h>
34 #include <WebKit/CarbonUtils.h>
36 #include <Foundation/NSURLError.h>
38 #define DEBUG_WEBKIT_SIZING 0
40 // ----------------------------------------------------------------------------
42 // ----------------------------------------------------------------------------
44 wxIMPLEMENT_DYNAMIC_CLASS(wxWebViewWebKit, wxWebView);
46 BEGIN_EVENT_TABLE(wxWebViewWebKit, wxControl)
47 #if defined(__WXMAC__) && wxOSX_USE_CARBON
48 EVT_SIZE(wxWebViewWebKit::OnSize)
52 #if defined(__WXOSX__) && wxOSX_USE_CARBON
54 // ----------------------------------------------------------------------------
55 // Carbon Events handlers
56 // ----------------------------------------------------------------------------
58 // prototype for function in src/osx/carbon/nonownedwnd.cpp
59 void SetupMouseEvent( wxMouseEvent &wxevent , wxMacCarbonEvent &cEvent );
61 static const EventTypeSpec eventList[] =
63 //{ kEventClassControl, kEventControlTrack } ,
64 { kEventClassMouse, kEventMouseUp },
65 { kEventClassMouse, kEventMouseDown },
66 { kEventClassMouse, kEventMouseMoved },
67 { kEventClassMouse, kEventMouseDragged },
69 { kEventClassKeyboard, kEventRawKeyDown } ,
70 { kEventClassKeyboard, kEventRawKeyRepeat } ,
71 { kEventClassKeyboard, kEventRawKeyUp } ,
72 { kEventClassKeyboard, kEventRawKeyModifiersChanged } ,
74 { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent } ,
75 { kEventClassTextInput, kEventTextInputUpdateActiveInputArea } ,
77 #if DEBUG_WEBKIT_SIZING == 1
78 { kEventClassControl, kEventControlBoundsChanged } ,
82 // mix this in from window.cpp
83 pascal OSStatus wxMacUnicodeTextEventHandler(EventHandlerCallRef handler,
84 EventRef event, void *data) ;
86 // NOTE: This is mostly taken from KeyboardEventHandler in toplevel.cpp, but
87 // that expects the data pointer is a top-level window, so I needed to change
88 // that in this case. However, once 2.8 is out, we should factor out the common
89 // logic among the two functions and merge them.
90 static pascal OSStatus wxWebKitKeyEventHandler(EventHandlerCallRef handler,
91 EventRef event, void *data)
93 OSStatus result = eventNotHandledErr ;
94 wxMacCarbonEvent cEvent( event ) ;
96 wxWebViewWebKit* thisWindow = (wxWebViewWebKit*) data ;
97 wxWindow* focus = thisWindow ;
99 unsigned char charCode ;
106 UInt32 when = EventTimeToTicks( GetEventTime( event ) ) ;
109 ByteCount dataSize = 0 ;
110 if ( GetEventParameter(event, kEventParamKeyUnicodes, typeUnicodeText,
111 NULL, 0 , &dataSize, NULL ) == noErr)
114 int numChars = dataSize / sizeof( UniChar) + 1;
116 UniChar* charBuf = buf ;
118 if ( numChars * 2 > 4 )
119 charBuf = new UniChar[ numChars ] ;
120 GetEventParameter(event, kEventParamKeyUnicodes, typeUnicodeText, NULL,
121 dataSize , NULL , charBuf) ;
122 charBuf[ numChars - 1 ] = 0;
124 #if SIZEOF_WCHAR_T == 2
125 uniChar = charBuf[0] ;
127 wxMBConvUTF16 converter ;
128 converter.MB2WC( uniChar , (const char*)charBuf , 2 ) ;
131 if ( numChars * 2 > 4 )
136 GetEventParameter(event, kEventParamKeyMacCharCodes, typeChar, NULL,
137 sizeof(char), NULL, &charCode );
138 GetEventParameter(event, kEventParamKeyCode, typeUInt32, NULL,
139 sizeof(UInt32), NULL, &keyCode );
140 GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, NULL,
141 sizeof(UInt32), NULL, &modifiers );
143 UInt32 message = (keyCode << 8) + charCode;
144 switch ( GetEventKind( event ) )
146 case kEventRawKeyRepeat :
147 case kEventRawKeyDown :
149 WXEVENTREF formerEvent = wxTheApp->MacGetCurrentEvent() ;
150 WXEVENTHANDLERCALLREF formerHandler =
151 wxTheApp->MacGetCurrentEventHandlerCallRef() ;
153 wxTheApp->MacSetCurrentEvent( event , handler ) ;
154 if ( /* focus && */ wxTheApp->MacSendKeyDownEvent(
155 focus, message, modifiers, when, uniChar[0]))
159 wxTheApp->MacSetCurrentEvent( formerEvent , formerHandler ) ;
163 case kEventRawKeyUp :
164 if ( /* focus && */ wxTheApp->MacSendKeyUpEvent(
165 focus , message , modifiers , when , uniChar[0] ) )
171 case kEventRawKeyModifiersChanged :
173 wxKeyEvent event(wxEVT_KEY_DOWN);
175 event.m_shiftDown = modifiers & shiftKey;
176 event.m_controlDown = modifiers & controlKey;
177 event.m_altDown = modifiers & optionKey;
178 event.m_metaDown = modifiers & cmdKey;
181 event.m_uniChar = uniChar[0] ;
184 event.SetTimestamp(when);
185 event.SetEventObject(focus);
187 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & controlKey )
189 event.m_keyCode = WXK_CONTROL ;
190 event.SetEventType( ( modifiers & controlKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
191 focus->GetEventHandler()->ProcessEvent( event ) ;
193 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & shiftKey )
195 event.m_keyCode = WXK_SHIFT ;
196 event.SetEventType( ( modifiers & shiftKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
197 focus->GetEventHandler()->ProcessEvent( event ) ;
199 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & optionKey )
201 event.m_keyCode = WXK_ALT ;
202 event.SetEventType( ( modifiers & optionKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
203 focus->GetEventHandler()->ProcessEvent( event ) ;
205 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & cmdKey )
207 event.m_keyCode = WXK_COMMAND ;
208 event.SetEventType( ( modifiers & cmdKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
209 focus->GetEventHandler()->ProcessEvent( event ) ;
212 wxApp::s_lastModifiers = modifiers ;
223 static pascal OSStatus wxWebViewWebKitEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
225 OSStatus result = eventNotHandledErr ;
227 wxMacCarbonEvent cEvent( event ) ;
229 ControlRef controlRef ;
230 wxWebViewWebKit* thisWindow = (wxWebViewWebKit*) data ;
231 wxNonOwnedWindow* tlw = NULL;
233 tlw = thisWindow->MacGetTopLevelWindow();
235 cEvent.GetParameter( kEventParamDirectObject , &controlRef ) ;
237 wxWindow* currentMouseWindow = thisWindow ;
239 if ( wxApp::s_captureWindow )
240 currentMouseWindow = wxApp::s_captureWindow;
242 switch ( GetEventClass( event ) )
244 case kEventClassKeyboard:
246 result = wxWebKitKeyEventHandler(handler, event, data);
250 case kEventClassTextInput:
252 result = wxMacUnicodeTextEventHandler(handler, event, data);
256 case kEventClassMouse:
258 switch ( GetEventKind( event ) )
260 case kEventMouseDragged :
261 case kEventMouseMoved :
262 case kEventMouseDown :
265 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
266 SetupMouseEvent( wxevent , cEvent ) ;
268 currentMouseWindow->ScreenToClient( &wxevent.m_x , &wxevent.m_y ) ;
269 wxevent.SetEventObject( currentMouseWindow ) ;
270 wxevent.SetId( currentMouseWindow->GetId() ) ;
272 if ( currentMouseWindow->GetEventHandler()->ProcessEvent(wxevent) )
277 break; // this should enable WebKit to fire mouse dragged and mouse up events...
287 result = CallNextEventHandler(handler, event);
291 DEFINE_ONE_SHOT_HANDLER_GETTER( wxWebViewWebKitEventHandler )
295 @interface WebViewLoadDelegate : NSObject
297 wxWebViewWebKit* webKitWindow;
300 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
304 @interface WebViewPolicyDelegate : NSObject
306 wxWebViewWebKit* webKitWindow;
309 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
313 //We use a hash to map scheme names to wxWebViewHandler
314 WX_DECLARE_STRING_HASH_MAP(wxSharedPtr<wxWebViewHandler>, wxStringToWebHandlerMap);
316 static wxStringToWebHandlerMap g_stringHandlerMap;
318 @interface WebViewCustomProtocol : NSURLProtocol
323 // ----------------------------------------------------------------------------
324 // creation/destruction
325 // ----------------------------------------------------------------------------
327 bool wxWebViewWebKit::Create(wxWindow *parent,
329 const wxString& strURL,
331 const wxSize& size, long style,
332 const wxString& name)
337 wxControl::Create(parent, winID, pos, size, style, wxDefaultValidator, name);
340 wxMacControl* peer = new wxMacControl(this);
342 HIWebViewCreate( peer->GetControlRefAddr() );
344 m_webView = (WebView*) HIWebViewGetWebView( peer->GetControlRef() );
346 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_3
347 if ( UMAGetSystemVersion() >= 0x1030 )
348 HIViewChangeFeatures( peer->GetControlRef() , kHIViewIsOpaque , 0 ) ;
350 InstallControlEventHandler(peer->GetControlRef(),
351 GetwxWebViewWebKitEventHandlerUPP(),
352 GetEventTypeCount(eventList), eventList, this,
353 (EventHandlerRef *)&m_webKitCtrlEventHandler);
356 NSRect r = wxOSXGetFrameForControl( this, pos , size ) ;
357 m_webView = [[WebView alloc] initWithFrame:r
358 frameName:@"webkitFrame"
359 groupName:@"webkitGroup"];
360 SetPeer(new wxWidgetCocoaImpl( this, m_webView ));
363 MacPostControlCreate(pos, size);
366 HIViewSetVisible( GetPeer()->GetControlRef(), true );
368 [m_webView setHidden:false];
372 // Register event listener interfaces
373 WebViewLoadDelegate* loadDelegate =
374 [[WebViewLoadDelegate alloc] initWithWxWindow: this];
376 [m_webView setFrameLoadDelegate:loadDelegate];
378 // this is used to veto page loads, etc.
379 WebViewPolicyDelegate* policyDelegate =
380 [[WebViewPolicyDelegate alloc] initWithWxWindow: this];
382 [m_webView setPolicyDelegate:policyDelegate];
384 //Register our own class for custom scheme handling
385 [NSURLProtocol registerClass:[WebViewCustomProtocol class]];
391 wxWebViewWebKit::~wxWebViewWebKit()
393 WebViewLoadDelegate* loadDelegate = [m_webView frameLoadDelegate];
394 WebViewPolicyDelegate* policyDelegate = [m_webView policyDelegate];
395 [m_webView setFrameLoadDelegate: nil];
396 [m_webView setPolicyDelegate: nil];
399 [loadDelegate release];
402 [policyDelegate release];
405 // ----------------------------------------------------------------------------
407 // ----------------------------------------------------------------------------
409 bool wxWebViewWebKit::CanGoBack() const
414 return [m_webView canGoBack];
417 bool wxWebViewWebKit::CanGoForward() const
422 return [m_webView canGoForward];
425 void wxWebViewWebKit::GoBack()
430 [(WebView*)m_webView goBack];
433 void wxWebViewWebKit::GoForward()
438 [(WebView*)m_webView goForward];
441 void wxWebViewWebKit::Reload(wxWebViewReloadFlags flags)
446 if (flags & wxWEB_VIEW_RELOAD_NO_CACHE)
448 // TODO: test this indeed bypasses the cache
449 [[m_webView preferences] setUsesPageCache:NO];
450 [[m_webView mainFrame] reload];
451 [[m_webView preferences] setUsesPageCache:YES];
455 [[m_webView mainFrame] reload];
459 void wxWebViewWebKit::Stop()
464 [[m_webView mainFrame] stopLoading];
467 bool wxWebViewWebKit::CanGetPageSource() const
472 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
473 return ( [[dataSource representation] canProvideDocumentSource] );
476 wxString wxWebViewWebKit::GetPageSource() const
479 if (CanGetPageSource())
481 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
482 wxASSERT (dataSource != nil);
484 id<WebDocumentRepresentation> representation = [dataSource representation];
485 wxASSERT (representation != nil);
487 NSString* source = [representation documentSource];
490 return wxEmptyString;
493 return wxStringWithNSString( source );
496 return wxEmptyString;
499 bool wxWebViewWebKit::CanIncreaseTextSize() const
504 if ([m_webView canMakeTextLarger])
510 void wxWebViewWebKit::IncreaseTextSize()
515 if (CanIncreaseTextSize())
516 [m_webView makeTextLarger:(WebView*)m_webView];
519 bool wxWebViewWebKit::CanDecreaseTextSize() const
524 if ([m_webView canMakeTextSmaller])
530 void wxWebViewWebKit::DecreaseTextSize()
535 if (CanDecreaseTextSize())
536 [m_webView makeTextSmaller:(WebView*)m_webView];
539 void wxWebViewWebKit::Print()
542 // TODO: allow specifying the "show prompt" parameter in Print() ?
543 bool showPrompt = true;
548 id view = [[[m_webView mainFrame] frameView] documentView];
549 NSPrintOperation *op = [NSPrintOperation printOperationWithView:view
550 printInfo: [NSPrintInfo sharedPrintInfo]];
553 [op setShowsPrintPanel: showPrompt];
554 // in my tests, the progress bar always freezes and it stops the whole
555 // print operation. do not turn this to true unless there is a
556 // workaround for the bug.
557 [op setShowsProgressPanel: false];
563 void wxWebViewWebKit::SetEditable(bool enable)
568 [m_webView setEditable:enable ];
571 bool wxWebViewWebKit::IsEditable() const
576 return [m_webView isEditable];
579 void wxWebViewWebKit::SetZoomType(wxWebViewZoomType zoomType)
581 // there is only one supported zoom type at the moment so this setter
582 // does nothing beyond checking sanity
583 wxASSERT(zoomType == wxWEB_VIEW_ZOOM_TYPE_TEXT);
586 wxWebViewZoomType wxWebViewWebKit::GetZoomType() const
588 // for now that's the only one that is supported
589 // FIXME: does the default zoom type change depending on webkit versions? :S
590 // Then this will be wrong
591 return wxWEB_VIEW_ZOOM_TYPE_TEXT;
594 bool wxWebViewWebKit::CanSetZoomType(wxWebViewZoomType type) const
598 // for now that's the only one that is supported
599 // TODO: I know recent versions of webkit support layout zoom too,
600 // check if we can support it
601 case wxWEB_VIEW_ZOOM_TYPE_TEXT:
609 int wxWebViewWebKit::GetScrollPos()
611 id result = [[m_webView windowScriptObject]
612 evaluateWebScript:@"document.body.scrollTop"];
613 return [result intValue];
616 void wxWebViewWebKit::SetScrollPos(int pos)
622 javascript.Printf(wxT("document.body.scrollTop = %d;"), pos);
623 [[m_webView windowScriptObject] evaluateWebScript:
624 (NSString*)wxNSStringWithWxString( javascript )];
627 wxString wxWebViewWebKit::GetSelectedText() const
629 NSString* selection = [[m_webView selectedDOMRange] markupString];
630 if (!selection) return wxEmptyString;
632 return wxStringWithNSString(selection);
635 void wxWebViewWebKit::RunScript(const wxString& javascript)
640 [[m_webView windowScriptObject] evaluateWebScript:
641 (NSString*)wxNSStringWithWxString( javascript )];
644 void wxWebViewWebKit::OnSize(wxSizeEvent &event)
646 #if defined(__WXMAC__) && wxOSX_USE_CARBON
647 // This is a nasty hack because WebKit seems to lose its position when it is
648 // embedded in a control that is not itself the content view for a TLW.
649 // I put it in OnSize because these calcs are not perfect, and in fact are
650 // basically guesses based on reverse engineering, so it's best to give
651 // people the option of overriding OnSize with their own calcs if need be.
652 // I also left some test debugging print statements as a convenience if
653 // a(nother) problem crops up.
655 wxWindow* tlw = MacGetTopLevelWindow();
657 NSRect frame = [(WebView*)m_webView frame];
658 NSRect bounds = [(WebView*)m_webView bounds];
660 #if DEBUG_WEBKIT_SIZING
661 fprintf(stderr,"Carbon window x=%d, y=%d, width=%d, height=%d\n",
662 GetPosition().x, GetPosition().y, GetSize().x, GetSize().y);
663 fprintf(stderr, "Cocoa window frame x=%G, y=%G, width=%G, height=%G\n",
664 frame.origin.x, frame.origin.y,
665 frame.size.width, frame.size.height);
666 fprintf(stderr, "Cocoa window bounds x=%G, y=%G, width=%G, height=%G\n",
667 bounds.origin.x, bounds.origin.y,
668 bounds.size.width, bounds.size.height);
671 // This must be the case that Apple tested with, because well, in this one case
672 // we don't need to do anything! It just works. ;)
673 if (GetParent() == tlw) return;
675 // since we no longer use parent coordinates, we always want 0,0.
683 #if DEBUG_WEBKIT_SIZING
684 printf("Before conversion, origin is: x = %d, y = %d\n", x, y);
687 // NB: In most cases, when calling HIViewConvertRect, what people want is to
688 // use GetRootControl(), and this tripped me up at first. But in fact, what
689 // we want is the root view, because we need to make the y origin relative
690 // to the very top of the window, not its contents, since we later flip
691 // the y coordinate for Cocoa.
692 HIViewConvertRect (&rect, GetPeer()->GetControlRef(),
694 (WindowRef) MacGetTopLevelWindowRef()
697 x = (int)rect.origin.x;
698 y = (int)rect.origin.y;
700 #if DEBUG_WEBKIT_SIZING
701 printf("Moving Cocoa frame origin to: x = %d, y = %d\n", x, y);
705 //flip the y coordinate to convert to Cocoa coordinates
706 y = tlw->GetSize().y - ((GetSize().y) + y);
709 #if DEBUG_WEBKIT_SIZING
710 printf("y = %d after flipping value\n", y);
715 [(WebView*)m_webView setFrame:frame];
718 [(WebView*)m_webView display];
723 void wxWebViewWebKit::MacVisibilityChanged(){
724 #if defined(__WXMAC__) && wxOSX_USE_CARBON
725 bool isHidden = !IsControlVisible( GetPeer()->GetControlRef());
727 [(WebView*)m_webView display];
729 [m_webView setHidden:isHidden];
733 void wxWebViewWebKit::LoadURL(const wxString& url)
735 [[m_webView mainFrame] loadRequest:[NSURLRequest requestWithURL:
736 [NSURL URLWithString:wxNSStringWithWxString(url)]]];
739 wxString wxWebViewWebKit::GetCurrentURL() const
741 return wxStringWithNSString([m_webView mainFrameURL]);
744 wxString wxWebViewWebKit::GetCurrentTitle() const
746 return wxStringWithNSString([m_webView mainFrameTitle]);
749 float wxWebViewWebKit::GetWebkitZoom() const
751 return [m_webView textSizeMultiplier];
754 void wxWebViewWebKit::SetWebkitZoom(float zoom)
756 [m_webView setTextSizeMultiplier:zoom];
759 wxWebViewZoom wxWebViewWebKit::GetZoom() const
761 float zoom = GetWebkitZoom();
763 // arbitrary way to map float zoom to our common zoom enum
766 return wxWEB_VIEW_ZOOM_TINY;
768 else if (zoom > 0.55 && zoom <= 0.85)
770 return wxWEB_VIEW_ZOOM_SMALL;
772 else if (zoom > 0.85 && zoom <= 1.15)
774 return wxWEB_VIEW_ZOOM_MEDIUM;
776 else if (zoom > 1.15 && zoom <= 1.45)
778 return wxWEB_VIEW_ZOOM_LARGE;
780 else if (zoom > 1.45)
782 return wxWEB_VIEW_ZOOM_LARGEST;
785 // to shut up compilers, this can never be reached logically
787 return wxWEB_VIEW_ZOOM_MEDIUM;
790 void wxWebViewWebKit::SetZoom(wxWebViewZoom zoom)
792 // arbitrary way to map our common zoom enum to float zoom
795 case wxWEB_VIEW_ZOOM_TINY:
799 case wxWEB_VIEW_ZOOM_SMALL:
803 case wxWEB_VIEW_ZOOM_MEDIUM:
807 case wxWEB_VIEW_ZOOM_LARGE:
811 case wxWEB_VIEW_ZOOM_LARGEST:
821 void wxWebViewWebKit::DoSetPage(const wxString& src, const wxString& baseUrl)
826 [[m_webView mainFrame] loadHTMLString:(NSString*)wxNSStringWithWxString(src)
827 baseURL:[NSURL URLWithString:
828 wxNSStringWithWxString( baseUrl )]];
831 void wxWebViewWebKit::Cut()
836 [(WebView*)m_webView cut:m_webView];
839 void wxWebViewWebKit::Copy()
844 [(WebView*)m_webView copy:m_webView];
847 void wxWebViewWebKit::Paste()
852 [(WebView*)m_webView paste:m_webView];
855 void wxWebViewWebKit::DeleteSelection()
860 [(WebView*)m_webView deleteSelection];
863 bool wxWebViewWebKit::HasSelection() const
865 DOMRange* range = [m_webView selectedDOMRange];
876 void wxWebViewWebKit::ClearSelection()
878 //We use javascript as selection isn't exposed at the moment in webkit
879 RunScript("window.getSelection().removeAllRanges();");
882 void wxWebViewWebKit::SelectAll()
884 RunScript("window.getSelection().selectAllChildren(document.body);");
887 wxString wxWebViewWebKit::GetSelectedSource() const
889 wxString script = ("var range = window.getSelection().getRangeAt(0);"
890 "var element = document.createElement('div');"
891 "element.appendChild(range.cloneContents());"
892 "return element.innerHTML;");
893 id result = [[m_webView windowScriptObject]
894 evaluateWebScript:wxNSStringWithWxString(script)];
895 return wxStringWithNSString([result stringValue]);
898 wxString wxWebViewWebKit::GetPageText() const
900 id result = [[m_webView windowScriptObject]
901 evaluateWebScript:@"document.body.textContent"];
902 return wxStringWithNSString([result stringValue]);
905 void wxWebViewWebKit::EnableHistory(bool enable)
910 [m_webView setMaintainsBackForwardList:enable];
913 void wxWebViewWebKit::ClearHistory()
915 [m_webView setMaintainsBackForwardList:NO];
916 [m_webView setMaintainsBackForwardList:YES];
919 wxVector<wxSharedPtr<wxWebViewHistoryItem> > wxWebViewWebKit::GetBackwardHistory()
921 wxVector<wxSharedPtr<wxWebViewHistoryItem> > backhist;
922 WebBackForwardList* history = [m_webView backForwardList];
923 int count = [history backListCount];
924 for(int i = -count; i < 0; i++)
926 WebHistoryItem* item = [history itemAtIndex:i];
927 wxString url = wxStringWithNSString([item URLString]);
928 wxString title = wxStringWithNSString([item title]);
929 wxWebViewHistoryItem* wxitem = new wxWebViewHistoryItem(url, title);
930 wxitem->m_histItem = item;
931 wxSharedPtr<wxWebViewHistoryItem> itemptr(wxitem);
932 backhist.push_back(itemptr);
937 wxVector<wxSharedPtr<wxWebViewHistoryItem> > wxWebViewWebKit::GetForwardHistory()
939 wxVector<wxSharedPtr<wxWebViewHistoryItem> > forwardhist;
940 WebBackForwardList* history = [m_webView backForwardList];
941 int count = [history forwardListCount];
942 for(int i = 1; i <= count; i++)
944 WebHistoryItem* item = [history itemAtIndex:i];
945 wxString url = wxStringWithNSString([item URLString]);
946 wxString title = wxStringWithNSString([item title]);
947 wxWebViewHistoryItem* wxitem = new wxWebViewHistoryItem(url, title);
948 wxitem->m_histItem = item;
949 wxSharedPtr<wxWebViewHistoryItem> itemptr(wxitem);
950 forwardhist.push_back(itemptr);
955 void wxWebViewWebKit::LoadHistoryItem(wxSharedPtr<wxWebViewHistoryItem> item)
957 [m_webView goToBackForwardItem:item->m_histItem];
960 bool wxWebViewWebKit::CanUndo() const
962 return [[m_webView undoManager] canUndo];
965 bool wxWebViewWebKit::CanRedo() const
967 return [[m_webView undoManager] canRedo];
970 void wxWebViewWebKit::Undo()
972 [[m_webView undoManager] undo];
975 void wxWebViewWebKit::Redo()
977 [[m_webView undoManager] redo];
980 void wxWebViewWebKit::RegisterHandler(wxSharedPtr<wxWebViewHandler> handler)
982 g_stringHandlerMap[handler->GetName()] = handler;
985 //------------------------------------------------------------
986 // Listener interfaces
987 //------------------------------------------------------------
989 // NB: I'm still tracking this down, but it appears the Cocoa window
990 // still has these events fired on it while the Carbon control is being
991 // destroyed. Therefore, we must be careful to check both the existence
992 // of the Carbon control and the event handler before firing events.
994 @implementation WebViewLoadDelegate
996 - initWithWxWindow: (wxWebViewWebKit*)inWindow
999 webKitWindow = inWindow; // non retained
1003 - (void)webView:(WebView *)sender
1004 didStartProvisionalLoadForFrame:(WebFrame *)frame
1006 webKitWindow->m_busy = true;
1009 - (void)webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame
1011 webKitWindow->m_busy = true;
1013 if (webKitWindow && frame == [sender mainFrame]){
1014 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1015 wxString target = wxStringWithNSString([frame name]);
1016 wxWebViewEvent event(wxEVT_COMMAND_WEB_VIEW_NAVIGATED,
1017 webKitWindow->GetId(),
1018 wxStringWithNSString( url ),
1021 if (webKitWindow && webKitWindow->GetEventHandler())
1022 webKitWindow->GetEventHandler()->ProcessEvent(event);
1026 - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
1028 webKitWindow->m_busy = false;
1030 if (webKitWindow && frame == [sender mainFrame]){
1031 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1033 wxString target = wxStringWithNSString([frame name]);
1034 wxWebViewEvent event(wxEVT_COMMAND_WEB_VIEW_LOADED,
1035 webKitWindow->GetId(),
1036 wxStringWithNSString( url ),
1039 if (webKitWindow && webKitWindow->GetEventHandler())
1040 webKitWindow->GetEventHandler()->ProcessEvent(event);
1044 wxString nsErrorToWxHtmlError(NSError* error, wxWebViewNavigationError* out)
1046 *out = wxWEB_NAV_ERR_OTHER;
1048 if ([[error domain] isEqualToString:NSURLErrorDomain])
1050 switch ([error code])
1052 case NSURLErrorCannotFindHost:
1053 case NSURLErrorFileDoesNotExist:
1054 case NSURLErrorRedirectToNonExistentLocation:
1055 *out = wxWEB_NAV_ERR_NOT_FOUND;
1058 case NSURLErrorResourceUnavailable:
1059 case NSURLErrorHTTPTooManyRedirects:
1060 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
1061 case NSURLErrorDataLengthExceedsMaximum:
1063 case NSURLErrorBadURL:
1064 case NSURLErrorFileIsDirectory:
1065 *out = wxWEB_NAV_ERR_REQUEST;
1068 case NSURLErrorTimedOut:
1069 case NSURLErrorDNSLookupFailed:
1070 case NSURLErrorNetworkConnectionLost:
1071 case NSURLErrorCannotConnectToHost:
1072 case NSURLErrorNotConnectedToInternet:
1073 //case NSURLErrorInternationalRoamingOff:
1074 //case NSURLErrorCallIsActive:
1075 //case NSURLErrorDataNotAllowed:
1076 *out = wxWEB_NAV_ERR_CONNECTION;
1079 case NSURLErrorCancelled:
1080 case NSURLErrorUserCancelledAuthentication:
1081 *out = wxWEB_NAV_ERR_USER_CANCELLED;
1084 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
1085 case NSURLErrorCannotDecodeRawData:
1086 case NSURLErrorCannotDecodeContentData:
1087 case NSURLErrorCannotParseResponse:
1089 case NSURLErrorBadServerResponse:
1090 *out = wxWEB_NAV_ERR_REQUEST;
1093 case NSURLErrorUserAuthenticationRequired:
1094 case NSURLErrorSecureConnectionFailed:
1095 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
1096 case NSURLErrorClientCertificateRequired:
1098 *out = wxWEB_NAV_ERR_AUTH;
1101 case NSURLErrorNoPermissionsToReadFile:
1102 *out = wxWEB_NAV_ERR_SECURITY;
1105 case NSURLErrorServerCertificateHasBadDate:
1106 case NSURLErrorServerCertificateUntrusted:
1107 case NSURLErrorServerCertificateHasUnknownRoot:
1108 case NSURLErrorServerCertificateNotYetValid:
1109 case NSURLErrorClientCertificateRejected:
1110 *out = wxWEB_NAV_ERR_CERTIFICATE;
1115 wxString message = wxStringWithNSString([error localizedDescription]);
1116 NSString* detail = [error localizedFailureReason];
1119 message = message + " (" + wxStringWithNSString(detail) + ")";
1124 - (void)webView:(WebView *)sender didFailLoadWithError:(NSError*) error
1125 forFrame:(WebFrame *)frame
1127 webKitWindow->m_busy = false;
1129 if (webKitWindow && frame == [sender mainFrame]){
1130 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1132 wxWebViewNavigationError type;
1133 wxString description = nsErrorToWxHtmlError(error, &type);
1134 wxWebViewEvent event(wxEVT_COMMAND_WEB_VIEW_ERROR,
1135 webKitWindow->GetId(),
1136 wxStringWithNSString( url ),
1138 event.SetString(description);
1141 if (webKitWindow && webKitWindow->GetEventHandler())
1143 webKitWindow->GetEventHandler()->ProcessEvent(event);
1148 - (void)webView:(WebView *)sender
1149 didFailProvisionalLoadWithError:(NSError*)error
1150 forFrame:(WebFrame *)frame
1152 webKitWindow->m_busy = false;
1154 if (webKitWindow && frame == [sender mainFrame]){
1155 NSString *url = [[[[frame provisionalDataSource] request] URL]
1158 wxWebViewNavigationError type;
1159 wxString description = nsErrorToWxHtmlError(error, &type);
1160 wxWebViewEvent event(wxEVT_COMMAND_WEB_VIEW_ERROR,
1161 webKitWindow->GetId(),
1162 wxStringWithNSString( url ),
1164 event.SetString(description);
1167 if (webKitWindow && webKitWindow->GetEventHandler())
1168 webKitWindow->GetEventHandler()->ProcessEvent(event);
1172 - (void)webView:(WebView *)sender didReceiveTitle:(NSString *)title
1173 forFrame:(WebFrame *)frame
1175 wxString target = wxStringWithNSString([frame name]);
1176 wxWebViewEvent event(wxEVT_COMMAND_WEB_VIEW_TITLE_CHANGED,
1177 webKitWindow->GetId(),
1178 webKitWindow->GetCurrentURL(),
1181 event.SetString(wxStringWithNSString(title));
1183 if (webKitWindow && webKitWindow->GetEventHandler())
1184 webKitWindow->GetEventHandler()->ProcessEvent(event);
1188 @implementation WebViewPolicyDelegate
1190 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1193 webKitWindow = inWindow; // non retained
1197 - (void)webView:(WebView *)sender
1198 decidePolicyForNavigationAction:(NSDictionary *)actionInformation
1199 request:(NSURLRequest *)request
1200 frame:(WebFrame *)frame
1201 decisionListener:(id<WebPolicyDecisionListener>)listener
1205 webKitWindow->m_busy = true;
1206 NSString *url = [[request URL] absoluteString];
1207 wxString target = wxStringWithNSString([frame name]);
1208 wxWebViewEvent event(wxEVT_COMMAND_WEB_VIEW_NAVIGATING,
1209 webKitWindow->GetId(),
1210 wxStringWithNSString( url ), target);
1212 if (webKitWindow && webKitWindow->GetEventHandler())
1213 webKitWindow->GetEventHandler()->ProcessEvent(event);
1215 if (!event.IsAllowed())
1217 webKitWindow->m_busy = false;
1226 - (void)webView:(WebView *)sender
1227 decidePolicyForNewWindowAction:(NSDictionary *)actionInformation
1228 request:(NSURLRequest *)request
1229 newFrameName:(NSString *)frameName
1230 decisionListener:(id < WebPolicyDecisionListener >)listener
1232 wxUnusedVar(actionInformation);
1234 NSString *url = [[request URL] absoluteString];
1235 wxWebViewEvent event(wxEVT_COMMAND_WEB_VIEW_NEWWINDOW,
1236 webKitWindow->GetId(),
1237 wxStringWithNSString( url ), "");
1239 if (webKitWindow && webKitWindow->GetEventHandler())
1240 webKitWindow->GetEventHandler()->ProcessEvent(event);
1246 @implementation WebViewCustomProtocol
1248 + (BOOL)canInitWithRequest:(NSURLRequest *)request
1250 NSString *scheme = [[request URL] scheme];
1252 wxStringToWebHandlerMap::const_iterator it;
1253 for( it = g_stringHandlerMap.begin(); it != g_stringHandlerMap.end(); ++it )
1255 if(it->first.IsSameAs(wxStringWithNSString(scheme)))
1264 + (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
1266 //We don't do any processing here as the wxWebViewHandler classes do it
1270 - (void)startLoading
1272 NSURLRequest *request = [self request];
1273 NSString* path = [[request URL] absoluteString];
1275 wxString wxpath = wxStringWithNSString(path);
1276 wxString scheme = wxStringWithNSString([[request URL] scheme]);
1277 wxFSFile* file = g_stringHandlerMap[scheme]->GetFile(wxpath);
1278 size_t length = file->GetStream()->GetLength();
1281 NSURLResponse *response = [[NSURLResponse alloc] initWithURL:[request URL]
1282 MIMEType:wxNSStringWithWxString(file->GetMimeType())
1283 expectedContentLength:length
1284 textEncodingName:nil];
1286 //Load the data, we malloc it so it is tidied up properly
1287 void* buffer = malloc(length);
1288 file->GetStream()->Read(buffer, length);
1289 NSData *data = [[NSData alloc] initWithBytesNoCopy:buffer length:length];
1291 id<NSURLProtocolClient> client = [self client];
1293 //We do not support caching anything yet
1294 [client URLProtocol:self didReceiveResponse:response
1295 cacheStoragePolicy:NSURLCacheStorageNotAllowed];
1298 [client URLProtocol:self didLoadData:data];
1300 //Notify that we have finished
1301 [client URLProtocolDidFinishLoading:self];
1313 #endif //wxUSE_WEBVIEW && wxUSE_WEBVIEW_WEBKIT