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
8 // Copyright: (c) Jethro Grassie / Kevin Ollivier / Marianne Gagnon
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // http://developer.apple.com/mac/library/documentation/Cocoa/Reference/WebKit/Classes/WebView_Class/Reference/Reference.html
14 #include "wx/osx/webview_webkit.h"
16 #if wxUSE_WEBVIEW && wxUSE_WEBVIEW_WEBKIT && (defined(__WXOSX_COCOA__) \
17 || defined(__WXOSX_CARBON__))
19 // For compilers that support precompilation, includes "wx.h".
20 #include "wx/wxprec.h"
26 #include "wx/osx/private.h"
27 #include "wx/cocoa/string.h"
28 #include "wx/hashmap.h"
29 #include "wx/filesys.h"
31 #include <WebKit/WebKit.h>
32 #include <WebKit/HIWebView.h>
33 #include <WebKit/CarbonUtils.h>
35 #include <Foundation/NSURLError.h>
37 #define DEBUG_WEBKIT_SIZING 0
39 // ----------------------------------------------------------------------------
41 // ----------------------------------------------------------------------------
43 wxIMPLEMENT_DYNAMIC_CLASS(wxWebViewWebKit, wxWebView);
45 BEGIN_EVENT_TABLE(wxWebViewWebKit, wxControl)
46 #if defined(__WXMAC__) && wxOSX_USE_CARBON
47 EVT_SIZE(wxWebViewWebKit::OnSize)
51 #if defined(__WXOSX__) && wxOSX_USE_CARBON
53 // ----------------------------------------------------------------------------
54 // Carbon Events handlers
55 // ----------------------------------------------------------------------------
57 // prototype for function in src/osx/carbon/nonownedwnd.cpp
58 void SetupMouseEvent( wxMouseEvent &wxevent , wxMacCarbonEvent &cEvent );
60 static const EventTypeSpec eventList[] =
62 //{ kEventClassControl, kEventControlTrack } ,
63 { kEventClassMouse, kEventMouseUp },
64 { kEventClassMouse, kEventMouseDown },
65 { kEventClassMouse, kEventMouseMoved },
66 { kEventClassMouse, kEventMouseDragged },
68 { kEventClassKeyboard, kEventRawKeyDown } ,
69 { kEventClassKeyboard, kEventRawKeyRepeat } ,
70 { kEventClassKeyboard, kEventRawKeyUp } ,
71 { kEventClassKeyboard, kEventRawKeyModifiersChanged } ,
73 { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent } ,
74 { kEventClassTextInput, kEventTextInputUpdateActiveInputArea } ,
76 #if DEBUG_WEBKIT_SIZING == 1
77 { kEventClassControl, kEventControlBoundsChanged } ,
81 // mix this in from window.cpp
82 pascal OSStatus wxMacUnicodeTextEventHandler(EventHandlerCallRef handler,
83 EventRef event, void *data) ;
85 // NOTE: This is mostly taken from KeyboardEventHandler in toplevel.cpp, but
86 // that expects the data pointer is a top-level window, so I needed to change
87 // that in this case. However, once 2.8 is out, we should factor out the common
88 // logic among the two functions and merge them.
89 static pascal OSStatus wxWebKitKeyEventHandler(EventHandlerCallRef handler,
90 EventRef event, void *data)
92 OSStatus result = eventNotHandledErr ;
93 wxMacCarbonEvent cEvent( event ) ;
95 wxWebViewWebKit* thisWindow = (wxWebViewWebKit*) data ;
96 wxWindow* focus = thisWindow ;
98 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 1, NULL, &charCode );
137 GetEventParameter(event, kEventParamKeyCode, typeUInt32, NULL,
138 sizeof(UInt32), NULL, &keyCode );
139 GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, NULL,
140 sizeof(UInt32), NULL, &modifiers );
142 UInt32 message = (keyCode << 8) + charCode;
143 switch ( GetEventKind( event ) )
145 case kEventRawKeyRepeat :
146 case kEventRawKeyDown :
148 WXEVENTREF formerEvent = wxTheApp->MacGetCurrentEvent() ;
149 WXEVENTHANDLERCALLREF formerHandler =
150 wxTheApp->MacGetCurrentEventHandlerCallRef() ;
152 wxTheApp->MacSetCurrentEvent( event , handler ) ;
153 if ( /* focus && */ wxTheApp->MacSendKeyDownEvent(
154 focus, message, modifiers, when, uniChar[0]))
158 wxTheApp->MacSetCurrentEvent( formerEvent , formerHandler ) ;
162 case kEventRawKeyUp :
163 if ( /* focus && */ wxTheApp->MacSendKeyUpEvent(
164 focus , message , modifiers , when , uniChar[0] ) )
170 case kEventRawKeyModifiersChanged :
172 wxKeyEvent event(wxEVT_KEY_DOWN);
174 event.m_shiftDown = modifiers & shiftKey;
175 event.m_controlDown = modifiers & controlKey;
176 event.m_altDown = modifiers & optionKey;
177 event.m_metaDown = modifiers & cmdKey;
180 event.m_uniChar = uniChar[0] ;
183 event.SetTimestamp(when);
184 event.SetEventObject(focus);
186 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & controlKey )
188 event.m_keyCode = WXK_CONTROL ;
189 event.SetEventType( ( modifiers & controlKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
190 focus->GetEventHandler()->ProcessEvent( event ) ;
192 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & shiftKey )
194 event.m_keyCode = WXK_SHIFT ;
195 event.SetEventType( ( modifiers & shiftKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
196 focus->GetEventHandler()->ProcessEvent( event ) ;
198 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & optionKey )
200 event.m_keyCode = WXK_ALT ;
201 event.SetEventType( ( modifiers & optionKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
202 focus->GetEventHandler()->ProcessEvent( event ) ;
204 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & cmdKey )
206 event.m_keyCode = WXK_COMMAND ;
207 event.SetEventType( ( modifiers & cmdKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
208 focus->GetEventHandler()->ProcessEvent( event ) ;
211 wxApp::s_lastModifiers = modifiers ;
222 static pascal OSStatus wxWebViewWebKitEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
224 OSStatus result = eventNotHandledErr ;
226 wxMacCarbonEvent cEvent( event ) ;
228 ControlRef controlRef ;
229 wxWebViewWebKit* thisWindow = (wxWebViewWebKit*) data ;
230 wxNonOwnedWindow* tlw = NULL;
232 tlw = thisWindow->MacGetTopLevelWindow();
234 cEvent.GetParameter( kEventParamDirectObject , &controlRef ) ;
236 wxWindow* currentMouseWindow = thisWindow ;
238 if ( wxApp::s_captureWindow )
239 currentMouseWindow = wxApp::s_captureWindow;
241 switch ( GetEventClass( event ) )
243 case kEventClassKeyboard:
245 result = wxWebKitKeyEventHandler(handler, event, data);
249 case kEventClassTextInput:
251 result = wxMacUnicodeTextEventHandler(handler, event, data);
255 case kEventClassMouse:
257 switch ( GetEventKind( event ) )
259 case kEventMouseDragged :
260 case kEventMouseMoved :
261 case kEventMouseDown :
264 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
265 SetupMouseEvent( wxevent , cEvent ) ;
267 currentMouseWindow->ScreenToClient( &wxevent.m_x , &wxevent.m_y ) ;
268 wxevent.SetEventObject( currentMouseWindow ) ;
269 wxevent.SetId( currentMouseWindow->GetId() ) ;
271 if ( currentMouseWindow->GetEventHandler()->ProcessEvent(wxevent) )
276 break; // this should enable WebKit to fire mouse dragged and mouse up events...
286 result = CallNextEventHandler(handler, event);
290 DEFINE_ONE_SHOT_HANDLER_GETTER( wxWebViewWebKitEventHandler )
294 @interface WebViewLoadDelegate : NSObject
296 wxWebViewWebKit* webKitWindow;
299 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
303 @interface WebViewPolicyDelegate : NSObject
305 wxWebViewWebKit* webKitWindow;
308 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
312 @interface WebViewUIDelegate : NSObject
314 wxWebViewWebKit* webKitWindow;
317 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
321 //We use a hash to map scheme names to wxWebViewHandler
322 WX_DECLARE_STRING_HASH_MAP(wxSharedPtr<wxWebViewHandler>, wxStringToWebHandlerMap);
324 static wxStringToWebHandlerMap g_stringHandlerMap;
326 @interface WebViewCustomProtocol : NSURLProtocol
331 // ----------------------------------------------------------------------------
332 // creation/destruction
333 // ----------------------------------------------------------------------------
335 bool wxWebViewWebKit::Create(wxWindow *parent,
337 const wxString& strURL,
339 const wxSize& size, long style,
340 const wxString& name)
345 wxControl::Create(parent, winID, pos, size, style, wxDefaultValidator, name);
348 wxMacControl* peer = new wxMacControl(this);
350 HIWebViewCreate( peer->GetControlRefAddr() );
352 m_webView = (WebView*) HIWebViewGetWebView( peer->GetControlRef() );
354 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_3
355 if ( UMAGetSystemVersion() >= 0x1030 )
356 HIViewChangeFeatures( peer->GetControlRef() , kHIViewIsOpaque , 0 ) ;
358 InstallControlEventHandler(peer->GetControlRef(),
359 GetwxWebViewWebKitEventHandlerUPP(),
360 GetEventTypeCount(eventList), eventList, this,
361 (EventHandlerRef *)&m_webKitCtrlEventHandler);
364 NSRect r = wxOSXGetFrameForControl( this, pos , size ) ;
365 m_webView = [[WebView alloc] initWithFrame:r
366 frameName:@"webkitFrame"
367 groupName:@"webkitGroup"];
368 SetPeer(new wxWidgetCocoaImpl( this, m_webView ));
371 MacPostControlCreate(pos, size);
374 HIViewSetVisible( GetPeer()->GetControlRef(), true );
376 [m_webView setHidden:false];
380 // Register event listener interfaces
381 WebViewLoadDelegate* loadDelegate =
382 [[WebViewLoadDelegate alloc] initWithWxWindow: this];
384 [m_webView setFrameLoadDelegate:loadDelegate];
386 // this is used to veto page loads, etc.
387 WebViewPolicyDelegate* policyDelegate =
388 [[WebViewPolicyDelegate alloc] initWithWxWindow: this];
390 [m_webView setPolicyDelegate:policyDelegate];
392 WebViewUIDelegate* uiDelegate =
393 [[WebViewUIDelegate alloc] initWithWxWindow: this];
395 [m_webView setUIDelegate:uiDelegate];
397 //Register our own class for custom scheme handling
398 [NSURLProtocol registerClass:[WebViewCustomProtocol class]];
404 wxWebViewWebKit::~wxWebViewWebKit()
406 WebViewLoadDelegate* loadDelegate = [m_webView frameLoadDelegate];
407 WebViewPolicyDelegate* policyDelegate = [m_webView policyDelegate];
408 WebViewUIDelegate* uiDelegate = [m_webView UIDelegate];
409 [m_webView setFrameLoadDelegate: nil];
410 [m_webView setPolicyDelegate: nil];
411 [m_webView setUIDelegate: nil];
414 [loadDelegate release];
417 [policyDelegate release];
420 [uiDelegate release];
423 // ----------------------------------------------------------------------------
425 // ----------------------------------------------------------------------------
427 bool wxWebViewWebKit::CanGoBack() const
432 return [m_webView canGoBack];
435 bool wxWebViewWebKit::CanGoForward() const
440 return [m_webView canGoForward];
443 void wxWebViewWebKit::GoBack()
448 [(WebView*)m_webView goBack];
451 void wxWebViewWebKit::GoForward()
456 [(WebView*)m_webView goForward];
459 void wxWebViewWebKit::Reload(wxWebViewReloadFlags flags)
464 if (flags & wxWEBVIEW_RELOAD_NO_CACHE)
466 // TODO: test this indeed bypasses the cache
467 [[m_webView preferences] setUsesPageCache:NO];
468 [[m_webView mainFrame] reload];
469 [[m_webView preferences] setUsesPageCache:YES];
473 [[m_webView mainFrame] reload];
477 void wxWebViewWebKit::Stop()
482 [[m_webView mainFrame] stopLoading];
485 bool wxWebViewWebKit::CanGetPageSource() const
490 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
491 return ( [[dataSource representation] canProvideDocumentSource] );
494 wxString wxWebViewWebKit::GetPageSource() const
497 if (CanGetPageSource())
499 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
500 wxASSERT (dataSource != nil);
502 id<WebDocumentRepresentation> representation = [dataSource representation];
503 wxASSERT (representation != nil);
505 NSString* source = [representation documentSource];
508 return wxEmptyString;
511 return wxStringWithNSString( source );
514 return wxEmptyString;
517 bool wxWebViewWebKit::CanIncreaseTextSize() const
522 if ([m_webView canMakeTextLarger])
528 void wxWebViewWebKit::IncreaseTextSize()
533 if (CanIncreaseTextSize())
534 [m_webView makeTextLarger:(WebView*)m_webView];
537 bool wxWebViewWebKit::CanDecreaseTextSize() const
542 if ([m_webView canMakeTextSmaller])
548 void wxWebViewWebKit::DecreaseTextSize()
553 if (CanDecreaseTextSize())
554 [m_webView makeTextSmaller:(WebView*)m_webView];
557 void wxWebViewWebKit::Print()
560 // TODO: allow specifying the "show prompt" parameter in Print() ?
561 bool showPrompt = true;
566 id view = [[[m_webView mainFrame] frameView] documentView];
567 NSPrintOperation *op = [NSPrintOperation printOperationWithView:view
568 printInfo: [NSPrintInfo sharedPrintInfo]];
571 [op setShowsPrintPanel: showPrompt];
572 // in my tests, the progress bar always freezes and it stops the whole
573 // print operation. do not turn this to true unless there is a
574 // workaround for the bug.
575 [op setShowsProgressPanel: false];
581 void wxWebViewWebKit::SetEditable(bool enable)
586 [m_webView setEditable:enable ];
589 bool wxWebViewWebKit::IsEditable() const
594 return [m_webView isEditable];
597 void wxWebViewWebKit::SetZoomType(wxWebViewZoomType zoomType)
599 // there is only one supported zoom type at the moment so this setter
600 // does nothing beyond checking sanity
601 wxASSERT(zoomType == wxWEBVIEW_ZOOM_TYPE_TEXT);
604 wxWebViewZoomType wxWebViewWebKit::GetZoomType() const
606 // for now that's the only one that is supported
607 // FIXME: does the default zoom type change depending on webkit versions? :S
608 // Then this will be wrong
609 return wxWEBVIEW_ZOOM_TYPE_TEXT;
612 bool wxWebViewWebKit::CanSetZoomType(wxWebViewZoomType type) const
616 // for now that's the only one that is supported
617 // TODO: I know recent versions of webkit support layout zoom too,
618 // check if we can support it
619 case wxWEBVIEW_ZOOM_TYPE_TEXT:
627 int wxWebViewWebKit::GetScrollPos()
629 id result = [[m_webView windowScriptObject]
630 evaluateWebScript:@"document.body.scrollTop"];
631 return [result intValue];
634 void wxWebViewWebKit::SetScrollPos(int pos)
640 javascript.Printf(wxT("document.body.scrollTop = %d;"), pos);
641 [[m_webView windowScriptObject] evaluateWebScript:
642 (NSString*)wxNSStringWithWxString( javascript )];
645 wxString wxWebViewWebKit::GetSelectedText() const
647 DOMRange* dr = [m_webView selectedDOMRange];
651 return wxStringWithNSString([dr toString]);
654 void wxWebViewWebKit::RunScript(const wxString& javascript)
659 [[m_webView windowScriptObject] evaluateWebScript:
660 (NSString*)wxNSStringWithWxString( javascript )];
663 void wxWebViewWebKit::OnSize(wxSizeEvent &event)
665 #if defined(__WXMAC__) && wxOSX_USE_CARBON
666 // This is a nasty hack because WebKit seems to lose its position when it is
667 // embedded in a control that is not itself the content view for a TLW.
668 // I put it in OnSize because these calcs are not perfect, and in fact are
669 // basically guesses based on reverse engineering, so it's best to give
670 // people the option of overriding OnSize with their own calcs if need be.
671 // I also left some test debugging print statements as a convenience if
672 // a(nother) problem crops up.
674 wxWindow* tlw = MacGetTopLevelWindow();
676 NSRect frame = [(WebView*)m_webView frame];
677 NSRect bounds = [(WebView*)m_webView bounds];
679 #if DEBUG_WEBKIT_SIZING
680 fprintf(stderr,"Carbon window x=%d, y=%d, width=%d, height=%d\n",
681 GetPosition().x, GetPosition().y, GetSize().x, GetSize().y);
682 fprintf(stderr, "Cocoa window frame x=%G, y=%G, width=%G, height=%G\n",
683 frame.origin.x, frame.origin.y,
684 frame.size.width, frame.size.height);
685 fprintf(stderr, "Cocoa window bounds x=%G, y=%G, width=%G, height=%G\n",
686 bounds.origin.x, bounds.origin.y,
687 bounds.size.width, bounds.size.height);
690 // This must be the case that Apple tested with, because well, in this one case
691 // we don't need to do anything! It just works. ;)
692 if (GetParent() == tlw) return;
694 // since we no longer use parent coordinates, we always want 0,0.
702 #if DEBUG_WEBKIT_SIZING
703 printf("Before conversion, origin is: x = %d, y = %d\n", x, y);
706 // NB: In most cases, when calling HIViewConvertRect, what people want is to
707 // use GetRootControl(), and this tripped me up at first. But in fact, what
708 // we want is the root view, because we need to make the y origin relative
709 // to the very top of the window, not its contents, since we later flip
710 // the y coordinate for Cocoa.
711 HIViewConvertRect (&rect, GetPeer()->GetControlRef(),
713 (WindowRef) MacGetTopLevelWindowRef()
716 x = (int)rect.origin.x;
717 y = (int)rect.origin.y;
719 #if DEBUG_WEBKIT_SIZING
720 printf("Moving Cocoa frame origin to: x = %d, y = %d\n", x, y);
724 //flip the y coordinate to convert to Cocoa coordinates
725 y = tlw->GetSize().y - ((GetSize().y) + y);
728 #if DEBUG_WEBKIT_SIZING
729 printf("y = %d after flipping value\n", y);
734 [(WebView*)m_webView setFrame:frame];
737 [(WebView*)m_webView display];
742 void wxWebViewWebKit::MacVisibilityChanged(){
743 #if defined(__WXMAC__) && wxOSX_USE_CARBON
744 bool isHidden = !IsControlVisible( GetPeer()->GetControlRef());
746 [(WebView*)m_webView display];
748 [m_webView setHidden:isHidden];
752 void wxWebViewWebKit::LoadURL(const wxString& url)
754 [[m_webView mainFrame] loadRequest:[NSURLRequest requestWithURL:
755 [NSURL URLWithString:wxNSStringWithWxString(url)]]];
758 wxString wxWebViewWebKit::GetCurrentURL() const
760 return wxStringWithNSString([m_webView mainFrameURL]);
763 wxString wxWebViewWebKit::GetCurrentTitle() const
765 return wxStringWithNSString([m_webView mainFrameTitle]);
768 float wxWebViewWebKit::GetWebkitZoom() const
770 return [m_webView textSizeMultiplier];
773 void wxWebViewWebKit::SetWebkitZoom(float zoom)
775 [m_webView setTextSizeMultiplier:zoom];
778 wxWebViewZoom wxWebViewWebKit::GetZoom() const
780 float zoom = GetWebkitZoom();
782 // arbitrary way to map float zoom to our common zoom enum
785 return wxWEBVIEW_ZOOM_TINY;
787 else if (zoom > 0.55 && zoom <= 0.85)
789 return wxWEBVIEW_ZOOM_SMALL;
791 else if (zoom > 0.85 && zoom <= 1.15)
793 return wxWEBVIEW_ZOOM_MEDIUM;
795 else if (zoom > 1.15 && zoom <= 1.45)
797 return wxWEBVIEW_ZOOM_LARGE;
799 else if (zoom > 1.45)
801 return wxWEBVIEW_ZOOM_LARGEST;
804 // to shut up compilers, this can never be reached logically
806 return wxWEBVIEW_ZOOM_MEDIUM;
809 void wxWebViewWebKit::SetZoom(wxWebViewZoom zoom)
811 // arbitrary way to map our common zoom enum to float zoom
814 case wxWEBVIEW_ZOOM_TINY:
818 case wxWEBVIEW_ZOOM_SMALL:
822 case wxWEBVIEW_ZOOM_MEDIUM:
826 case wxWEBVIEW_ZOOM_LARGE:
830 case wxWEBVIEW_ZOOM_LARGEST:
840 void wxWebViewWebKit::DoSetPage(const wxString& src, const wxString& baseUrl)
845 [[m_webView mainFrame] loadHTMLString:(NSString*)wxNSStringWithWxString(src)
846 baseURL:[NSURL URLWithString:
847 wxNSStringWithWxString( baseUrl )]];
850 void wxWebViewWebKit::Cut()
855 [(WebView*)m_webView cut:m_webView];
858 void wxWebViewWebKit::Copy()
863 [(WebView*)m_webView copy:m_webView];
866 void wxWebViewWebKit::Paste()
871 [(WebView*)m_webView paste:m_webView];
874 void wxWebViewWebKit::DeleteSelection()
879 [(WebView*)m_webView deleteSelection];
882 bool wxWebViewWebKit::HasSelection() const
884 DOMRange* range = [m_webView selectedDOMRange];
895 void wxWebViewWebKit::ClearSelection()
897 //We use javascript as selection isn't exposed at the moment in webkit
898 RunScript("window.getSelection().removeAllRanges();");
901 void wxWebViewWebKit::SelectAll()
903 RunScript("window.getSelection().selectAllChildren(document.body);");
906 wxString wxWebViewWebKit::GetSelectedSource() const
908 DOMRange* dr = [m_webView selectedDOMRange];
912 return wxStringWithNSString([dr markupString]);
915 wxString wxWebViewWebKit::GetPageText() const
917 NSString *result = [m_webView stringByEvaluatingJavaScriptFromString:
918 @"document.body.textContent"];
919 return wxStringWithNSString(result);
922 void wxWebViewWebKit::EnableHistory(bool enable)
927 [m_webView setMaintainsBackForwardList:enable];
930 void wxWebViewWebKit::ClearHistory()
932 [m_webView setMaintainsBackForwardList:NO];
933 [m_webView setMaintainsBackForwardList:YES];
936 wxVector<wxSharedPtr<wxWebViewHistoryItem> > wxWebViewWebKit::GetBackwardHistory()
938 wxVector<wxSharedPtr<wxWebViewHistoryItem> > backhist;
939 WebBackForwardList* history = [m_webView backForwardList];
940 int count = [history backListCount];
941 for(int i = -count; i < 0; i++)
943 WebHistoryItem* item = [history itemAtIndex:i];
944 wxString url = wxStringWithNSString([item URLString]);
945 wxString title = wxStringWithNSString([item title]);
946 wxWebViewHistoryItem* wxitem = new wxWebViewHistoryItem(url, title);
947 wxitem->m_histItem = item;
948 wxSharedPtr<wxWebViewHistoryItem> itemptr(wxitem);
949 backhist.push_back(itemptr);
954 wxVector<wxSharedPtr<wxWebViewHistoryItem> > wxWebViewWebKit::GetForwardHistory()
956 wxVector<wxSharedPtr<wxWebViewHistoryItem> > forwardhist;
957 WebBackForwardList* history = [m_webView backForwardList];
958 int count = [history forwardListCount];
959 for(int i = 1; i <= count; i++)
961 WebHistoryItem* item = [history itemAtIndex:i];
962 wxString url = wxStringWithNSString([item URLString]);
963 wxString title = wxStringWithNSString([item title]);
964 wxWebViewHistoryItem* wxitem = new wxWebViewHistoryItem(url, title);
965 wxitem->m_histItem = item;
966 wxSharedPtr<wxWebViewHistoryItem> itemptr(wxitem);
967 forwardhist.push_back(itemptr);
972 void wxWebViewWebKit::LoadHistoryItem(wxSharedPtr<wxWebViewHistoryItem> item)
974 [m_webView goToBackForwardItem:item->m_histItem];
977 bool wxWebViewWebKit::CanUndo() const
979 return [[m_webView undoManager] canUndo];
982 bool wxWebViewWebKit::CanRedo() const
984 return [[m_webView undoManager] canRedo];
987 void wxWebViewWebKit::Undo()
989 [[m_webView undoManager] undo];
992 void wxWebViewWebKit::Redo()
994 [[m_webView undoManager] redo];
997 void wxWebViewWebKit::RegisterHandler(wxSharedPtr<wxWebViewHandler> handler)
999 g_stringHandlerMap[handler->GetName()] = handler;
1002 //------------------------------------------------------------
1003 // Listener interfaces
1004 //------------------------------------------------------------
1006 // NB: I'm still tracking this down, but it appears the Cocoa window
1007 // still has these events fired on it while the Carbon control is being
1008 // destroyed. Therefore, we must be careful to check both the existence
1009 // of the Carbon control and the event handler before firing events.
1011 @implementation WebViewLoadDelegate
1013 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1016 webKitWindow = inWindow; // non retained
1020 - (void)webView:(WebView *)sender
1021 didStartProvisionalLoadForFrame:(WebFrame *)frame
1023 webKitWindow->m_busy = true;
1026 - (void)webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame
1028 webKitWindow->m_busy = true;
1030 if (webKitWindow && frame == [sender mainFrame]){
1031 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1032 wxString target = wxStringWithNSString([frame name]);
1033 wxWebViewEvent event(wxEVT_WEBVIEW_NAVIGATED,
1034 webKitWindow->GetId(),
1035 wxStringWithNSString( url ),
1038 if (webKitWindow && webKitWindow->GetEventHandler())
1039 webKitWindow->GetEventHandler()->ProcessEvent(event);
1043 - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
1045 webKitWindow->m_busy = false;
1047 if (webKitWindow && frame == [sender mainFrame]){
1048 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1050 wxString target = wxStringWithNSString([frame name]);
1051 wxWebViewEvent event(wxEVT_WEBVIEW_LOADED,
1052 webKitWindow->GetId(),
1053 wxStringWithNSString( url ),
1056 if (webKitWindow && webKitWindow->GetEventHandler())
1057 webKitWindow->GetEventHandler()->ProcessEvent(event);
1061 wxString nsErrorToWxHtmlError(NSError* error, wxWebViewNavigationError* out)
1063 *out = wxWEBVIEW_NAV_ERR_OTHER;
1065 if ([[error domain] isEqualToString:NSURLErrorDomain])
1067 switch ([error code])
1069 case NSURLErrorCannotFindHost:
1070 case NSURLErrorFileDoesNotExist:
1071 case NSURLErrorRedirectToNonExistentLocation:
1072 *out = wxWEBVIEW_NAV_ERR_NOT_FOUND;
1075 case NSURLErrorResourceUnavailable:
1076 case NSURLErrorHTTPTooManyRedirects:
1077 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
1078 case NSURLErrorDataLengthExceedsMaximum:
1080 case NSURLErrorBadURL:
1081 case NSURLErrorFileIsDirectory:
1082 *out = wxWEBVIEW_NAV_ERR_REQUEST;
1085 case NSURLErrorTimedOut:
1086 case NSURLErrorDNSLookupFailed:
1087 case NSURLErrorNetworkConnectionLost:
1088 case NSURLErrorCannotConnectToHost:
1089 case NSURLErrorNotConnectedToInternet:
1090 //case NSURLErrorInternationalRoamingOff:
1091 //case NSURLErrorCallIsActive:
1092 //case NSURLErrorDataNotAllowed:
1093 *out = wxWEBVIEW_NAV_ERR_CONNECTION;
1096 case NSURLErrorCancelled:
1097 case NSURLErrorUserCancelledAuthentication:
1098 *out = wxWEBVIEW_NAV_ERR_USER_CANCELLED;
1101 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
1102 case NSURLErrorCannotDecodeRawData:
1103 case NSURLErrorCannotDecodeContentData:
1104 case NSURLErrorCannotParseResponse:
1106 case NSURLErrorBadServerResponse:
1107 *out = wxWEBVIEW_NAV_ERR_REQUEST;
1110 case NSURLErrorUserAuthenticationRequired:
1111 case NSURLErrorSecureConnectionFailed:
1112 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
1113 case NSURLErrorClientCertificateRequired:
1115 *out = wxWEBVIEW_NAV_ERR_AUTH;
1118 case NSURLErrorNoPermissionsToReadFile:
1119 *out = wxWEBVIEW_NAV_ERR_SECURITY;
1122 case NSURLErrorServerCertificateHasBadDate:
1123 case NSURLErrorServerCertificateUntrusted:
1124 case NSURLErrorServerCertificateHasUnknownRoot:
1125 case NSURLErrorServerCertificateNotYetValid:
1126 case NSURLErrorClientCertificateRejected:
1127 *out = wxWEBVIEW_NAV_ERR_CERTIFICATE;
1132 wxString message = wxStringWithNSString([error localizedDescription]);
1133 NSString* detail = [error localizedFailureReason];
1136 message = message + " (" + wxStringWithNSString(detail) + ")";
1141 - (void)webView:(WebView *)sender didFailLoadWithError:(NSError*) error
1142 forFrame:(WebFrame *)frame
1144 webKitWindow->m_busy = false;
1146 if (webKitWindow && frame == [sender mainFrame]){
1147 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1149 wxWebViewNavigationError type;
1150 wxString description = nsErrorToWxHtmlError(error, &type);
1151 wxWebViewEvent event(wxEVT_WEBVIEW_ERROR,
1152 webKitWindow->GetId(),
1153 wxStringWithNSString( url ),
1155 event.SetString(description);
1158 if (webKitWindow && webKitWindow->GetEventHandler())
1160 webKitWindow->GetEventHandler()->ProcessEvent(event);
1165 - (void)webView:(WebView *)sender
1166 didFailProvisionalLoadWithError:(NSError*)error
1167 forFrame:(WebFrame *)frame
1169 webKitWindow->m_busy = false;
1171 if (webKitWindow && frame == [sender mainFrame]){
1172 NSString *url = [[[[frame provisionalDataSource] request] URL]
1175 wxWebViewNavigationError type;
1176 wxString description = nsErrorToWxHtmlError(error, &type);
1177 wxWebViewEvent event(wxEVT_WEBVIEW_ERROR,
1178 webKitWindow->GetId(),
1179 wxStringWithNSString( url ),
1181 event.SetString(description);
1184 if (webKitWindow && webKitWindow->GetEventHandler())
1185 webKitWindow->GetEventHandler()->ProcessEvent(event);
1189 - (void)webView:(WebView *)sender didReceiveTitle:(NSString *)title
1190 forFrame:(WebFrame *)frame
1192 wxString target = wxStringWithNSString([frame name]);
1193 wxWebViewEvent event(wxEVT_WEBVIEW_TITLE_CHANGED,
1194 webKitWindow->GetId(),
1195 webKitWindow->GetCurrentURL(),
1198 event.SetString(wxStringWithNSString(title));
1200 if (webKitWindow && webKitWindow->GetEventHandler())
1201 webKitWindow->GetEventHandler()->ProcessEvent(event);
1205 @implementation WebViewPolicyDelegate
1207 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1210 webKitWindow = inWindow; // non retained
1214 - (void)webView:(WebView *)sender
1215 decidePolicyForNavigationAction:(NSDictionary *)actionInformation
1216 request:(NSURLRequest *)request
1217 frame:(WebFrame *)frame
1218 decisionListener:(id<WebPolicyDecisionListener>)listener
1222 webKitWindow->m_busy = true;
1223 NSString *url = [[request URL] absoluteString];
1224 wxString target = wxStringWithNSString([frame name]);
1225 wxWebViewEvent event(wxEVT_WEBVIEW_NAVIGATING,
1226 webKitWindow->GetId(),
1227 wxStringWithNSString( url ), target);
1229 if (webKitWindow && webKitWindow->GetEventHandler())
1230 webKitWindow->GetEventHandler()->ProcessEvent(event);
1232 if (!event.IsAllowed())
1234 webKitWindow->m_busy = false;
1243 - (void)webView:(WebView *)sender
1244 decidePolicyForNewWindowAction:(NSDictionary *)actionInformation
1245 request:(NSURLRequest *)request
1246 newFrameName:(NSString *)frameName
1247 decisionListener:(id < WebPolicyDecisionListener >)listener
1249 wxUnusedVar(actionInformation);
1251 NSString *url = [[request URL] absoluteString];
1252 wxWebViewEvent event(wxEVT_WEBVIEW_NEWWINDOW,
1253 webKitWindow->GetId(),
1254 wxStringWithNSString( url ), "");
1256 if (webKitWindow && webKitWindow->GetEventHandler())
1257 webKitWindow->GetEventHandler()->ProcessEvent(event);
1263 @implementation WebViewCustomProtocol
1265 + (BOOL)canInitWithRequest:(NSURLRequest *)request
1267 NSString *scheme = [[request URL] scheme];
1269 wxStringToWebHandlerMap::const_iterator it;
1270 for( it = g_stringHandlerMap.begin(); it != g_stringHandlerMap.end(); ++it )
1272 if(it->first.IsSameAs(wxStringWithNSString(scheme)))
1281 + (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
1283 //We don't do any processing here as the wxWebViewHandler classes do it
1287 - (void)startLoading
1289 NSURLRequest *request = [self request];
1290 NSString* path = [[request URL] absoluteString];
1292 id<NSURLProtocolClient> client = [self client];
1294 wxString wxpath = wxStringWithNSString(path);
1295 wxString scheme = wxStringWithNSString([[request URL] scheme]);
1296 wxFSFile* file = g_stringHandlerMap[scheme]->GetFile(wxpath);
1300 NSError *error = [[NSError alloc] initWithDomain:NSURLErrorDomain
1301 code:NSURLErrorFileDoesNotExist
1304 [client URLProtocol:self didFailWithError:error];
1309 size_t length = file->GetStream()->GetLength();
1312 NSURLResponse *response = [[NSURLResponse alloc] initWithURL:[request URL]
1313 MIMEType:wxNSStringWithWxString(file->GetMimeType())
1314 expectedContentLength:length
1315 textEncodingName:nil];
1317 //Load the data, we malloc it so it is tidied up properly
1318 void* buffer = malloc(length);
1319 file->GetStream()->Read(buffer, length);
1320 NSData *data = [[NSData alloc] initWithBytesNoCopy:buffer length:length];
1322 //We do not support caching anything yet
1323 [client URLProtocol:self didReceiveResponse:response
1324 cacheStoragePolicy:NSURLCacheStorageNotAllowed];
1327 [client URLProtocol:self didLoadData:data];
1329 //Notify that we have finished
1330 [client URLProtocolDidFinishLoading:self];
1343 @implementation WebViewUIDelegate
1345 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1348 webKitWindow = inWindow; // non retained
1352 - (void)webView:(WebView *)sender printFrameView:(WebFrameView *)frameView
1354 wxUnusedVar(sender);
1355 wxUnusedVar(frameView);
1357 webKitWindow->Print();
1360 - (NSArray *)webView:(WebView *)sender contextMenuItemsForElement:(NSDictionary *)element
1361 defaultMenuItems:(NSArray *) defaultMenuItems
1363 if(webKitWindow->IsContextMenuEnabled())
1364 return defaultMenuItems;
1370 #endif //wxUSE_WEBVIEW && wxUSE_WEBVIEW_WEBKIT