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 ;
107 UInt32 when = EventTimeToTicks( GetEventTime( event ) ) ;
110 ByteCount dataSize = 0 ;
111 if ( GetEventParameter(event, kEventParamKeyUnicodes, typeUnicodeText,
112 NULL, 0 , &dataSize, NULL ) == noErr)
115 int numChars = dataSize / sizeof( UniChar) + 1;
117 UniChar* charBuf = buf ;
119 if ( numChars * 2 > 4 )
120 charBuf = new UniChar[ numChars ] ;
121 GetEventParameter(event, kEventParamKeyUnicodes, typeUnicodeText, NULL,
122 dataSize , NULL , charBuf) ;
123 charBuf[ numChars - 1 ] = 0;
125 #if SIZEOF_WCHAR_T == 2
126 uniChar = charBuf[0] ;
128 wxMBConvUTF16 converter ;
129 converter.MB2WC( uniChar , (const char*)charBuf , 2 ) ;
132 if ( numChars * 2 > 4 )
137 GetEventParameter(event, kEventParamKeyMacCharCodes, typeChar, NULL,
138 sizeof(char), NULL, &charCode );
139 GetEventParameter(event, kEventParamKeyCode, typeUInt32, NULL,
140 sizeof(UInt32), NULL, &keyCode );
141 GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, NULL,
142 sizeof(UInt32), NULL, &modifiers );
143 GetEventParameter(event, kEventParamMouseLocation, typeQDPoint, NULL,
144 sizeof(Point), NULL, &point );
146 UInt32 message = (keyCode << 8) + charCode;
147 switch ( GetEventKind( event ) )
149 case kEventRawKeyRepeat :
150 case kEventRawKeyDown :
152 WXEVENTREF formerEvent = wxTheApp->MacGetCurrentEvent() ;
153 WXEVENTHANDLERCALLREF formerHandler =
154 wxTheApp->MacGetCurrentEventHandlerCallRef() ;
156 wxTheApp->MacSetCurrentEvent( event , handler ) ;
157 if ( /* focus && */ wxTheApp->MacSendKeyDownEvent(
158 focus, message, modifiers, when, point.h, point.v, uniChar[0]))
162 wxTheApp->MacSetCurrentEvent( formerEvent , formerHandler ) ;
166 case kEventRawKeyUp :
167 if ( /* focus && */ wxTheApp->MacSendKeyUpEvent(
168 focus , message , modifiers , when , point.h , point.v , uniChar[0] ) )
174 case kEventRawKeyModifiersChanged :
176 wxKeyEvent event(wxEVT_KEY_DOWN);
178 event.m_shiftDown = modifiers & shiftKey;
179 event.m_controlDown = modifiers & controlKey;
180 event.m_altDown = modifiers & optionKey;
181 event.m_metaDown = modifiers & cmdKey;
186 event.m_uniChar = uniChar[0] ;
189 event.SetTimestamp(when);
190 event.SetEventObject(focus);
192 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & controlKey )
194 event.m_keyCode = WXK_CONTROL ;
195 event.SetEventType( ( modifiers & controlKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
196 focus->GetEventHandler()->ProcessEvent( event ) ;
198 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & shiftKey )
200 event.m_keyCode = WXK_SHIFT ;
201 event.SetEventType( ( modifiers & shiftKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
202 focus->GetEventHandler()->ProcessEvent( event ) ;
204 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & optionKey )
206 event.m_keyCode = WXK_ALT ;
207 event.SetEventType( ( modifiers & optionKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
208 focus->GetEventHandler()->ProcessEvent( event ) ;
210 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & cmdKey )
212 event.m_keyCode = WXK_COMMAND ;
213 event.SetEventType( ( modifiers & cmdKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
214 focus->GetEventHandler()->ProcessEvent( event ) ;
217 wxApp::s_lastModifiers = modifiers ;
228 static pascal OSStatus wxWebViewWebKitEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
230 OSStatus result = eventNotHandledErr ;
232 wxMacCarbonEvent cEvent( event ) ;
234 ControlRef controlRef ;
235 wxWebViewWebKit* thisWindow = (wxWebViewWebKit*) data ;
236 wxNonOwnedWindow* tlw = NULL;
238 tlw = thisWindow->MacGetTopLevelWindow();
240 cEvent.GetParameter( kEventParamDirectObject , &controlRef ) ;
242 wxWindow* currentMouseWindow = thisWindow ;
244 if ( wxApp::s_captureWindow )
245 currentMouseWindow = wxApp::s_captureWindow;
247 switch ( GetEventClass( event ) )
249 case kEventClassKeyboard:
251 result = wxWebKitKeyEventHandler(handler, event, data);
255 case kEventClassTextInput:
257 result = wxMacUnicodeTextEventHandler(handler, event, data);
261 case kEventClassMouse:
263 switch ( GetEventKind( event ) )
265 case kEventMouseDragged :
266 case kEventMouseMoved :
267 case kEventMouseDown :
270 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
271 SetupMouseEvent( wxevent , cEvent ) ;
273 currentMouseWindow->ScreenToClient( &wxevent.m_x , &wxevent.m_y ) ;
274 wxevent.SetEventObject( currentMouseWindow ) ;
275 wxevent.SetId( currentMouseWindow->GetId() ) ;
277 if ( currentMouseWindow->GetEventHandler()->ProcessEvent(wxevent) )
282 break; // this should enable WebKit to fire mouse dragged and mouse up events...
292 result = CallNextEventHandler(handler, event);
296 DEFINE_ONE_SHOT_HANDLER_GETTER( wxWebViewWebKitEventHandler )
300 @interface WebViewLoadDelegate : NSObject
302 wxWebViewWebKit* webKitWindow;
305 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
309 @interface WebViewPolicyDelegate : NSObject
311 wxWebViewWebKit* webKitWindow;
314 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
318 //We use a hash to map scheme names to wxWebViewHandler
319 WX_DECLARE_STRING_HASH_MAP(wxSharedPtr<wxWebViewHandler>, wxStringToWebHandlerMap);
321 static wxStringToWebHandlerMap g_stringHandlerMap;
323 @interface WebViewCustomProtocol : NSURLProtocol
328 // ----------------------------------------------------------------------------
329 // creation/destruction
330 // ----------------------------------------------------------------------------
332 bool wxWebViewWebKit::Create(wxWindow *parent,
334 const wxString& strURL,
336 const wxSize& size, long style,
337 const wxString& name)
342 wxControl::Create(parent, winID, pos, size, style, wxDefaultValidator, name);
345 wxMacControl* peer = new wxMacControl(this);
347 HIWebViewCreate( peer->GetControlRefAddr() );
349 m_webView = (WebView*) HIWebViewGetWebView( peer->GetControlRef() );
351 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_3
352 if ( UMAGetSystemVersion() >= 0x1030 )
353 HIViewChangeFeatures( peer->GetControlRef() , kHIViewIsOpaque , 0 ) ;
355 InstallControlEventHandler(peer->GetControlRef(),
356 GetwxWebViewWebKitEventHandlerUPP(),
357 GetEventTypeCount(eventList), eventList, this,
358 (EventHandlerRef *)&m_webKitCtrlEventHandler);
361 NSRect r = wxOSXGetFrameForControl( this, pos , size ) ;
362 m_webView = [[WebView alloc] initWithFrame:r
363 frameName:@"webkitFrame"
364 groupName:@"webkitGroup"];
365 SetPeer(new wxWidgetCocoaImpl( this, m_webView ));
368 MacPostControlCreate(pos, size);
371 HIViewSetVisible( GetPeer()->GetControlRef(), true );
373 [m_webView setHidden:false];
377 // Register event listener interfaces
378 WebViewLoadDelegate* loadDelegate =
379 [[WebViewLoadDelegate alloc] initWithWxWindow: this];
381 [m_webView setFrameLoadDelegate:loadDelegate];
383 // this is used to veto page loads, etc.
384 WebViewPolicyDelegate* policyDelegate =
385 [[WebViewPolicyDelegate alloc] initWithWxWindow: this];
387 [m_webView setPolicyDelegate:policyDelegate];
389 //Register our own class for custom scheme handling
390 [NSURLProtocol registerClass:[WebViewCustomProtocol class]];
396 wxWebViewWebKit::~wxWebViewWebKit()
398 WebViewLoadDelegate* loadDelegate = [m_webView frameLoadDelegate];
399 WebViewPolicyDelegate* policyDelegate = [m_webView policyDelegate];
400 [m_webView setFrameLoadDelegate: nil];
401 [m_webView setPolicyDelegate: nil];
404 [loadDelegate release];
407 [policyDelegate release];
410 // ----------------------------------------------------------------------------
412 // ----------------------------------------------------------------------------
414 bool wxWebViewWebKit::CanGoBack() const
419 return [m_webView canGoBack];
422 bool wxWebViewWebKit::CanGoForward() const
427 return [m_webView canGoForward];
430 void wxWebViewWebKit::GoBack()
435 [(WebView*)m_webView goBack];
438 void wxWebViewWebKit::GoForward()
443 [(WebView*)m_webView goForward];
446 void wxWebViewWebKit::Reload(wxWebViewReloadFlags flags)
451 if (flags & wxWEB_VIEW_RELOAD_NO_CACHE)
453 // TODO: test this indeed bypasses the cache
454 [[m_webView preferences] setUsesPageCache:NO];
455 [[m_webView mainFrame] reload];
456 [[m_webView preferences] setUsesPageCache:YES];
460 [[m_webView mainFrame] reload];
464 void wxWebViewWebKit::Stop()
469 [[m_webView mainFrame] stopLoading];
472 bool wxWebViewWebKit::CanGetPageSource() const
477 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
478 return ( [[dataSource representation] canProvideDocumentSource] );
481 wxString wxWebViewWebKit::GetPageSource() const
484 if (CanGetPageSource())
486 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
487 wxASSERT (dataSource != nil);
489 id<WebDocumentRepresentation> representation = [dataSource representation];
490 wxASSERT (representation != nil);
492 NSString* source = [representation documentSource];
495 return wxEmptyString;
498 return wxStringWithNSString( source );
501 return wxEmptyString;
504 bool wxWebViewWebKit::CanIncreaseTextSize() const
509 if ([m_webView canMakeTextLarger])
515 void wxWebViewWebKit::IncreaseTextSize()
520 if (CanIncreaseTextSize())
521 [m_webView makeTextLarger:(WebView*)m_webView];
524 bool wxWebViewWebKit::CanDecreaseTextSize() const
529 if ([m_webView canMakeTextSmaller])
535 void wxWebViewWebKit::DecreaseTextSize()
540 if (CanDecreaseTextSize())
541 [m_webView makeTextSmaller:(WebView*)m_webView];
544 void wxWebViewWebKit::Print()
547 // TODO: allow specifying the "show prompt" parameter in Print() ?
548 bool showPrompt = true;
553 id view = [[[m_webView mainFrame] frameView] documentView];
554 NSPrintOperation *op = [NSPrintOperation printOperationWithView:view
555 printInfo: [NSPrintInfo sharedPrintInfo]];
558 [op setShowsPrintPanel: showPrompt];
559 // in my tests, the progress bar always freezes and it stops the whole
560 // print operation. do not turn this to true unless there is a
561 // workaround for the bug.
562 [op setShowsProgressPanel: false];
568 void wxWebViewWebKit::SetEditable(bool enable)
573 [m_webView setEditable:enable ];
576 bool wxWebViewWebKit::IsEditable() const
581 return [m_webView isEditable];
584 void wxWebViewWebKit::SetZoomType(wxWebViewZoomType zoomType)
586 // there is only one supported zoom type at the moment so this setter
587 // does nothing beyond checking sanity
588 wxASSERT(zoomType == wxWEB_VIEW_ZOOM_TYPE_TEXT);
591 wxWebViewZoomType wxWebViewWebKit::GetZoomType() const
593 // for now that's the only one that is supported
594 // FIXME: does the default zoom type change depending on webkit versions? :S
595 // Then this will be wrong
596 return wxWEB_VIEW_ZOOM_TYPE_TEXT;
599 bool wxWebViewWebKit::CanSetZoomType(wxWebViewZoomType type) const
603 // for now that's the only one that is supported
604 // TODO: I know recent versions of webkit support layout zoom too,
605 // check if we can support it
606 case wxWEB_VIEW_ZOOM_TYPE_TEXT:
614 int wxWebViewWebKit::GetScrollPos()
616 id result = [[m_webView windowScriptObject]
617 evaluateWebScript:@"document.body.scrollTop"];
618 return [result intValue];
621 void wxWebViewWebKit::SetScrollPos(int pos)
627 javascript.Printf(wxT("document.body.scrollTop = %d;"), pos);
628 [[m_webView windowScriptObject] evaluateWebScript:
629 (NSString*)wxNSStringWithWxString( javascript )];
632 wxString wxWebViewWebKit::GetSelectedText() const
634 NSString* selection = [[m_webView selectedDOMRange] markupString];
635 if (!selection) return wxEmptyString;
637 return wxStringWithNSString(selection);
640 void wxWebViewWebKit::RunScript(const wxString& javascript)
645 [[m_webView windowScriptObject] evaluateWebScript:
646 (NSString*)wxNSStringWithWxString( javascript )];
649 void wxWebViewWebKit::OnSize(wxSizeEvent &event)
651 #if defined(__WXMAC_) && wxOSX_USE_CARBON
652 // This is a nasty hack because WebKit seems to lose its position when it is
653 // embedded in a control that is not itself the content view for a TLW.
654 // I put it in OnSize because these calcs are not perfect, and in fact are
655 // basically guesses based on reverse engineering, so it's best to give
656 // people the option of overriding OnSize with their own calcs if need be.
657 // I also left some test debugging print statements as a convenience if
658 // a(nother) problem crops up.
660 wxWindow* tlw = MacGetTopLevelWindow();
662 NSRect frame = [(WebView*)m_webView frame];
663 NSRect bounds = [(WebView*)m_webView bounds];
665 #if DEBUG_WEBKIT_SIZING
666 fprintf(stderr,"Carbon window x=%d, y=%d, width=%d, height=%d\n",
667 GetPosition().x, GetPosition().y, GetSize().x, GetSize().y);
668 fprintf(stderr, "Cocoa window frame x=%G, y=%G, width=%G, height=%G\n",
669 frame.origin.x, frame.origin.y,
670 frame.size.width, frame.size.height);
671 fprintf(stderr, "Cocoa window bounds x=%G, y=%G, width=%G, height=%G\n",
672 bounds.origin.x, bounds.origin.y,
673 bounds.size.width, bounds.size.height);
676 // This must be the case that Apple tested with, because well, in this one case
677 // we don't need to do anything! It just works. ;)
678 if (GetParent() == tlw) return;
680 // since we no longer use parent coordinates, we always want 0,0.
688 #if DEBUG_WEBKIT_SIZING
689 printf("Before conversion, origin is: x = %d, y = %d\n", x, y);
692 // NB: In most cases, when calling HIViewConvertRect, what people want is to
693 // use GetRootControl(), and this tripped me up at first. But in fact, what
694 // we want is the root view, because we need to make the y origin relative
695 // to the very top of the window, not its contents, since we later flip
696 // the y coordinate for Cocoa.
697 HIViewConvertRect (&rect, m_peer->GetControlRef(),
699 (WindowRef) MacGetTopLevelWindowRef()
702 x = (int)rect.origin.x;
703 y = (int)rect.origin.y;
705 #if DEBUG_WEBKIT_SIZING
706 printf("Moving Cocoa frame origin to: x = %d, y = %d\n", x, y);
710 //flip the y coordinate to convert to Cocoa coordinates
711 y = tlw->GetSize().y - ((GetSize().y) + y);
714 #if DEBUG_WEBKIT_SIZING
715 printf("y = %d after flipping value\n", y);
720 [(WebView*)m_webView setFrame:frame];
723 [(WebView*)m_webView display];
728 void wxWebViewWebKit::MacVisibilityChanged(){
729 #if defined(__WXMAC__) && wxOSX_USE_CARBON
730 bool isHidden = !IsControlVisible( GetPeer()->GetControlRef());
732 [(WebView*)m_webView display];
734 [m_webView setHidden:isHidden];
738 void wxWebViewWebKit::LoadURL(const wxString& url)
740 [[m_webView mainFrame] loadRequest:[NSURLRequest requestWithURL:
741 [NSURL URLWithString:wxNSStringWithWxString(url)]]];
744 wxString wxWebViewWebKit::GetCurrentURL() const
746 return wxStringWithNSString([m_webView mainFrameURL]);
749 wxString wxWebViewWebKit::GetCurrentTitle() const
751 return wxStringWithNSString([m_webView mainFrameTitle]);
754 float wxWebViewWebKit::GetWebkitZoom() const
756 return [m_webView textSizeMultiplier];
759 void wxWebViewWebKit::SetWebkitZoom(float zoom)
761 [m_webView setTextSizeMultiplier:zoom];
764 wxWebViewZoom wxWebViewWebKit::GetZoom() const
766 float zoom = GetWebkitZoom();
768 // arbitrary way to map float zoom to our common zoom enum
771 return wxWEB_VIEW_ZOOM_TINY;
773 else if (zoom > 0.55 && zoom <= 0.85)
775 return wxWEB_VIEW_ZOOM_SMALL;
777 else if (zoom > 0.85 && zoom <= 1.15)
779 return wxWEB_VIEW_ZOOM_MEDIUM;
781 else if (zoom > 1.15 && zoom <= 1.45)
783 return wxWEB_VIEW_ZOOM_LARGE;
785 else if (zoom > 1.45)
787 return wxWEB_VIEW_ZOOM_LARGEST;
790 // to shut up compilers, this can never be reached logically
792 return wxWEB_VIEW_ZOOM_MEDIUM;
795 void wxWebViewWebKit::SetZoom(wxWebViewZoom zoom)
797 // arbitrary way to map our common zoom enum to float zoom
800 case wxWEB_VIEW_ZOOM_TINY:
804 case wxWEB_VIEW_ZOOM_SMALL:
808 case wxWEB_VIEW_ZOOM_MEDIUM:
812 case wxWEB_VIEW_ZOOM_LARGE:
816 case wxWEB_VIEW_ZOOM_LARGEST:
826 void wxWebViewWebKit::SetPage(const wxString& src, const wxString& baseUrl)
831 [[m_webView mainFrame] loadHTMLString:(NSString*)wxNSStringWithWxString(src)
832 baseURL:[NSURL URLWithString:
833 wxNSStringWithWxString( baseUrl )]];
836 void wxWebViewWebKit::Cut()
841 [(WebView*)m_webView cut:m_webView];
844 void wxWebViewWebKit::Copy()
849 [(WebView*)m_webView copy:m_webView];
852 void wxWebViewWebKit::Paste()
857 [(WebView*)m_webView paste:m_webView];
860 void wxWebViewWebKit::DeleteSelection()
865 [(WebView*)m_webView deleteSelection];
868 bool wxWebViewWebKit::HasSelection() const
870 DOMRange* range = [m_webView selectedDOMRange];
881 void wxWebViewWebKit::ClearSelection()
883 //We use javascript as selection isn't exposed at the moment in webkit
884 RunScript("window.getSelection().removeAllRanges();");
887 void wxWebViewWebKit::SelectAll()
889 RunScript("window.getSelection().selectAllChildren(document.body);");
892 wxString wxWebViewWebKit::GetSelectedSource() const
894 wxString script = ("var range = window.getSelection().getRangeAt(0);"
895 "var element = document.createElement('div');"
896 "element.appendChild(range.cloneContents());"
897 "return element.innerHTML;");
898 id result = [[m_webView windowScriptObject]
899 evaluateWebScript:wxNSStringWithWxString(script)];
900 return wxStringWithNSString([result stringValue]);
903 wxString wxWebViewWebKit::GetPageText() const
905 id result = [[m_webView windowScriptObject]
906 evaluateWebScript:@"document.body.textContent"];
907 return wxStringWithNSString([result stringValue]);
910 void wxWebViewWebKit::EnableHistory(bool enable)
915 [m_webView setMaintainsBackForwardList:enable];
918 void wxWebViewWebKit::ClearHistory()
920 [m_webView setMaintainsBackForwardList:NO];
921 [m_webView setMaintainsBackForwardList:YES];
924 wxVector<wxSharedPtr<wxWebViewHistoryItem> > wxWebViewWebKit::GetBackwardHistory()
926 wxVector<wxSharedPtr<wxWebViewHistoryItem> > backhist;
927 WebBackForwardList* history = [m_webView backForwardList];
928 int count = [history backListCount];
929 for(int i = -count; i < 0; i++)
931 WebHistoryItem* item = [history itemAtIndex:i];
932 wxString url = wxStringWithNSString([item URLString]);
933 wxString title = wxStringWithNSString([item title]);
934 wxWebViewHistoryItem* wxitem = new wxWebViewHistoryItem(url, title);
935 wxitem->m_histItem = item;
936 wxSharedPtr<wxWebViewHistoryItem> itemptr(wxitem);
937 backhist.push_back(itemptr);
942 wxVector<wxSharedPtr<wxWebViewHistoryItem> > wxWebViewWebKit::GetForwardHistory()
944 wxVector<wxSharedPtr<wxWebViewHistoryItem> > forwardhist;
945 WebBackForwardList* history = [m_webView backForwardList];
946 int count = [history forwardListCount];
947 for(int i = 1; i <= count; i++)
949 WebHistoryItem* item = [history itemAtIndex:i];
950 wxString url = wxStringWithNSString([item URLString]);
951 wxString title = wxStringWithNSString([item title]);
952 wxWebViewHistoryItem* wxitem = new wxWebViewHistoryItem(url, title);
953 wxitem->m_histItem = item;
954 wxSharedPtr<wxWebViewHistoryItem> itemptr(wxitem);
955 forwardhist.push_back(itemptr);
960 void wxWebViewWebKit::LoadHistoryItem(wxSharedPtr<wxWebViewHistoryItem> item)
962 [m_webView goToBackForwardItem:item->m_histItem];
965 bool wxWebViewWebKit::CanUndo() const
967 return [[m_webView undoManager] canUndo];
970 bool wxWebViewWebKit::CanRedo() const
972 return [[m_webView undoManager] canRedo];
975 void wxWebViewWebKit::Undo()
977 [[m_webView undoManager] undo];
980 void wxWebViewWebKit::Redo()
982 [[m_webView undoManager] redo];
985 void wxWebViewWebKit::RegisterHandler(wxSharedPtr<wxWebViewHandler> handler)
987 g_stringHandlerMap[handler->GetName()] = handler;
990 //------------------------------------------------------------
991 // Listener interfaces
992 //------------------------------------------------------------
994 // NB: I'm still tracking this down, but it appears the Cocoa window
995 // still has these events fired on it while the Carbon control is being
996 // destroyed. Therefore, we must be careful to check both the existence
997 // of the Carbon control and the event handler before firing events.
999 @implementation WebViewLoadDelegate
1001 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1004 webKitWindow = inWindow; // non retained
1008 - (void)webView:(WebView *)sender
1009 didStartProvisionalLoadForFrame:(WebFrame *)frame
1011 webKitWindow->m_busy = true;
1014 - (void)webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame
1016 webKitWindow->m_busy = true;
1018 if (webKitWindow && frame == [sender mainFrame]){
1019 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1020 wxString target = wxStringWithNSString([frame name]);
1021 wxWebViewEvent event(wxEVT_COMMAND_WEB_VIEW_NAVIGATED,
1022 webKitWindow->GetId(),
1023 wxStringWithNSString( url ),
1026 if (webKitWindow && webKitWindow->GetEventHandler())
1027 webKitWindow->GetEventHandler()->ProcessEvent(event);
1031 - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
1033 webKitWindow->m_busy = false;
1035 if (webKitWindow && frame == [sender mainFrame]){
1036 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1038 wxString target = wxStringWithNSString([frame name]);
1039 wxWebViewEvent event(wxEVT_COMMAND_WEB_VIEW_LOADED,
1040 webKitWindow->GetId(),
1041 wxStringWithNSString( url ),
1044 if (webKitWindow && webKitWindow->GetEventHandler())
1045 webKitWindow->GetEventHandler()->ProcessEvent(event);
1049 wxString nsErrorToWxHtmlError(NSError* error, wxWebViewNavigationError* out)
1051 *out = wxWEB_NAV_ERR_OTHER;
1053 if ([[error domain] isEqualToString:NSURLErrorDomain])
1055 switch ([error code])
1057 case NSURLErrorCannotFindHost:
1058 case NSURLErrorFileDoesNotExist:
1059 case NSURLErrorRedirectToNonExistentLocation:
1060 *out = wxWEB_NAV_ERR_NOT_FOUND;
1063 case NSURLErrorResourceUnavailable:
1064 case NSURLErrorHTTPTooManyRedirects:
1065 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
1066 case NSURLErrorDataLengthExceedsMaximum:
1068 case NSURLErrorBadURL:
1069 case NSURLErrorFileIsDirectory:
1070 *out = wxWEB_NAV_ERR_REQUEST;
1073 case NSURLErrorTimedOut:
1074 case NSURLErrorDNSLookupFailed:
1075 case NSURLErrorNetworkConnectionLost:
1076 case NSURLErrorCannotConnectToHost:
1077 case NSURLErrorNotConnectedToInternet:
1078 //case NSURLErrorInternationalRoamingOff:
1079 //case NSURLErrorCallIsActive:
1080 //case NSURLErrorDataNotAllowed:
1081 *out = wxWEB_NAV_ERR_CONNECTION;
1084 case NSURLErrorCancelled:
1085 case NSURLErrorUserCancelledAuthentication:
1086 *out = wxWEB_NAV_ERR_USER_CANCELLED;
1089 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
1090 case NSURLErrorCannotDecodeRawData:
1091 case NSURLErrorCannotDecodeContentData:
1092 case NSURLErrorCannotParseResponse:
1094 case NSURLErrorBadServerResponse:
1095 *out = wxWEB_NAV_ERR_REQUEST;
1098 case NSURLErrorUserAuthenticationRequired:
1099 case NSURLErrorSecureConnectionFailed:
1100 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
1101 case NSURLErrorClientCertificateRequired:
1103 *out = wxWEB_NAV_ERR_AUTH;
1106 case NSURLErrorNoPermissionsToReadFile:
1107 *out = wxWEB_NAV_ERR_SECURITY;
1110 case NSURLErrorServerCertificateHasBadDate:
1111 case NSURLErrorServerCertificateUntrusted:
1112 case NSURLErrorServerCertificateHasUnknownRoot:
1113 case NSURLErrorServerCertificateNotYetValid:
1114 case NSURLErrorClientCertificateRejected:
1115 *out = wxWEB_NAV_ERR_CERTIFICATE;
1120 wxString message = wxStringWithNSString([error localizedDescription]);
1121 NSString* detail = [error localizedFailureReason];
1124 message = message + " (" + wxStringWithNSString(detail) + ")";
1129 - (void)webView:(WebView *)sender didFailLoadWithError:(NSError*) error
1130 forFrame:(WebFrame *)frame
1132 webKitWindow->m_busy = false;
1134 if (webKitWindow && frame == [sender mainFrame]){
1135 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1137 wxWebViewNavigationError type;
1138 wxString description = nsErrorToWxHtmlError(error, &type);
1139 wxWebViewEvent event(wxEVT_COMMAND_WEB_VIEW_ERROR,
1140 webKitWindow->GetId(),
1141 wxStringWithNSString( url ),
1143 event.SetString(description);
1146 if (webKitWindow && webKitWindow->GetEventHandler())
1148 webKitWindow->GetEventHandler()->ProcessEvent(event);
1153 - (void)webView:(WebView *)sender
1154 didFailProvisionalLoadWithError:(NSError*)error
1155 forFrame:(WebFrame *)frame
1157 webKitWindow->m_busy = false;
1159 if (webKitWindow && frame == [sender mainFrame]){
1160 NSString *url = [[[[frame provisionalDataSource] request] URL]
1163 wxWebViewNavigationError type;
1164 wxString description = nsErrorToWxHtmlError(error, &type);
1165 wxWebViewEvent event(wxEVT_COMMAND_WEB_VIEW_ERROR,
1166 webKitWindow->GetId(),
1167 wxStringWithNSString( url ),
1169 event.SetString(description);
1172 if (webKitWindow && webKitWindow->GetEventHandler())
1173 webKitWindow->GetEventHandler()->ProcessEvent(event);
1177 - (void)webView:(WebView *)sender didReceiveTitle:(NSString *)title
1178 forFrame:(WebFrame *)frame
1180 wxString target = wxStringWithNSString([frame name]);
1181 wxWebViewEvent event(wxEVT_COMMAND_WEB_VIEW_TITLE_CHANGED,
1182 webKitWindow->GetId(),
1183 webKitWindow->GetCurrentURL(),
1186 event.SetString(wxStringWithNSString(title));
1188 if (webKitWindow && webKitWindow->GetEventHandler())
1189 webKitWindow->GetEventHandler()->ProcessEvent(event);
1193 @implementation WebViewPolicyDelegate
1195 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1198 webKitWindow = inWindow; // non retained
1202 - (void)webView:(WebView *)sender
1203 decidePolicyForNavigationAction:(NSDictionary *)actionInformation
1204 request:(NSURLRequest *)request
1205 frame:(WebFrame *)frame
1206 decisionListener:(id<WebPolicyDecisionListener>)listener
1210 webKitWindow->m_busy = true;
1211 NSString *url = [[request URL] absoluteString];
1212 wxString target = wxStringWithNSString([frame name]);
1213 wxWebViewEvent event(wxEVT_COMMAND_WEB_VIEW_NAVIGATING,
1214 webKitWindow->GetId(),
1215 wxStringWithNSString( url ), target);
1217 if (webKitWindow && webKitWindow->GetEventHandler())
1218 webKitWindow->GetEventHandler()->ProcessEvent(event);
1220 if (!event.IsAllowed())
1222 webKitWindow->m_busy = false;
1231 - (void)webView:(WebView *)sender
1232 decidePolicyForNewWindowAction:(NSDictionary *)actionInformation
1233 request:(NSURLRequest *)request
1234 newFrameName:(NSString *)frameName
1235 decisionListener:(id < WebPolicyDecisionListener >)listener
1237 wxUnusedVar(actionInformation);
1239 NSString *url = [[request URL] absoluteString];
1240 wxWebViewEvent event(wxEVT_COMMAND_WEB_VIEW_NEWWINDOW,
1241 webKitWindow->GetId(),
1242 wxStringWithNSString( url ), "");
1244 if (webKitWindow && webKitWindow->GetEventHandler())
1245 webKitWindow->GetEventHandler()->ProcessEvent(event);
1251 @implementation WebViewCustomProtocol
1253 + (BOOL)canInitWithRequest:(NSURLRequest *)request
1255 NSString *scheme = [[request URL] scheme];
1257 wxStringToWebHandlerMap::const_iterator it;
1258 for( it = g_stringHandlerMap.begin(); it != g_stringHandlerMap.end(); ++it )
1260 if(it->first.IsSameAs(wxStringWithNSString(scheme)))
1269 + (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
1271 //We don't do any processing here as the wxWebViewHandler classes do it
1275 - (void)startLoading
1277 NSURLRequest *request = [self request];
1278 NSString* path = [[request URL] absoluteString];
1280 wxString wxpath = wxStringWithNSString(path);
1281 wxString scheme = wxStringWithNSString([[request URL] scheme]);
1282 wxFSFile* file = g_stringHandlerMap[scheme]->GetFile(wxpath);
1283 size_t length = file->GetStream()->GetLength();
1286 NSURLResponse *response = [[NSURLResponse alloc] initWithURL:[request URL]
1287 MIMEType:wxNSStringWithWxString(file->GetMimeType())
1288 expectedContentLength:length
1289 textEncodingName:nil];
1291 //Load the data, we malloc it so it is tidied up properly
1292 void* buffer = malloc(length);
1293 file->GetStream()->Read(buffer, length);
1294 NSData *data = [[NSData alloc] initWithBytesNoCopy:buffer length:length];
1296 id<NSURLProtocolClient> client = [self client];
1298 //We do not support caching anything yet
1299 [client URLProtocol:self didReceiveResponse:response
1300 cacheStoragePolicy:NSURLCacheStorageNotAllowed];
1303 [client URLProtocol:self didLoadData:data];
1305 //Notify that we have finished
1306 [client URLProtocolDidFinishLoading:self];
1318 #endif //wxUSE_WEBVIEW && wxUSE_WEBVIEW_WEBKIT