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 // For compilers that support precompilation, includes "wx.h".
18 #include "wx/wxprec.h"
24 #if wxHAVE_WEB_BACKEND_OSX_WEBKIT
27 #include "wx/cocoa/autorelease.h"
29 #include "wx/osx/private.h"
31 #include <WebKit/WebKit.h>
32 #include <WebKit/HIWebView.h>
33 #include <WebKit/CarbonUtils.h>
36 #include <Foundation/NSURLError.h>
38 // FIXME: find cleaner way to find the wxWidgets ID of a webview than this hack
40 std::map<WebView*, wxWebViewWebKit*> wx_webviewctrls;
42 #define DEBUG_WEBKIT_SIZING 0
44 // ----------------------------------------------------------------------------
46 // ----------------------------------------------------------------------------
48 IMPLEMENT_DYNAMIC_CLASS(wxWebViewWebKit, wxControl)
50 BEGIN_EVENT_TABLE(wxWebViewWebKit, wxControl)
51 #if defined(__WXMAC__) && wxOSX_USE_CARBON
52 EVT_SIZE(wxWebViewWebKit::OnSize)
56 #if defined(__WXOSX__) && wxOSX_USE_CARBON
58 // ----------------------------------------------------------------------------
59 // Carbon Events handlers
60 // ----------------------------------------------------------------------------
62 // prototype for function in src/osx/carbon/nonownedwnd.cpp
63 void SetupMouseEvent( wxMouseEvent &wxevent , wxMacCarbonEvent &cEvent );
65 static const EventTypeSpec eventList[] =
67 //{ kEventClassControl, kEventControlTrack } ,
68 { kEventClassMouse, kEventMouseUp },
69 { kEventClassMouse, kEventMouseDown },
70 { kEventClassMouse, kEventMouseMoved },
71 { kEventClassMouse, kEventMouseDragged },
73 { kEventClassKeyboard, kEventRawKeyDown } ,
74 { kEventClassKeyboard, kEventRawKeyRepeat } ,
75 { kEventClassKeyboard, kEventRawKeyUp } ,
76 { kEventClassKeyboard, kEventRawKeyModifiersChanged } ,
78 { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent } ,
79 { kEventClassTextInput, kEventTextInputUpdateActiveInputArea } ,
81 #if DEBUG_WEBKIT_SIZING == 1
82 { kEventClassControl, kEventControlBoundsChanged } ,
86 // mix this in from window.cpp
87 pascal OSStatus wxMacUnicodeTextEventHandler(EventHandlerCallRef handler,
88 EventRef event, void *data) ;
90 // NOTE: This is mostly taken from KeyboardEventHandler in toplevel.cpp, but
91 // that expects the data pointer is a top-level window, so I needed to change
92 // that in this case. However, once 2.8 is out, we should factor out the common
93 // logic among the two functions and merge them.
94 static pascal OSStatus wxWebKitKeyEventHandler(EventHandlerCallRef handler,
95 EventRef event, void *data)
97 OSStatus result = eventNotHandledErr ;
98 wxMacCarbonEvent cEvent( event ) ;
100 wxWebViewWebKit* thisWindow = (wxWebViewWebKit*) data ;
101 wxWindow* focus = thisWindow ;
103 unsigned char charCode ;
111 UInt32 when = EventTimeToTicks( GetEventTime( event ) ) ;
114 ByteCount dataSize = 0 ;
115 if ( GetEventParameter(event, kEventParamKeyUnicodes, typeUnicodeText,
116 NULL, 0 , &dataSize, NULL ) == noErr)
119 int numChars = dataSize / sizeof( UniChar) + 1;
121 UniChar* charBuf = buf ;
123 if ( numChars * 2 > 4 )
124 charBuf = new UniChar[ numChars ] ;
125 GetEventParameter(event, kEventParamKeyUnicodes, typeUnicodeText, NULL,
126 dataSize , NULL , charBuf) ;
127 charBuf[ numChars - 1 ] = 0;
129 #if SIZEOF_WCHAR_T == 2
130 uniChar = charBuf[0] ;
132 wxMBConvUTF16 converter ;
133 converter.MB2WC( uniChar , (const char*)charBuf , 2 ) ;
136 if ( numChars * 2 > 4 )
141 GetEventParameter(event, kEventParamKeyMacCharCodes, typeChar, NULL,
142 sizeof(char), NULL, &charCode );
143 GetEventParameter(event, kEventParamKeyCode, typeUInt32, NULL,
144 sizeof(UInt32), NULL, &keyCode );
145 GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, NULL,
146 sizeof(UInt32), NULL, &modifiers );
147 GetEventParameter(event, kEventParamMouseLocation, typeQDPoint, NULL,
148 sizeof(Point), NULL, &point );
150 UInt32 message = (keyCode << 8) + charCode;
151 switch ( GetEventKind( event ) )
153 case kEventRawKeyRepeat :
154 case kEventRawKeyDown :
156 WXEVENTREF formerEvent = wxTheApp->MacGetCurrentEvent() ;
157 WXEVENTHANDLERCALLREF formerHandler =
158 wxTheApp->MacGetCurrentEventHandlerCallRef() ;
160 wxTheApp->MacSetCurrentEvent( event , handler ) ;
161 if ( /* focus && */ wxTheApp->MacSendKeyDownEvent(
162 focus, message, modifiers, when, point.h, point.v, uniChar[0]))
166 wxTheApp->MacSetCurrentEvent( formerEvent , formerHandler ) ;
170 case kEventRawKeyUp :
171 if ( /* focus && */ wxTheApp->MacSendKeyUpEvent(
172 focus , message , modifiers , when , point.h , point.v , uniChar[0] ) )
178 case kEventRawKeyModifiersChanged :
180 wxKeyEvent event(wxEVT_KEY_DOWN);
182 event.m_shiftDown = modifiers & shiftKey;
183 event.m_controlDown = modifiers & controlKey;
184 event.m_altDown = modifiers & optionKey;
185 event.m_metaDown = modifiers & cmdKey;
190 event.m_uniChar = uniChar[0] ;
193 event.SetTimestamp(when);
194 event.SetEventObject(focus);
196 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & controlKey )
198 event.m_keyCode = WXK_CONTROL ;
199 event.SetEventType( ( modifiers & controlKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
200 focus->GetEventHandler()->ProcessEvent( event ) ;
202 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & shiftKey )
204 event.m_keyCode = WXK_SHIFT ;
205 event.SetEventType( ( modifiers & shiftKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
206 focus->GetEventHandler()->ProcessEvent( event ) ;
208 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & optionKey )
210 event.m_keyCode = WXK_ALT ;
211 event.SetEventType( ( modifiers & optionKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
212 focus->GetEventHandler()->ProcessEvent( event ) ;
214 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & cmdKey )
216 event.m_keyCode = WXK_COMMAND ;
217 event.SetEventType( ( modifiers & cmdKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
218 focus->GetEventHandler()->ProcessEvent( event ) ;
221 wxApp::s_lastModifiers = modifiers ;
232 static pascal OSStatus wxWebViewWebKitEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
234 OSStatus result = eventNotHandledErr ;
236 wxMacCarbonEvent cEvent( event ) ;
238 ControlRef controlRef ;
239 wxWebViewWebKit* thisWindow = (wxWebViewWebKit*) data ;
240 wxNonOwnedWindow* tlw = NULL;
242 tlw = thisWindow->MacGetTopLevelWindow();
244 cEvent.GetParameter( kEventParamDirectObject , &controlRef ) ;
246 wxWindow* currentMouseWindow = thisWindow ;
248 if ( wxApp::s_captureWindow )
249 currentMouseWindow = wxApp::s_captureWindow;
251 switch ( GetEventClass( event ) )
253 case kEventClassKeyboard:
255 result = wxWebKitKeyEventHandler(handler, event, data);
259 case kEventClassTextInput:
261 result = wxMacUnicodeTextEventHandler(handler, event, data);
265 case kEventClassMouse:
267 switch ( GetEventKind( event ) )
269 case kEventMouseDragged :
270 case kEventMouseMoved :
271 case kEventMouseDown :
274 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
275 SetupMouseEvent( wxevent , cEvent ) ;
277 currentMouseWindow->ScreenToClient( &wxevent.m_x , &wxevent.m_y ) ;
278 wxevent.SetEventObject( currentMouseWindow ) ;
279 wxevent.SetId( currentMouseWindow->GetId() ) ;
281 if ( currentMouseWindow->GetEventHandler()->ProcessEvent(wxevent) )
286 break; // this should enable WebKit to fire mouse dragged and mouse up events...
296 result = CallNextEventHandler(handler, event);
300 DEFINE_ONE_SHOT_HANDLER_GETTER( wxWebViewWebKitEventHandler )
304 //---------------------------------------------------------
305 // helper functions for NSString<->wxString conversion
306 //---------------------------------------------------------
308 inline wxString wxStringWithNSString(NSString *nsstring)
311 return wxString([nsstring UTF8String], wxConvUTF8);
313 return wxString([nsstring lossyCString]);
314 #endif // wxUSE_UNICODE
317 inline NSString* wxNSStringWithWxString(const wxString &wxstring)
320 return [NSString stringWithUTF8String: wxstring.mb_str(wxConvUTF8)];
322 return [NSString stringWithCString: wxstring.c_str() length:wxstring.Len()];
323 #endif // wxUSE_UNICODE
326 inline int wxNavTypeFromWebNavType(int type){
327 if (type == WebNavigationTypeLinkClicked)
328 return wxWEBKIT_NAV_LINK_CLICKED;
330 if (type == WebNavigationTypeFormSubmitted)
331 return wxWEBKIT_NAV_FORM_SUBMITTED;
333 if (type == WebNavigationTypeBackForward)
334 return wxWEBKIT_NAV_BACK_NEXT;
336 if (type == WebNavigationTypeReload)
337 return wxWEBKIT_NAV_RELOAD;
339 if (type == WebNavigationTypeFormResubmitted)
340 return wxWEBKIT_NAV_FORM_RESUBMITTED;
342 return wxWEBKIT_NAV_OTHER;
345 @interface MyFrameLoadMonitor : NSObject
347 wxWebViewWebKit* webKitWindow;
350 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
354 @interface MyPolicyDelegate : NSObject
356 wxWebViewWebKit* webKitWindow;
359 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
363 // ----------------------------------------------------------------------------
364 // creation/destruction
365 // ----------------------------------------------------------------------------
367 bool wxWebViewWebKit::Create(wxWindow *parent,
369 const wxString& strURL,
371 const wxSize& size, long style,
372 const wxString& name)
375 //m_pageTitle = _("Untitled Page");
377 //still needed for wxCocoa??
381 if (size.x == wxDefaultCoord || size.y == wxDefaultCoord)
383 m_parent->GetClientSize(&width, &height);
384 sizeInstance.x = width;
385 sizeInstance.y = height;
389 sizeInstance.x = size.x;
390 sizeInstance.y = size.y;
393 // now create and attach WebKit view...
395 wxControl::Create(parent, m_windowID, pos, sizeInstance, style, name);
396 SetSize(pos.x, pos.y, sizeInstance.x, sizeInstance.y);
398 wxTopLevelWindowCocoa *topWin = wxDynamicCast(this, wxTopLevelWindowCocoa);
399 NSWindow* nsWin = topWin->GetNSWindow();
401 rect.origin.x = pos.x;
402 rect.origin.y = pos.y;
403 rect.size.width = sizeInstance.x;
404 rect.size.height = sizeInstance.y;
405 m_webView = (WebView*)[[WebView alloc] initWithFrame:rect
406 frameName:@"webkitFrame"
407 groupName:@"webkitGroup"];
408 SetNSView(m_webView);
409 [m_cocoaNSView release];
411 if(m_parent) m_parent->CocoaAddChild(this);
412 SetInitialFrameRect(pos,sizeInstance);
414 m_macIsUserPane = false;
415 wxControl::Create(parent, winID, pos, size, style, wxDefaultValidator, name);
418 m_peer = new wxMacControl(this);
420 HIWebViewCreate( m_peer->GetControlRefAddr() );
422 m_webView = (WebView*) HIWebViewGetWebView( m_peer->GetControlRef() );
424 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_3
425 if ( UMAGetSystemVersion() >= 0x1030 )
426 HIViewChangeFeatures( m_peer->GetControlRef() , kHIViewIsOpaque , 0 ) ;
428 InstallControlEventHandler(m_peer->GetControlRef(),
429 GetwxWebViewWebKitEventHandlerUPP(),
430 GetEventTypeCount(eventList), eventList, this,
431 (EventHandlerRef *)&m_webKitCtrlEventHandler);
433 NSRect r = wxOSXGetFrameForControl( this, pos , size ) ;
434 m_webView = [[WebView alloc] initWithFrame:r
435 frameName:@"webkitFrame"
436 groupName:@"webkitGroup"];
437 m_peer = new wxWidgetCocoaImpl( this, m_webView );
440 wx_webviewctrls[m_webView] = this;
442 MacPostControlCreate(pos, size);
445 HIViewSetVisible( m_peer->GetControlRef(), true );
447 [m_webView setHidden:false];
451 // Register event listener interfaces
452 MyFrameLoadMonitor* myFrameLoadMonitor =
453 [[MyFrameLoadMonitor alloc] initWithWxWindow: this];
455 [m_webView setFrameLoadDelegate:myFrameLoadMonitor];
457 // this is used to veto page loads, etc.
458 MyPolicyDelegate* myPolicyDelegate =
459 [[MyPolicyDelegate alloc] initWithWxWindow: this];
461 [m_webView setPolicyDelegate:myPolicyDelegate];
463 InternalLoadURL(strURL);
467 wxWebViewWebKit::~wxWebViewWebKit()
469 MyFrameLoadMonitor* myFrameLoadMonitor = [m_webView frameLoadDelegate];
470 MyPolicyDelegate* myPolicyDelegate = [m_webView policyDelegate];
471 [m_webView setFrameLoadDelegate: nil];
472 [m_webView setPolicyDelegate: nil];
474 if (myFrameLoadMonitor)
475 [myFrameLoadMonitor release];
477 if (myPolicyDelegate)
478 [myPolicyDelegate release];
481 // ----------------------------------------------------------------------------
483 // ----------------------------------------------------------------------------
485 void wxWebViewWebKit::InternalLoadURL(const wxString &url)
490 [[m_webView mainFrame] loadRequest:[NSURLRequest requestWithURL:
491 [NSURL URLWithString:wxNSStringWithWxString(url)]]];
494 bool wxWebViewWebKit::CanGoBack()
499 return [m_webView canGoBack];
502 bool wxWebViewWebKit::CanGoForward()
507 return [m_webView canGoForward];
510 void wxWebViewWebKit::GoBack()
515 bool result = [(WebView*)m_webView goBack];
517 // TODO: return result (if it also exists in other backends...)
521 void wxWebViewWebKit::GoForward()
526 bool result = [(WebView*)m_webView goForward];
528 // TODO: return result (if it also exists in other backends...)
532 void wxWebViewWebKit::Reload(wxWebViewReloadFlags flags)
537 if (flags & wxWEB_VIEW_RELOAD_NO_CACHE)
539 // TODO: test this indeed bypasses the cache
540 [[m_webView preferences] setUsesPageCache:NO];
541 [[m_webView mainFrame] reload];
542 [[m_webView preferences] setUsesPageCache:YES];
546 [[m_webView mainFrame] reload];
550 void wxWebViewWebKit::Stop()
555 [[m_webView mainFrame] stopLoading];
558 bool wxWebViewWebKit::CanGetPageSource()
563 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
564 return ( [[dataSource representation] canProvideDocumentSource] );
567 wxString wxWebViewWebKit::GetPageSource()
570 if (CanGetPageSource())
572 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
573 wxASSERT (dataSource != nil);
575 id<WebDocumentRepresentation> representation = [dataSource representation];
576 wxASSERT (representation != nil);
578 NSString* source = [representation documentSource];
581 return wxEmptyString;
584 return wxStringWithNSString( source );
587 return wxEmptyString;
590 wxString wxWebViewWebKit::GetSelection()
593 return wxEmptyString;
595 NSString* selectedText = [[m_webView selectedDOMRange] toString];
596 return wxStringWithNSString( selectedText );
599 bool wxWebViewWebKit::CanIncreaseTextSize()
604 if ([m_webView canMakeTextLarger])
610 void wxWebViewWebKit::IncreaseTextSize()
615 if (CanIncreaseTextSize())
616 [m_webView makeTextLarger:(WebView*)m_webView];
619 bool wxWebViewWebKit::CanDecreaseTextSize()
624 if ([m_webView canMakeTextSmaller])
630 void wxWebViewWebKit::DecreaseTextSize()
635 if (CanDecreaseTextSize())
636 [m_webView makeTextSmaller:(WebView*)m_webView];
639 void wxWebViewWebKit::Print()
642 // TODO: allow specifying the "show prompt" parameter in Print() ?
643 bool showPrompt = true;
648 id view = [[[m_webView mainFrame] frameView] documentView];
649 NSPrintOperation *op = [NSPrintOperation printOperationWithView:view
650 printInfo: [NSPrintInfo sharedPrintInfo]];
653 [op setShowsPrintPanel: showPrompt];
654 // in my tests, the progress bar always freezes and it stops the whole
655 // print operation. do not turn this to true unless there is a
656 // workaround for the bug.
657 [op setShowsProgressPanel: false];
663 void wxWebViewWebKit::SetEditable(bool enable)
668 [m_webView setEditable:enable ];
671 bool wxWebViewWebKit::IsEditable()
676 return [m_webView isEditable];
679 void wxWebViewWebKit::SetZoomType(wxWebViewZoomType zoomType)
681 // there is only one supported zoom type at the moment so this setter
682 // does nothing beyond checking sanity
683 wxASSERT(zoomType == wxWEB_VIEW_ZOOM_TYPE_TEXT);
686 wxWebViewZoomType wxWebViewWebKit::GetZoomType() const
688 // for now that's the only one that is supported
689 // FIXME: does the default zoom type change depending on webkit versions? :S
690 // Then this will be wrong
691 return wxWEB_VIEW_ZOOM_TYPE_TEXT;
694 bool wxWebViewWebKit::CanSetZoomType(wxWebViewZoomType type) const
698 // for now that's the only one that is supported
699 // TODO: I know recent versions of webkit support layout zoom too,
700 // check if we can support it
701 case wxWEB_VIEW_ZOOM_TYPE_TEXT:
709 int wxWebViewWebKit::GetScrollPos()
711 id result = [[m_webView windowScriptObject]
712 evaluateWebScript:@"document.body.scrollTop"];
713 return [result intValue];
716 void wxWebViewWebKit::SetScrollPos(int pos)
722 javascript.Printf(wxT("document.body.scrollTop = %d;"), pos);
723 [[m_webView windowScriptObject] evaluateWebScript:
724 (NSString*)wxNSStringWithWxString( javascript )];
727 wxString wxWebViewWebKit::GetSelectedText()
729 NSString* selection = [[m_webView selectedDOMRange] markupString];
730 if (!selection) return wxEmptyString;
732 return wxStringWithNSString(selection);
735 wxString wxWebViewWebKit::RunScript(const wxString& javascript)
738 return wxEmptyString;
740 id result = [[m_webView windowScriptObject] evaluateWebScript:
741 (NSString*)wxNSStringWithWxString( javascript )];
743 NSString* resultAsString;
744 NSString* className = NSStringFromClass([result class]);
746 if ([className isEqualToString:@"NSCFNumber"])
748 resultAsString = [NSString stringWithFormat:@"%@", result];
750 else if ([className isEqualToString:@"NSCFString"])
752 resultAsString = result;
754 else if ([className isEqualToString:@"NSCFBoolean"])
756 if ([result boolValue])
757 resultAsString = @"true";
759 resultAsString = @"false";
761 else if ([className isEqualToString:@"WebScriptObject"])
763 resultAsString = [result stringRepresentation];
770 return wxStringWithNSString( resultAsString );
773 void wxWebViewWebKit::OnSize(wxSizeEvent &event)
775 #if defined(__WXMAC_) && wxOSX_USE_CARBON
776 // This is a nasty hack because WebKit seems to lose its position when it is
777 // embedded in a control that is not itself the content view for a TLW.
778 // I put it in OnSize because these calcs are not perfect, and in fact are
779 // basically guesses based on reverse engineering, so it's best to give
780 // people the option of overriding OnSize with their own calcs if need be.
781 // I also left some test debugging print statements as a convenience if
782 // a(nother) problem crops up.
784 wxWindow* tlw = MacGetTopLevelWindow();
786 NSRect frame = [(WebView*)m_webView frame];
787 NSRect bounds = [(WebView*)m_webView bounds];
789 #if DEBUG_WEBKIT_SIZING
790 fprintf(stderr,"Carbon window x=%d, y=%d, width=%d, height=%d\n",
791 GetPosition().x, GetPosition().y, GetSize().x, GetSize().y);
792 fprintf(stderr, "Cocoa window frame x=%G, y=%G, width=%G, height=%G\n",
793 frame.origin.x, frame.origin.y,
794 frame.size.width, frame.size.height);
795 fprintf(stderr, "Cocoa window bounds x=%G, y=%G, width=%G, height=%G\n",
796 bounds.origin.x, bounds.origin.y,
797 bounds.size.width, bounds.size.height);
800 // This must be the case that Apple tested with, because well, in this one case
801 // we don't need to do anything! It just works. ;)
802 if (GetParent() == tlw) return;
804 // since we no longer use parent coordinates, we always want 0,0.
812 #if DEBUG_WEBKIT_SIZING
813 printf("Before conversion, origin is: x = %d, y = %d\n", x, y);
816 // NB: In most cases, when calling HIViewConvertRect, what people want is to
817 // use GetRootControl(), and this tripped me up at first. But in fact, what
818 // we want is the root view, because we need to make the y origin relative
819 // to the very top of the window, not its contents, since we later flip
820 // the y coordinate for Cocoa.
821 HIViewConvertRect (&rect, m_peer->GetControlRef(),
823 (WindowRef) MacGetTopLevelWindowRef()
826 x = (int)rect.origin.x;
827 y = (int)rect.origin.y;
829 #if DEBUG_WEBKIT_SIZING
830 printf("Moving Cocoa frame origin to: x = %d, y = %d\n", x, y);
834 //flip the y coordinate to convert to Cocoa coordinates
835 y = tlw->GetSize().y - ((GetSize().y) + y);
838 #if DEBUG_WEBKIT_SIZING
839 printf("y = %d after flipping value\n", y);
844 [(WebView*)m_webView setFrame:frame];
847 [(WebView*)m_webView display];
852 void wxWebViewWebKit::MacVisibilityChanged(){
853 #if defined(__WXMAC__) && wxOSX_USE_CARBON
854 bool isHidden = !IsControlVisible( m_peer->GetControlRef());
856 [(WebView*)m_webView display];
858 [m_webView setHidden:isHidden];
862 void wxWebViewWebKit::LoadUrl(const wxString& url)
864 InternalLoadURL(url);
867 wxString wxWebViewWebKit::GetCurrentURL()
869 return wxStringWithNSString([m_webView mainFrameURL]);
872 wxString wxWebViewWebKit::GetCurrentTitle()
874 return GetPageTitle();
877 float wxWebViewWebKit::GetWebkitZoom()
879 return [m_webView textSizeMultiplier];
882 void wxWebViewWebKit::SetWebkitZoom(float zoom)
884 [m_webView setTextSizeMultiplier:zoom];
887 wxWebViewZoom wxWebViewWebKit::GetZoom()
889 float zoom = GetWebkitZoom();
891 // arbitrary way to map float zoom to our common zoom enum
894 return wxWEB_VIEW_ZOOM_TINY;
896 else if (zoom > 0.55 && zoom <= 0.85)
898 return wxWEB_VIEW_ZOOM_SMALL;
900 else if (zoom > 0.85 && zoom <= 1.15)
902 return wxWEB_VIEW_ZOOM_MEDIUM;
904 else if (zoom > 1.15 && zoom <= 1.45)
906 return wxWEB_VIEW_ZOOM_LARGE;
908 else if (zoom > 1.45)
910 return wxWEB_VIEW_ZOOM_LARGEST;
913 // to shut up compilers, this can never be reached logically
915 return wxWEB_VIEW_ZOOM_MEDIUM;
918 void wxWebViewWebKit::SetZoom(wxWebViewZoom zoom)
920 // arbitrary way to map our common zoom enum to float zoom
923 case wxWEB_VIEW_ZOOM_TINY:
927 case wxWEB_VIEW_ZOOM_SMALL:
931 case wxWEB_VIEW_ZOOM_MEDIUM:
935 case wxWEB_VIEW_ZOOM_LARGE:
939 case wxWEB_VIEW_ZOOM_LARGEST:
949 void wxWebViewWebKit::SetPage(const wxString& src, const wxString& baseUrl)
954 [[m_webView mainFrame] loadHTMLString:(NSString*)wxNSStringWithWxString(src)
955 baseURL:[NSURL URLWithString:
956 wxNSStringWithWxString( baseUrl )]];
959 void wxWebViewWebKit::Cut()
964 [(WebView*)m_webView cut];
967 void wxWebViewWebKit::Copy()
972 [(WebView*)m_webView copy];
975 void wxWebViewWebKit::Paste()
980 [(WebView*)m_webView paste];
983 void wxWebViewWebKit::DeleteSelection()
988 [(WebView*)m_webView deleteSelection];
991 //------------------------------------------------------------
992 // Listener interfaces
993 //------------------------------------------------------------
995 // NB: I'm still tracking this down, but it appears the Cocoa window
996 // still has these events fired on it while the Carbon control is being
997 // destroyed. Therefore, we must be careful to check both the existence
998 // of the Carbon control and the event handler before firing events.
1000 @implementation MyFrameLoadMonitor
1002 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1005 webKitWindow = inWindow; // non retained
1009 - (void)webView:(WebView *)sender
1010 didStartProvisionalLoadForFrame:(WebFrame *)frame
1012 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1013 wx_webviewctrls[sender]->m_busy = true;
1016 - (void)webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame
1018 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1019 wx_webviewctrls[sender]->m_busy = true;
1021 if (webKitWindow && frame == [sender mainFrame]){
1022 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1023 wxString target = wxStringWithNSString([frame name]);
1024 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATED,
1025 wx_webviewctrls[sender]->GetId(),
1026 wxStringWithNSString( url ),
1029 if (webKitWindow && webKitWindow->GetEventHandler())
1030 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1034 - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
1036 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1037 wx_webviewctrls[sender]->m_busy = false;
1039 if (webKitWindow && frame == [sender mainFrame]){
1040 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1042 wxString target = wxStringWithNSString([frame name]);
1043 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_LOADED,
1044 wx_webviewctrls[sender]->GetId(),
1045 wxStringWithNSString( url ),
1048 if (webKitWindow && webKitWindow->GetEventHandler())
1049 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1053 wxString nsErrorToWxHtmlError(NSError* error, wxWebNavigationError* out)
1055 *out = wxWEB_NAV_ERR_OTHER;
1057 if ([[error domain] isEqualToString:NSURLErrorDomain])
1059 switch ([error code])
1061 case NSURLErrorCannotFindHost:
1062 case NSURLErrorFileDoesNotExist:
1063 case NSURLErrorRedirectToNonExistentLocation:
1064 *out = wxWEB_NAV_ERR_NOT_FOUND;
1067 case NSURLErrorResourceUnavailable:
1068 case NSURLErrorHTTPTooManyRedirects:
1069 case NSURLErrorDataLengthExceedsMaximum:
1070 case NSURLErrorBadURL:
1071 case NSURLErrorFileIsDirectory:
1072 *out = wxWEB_NAV_ERR_REQUEST;
1075 case NSURLErrorTimedOut:
1076 case NSURLErrorDNSLookupFailed:
1077 case NSURLErrorNetworkConnectionLost:
1078 case NSURLErrorCannotConnectToHost:
1079 case NSURLErrorNotConnectedToInternet:
1080 //case NSURLErrorInternationalRoamingOff:
1081 //case NSURLErrorCallIsActive:
1082 //case NSURLErrorDataNotAllowed:
1083 *out = wxWEB_NAV_ERR_CONNECTION;
1086 case NSURLErrorCancelled:
1087 case NSURLErrorUserCancelledAuthentication:
1088 *out = wxWEB_NAV_ERR_USER_CANCELLED;
1091 case NSURLErrorCannotDecodeRawData:
1092 case NSURLErrorCannotDecodeContentData:
1093 case NSURLErrorBadServerResponse:
1094 case NSURLErrorCannotParseResponse:
1095 *out = wxWEB_NAV_ERR_REQUEST;
1098 case NSURLErrorUserAuthenticationRequired:
1099 case NSURLErrorSecureConnectionFailed:
1100 case NSURLErrorClientCertificateRequired:
1101 *out = wxWEB_NAV_ERR_AUTH;
1104 case NSURLErrorNoPermissionsToReadFile:
1105 *out = wxWEB_NAV_ERR_SECURITY;
1108 case NSURLErrorServerCertificateHasBadDate:
1109 case NSURLErrorServerCertificateUntrusted:
1110 case NSURLErrorServerCertificateHasUnknownRoot:
1111 case NSURLErrorServerCertificateNotYetValid:
1112 case NSURLErrorClientCertificateRejected:
1113 *out = wxWEB_NAV_ERR_CERTIFICATE;
1118 wxString message = wxStringWithNSString([error localizedDescription]);
1119 NSString* detail = [error localizedFailureReason];
1122 message = message + " (" + wxStringWithNSString(detail) + ")";
1127 - (void)webView:(WebView *)sender didFailLoadWithError:(NSError*) error
1128 forFrame:(WebFrame *)frame
1130 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1131 wx_webviewctrls[sender]->m_busy = false;
1133 if (webKitWindow && frame == [sender mainFrame]){
1134 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1136 wxWebNavigationError type;
1137 wxString description = nsErrorToWxHtmlError(error, &type);
1138 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1139 wx_webviewctrls[sender]->GetId(),
1140 wxStringWithNSString( url ),
1141 wxEmptyString, false);
1142 thisEvent.SetString(description);
1143 thisEvent.SetInt(type);
1145 if (webKitWindow && webKitWindow->GetEventHandler())
1147 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1152 - (void)webView:(WebView *)sender
1153 didFailProvisionalLoadWithError:(NSError*)error
1154 forFrame:(WebFrame *)frame
1156 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1157 wx_webviewctrls[sender]->m_busy = false;
1159 if (webKitWindow && frame == [sender mainFrame]){
1160 NSString *url = [[[[frame provisionalDataSource] request] URL]
1163 wxWebNavigationError type;
1164 wxString description = nsErrorToWxHtmlError(error, &type);
1165 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1166 wx_webviewctrls[sender]->GetId(),
1167 wxStringWithNSString( url ),
1168 wxEmptyString, false);
1169 thisEvent.SetString(description);
1170 thisEvent.SetInt(type);
1172 if (webKitWindow && webKitWindow->GetEventHandler())
1173 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1177 - (void)webView:(WebView *)sender didReceiveTitle:(NSString *)title
1178 forFrame:(WebFrame *)frame
1180 if (webKitWindow && frame == [sender mainFrame])
1182 webKitWindow->SetPageTitle(wxStringWithNSString( title ));
1187 @implementation MyPolicyDelegate
1189 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1192 webKitWindow = inWindow; // non retained
1196 - (void)webView:(WebView *)sender
1197 decidePolicyForNavigationAction:(NSDictionary *)actionInformation
1198 request:(NSURLRequest *)request
1199 frame:(WebFrame *)frame
1200 decisionListener:(id<WebPolicyDecisionListener>)listener
1202 //wxUnusedVar(sender);
1205 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1206 wx_webviewctrls[sender]->m_busy = true;
1207 NSString *url = [[request URL] absoluteString];
1208 wxString target = wxStringWithNSString([frame name]);
1209 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATING,
1210 wx_webviewctrls[sender]->GetId(),
1211 wxStringWithNSString( url ), target, true);
1213 if (webKitWindow && webKitWindow->GetEventHandler())
1214 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1216 if (thisEvent.IsVetoed())
1218 wx_webviewctrls[sender]->m_busy = false;
1227 - (void)webView:(WebView *)sender
1228 decidePolicyForNewWindowAction:(NSDictionary *)actionInformation
1229 request:(NSURLRequest *)request
1230 newFrameName:(NSString *)frameName
1231 decisionListener:(id < WebPolicyDecisionListener >)listener
1233 wxUnusedVar(sender);
1234 wxUnusedVar(actionInformation);
1240 #endif //wxHAVE_WEB_BACKEND_OSX_WEBKIT