1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/osx/webkit.mm
3 // Purpose: wxOSXWebKitCtrl - 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.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*, wxOSXWebKitCtrl*> wx_webviewctrls;
42 #define DEBUG_WEBKIT_SIZING 0
44 // ----------------------------------------------------------------------------
46 // ----------------------------------------------------------------------------
48 IMPLEMENT_DYNAMIC_CLASS(wxOSXWebKitCtrl, wxControl)
50 BEGIN_EVENT_TABLE(wxOSXWebKitCtrl, wxControl)
51 #if defined(__WXMAC__) && wxOSX_USE_CARBON
52 EVT_SIZE(wxOSXWebKitCtrl::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 wxOSXWebKitCtrl* thisWindow = (wxOSXWebKitCtrl*) 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 wxOSXWebKitCtrlEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
234 OSStatus result = eventNotHandledErr ;
236 wxMacCarbonEvent cEvent( event ) ;
238 ControlRef controlRef ;
239 wxOSXWebKitCtrl* thisWindow = (wxOSXWebKitCtrl*) 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( wxOSXWebKitCtrlEventHandler )
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 wxOSXWebKitCtrl* webKitWindow;
350 - initWithWxWindow: (wxOSXWebKitCtrl*)inWindow;
354 @interface MyPolicyDelegate : NSObject
356 wxOSXWebKitCtrl* webKitWindow;
359 - initWithWxWindow: (wxOSXWebKitCtrl*)inWindow;
363 // ----------------------------------------------------------------------------
364 // creation/destruction
365 // ----------------------------------------------------------------------------
367 bool wxOSXWebKitCtrl::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 GetwxOSXWebKitCtrlEventHandlerUPP(),
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 wxOSXWebKitCtrl::~wxOSXWebKitCtrl()
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 wxOSXWebKitCtrl::InternalLoadURL(const wxString &url)
490 [[m_webView mainFrame] loadRequest:[NSURLRequest requestWithURL:
491 [NSURL URLWithString:wxNSStringWithWxString(url)]]];
494 bool wxOSXWebKitCtrl::CanGoBack()
499 return [m_webView canGoBack];
502 bool wxOSXWebKitCtrl::CanGoForward()
507 return [m_webView canGoForward];
510 void wxOSXWebKitCtrl::GoBack()
515 bool result = [(WebView*)m_webView goBack];
517 // TODO: return result (if it also exists in other backends...)
521 void wxOSXWebKitCtrl::GoForward()
526 bool result = [(WebView*)m_webView goForward];
528 // TODO: return result (if it also exists in other backends...)
532 void wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::Stop()
555 [[m_webView mainFrame] stopLoading];
558 bool wxOSXWebKitCtrl::CanGetPageSource()
563 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
564 return ( [[dataSource representation] canProvideDocumentSource] );
567 wxString wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::GetSelection()
593 return wxEmptyString;
595 NSString* selectedText = [[m_webView selectedDOMRange] toString];
596 return wxStringWithNSString( selectedText );
599 bool wxOSXWebKitCtrl::CanIncreaseTextSize()
604 if ([m_webView canMakeTextLarger])
610 void wxOSXWebKitCtrl::IncreaseTextSize()
615 if (CanIncreaseTextSize())
616 [m_webView makeTextLarger:(WebView*)m_webView];
619 bool wxOSXWebKitCtrl::CanDecreaseTextSize()
624 if ([m_webView canMakeTextSmaller])
630 void wxOSXWebKitCtrl::DecreaseTextSize()
635 if (CanDecreaseTextSize())
636 [m_webView makeTextSmaller:(WebView*)m_webView];
639 void wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::MakeEditable(bool enable)
668 [m_webView setEditable:enable ];
671 bool wxOSXWebKitCtrl::IsEditable()
676 return [m_webView isEditable];
679 void wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::GetScrollPos()
711 id result = [[m_webView windowScriptObject]
712 evaluateWebScript:@"document.body.scrollTop"];
713 return [result intValue];
716 void wxOSXWebKitCtrl::SetScrollPos(int pos)
722 javascript.Printf(wxT("document.body.scrollTop = %d;"), pos);
723 [[m_webView windowScriptObject] evaluateWebScript:
724 (NSString*)wxNSStringWithWxString( javascript )];
727 wxString wxOSXWebKitCtrl::GetSelectedText()
729 NSString* selection = [[m_webView selectedDOMRange] markupString];
730 if (!selection) return wxEmptyString;
732 return wxStringWithNSString(selection);
735 wxString wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::LoadUrl(const wxString& url)
864 InternalLoadURL(url);
867 wxString wxOSXWebKitCtrl::GetCurrentURL()
869 return wxStringWithNSString([m_webView mainFrameURL]);
872 wxString wxOSXWebKitCtrl::GetCurrentTitle()
874 return GetPageTitle();
877 float wxOSXWebKitCtrl::GetWebkitZoom()
879 return [m_webView textSizeMultiplier];
882 void wxOSXWebKitCtrl::SetWebkitZoom(float zoom)
884 [m_webView setTextSizeMultiplier:zoom];
887 wxWebViewZoom wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::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 wxOSXWebKitCtrl::SetPage(const wxString& src, const wxString& baseUrl)
954 [[m_webView mainFrame] loadHTMLString:(NSString*)wxNSStringWithWxString(src)
955 baseURL:[NSURL URLWithString:
956 wxNSStringWithWxString( baseUrl )]];
959 //------------------------------------------------------------
960 // Listener interfaces
961 //------------------------------------------------------------
963 // NB: I'm still tracking this down, but it appears the Cocoa window
964 // still has these events fired on it while the Carbon control is being
965 // destroyed. Therefore, we must be careful to check both the existence
966 // of the Carbon control and the event handler before firing events.
968 @implementation MyFrameLoadMonitor
970 - initWithWxWindow: (wxOSXWebKitCtrl*)inWindow
973 webKitWindow = inWindow; // non retained
977 - (void)webView:(WebView *)sender
978 didStartProvisionalLoadForFrame:(WebFrame *)frame
980 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
981 wx_webviewctrls[sender]->m_busy = true;
984 - (void)webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame
986 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
987 wx_webviewctrls[sender]->m_busy = true;
989 if (webKitWindow && frame == [sender mainFrame]){
990 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
991 wxString target = wxStringWithNSString([frame name]);
992 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATED,
993 wx_webviewctrls[sender]->GetId(),
994 wxStringWithNSString( url ),
997 if (webKitWindow && webKitWindow->GetEventHandler())
998 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1002 - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
1004 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1005 wx_webviewctrls[sender]->m_busy = false;
1007 if (webKitWindow && frame == [sender mainFrame]){
1008 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1010 wxString target = wxStringWithNSString([frame name]);
1011 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_LOADED,
1012 wx_webviewctrls[sender]->GetId(),
1013 wxStringWithNSString( url ),
1016 if (webKitWindow && webKitWindow->GetEventHandler())
1017 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1021 wxString nsErrorToWxHtmlError(NSError* error, wxWebNavigationError* out)
1023 *out = wxWEB_NAV_ERR_OTHER;
1025 if ([[error domain] isEqualToString:NSURLErrorDomain])
1027 switch ([error code])
1029 case NSURLErrorCannotFindHost:
1030 case NSURLErrorFileDoesNotExist:
1031 case NSURLErrorRedirectToNonExistentLocation:
1032 *out = wxWEB_NAV_ERR_NOT_FOUND;
1035 case NSURLErrorResourceUnavailable:
1036 case NSURLErrorHTTPTooManyRedirects:
1037 case NSURLErrorDataLengthExceedsMaximum:
1038 case NSURLErrorBadURL:
1039 case NSURLErrorFileIsDirectory:
1040 *out = wxWEB_NAV_ERR_REQUEST;
1043 case NSURLErrorTimedOut:
1044 case NSURLErrorDNSLookupFailed:
1045 case NSURLErrorNetworkConnectionLost:
1046 case NSURLErrorCannotConnectToHost:
1047 case NSURLErrorNotConnectedToInternet:
1048 //case NSURLErrorInternationalRoamingOff:
1049 //case NSURLErrorCallIsActive:
1050 //case NSURLErrorDataNotAllowed:
1051 *out = wxWEB_NAV_ERR_CONNECTION;
1054 case NSURLErrorCancelled:
1055 case NSURLErrorUserCancelledAuthentication:
1056 *out = wxWEB_NAV_ERR_USER_CANCELLED;
1059 case NSURLErrorCannotDecodeRawData:
1060 case NSURLErrorCannotDecodeContentData:
1061 case NSURLErrorBadServerResponse:
1062 case NSURLErrorCannotParseResponse:
1063 *out = wxWEB_NAV_ERR_REQUEST;
1066 case NSURLErrorUserAuthenticationRequired:
1067 case NSURLErrorSecureConnectionFailed:
1068 case NSURLErrorClientCertificateRequired:
1069 *out = wxWEB_NAV_ERR_AUTH;
1072 case NSURLErrorNoPermissionsToReadFile:
1073 *out = wxWEB_NAV_ERR_SECURITY;
1076 case NSURLErrorServerCertificateHasBadDate:
1077 case NSURLErrorServerCertificateUntrusted:
1078 case NSURLErrorServerCertificateHasUnknownRoot:
1079 case NSURLErrorServerCertificateNotYetValid:
1080 case NSURLErrorClientCertificateRejected:
1081 *out = wxWEB_NAV_ERR_CERTIFICATE;
1086 wxString message = wxStringWithNSString([error localizedDescription]);
1087 NSString* detail = [error localizedFailureReason];
1090 message = message + " (" + wxStringWithNSString(detail) + ")";
1095 - (void)webView:(WebView *)sender didFailLoadWithError:(NSError*) error
1096 forFrame:(WebFrame *)frame
1098 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1099 wx_webviewctrls[sender]->m_busy = false;
1101 if (webKitWindow && frame == [sender mainFrame]){
1102 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1104 wxWebNavigationError type;
1105 wxString description = nsErrorToWxHtmlError(error, &type);
1106 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1107 wx_webviewctrls[sender]->GetId(),
1108 wxStringWithNSString( url ),
1109 wxEmptyString, false);
1110 thisEvent.SetString(description);
1111 thisEvent.SetInt(type);
1113 if (webKitWindow && webKitWindow->GetEventHandler())
1115 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1120 - (void)webView:(WebView *)sender
1121 didFailProvisionalLoadWithError:(NSError*)error
1122 forFrame:(WebFrame *)frame
1124 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1125 wx_webviewctrls[sender]->m_busy = false;
1127 if (webKitWindow && frame == [sender mainFrame]){
1128 NSString *url = [[[[frame provisionalDataSource] request] URL]
1131 wxWebNavigationError type;
1132 wxString description = nsErrorToWxHtmlError(error, &type);
1133 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1134 wx_webviewctrls[sender]->GetId(),
1135 wxStringWithNSString( url ),
1136 wxEmptyString, false);
1137 thisEvent.SetString(description);
1138 thisEvent.SetInt(type);
1140 if (webKitWindow && webKitWindow->GetEventHandler())
1141 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1145 - (void)webView:(WebView *)sender didReceiveTitle:(NSString *)title
1146 forFrame:(WebFrame *)frame
1148 if (webKitWindow && frame == [sender mainFrame])
1150 webKitWindow->SetPageTitle(wxStringWithNSString( title ));
1155 @implementation MyPolicyDelegate
1157 - initWithWxWindow: (wxOSXWebKitCtrl*)inWindow
1160 webKitWindow = inWindow; // non retained
1164 - (void)webView:(WebView *)sender
1165 decidePolicyForNavigationAction:(NSDictionary *)actionInformation
1166 request:(NSURLRequest *)request
1167 frame:(WebFrame *)frame
1168 decisionListener:(id<WebPolicyDecisionListener>)listener
1170 //wxUnusedVar(sender);
1173 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1174 wx_webviewctrls[sender]->m_busy = true;
1175 NSString *url = [[request URL] absoluteString];
1176 wxString target = wxStringWithNSString([frame name]);
1177 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATING,
1178 wx_webviewctrls[sender]->GetId(),
1179 wxStringWithNSString( url ), target, true);
1181 if (webKitWindow && webKitWindow->GetEventHandler())
1182 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1184 if (thisEvent.IsVetoed())
1186 wx_webviewctrls[sender]->m_busy = false;
1195 - (void)webView:(WebView *)sender
1196 decidePolicyForNewWindowAction:(NSDictionary *)actionInformation
1197 request:(NSURLRequest *)request
1198 newFrameName:(NSString *)frameName
1199 decisionListener:(id < WebPolicyDecisionListener >)listener
1201 wxUnusedVar(sender);
1202 wxUnusedVar(actionInformation);
1208 #endif //wxHAVE_WEB_BACKEND_OSX_WEBKIT