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 1, 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 @interface WebViewUIDelegate : NSObject
315 wxWebViewWebKit* webKitWindow;
318 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
322 //We use a hash to map scheme names to wxWebViewHandler
323 WX_DECLARE_STRING_HASH_MAP(wxSharedPtr<wxWebViewHandler>, wxStringToWebHandlerMap);
325 static wxStringToWebHandlerMap g_stringHandlerMap;
327 @interface WebViewCustomProtocol : NSURLProtocol
332 // ----------------------------------------------------------------------------
333 // creation/destruction
334 // ----------------------------------------------------------------------------
336 bool wxWebViewWebKit::Create(wxWindow *parent,
338 const wxString& strURL,
340 const wxSize& size, long style,
341 const wxString& name)
346 wxControl::Create(parent, winID, pos, size, style, wxDefaultValidator, name);
349 wxMacControl* peer = new wxMacControl(this);
351 HIWebViewCreate( peer->GetControlRefAddr() );
353 m_webView = (WebView*) HIWebViewGetWebView( peer->GetControlRef() );
355 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_3
356 if ( UMAGetSystemVersion() >= 0x1030 )
357 HIViewChangeFeatures( peer->GetControlRef() , kHIViewIsOpaque , 0 ) ;
359 InstallControlEventHandler(peer->GetControlRef(),
360 GetwxWebViewWebKitEventHandlerUPP(),
361 GetEventTypeCount(eventList), eventList, this,
362 (EventHandlerRef *)&m_webKitCtrlEventHandler);
365 NSRect r = wxOSXGetFrameForControl( this, pos , size ) ;
366 m_webView = [[WebView alloc] initWithFrame:r
367 frameName:@"webkitFrame"
368 groupName:@"webkitGroup"];
369 SetPeer(new wxWidgetCocoaImpl( this, m_webView ));
372 MacPostControlCreate(pos, size);
375 HIViewSetVisible( GetPeer()->GetControlRef(), true );
377 [m_webView setHidden:false];
381 // Register event listener interfaces
382 WebViewLoadDelegate* loadDelegate =
383 [[WebViewLoadDelegate alloc] initWithWxWindow: this];
385 [m_webView setFrameLoadDelegate:loadDelegate];
387 // this is used to veto page loads, etc.
388 WebViewPolicyDelegate* policyDelegate =
389 [[WebViewPolicyDelegate alloc] initWithWxWindow: this];
391 [m_webView setPolicyDelegate:policyDelegate];
393 WebViewUIDelegate* uiDelegate =
394 [[WebViewUIDelegate alloc] initWithWxWindow: this];
396 [m_webView setUIDelegate:uiDelegate];
398 //Register our own class for custom scheme handling
399 [NSURLProtocol registerClass:[WebViewCustomProtocol class]];
405 wxWebViewWebKit::~wxWebViewWebKit()
407 WebViewLoadDelegate* loadDelegate = [m_webView frameLoadDelegate];
408 WebViewPolicyDelegate* policyDelegate = [m_webView policyDelegate];
409 WebViewUIDelegate* uiDelegate = [m_webView UIDelegate];
410 [m_webView setFrameLoadDelegate: nil];
411 [m_webView setPolicyDelegate: nil];
412 [m_webView setUIDelegate: nil];
415 [loadDelegate release];
418 [policyDelegate release];
421 [uiDelegate release];
424 // ----------------------------------------------------------------------------
426 // ----------------------------------------------------------------------------
428 bool wxWebViewWebKit::CanGoBack() const
433 return [m_webView canGoBack];
436 bool wxWebViewWebKit::CanGoForward() const
441 return [m_webView canGoForward];
444 void wxWebViewWebKit::GoBack()
449 [(WebView*)m_webView goBack];
452 void wxWebViewWebKit::GoForward()
457 [(WebView*)m_webView goForward];
460 void wxWebViewWebKit::Reload(wxWebViewReloadFlags flags)
465 if (flags & wxWEBVIEW_RELOAD_NO_CACHE)
467 // TODO: test this indeed bypasses the cache
468 [[m_webView preferences] setUsesPageCache:NO];
469 [[m_webView mainFrame] reload];
470 [[m_webView preferences] setUsesPageCache:YES];
474 [[m_webView mainFrame] reload];
478 void wxWebViewWebKit::Stop()
483 [[m_webView mainFrame] stopLoading];
486 bool wxWebViewWebKit::CanGetPageSource() const
491 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
492 return ( [[dataSource representation] canProvideDocumentSource] );
495 wxString wxWebViewWebKit::GetPageSource() const
498 if (CanGetPageSource())
500 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
501 wxASSERT (dataSource != nil);
503 id<WebDocumentRepresentation> representation = [dataSource representation];
504 wxASSERT (representation != nil);
506 NSString* source = [representation documentSource];
509 return wxEmptyString;
512 return wxStringWithNSString( source );
515 return wxEmptyString;
518 bool wxWebViewWebKit::CanIncreaseTextSize() const
523 if ([m_webView canMakeTextLarger])
529 void wxWebViewWebKit::IncreaseTextSize()
534 if (CanIncreaseTextSize())
535 [m_webView makeTextLarger:(WebView*)m_webView];
538 bool wxWebViewWebKit::CanDecreaseTextSize() const
543 if ([m_webView canMakeTextSmaller])
549 void wxWebViewWebKit::DecreaseTextSize()
554 if (CanDecreaseTextSize())
555 [m_webView makeTextSmaller:(WebView*)m_webView];
558 void wxWebViewWebKit::Print()
561 // TODO: allow specifying the "show prompt" parameter in Print() ?
562 bool showPrompt = true;
567 id view = [[[m_webView mainFrame] frameView] documentView];
568 NSPrintOperation *op = [NSPrintOperation printOperationWithView:view
569 printInfo: [NSPrintInfo sharedPrintInfo]];
572 [op setShowsPrintPanel: showPrompt];
573 // in my tests, the progress bar always freezes and it stops the whole
574 // print operation. do not turn this to true unless there is a
575 // workaround for the bug.
576 [op setShowsProgressPanel: false];
582 void wxWebViewWebKit::SetEditable(bool enable)
587 [m_webView setEditable:enable ];
590 bool wxWebViewWebKit::IsEditable() const
595 return [m_webView isEditable];
598 void wxWebViewWebKit::SetZoomType(wxWebViewZoomType zoomType)
600 // there is only one supported zoom type at the moment so this setter
601 // does nothing beyond checking sanity
602 wxASSERT(zoomType == wxWEBVIEW_ZOOM_TYPE_TEXT);
605 wxWebViewZoomType wxWebViewWebKit::GetZoomType() const
607 // for now that's the only one that is supported
608 // FIXME: does the default zoom type change depending on webkit versions? :S
609 // Then this will be wrong
610 return wxWEBVIEW_ZOOM_TYPE_TEXT;
613 bool wxWebViewWebKit::CanSetZoomType(wxWebViewZoomType type) const
617 // for now that's the only one that is supported
618 // TODO: I know recent versions of webkit support layout zoom too,
619 // check if we can support it
620 case wxWEBVIEW_ZOOM_TYPE_TEXT:
628 int wxWebViewWebKit::GetScrollPos()
630 id result = [[m_webView windowScriptObject]
631 evaluateWebScript:@"document.body.scrollTop"];
632 return [result intValue];
635 void wxWebViewWebKit::SetScrollPos(int pos)
641 javascript.Printf(wxT("document.body.scrollTop = %d;"), pos);
642 [[m_webView windowScriptObject] evaluateWebScript:
643 (NSString*)wxNSStringWithWxString( javascript )];
646 wxString wxWebViewWebKit::GetSelectedText() const
648 NSString* selection = [[m_webView selectedDOMRange] markupString];
649 if (!selection) return wxEmptyString;
651 return wxStringWithNSString(selection);
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 wxString script = ("var range = window.getSelection().getRangeAt(0);"
909 "var element = document.createElement('div');"
910 "element.appendChild(range.cloneContents());"
911 "return element.innerHTML;");
912 id result = [[m_webView windowScriptObject]
913 evaluateWebScript:wxNSStringWithWxString(script)];
914 return wxStringWithNSString([result stringValue]);
917 wxString wxWebViewWebKit::GetPageText() const
919 id result = [[m_webView windowScriptObject]
920 evaluateWebScript:@"document.body.textContent"];
921 return wxStringWithNSString([result stringValue]);
924 void wxWebViewWebKit::EnableHistory(bool enable)
929 [m_webView setMaintainsBackForwardList:enable];
932 void wxWebViewWebKit::ClearHistory()
934 [m_webView setMaintainsBackForwardList:NO];
935 [m_webView setMaintainsBackForwardList:YES];
938 wxVector<wxSharedPtr<wxWebViewHistoryItem> > wxWebViewWebKit::GetBackwardHistory()
940 wxVector<wxSharedPtr<wxWebViewHistoryItem> > backhist;
941 WebBackForwardList* history = [m_webView backForwardList];
942 int count = [history backListCount];
943 for(int i = -count; i < 0; i++)
945 WebHistoryItem* item = [history itemAtIndex:i];
946 wxString url = wxStringWithNSString([item URLString]);
947 wxString title = wxStringWithNSString([item title]);
948 wxWebViewHistoryItem* wxitem = new wxWebViewHistoryItem(url, title);
949 wxitem->m_histItem = item;
950 wxSharedPtr<wxWebViewHistoryItem> itemptr(wxitem);
951 backhist.push_back(itemptr);
956 wxVector<wxSharedPtr<wxWebViewHistoryItem> > wxWebViewWebKit::GetForwardHistory()
958 wxVector<wxSharedPtr<wxWebViewHistoryItem> > forwardhist;
959 WebBackForwardList* history = [m_webView backForwardList];
960 int count = [history forwardListCount];
961 for(int i = 1; i <= count; i++)
963 WebHistoryItem* item = [history itemAtIndex:i];
964 wxString url = wxStringWithNSString([item URLString]);
965 wxString title = wxStringWithNSString([item title]);
966 wxWebViewHistoryItem* wxitem = new wxWebViewHistoryItem(url, title);
967 wxitem->m_histItem = item;
968 wxSharedPtr<wxWebViewHistoryItem> itemptr(wxitem);
969 forwardhist.push_back(itemptr);
974 void wxWebViewWebKit::LoadHistoryItem(wxSharedPtr<wxWebViewHistoryItem> item)
976 [m_webView goToBackForwardItem:item->m_histItem];
979 bool wxWebViewWebKit::CanUndo() const
981 return [[m_webView undoManager] canUndo];
984 bool wxWebViewWebKit::CanRedo() const
986 return [[m_webView undoManager] canRedo];
989 void wxWebViewWebKit::Undo()
991 [[m_webView undoManager] undo];
994 void wxWebViewWebKit::Redo()
996 [[m_webView undoManager] redo];
999 void wxWebViewWebKit::RegisterHandler(wxSharedPtr<wxWebViewHandler> handler)
1001 g_stringHandlerMap[handler->GetName()] = handler;
1004 //------------------------------------------------------------
1005 // Listener interfaces
1006 //------------------------------------------------------------
1008 // NB: I'm still tracking this down, but it appears the Cocoa window
1009 // still has these events fired on it while the Carbon control is being
1010 // destroyed. Therefore, we must be careful to check both the existence
1011 // of the Carbon control and the event handler before firing events.
1013 @implementation WebViewLoadDelegate
1015 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1018 webKitWindow = inWindow; // non retained
1022 - (void)webView:(WebView *)sender
1023 didStartProvisionalLoadForFrame:(WebFrame *)frame
1025 webKitWindow->m_busy = true;
1028 - (void)webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame
1030 webKitWindow->m_busy = true;
1032 if (webKitWindow && frame == [sender mainFrame]){
1033 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1034 wxString target = wxStringWithNSString([frame name]);
1035 wxWebViewEvent event(wxEVT_WEBVIEW_NAVIGATED,
1036 webKitWindow->GetId(),
1037 wxStringWithNSString( url ),
1040 if (webKitWindow && webKitWindow->GetEventHandler())
1041 webKitWindow->GetEventHandler()->ProcessEvent(event);
1045 - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
1047 webKitWindow->m_busy = false;
1049 if (webKitWindow && frame == [sender mainFrame]){
1050 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1052 wxString target = wxStringWithNSString([frame name]);
1053 wxWebViewEvent event(wxEVT_WEBVIEW_LOADED,
1054 webKitWindow->GetId(),
1055 wxStringWithNSString( url ),
1058 if (webKitWindow && webKitWindow->GetEventHandler())
1059 webKitWindow->GetEventHandler()->ProcessEvent(event);
1063 wxString nsErrorToWxHtmlError(NSError* error, wxWebViewNavigationError* out)
1065 *out = wxWEBVIEW_NAV_ERR_OTHER;
1067 if ([[error domain] isEqualToString:NSURLErrorDomain])
1069 switch ([error code])
1071 case NSURLErrorCannotFindHost:
1072 case NSURLErrorFileDoesNotExist:
1073 case NSURLErrorRedirectToNonExistentLocation:
1074 *out = wxWEBVIEW_NAV_ERR_NOT_FOUND;
1077 case NSURLErrorResourceUnavailable:
1078 case NSURLErrorHTTPTooManyRedirects:
1079 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
1080 case NSURLErrorDataLengthExceedsMaximum:
1082 case NSURLErrorBadURL:
1083 case NSURLErrorFileIsDirectory:
1084 *out = wxWEBVIEW_NAV_ERR_REQUEST;
1087 case NSURLErrorTimedOut:
1088 case NSURLErrorDNSLookupFailed:
1089 case NSURLErrorNetworkConnectionLost:
1090 case NSURLErrorCannotConnectToHost:
1091 case NSURLErrorNotConnectedToInternet:
1092 //case NSURLErrorInternationalRoamingOff:
1093 //case NSURLErrorCallIsActive:
1094 //case NSURLErrorDataNotAllowed:
1095 *out = wxWEBVIEW_NAV_ERR_CONNECTION;
1098 case NSURLErrorCancelled:
1099 case NSURLErrorUserCancelledAuthentication:
1100 *out = wxWEBVIEW_NAV_ERR_USER_CANCELLED;
1103 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
1104 case NSURLErrorCannotDecodeRawData:
1105 case NSURLErrorCannotDecodeContentData:
1106 case NSURLErrorCannotParseResponse:
1108 case NSURLErrorBadServerResponse:
1109 *out = wxWEBVIEW_NAV_ERR_REQUEST;
1112 case NSURLErrorUserAuthenticationRequired:
1113 case NSURLErrorSecureConnectionFailed:
1114 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
1115 case NSURLErrorClientCertificateRequired:
1117 *out = wxWEBVIEW_NAV_ERR_AUTH;
1120 case NSURLErrorNoPermissionsToReadFile:
1121 *out = wxWEBVIEW_NAV_ERR_SECURITY;
1124 case NSURLErrorServerCertificateHasBadDate:
1125 case NSURLErrorServerCertificateUntrusted:
1126 case NSURLErrorServerCertificateHasUnknownRoot:
1127 case NSURLErrorServerCertificateNotYetValid:
1128 case NSURLErrorClientCertificateRejected:
1129 *out = wxWEBVIEW_NAV_ERR_CERTIFICATE;
1134 wxString message = wxStringWithNSString([error localizedDescription]);
1135 NSString* detail = [error localizedFailureReason];
1138 message = message + " (" + wxStringWithNSString(detail) + ")";
1143 - (void)webView:(WebView *)sender didFailLoadWithError:(NSError*) error
1144 forFrame:(WebFrame *)frame
1146 webKitWindow->m_busy = false;
1148 if (webKitWindow && frame == [sender mainFrame]){
1149 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1151 wxWebViewNavigationError type;
1152 wxString description = nsErrorToWxHtmlError(error, &type);
1153 wxWebViewEvent event(wxEVT_WEBVIEW_ERROR,
1154 webKitWindow->GetId(),
1155 wxStringWithNSString( url ),
1157 event.SetString(description);
1160 if (webKitWindow && webKitWindow->GetEventHandler())
1162 webKitWindow->GetEventHandler()->ProcessEvent(event);
1167 - (void)webView:(WebView *)sender
1168 didFailProvisionalLoadWithError:(NSError*)error
1169 forFrame:(WebFrame *)frame
1171 webKitWindow->m_busy = false;
1173 if (webKitWindow && frame == [sender mainFrame]){
1174 NSString *url = [[[[frame provisionalDataSource] request] URL]
1177 wxWebViewNavigationError type;
1178 wxString description = nsErrorToWxHtmlError(error, &type);
1179 wxWebViewEvent event(wxEVT_WEBVIEW_ERROR,
1180 webKitWindow->GetId(),
1181 wxStringWithNSString( url ),
1183 event.SetString(description);
1186 if (webKitWindow && webKitWindow->GetEventHandler())
1187 webKitWindow->GetEventHandler()->ProcessEvent(event);
1191 - (void)webView:(WebView *)sender didReceiveTitle:(NSString *)title
1192 forFrame:(WebFrame *)frame
1194 wxString target = wxStringWithNSString([frame name]);
1195 wxWebViewEvent event(wxEVT_WEBVIEW_TITLE_CHANGED,
1196 webKitWindow->GetId(),
1197 webKitWindow->GetCurrentURL(),
1200 event.SetString(wxStringWithNSString(title));
1202 if (webKitWindow && webKitWindow->GetEventHandler())
1203 webKitWindow->GetEventHandler()->ProcessEvent(event);
1207 @implementation WebViewPolicyDelegate
1209 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1212 webKitWindow = inWindow; // non retained
1216 - (void)webView:(WebView *)sender
1217 decidePolicyForNavigationAction:(NSDictionary *)actionInformation
1218 request:(NSURLRequest *)request
1219 frame:(WebFrame *)frame
1220 decisionListener:(id<WebPolicyDecisionListener>)listener
1224 webKitWindow->m_busy = true;
1225 NSString *url = [[request URL] absoluteString];
1226 wxString target = wxStringWithNSString([frame name]);
1227 wxWebViewEvent event(wxEVT_WEBVIEW_NAVIGATING,
1228 webKitWindow->GetId(),
1229 wxStringWithNSString( url ), target);
1231 if (webKitWindow && webKitWindow->GetEventHandler())
1232 webKitWindow->GetEventHandler()->ProcessEvent(event);
1234 if (!event.IsAllowed())
1236 webKitWindow->m_busy = false;
1245 - (void)webView:(WebView *)sender
1246 decidePolicyForNewWindowAction:(NSDictionary *)actionInformation
1247 request:(NSURLRequest *)request
1248 newFrameName:(NSString *)frameName
1249 decisionListener:(id < WebPolicyDecisionListener >)listener
1251 wxUnusedVar(actionInformation);
1253 NSString *url = [[request URL] absoluteString];
1254 wxWebViewEvent event(wxEVT_WEBVIEW_NEWWINDOW,
1255 webKitWindow->GetId(),
1256 wxStringWithNSString( url ), "");
1258 if (webKitWindow && webKitWindow->GetEventHandler())
1259 webKitWindow->GetEventHandler()->ProcessEvent(event);
1265 @implementation WebViewCustomProtocol
1267 + (BOOL)canInitWithRequest:(NSURLRequest *)request
1269 NSString *scheme = [[request URL] scheme];
1271 wxStringToWebHandlerMap::const_iterator it;
1272 for( it = g_stringHandlerMap.begin(); it != g_stringHandlerMap.end(); ++it )
1274 if(it->first.IsSameAs(wxStringWithNSString(scheme)))
1283 + (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
1285 //We don't do any processing here as the wxWebViewHandler classes do it
1289 - (void)startLoading
1291 NSURLRequest *request = [self request];
1292 NSString* path = [[request URL] absoluteString];
1294 wxString wxpath = wxStringWithNSString(path);
1295 wxString scheme = wxStringWithNSString([[request URL] scheme]);
1296 wxFSFile* file = g_stringHandlerMap[scheme]->GetFile(wxpath);
1297 size_t length = file->GetStream()->GetLength();
1300 NSURLResponse *response = [[NSURLResponse alloc] initWithURL:[request URL]
1301 MIMEType:wxNSStringWithWxString(file->GetMimeType())
1302 expectedContentLength:length
1303 textEncodingName:nil];
1305 //Load the data, we malloc it so it is tidied up properly
1306 void* buffer = malloc(length);
1307 file->GetStream()->Read(buffer, length);
1308 NSData *data = [[NSData alloc] initWithBytesNoCopy:buffer length:length];
1310 id<NSURLProtocolClient> client = [self client];
1312 //We do not support caching anything yet
1313 [client URLProtocol:self didReceiveResponse:response
1314 cacheStoragePolicy:NSURLCacheStorageNotAllowed];
1317 [client URLProtocol:self didLoadData:data];
1319 //Notify that we have finished
1320 [client URLProtocolDidFinishLoading:self];
1333 @implementation WebViewUIDelegate
1335 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1338 webKitWindow = inWindow; // non retained
1342 - (void)webView:(WebView *)sender printFrameView:(WebFrameView *)frameView
1344 wxUnusedVar(sender);
1345 wxUnusedVar(frameView);
1347 webKitWindow->Print();
1350 - (NSArray *)webView:(WebView *)sender contextMenuItemsForElement:(NSDictionary *)element
1351 defaultMenuItems:(NSArray *) defaultMenuItems
1353 if(webKitWindow->IsContextMenuEnabled())
1354 return defaultMenuItems;
1360 #endif //wxUSE_WEBVIEW && wxUSE_WEBVIEW_WEBKIT