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_WEBKIT && (defined(__WXOSX_COCOA__) \
18 || defined(__WXOSX_CARBON__))
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
28 #include "wx/cocoa/autorelease.h"
30 #include "wx/osx/private.h"
32 #include <WebKit/WebKit.h>
33 #include <WebKit/HIWebView.h>
34 #include <WebKit/CarbonUtils.h>
37 #include <Foundation/NSURLError.h>
39 // FIXME: find cleaner way to find the wxWidgets ID of a webview than this hack
41 std::map<WebView*, wxWebViewWebKit*> wx_webviewctrls;
43 #define DEBUG_WEBKIT_SIZING 0
45 // ----------------------------------------------------------------------------
47 // ----------------------------------------------------------------------------
49 wxIMPLEMENT_DYNAMIC_CLASS(wxWebViewWebKit, wxWebView);
51 BEGIN_EVENT_TABLE(wxWebViewWebKit, wxControl)
52 #if defined(__WXMAC__) && wxOSX_USE_CARBON
53 EVT_SIZE(wxWebViewWebKit::OnSize)
57 #if defined(__WXOSX__) && wxOSX_USE_CARBON
59 // ----------------------------------------------------------------------------
60 // Carbon Events handlers
61 // ----------------------------------------------------------------------------
63 // prototype for function in src/osx/carbon/nonownedwnd.cpp
64 void SetupMouseEvent( wxMouseEvent &wxevent , wxMacCarbonEvent &cEvent );
66 static const EventTypeSpec eventList[] =
68 //{ kEventClassControl, kEventControlTrack } ,
69 { kEventClassMouse, kEventMouseUp },
70 { kEventClassMouse, kEventMouseDown },
71 { kEventClassMouse, kEventMouseMoved },
72 { kEventClassMouse, kEventMouseDragged },
74 { kEventClassKeyboard, kEventRawKeyDown } ,
75 { kEventClassKeyboard, kEventRawKeyRepeat } ,
76 { kEventClassKeyboard, kEventRawKeyUp } ,
77 { kEventClassKeyboard, kEventRawKeyModifiersChanged } ,
79 { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent } ,
80 { kEventClassTextInput, kEventTextInputUpdateActiveInputArea } ,
82 #if DEBUG_WEBKIT_SIZING == 1
83 { kEventClassControl, kEventControlBoundsChanged } ,
87 // mix this in from window.cpp
88 pascal OSStatus wxMacUnicodeTextEventHandler(EventHandlerCallRef handler,
89 EventRef event, void *data) ;
91 // NOTE: This is mostly taken from KeyboardEventHandler in toplevel.cpp, but
92 // that expects the data pointer is a top-level window, so I needed to change
93 // that in this case. However, once 2.8 is out, we should factor out the common
94 // logic among the two functions and merge them.
95 static pascal OSStatus wxWebKitKeyEventHandler(EventHandlerCallRef handler,
96 EventRef event, void *data)
98 OSStatus result = eventNotHandledErr ;
99 wxMacCarbonEvent cEvent( event ) ;
101 wxWebViewWebKit* thisWindow = (wxWebViewWebKit*) data ;
102 wxWindow* focus = thisWindow ;
104 unsigned char charCode ;
112 UInt32 when = EventTimeToTicks( GetEventTime( event ) ) ;
115 ByteCount dataSize = 0 ;
116 if ( GetEventParameter(event, kEventParamKeyUnicodes, typeUnicodeText,
117 NULL, 0 , &dataSize, NULL ) == noErr)
120 int numChars = dataSize / sizeof( UniChar) + 1;
122 UniChar* charBuf = buf ;
124 if ( numChars * 2 > 4 )
125 charBuf = new UniChar[ numChars ] ;
126 GetEventParameter(event, kEventParamKeyUnicodes, typeUnicodeText, NULL,
127 dataSize , NULL , charBuf) ;
128 charBuf[ numChars - 1 ] = 0;
130 #if SIZEOF_WCHAR_T == 2
131 uniChar = charBuf[0] ;
133 wxMBConvUTF16 converter ;
134 converter.MB2WC( uniChar , (const char*)charBuf , 2 ) ;
137 if ( numChars * 2 > 4 )
142 GetEventParameter(event, kEventParamKeyMacCharCodes, typeChar, NULL,
143 sizeof(char), NULL, &charCode );
144 GetEventParameter(event, kEventParamKeyCode, typeUInt32, NULL,
145 sizeof(UInt32), NULL, &keyCode );
146 GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, NULL,
147 sizeof(UInt32), NULL, &modifiers );
148 GetEventParameter(event, kEventParamMouseLocation, typeQDPoint, NULL,
149 sizeof(Point), NULL, &point );
151 UInt32 message = (keyCode << 8) + charCode;
152 switch ( GetEventKind( event ) )
154 case kEventRawKeyRepeat :
155 case kEventRawKeyDown :
157 WXEVENTREF formerEvent = wxTheApp->MacGetCurrentEvent() ;
158 WXEVENTHANDLERCALLREF formerHandler =
159 wxTheApp->MacGetCurrentEventHandlerCallRef() ;
161 wxTheApp->MacSetCurrentEvent( event , handler ) ;
162 if ( /* focus && */ wxTheApp->MacSendKeyDownEvent(
163 focus, message, modifiers, when, point.h, point.v, uniChar[0]))
167 wxTheApp->MacSetCurrentEvent( formerEvent , formerHandler ) ;
171 case kEventRawKeyUp :
172 if ( /* focus && */ wxTheApp->MacSendKeyUpEvent(
173 focus , message , modifiers , when , point.h , point.v , uniChar[0] ) )
179 case kEventRawKeyModifiersChanged :
181 wxKeyEvent event(wxEVT_KEY_DOWN);
183 event.m_shiftDown = modifiers & shiftKey;
184 event.m_controlDown = modifiers & controlKey;
185 event.m_altDown = modifiers & optionKey;
186 event.m_metaDown = modifiers & cmdKey;
191 event.m_uniChar = uniChar[0] ;
194 event.SetTimestamp(when);
195 event.SetEventObject(focus);
197 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & controlKey )
199 event.m_keyCode = WXK_CONTROL ;
200 event.SetEventType( ( modifiers & controlKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
201 focus->GetEventHandler()->ProcessEvent( event ) ;
203 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & shiftKey )
205 event.m_keyCode = WXK_SHIFT ;
206 event.SetEventType( ( modifiers & shiftKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
207 focus->GetEventHandler()->ProcessEvent( event ) ;
209 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & optionKey )
211 event.m_keyCode = WXK_ALT ;
212 event.SetEventType( ( modifiers & optionKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
213 focus->GetEventHandler()->ProcessEvent( event ) ;
215 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & cmdKey )
217 event.m_keyCode = WXK_COMMAND ;
218 event.SetEventType( ( modifiers & cmdKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
219 focus->GetEventHandler()->ProcessEvent( event ) ;
222 wxApp::s_lastModifiers = modifiers ;
233 static pascal OSStatus wxWebViewWebKitEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
235 OSStatus result = eventNotHandledErr ;
237 wxMacCarbonEvent cEvent( event ) ;
239 ControlRef controlRef ;
240 wxWebViewWebKit* thisWindow = (wxWebViewWebKit*) data ;
241 wxNonOwnedWindow* tlw = NULL;
243 tlw = thisWindow->MacGetTopLevelWindow();
245 cEvent.GetParameter( kEventParamDirectObject , &controlRef ) ;
247 wxWindow* currentMouseWindow = thisWindow ;
249 if ( wxApp::s_captureWindow )
250 currentMouseWindow = wxApp::s_captureWindow;
252 switch ( GetEventClass( event ) )
254 case kEventClassKeyboard:
256 result = wxWebKitKeyEventHandler(handler, event, data);
260 case kEventClassTextInput:
262 result = wxMacUnicodeTextEventHandler(handler, event, data);
266 case kEventClassMouse:
268 switch ( GetEventKind( event ) )
270 case kEventMouseDragged :
271 case kEventMouseMoved :
272 case kEventMouseDown :
275 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
276 SetupMouseEvent( wxevent , cEvent ) ;
278 currentMouseWindow->ScreenToClient( &wxevent.m_x , &wxevent.m_y ) ;
279 wxevent.SetEventObject( currentMouseWindow ) ;
280 wxevent.SetId( currentMouseWindow->GetId() ) ;
282 if ( currentMouseWindow->GetEventHandler()->ProcessEvent(wxevent) )
287 break; // this should enable WebKit to fire mouse dragged and mouse up events...
297 result = CallNextEventHandler(handler, event);
301 DEFINE_ONE_SHOT_HANDLER_GETTER( wxWebViewWebKitEventHandler )
305 //---------------------------------------------------------
306 // helper functions for NSString<->wxString conversion
307 //---------------------------------------------------------
309 inline wxString wxStringWithNSString(NSString *nsstring)
312 return wxString([nsstring UTF8String], wxConvUTF8);
314 return wxString([nsstring lossyCString]);
315 #endif // wxUSE_UNICODE
318 inline NSString* wxNSStringWithWxString(const wxString &wxstring)
321 return [NSString stringWithUTF8String: wxstring.mb_str(wxConvUTF8)];
323 return [NSString stringWithCString: wxstring.c_str() length:wxstring.Len()];
324 #endif // wxUSE_UNICODE
327 @interface MyFrameLoadMonitor : NSObject
329 wxWebViewWebKit* webKitWindow;
332 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
336 @interface MyPolicyDelegate : NSObject
338 wxWebViewWebKit* webKitWindow;
341 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
345 // ----------------------------------------------------------------------------
346 // creation/destruction
347 // ----------------------------------------------------------------------------
349 bool wxWebViewWebKit::Create(wxWindow *parent,
351 const wxString& strURL,
353 const wxSize& size, long style,
354 const wxString& name)
357 //m_pageTitle = _("Untitled Page");
359 //still needed for wxCocoa??
363 if (size.x == wxDefaultCoord || size.y == wxDefaultCoord)
365 m_parent->GetClientSize(&width, &height);
366 sizeInstance.x = width;
367 sizeInstance.y = height;
371 sizeInstance.x = size.x;
372 sizeInstance.y = size.y;
375 // now create and attach WebKit view...
377 wxControl::Create(parent, m_windowID, pos, sizeInstance, style, name);
378 SetSize(pos.x, pos.y, sizeInstance.x, sizeInstance.y);
380 wxTopLevelWindowCocoa *topWin = wxDynamicCast(this, wxTopLevelWindowCocoa);
381 NSWindow* nsWin = topWin->GetNSWindow();
383 rect.origin.x = pos.x;
384 rect.origin.y = pos.y;
385 rect.size.width = sizeInstance.x;
386 rect.size.height = sizeInstance.y;
387 m_webView = (WebView*)[[WebView alloc] initWithFrame:rect
388 frameName:@"webkitFrame"
389 groupName:@"webkitGroup"];
390 SetNSView(m_webView);
391 [m_cocoaNSView release];
393 if(m_parent) m_parent->CocoaAddChild(this);
394 SetInitialFrameRect(pos,sizeInstance);
396 wxControl::Create(parent, winID, pos, size, style, wxDefaultValidator, name);
399 m_peer = new wxMacControl(this);
401 HIWebViewCreate( m_peer->GetControlRefAddr() );
403 m_webView = (WebView*) HIWebViewGetWebView( m_peer->GetControlRef() );
405 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_3
406 if ( UMAGetSystemVersion() >= 0x1030 )
407 HIViewChangeFeatures( m_peer->GetControlRef() , kHIViewIsOpaque , 0 ) ;
409 InstallControlEventHandler(m_peer->GetControlRef(),
410 GetwxWebViewWebKitEventHandlerUPP(),
411 GetEventTypeCount(eventList), eventList, this,
412 (EventHandlerRef *)&m_webKitCtrlEventHandler);
414 NSRect r = wxOSXGetFrameForControl( this, pos , size ) ;
415 m_webView = [[WebView alloc] initWithFrame:r
416 frameName:@"webkitFrame"
417 groupName:@"webkitGroup"];
418 m_peer = new wxWidgetCocoaImpl( this, m_webView );
421 wx_webviewctrls[m_webView] = this;
423 MacPostControlCreate(pos, size);
426 HIViewSetVisible( m_peer->GetControlRef(), true );
428 [m_webView setHidden:false];
432 // Register event listener interfaces
433 MyFrameLoadMonitor* myFrameLoadMonitor =
434 [[MyFrameLoadMonitor alloc] initWithWxWindow: this];
436 [m_webView setFrameLoadDelegate:myFrameLoadMonitor];
438 // this is used to veto page loads, etc.
439 MyPolicyDelegate* myPolicyDelegate =
440 [[MyPolicyDelegate alloc] initWithWxWindow: this];
442 [m_webView setPolicyDelegate:myPolicyDelegate];
445 WebHistory* history = [[WebHistory alloc] init];
446 [WebHistory setOptionalSharedHistory:history];
448 InternalLoadURL(strURL);
452 wxWebViewWebKit::~wxWebViewWebKit()
454 MyFrameLoadMonitor* myFrameLoadMonitor = [m_webView frameLoadDelegate];
455 MyPolicyDelegate* myPolicyDelegate = [m_webView policyDelegate];
456 [m_webView setFrameLoadDelegate: nil];
457 [m_webView setPolicyDelegate: nil];
459 if (myFrameLoadMonitor)
460 [myFrameLoadMonitor release];
462 if (myPolicyDelegate)
463 [myPolicyDelegate release];
466 // ----------------------------------------------------------------------------
468 // ----------------------------------------------------------------------------
470 void wxWebViewWebKit::InternalLoadURL(const wxString &url)
475 [[m_webView mainFrame] loadRequest:[NSURLRequest requestWithURL:
476 [NSURL URLWithString:wxNSStringWithWxString(url)]]];
479 bool wxWebViewWebKit::CanGoBack()
484 return [m_webView canGoBack];
487 bool wxWebViewWebKit::CanGoForward()
492 return [m_webView canGoForward];
495 void wxWebViewWebKit::GoBack()
500 bool result = [(WebView*)m_webView goBack];
502 // TODO: return result (if it also exists in other backends...)
506 void wxWebViewWebKit::GoForward()
511 bool result = [(WebView*)m_webView goForward];
513 // TODO: return result (if it also exists in other backends...)
517 void wxWebViewWebKit::Reload(wxWebViewReloadFlags flags)
522 if (flags & wxWEB_VIEW_RELOAD_NO_CACHE)
524 // TODO: test this indeed bypasses the cache
525 [[m_webView preferences] setUsesPageCache:NO];
526 [[m_webView mainFrame] reload];
527 [[m_webView preferences] setUsesPageCache:YES];
531 [[m_webView mainFrame] reload];
535 void wxWebViewWebKit::Stop()
540 [[m_webView mainFrame] stopLoading];
543 bool wxWebViewWebKit::CanGetPageSource()
548 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
549 return ( [[dataSource representation] canProvideDocumentSource] );
552 wxString wxWebViewWebKit::GetPageSource()
555 if (CanGetPageSource())
557 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
558 wxASSERT (dataSource != nil);
560 id<WebDocumentRepresentation> representation = [dataSource representation];
561 wxASSERT (representation != nil);
563 NSString* source = [representation documentSource];
566 return wxEmptyString;
569 return wxStringWithNSString( source );
572 return wxEmptyString;
575 bool wxWebViewWebKit::CanIncreaseTextSize()
580 if ([m_webView canMakeTextLarger])
586 void wxWebViewWebKit::IncreaseTextSize()
591 if (CanIncreaseTextSize())
592 [m_webView makeTextLarger:(WebView*)m_webView];
595 bool wxWebViewWebKit::CanDecreaseTextSize()
600 if ([m_webView canMakeTextSmaller])
606 void wxWebViewWebKit::DecreaseTextSize()
611 if (CanDecreaseTextSize())
612 [m_webView makeTextSmaller:(WebView*)m_webView];
615 void wxWebViewWebKit::Print()
618 // TODO: allow specifying the "show prompt" parameter in Print() ?
619 bool showPrompt = true;
624 id view = [[[m_webView mainFrame] frameView] documentView];
625 NSPrintOperation *op = [NSPrintOperation printOperationWithView:view
626 printInfo: [NSPrintInfo sharedPrintInfo]];
629 [op setShowsPrintPanel: showPrompt];
630 // in my tests, the progress bar always freezes and it stops the whole
631 // print operation. do not turn this to true unless there is a
632 // workaround for the bug.
633 [op setShowsProgressPanel: false];
639 void wxWebViewWebKit::SetEditable(bool enable)
644 [m_webView setEditable:enable ];
647 bool wxWebViewWebKit::IsEditable()
652 return [m_webView isEditable];
655 void wxWebViewWebKit::SetZoomType(wxWebViewZoomType zoomType)
657 // there is only one supported zoom type at the moment so this setter
658 // does nothing beyond checking sanity
659 wxASSERT(zoomType == wxWEB_VIEW_ZOOM_TYPE_TEXT);
662 wxWebViewZoomType wxWebViewWebKit::GetZoomType() const
664 // for now that's the only one that is supported
665 // FIXME: does the default zoom type change depending on webkit versions? :S
666 // Then this will be wrong
667 return wxWEB_VIEW_ZOOM_TYPE_TEXT;
670 bool wxWebViewWebKit::CanSetZoomType(wxWebViewZoomType type) const
674 // for now that's the only one that is supported
675 // TODO: I know recent versions of webkit support layout zoom too,
676 // check if we can support it
677 case wxWEB_VIEW_ZOOM_TYPE_TEXT:
685 int wxWebViewWebKit::GetScrollPos()
687 id result = [[m_webView windowScriptObject]
688 evaluateWebScript:@"document.body.scrollTop"];
689 return [result intValue];
692 void wxWebViewWebKit::SetScrollPos(int pos)
698 javascript.Printf(wxT("document.body.scrollTop = %d;"), pos);
699 [[m_webView windowScriptObject] evaluateWebScript:
700 (NSString*)wxNSStringWithWxString( javascript )];
703 wxString wxWebViewWebKit::GetSelectedText()
705 NSString* selection = [[m_webView selectedDOMRange] markupString];
706 if (!selection) return wxEmptyString;
708 return wxStringWithNSString(selection);
711 void wxWebViewWebKit::RunScript(const wxString& javascript)
716 [[m_webView windowScriptObject] evaluateWebScript:
717 (NSString*)wxNSStringWithWxString( javascript )];
720 void wxWebViewWebKit::OnSize(wxSizeEvent &event)
722 #if defined(__WXMAC_) && wxOSX_USE_CARBON
723 // This is a nasty hack because WebKit seems to lose its position when it is
724 // embedded in a control that is not itself the content view for a TLW.
725 // I put it in OnSize because these calcs are not perfect, and in fact are
726 // basically guesses based on reverse engineering, so it's best to give
727 // people the option of overriding OnSize with their own calcs if need be.
728 // I also left some test debugging print statements as a convenience if
729 // a(nother) problem crops up.
731 wxWindow* tlw = MacGetTopLevelWindow();
733 NSRect frame = [(WebView*)m_webView frame];
734 NSRect bounds = [(WebView*)m_webView bounds];
736 #if DEBUG_WEBKIT_SIZING
737 fprintf(stderr,"Carbon window x=%d, y=%d, width=%d, height=%d\n",
738 GetPosition().x, GetPosition().y, GetSize().x, GetSize().y);
739 fprintf(stderr, "Cocoa window frame x=%G, y=%G, width=%G, height=%G\n",
740 frame.origin.x, frame.origin.y,
741 frame.size.width, frame.size.height);
742 fprintf(stderr, "Cocoa window bounds x=%G, y=%G, width=%G, height=%G\n",
743 bounds.origin.x, bounds.origin.y,
744 bounds.size.width, bounds.size.height);
747 // This must be the case that Apple tested with, because well, in this one case
748 // we don't need to do anything! It just works. ;)
749 if (GetParent() == tlw) return;
751 // since we no longer use parent coordinates, we always want 0,0.
759 #if DEBUG_WEBKIT_SIZING
760 printf("Before conversion, origin is: x = %d, y = %d\n", x, y);
763 // NB: In most cases, when calling HIViewConvertRect, what people want is to
764 // use GetRootControl(), and this tripped me up at first. But in fact, what
765 // we want is the root view, because we need to make the y origin relative
766 // to the very top of the window, not its contents, since we later flip
767 // the y coordinate for Cocoa.
768 HIViewConvertRect (&rect, m_peer->GetControlRef(),
770 (WindowRef) MacGetTopLevelWindowRef()
773 x = (int)rect.origin.x;
774 y = (int)rect.origin.y;
776 #if DEBUG_WEBKIT_SIZING
777 printf("Moving Cocoa frame origin to: x = %d, y = %d\n", x, y);
781 //flip the y coordinate to convert to Cocoa coordinates
782 y = tlw->GetSize().y - ((GetSize().y) + y);
785 #if DEBUG_WEBKIT_SIZING
786 printf("y = %d after flipping value\n", y);
791 [(WebView*)m_webView setFrame:frame];
794 [(WebView*)m_webView display];
799 void wxWebViewWebKit::MacVisibilityChanged(){
800 #if defined(__WXMAC__) && wxOSX_USE_CARBON
801 bool isHidden = !IsControlVisible( m_peer->GetControlRef());
803 [(WebView*)m_webView display];
805 [m_webView setHidden:isHidden];
809 void wxWebViewWebKit::LoadUrl(const wxString& url)
811 InternalLoadURL(url);
814 wxString wxWebViewWebKit::GetCurrentURL()
816 return wxStringWithNSString([m_webView mainFrameURL]);
819 wxString wxWebViewWebKit::GetCurrentTitle()
821 return GetPageTitle();
824 float wxWebViewWebKit::GetWebkitZoom()
826 return [m_webView textSizeMultiplier];
829 void wxWebViewWebKit::SetWebkitZoom(float zoom)
831 [m_webView setTextSizeMultiplier:zoom];
834 wxWebViewZoom wxWebViewWebKit::GetZoom()
836 float zoom = GetWebkitZoom();
838 // arbitrary way to map float zoom to our common zoom enum
841 return wxWEB_VIEW_ZOOM_TINY;
843 else if (zoom > 0.55 && zoom <= 0.85)
845 return wxWEB_VIEW_ZOOM_SMALL;
847 else if (zoom > 0.85 && zoom <= 1.15)
849 return wxWEB_VIEW_ZOOM_MEDIUM;
851 else if (zoom > 1.15 && zoom <= 1.45)
853 return wxWEB_VIEW_ZOOM_LARGE;
855 else if (zoom > 1.45)
857 return wxWEB_VIEW_ZOOM_LARGEST;
860 // to shut up compilers, this can never be reached logically
862 return wxWEB_VIEW_ZOOM_MEDIUM;
865 void wxWebViewWebKit::SetZoom(wxWebViewZoom zoom)
867 // arbitrary way to map our common zoom enum to float zoom
870 case wxWEB_VIEW_ZOOM_TINY:
874 case wxWEB_VIEW_ZOOM_SMALL:
878 case wxWEB_VIEW_ZOOM_MEDIUM:
882 case wxWEB_VIEW_ZOOM_LARGE:
886 case wxWEB_VIEW_ZOOM_LARGEST:
896 void wxWebViewWebKit::SetPage(const wxString& src, const wxString& baseUrl)
901 [[m_webView mainFrame] loadHTMLString:(NSString*)wxNSStringWithWxString(src)
902 baseURL:[NSURL URLWithString:
903 wxNSStringWithWxString( baseUrl )]];
906 void wxWebViewWebKit::Cut()
911 [(WebView*)m_webView cut:m_webView];
914 void wxWebViewWebKit::Copy()
919 [(WebView*)m_webView copy:m_webView];
922 void wxWebViewWebKit::Paste()
927 [(WebView*)m_webView paste:m_webView];
930 void wxWebViewWebKit::DeleteSelection()
935 [(WebView*)m_webView deleteSelection];
938 bool wxWebViewWebKit::HasSelection()
940 DOMRange* range = [m_webView selectedDOMRange];
951 void wxWebViewWebKit::EnableHistory(bool enable)
956 [m_webView setMaintainsBackForwardList:enable];
959 void wxWebViewWebKit::ClearHistory()
961 [[WebHistory optionalSharedHistory] removeAllItems];
964 bool wxWebViewWebKit::CanUndo()
966 return [[m_webView undoManager] canUndo];
969 bool wxWebViewWebKit::CanRedo()
971 return [[m_webView undoManager] canRedo];
974 void wxWebViewWebKit::Undo()
976 [[m_webView undoManager] undo];
979 void wxWebViewWebKit::Redo()
981 [[m_webView undoManager] redo];
984 //------------------------------------------------------------
985 // Listener interfaces
986 //------------------------------------------------------------
988 // NB: I'm still tracking this down, but it appears the Cocoa window
989 // still has these events fired on it while the Carbon control is being
990 // destroyed. Therefore, we must be careful to check both the existence
991 // of the Carbon control and the event handler before firing events.
993 @implementation MyFrameLoadMonitor
995 - initWithWxWindow: (wxWebViewWebKit*)inWindow
998 webKitWindow = inWindow; // non retained
1002 - (void)webView:(WebView *)sender
1003 didStartProvisionalLoadForFrame:(WebFrame *)frame
1005 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1006 wx_webviewctrls[sender]->m_busy = true;
1009 - (void)webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame
1011 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1012 wx_webviewctrls[sender]->m_busy = true;
1014 if (webKitWindow && frame == [sender mainFrame]){
1015 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1016 wxString target = wxStringWithNSString([frame name]);
1017 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATED,
1018 wx_webviewctrls[sender]->GetId(),
1019 wxStringWithNSString( url ),
1022 if (webKitWindow && webKitWindow->GetEventHandler())
1023 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1027 - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
1029 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1030 wx_webviewctrls[sender]->m_busy = false;
1032 if (webKitWindow && frame == [sender mainFrame]){
1033 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1035 wxString target = wxStringWithNSString([frame name]);
1036 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_LOADED,
1037 wx_webviewctrls[sender]->GetId(),
1038 wxStringWithNSString( url ),
1041 if (webKitWindow && webKitWindow->GetEventHandler())
1042 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1046 wxString nsErrorToWxHtmlError(NSError* error, wxWebNavigationError* out)
1048 *out = wxWEB_NAV_ERR_OTHER;
1050 if ([[error domain] isEqualToString:NSURLErrorDomain])
1052 switch ([error code])
1054 case NSURLErrorCannotFindHost:
1055 case NSURLErrorFileDoesNotExist:
1056 case NSURLErrorRedirectToNonExistentLocation:
1057 *out = wxWEB_NAV_ERR_NOT_FOUND;
1060 case NSURLErrorResourceUnavailable:
1061 case NSURLErrorHTTPTooManyRedirects:
1062 case NSURLErrorDataLengthExceedsMaximum:
1063 case NSURLErrorBadURL:
1064 case NSURLErrorFileIsDirectory:
1065 *out = wxWEB_NAV_ERR_REQUEST;
1068 case NSURLErrorTimedOut:
1069 case NSURLErrorDNSLookupFailed:
1070 case NSURLErrorNetworkConnectionLost:
1071 case NSURLErrorCannotConnectToHost:
1072 case NSURLErrorNotConnectedToInternet:
1073 //case NSURLErrorInternationalRoamingOff:
1074 //case NSURLErrorCallIsActive:
1075 //case NSURLErrorDataNotAllowed:
1076 *out = wxWEB_NAV_ERR_CONNECTION;
1079 case NSURLErrorCancelled:
1080 case NSURLErrorUserCancelledAuthentication:
1081 *out = wxWEB_NAV_ERR_USER_CANCELLED;
1084 case NSURLErrorCannotDecodeRawData:
1085 case NSURLErrorCannotDecodeContentData:
1086 case NSURLErrorBadServerResponse:
1087 case NSURLErrorCannotParseResponse:
1088 *out = wxWEB_NAV_ERR_REQUEST;
1091 case NSURLErrorUserAuthenticationRequired:
1092 case NSURLErrorSecureConnectionFailed:
1093 case NSURLErrorClientCertificateRequired:
1094 *out = wxWEB_NAV_ERR_AUTH;
1097 case NSURLErrorNoPermissionsToReadFile:
1098 *out = wxWEB_NAV_ERR_SECURITY;
1101 case NSURLErrorServerCertificateHasBadDate:
1102 case NSURLErrorServerCertificateUntrusted:
1103 case NSURLErrorServerCertificateHasUnknownRoot:
1104 case NSURLErrorServerCertificateNotYetValid:
1105 case NSURLErrorClientCertificateRejected:
1106 *out = wxWEB_NAV_ERR_CERTIFICATE;
1111 wxString message = wxStringWithNSString([error localizedDescription]);
1112 NSString* detail = [error localizedFailureReason];
1115 message = message + " (" + wxStringWithNSString(detail) + ")";
1120 - (void)webView:(WebView *)sender didFailLoadWithError:(NSError*) error
1121 forFrame:(WebFrame *)frame
1123 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1124 wx_webviewctrls[sender]->m_busy = false;
1126 if (webKitWindow && frame == [sender mainFrame]){
1127 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1129 wxWebNavigationError type;
1130 wxString description = nsErrorToWxHtmlError(error, &type);
1131 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1132 wx_webviewctrls[sender]->GetId(),
1133 wxStringWithNSString( url ),
1134 wxEmptyString, false);
1135 thisEvent.SetString(description);
1136 thisEvent.SetInt(type);
1138 if (webKitWindow && webKitWindow->GetEventHandler())
1140 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1145 - (void)webView:(WebView *)sender
1146 didFailProvisionalLoadWithError:(NSError*)error
1147 forFrame:(WebFrame *)frame
1149 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1150 wx_webviewctrls[sender]->m_busy = false;
1152 if (webKitWindow && frame == [sender mainFrame]){
1153 NSString *url = [[[[frame provisionalDataSource] request] URL]
1156 wxWebNavigationError type;
1157 wxString description = nsErrorToWxHtmlError(error, &type);
1158 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1159 wx_webviewctrls[sender]->GetId(),
1160 wxStringWithNSString( url ),
1161 wxEmptyString, false);
1162 thisEvent.SetString(description);
1163 thisEvent.SetInt(type);
1165 if (webKitWindow && webKitWindow->GetEventHandler())
1166 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1170 - (void)webView:(WebView *)sender didReceiveTitle:(NSString *)title
1171 forFrame:(WebFrame *)frame
1173 if (webKitWindow && frame == [sender mainFrame])
1175 webKitWindow->SetPageTitle(wxStringWithNSString( title ));
1177 wxString target = wxStringWithNSString([frame name]);
1178 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_TITLE_CHANGED,
1179 wx_webviewctrls[sender]->GetId(),
1180 wx_webviewctrls[sender]->GetCurrentURL(),
1183 thisEvent.SetString(wxStringWithNSString(title));
1185 if (webKitWindow && webKitWindow->GetEventHandler())
1186 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1190 @implementation MyPolicyDelegate
1192 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1195 webKitWindow = inWindow; // non retained
1199 - (void)webView:(WebView *)sender
1200 decidePolicyForNavigationAction:(NSDictionary *)actionInformation
1201 request:(NSURLRequest *)request
1202 frame:(WebFrame *)frame
1203 decisionListener:(id<WebPolicyDecisionListener>)listener
1207 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1208 wx_webviewctrls[sender]->m_busy = true;
1209 NSString *url = [[request URL] absoluteString];
1210 wxString target = wxStringWithNSString([frame name]);
1211 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATING,
1212 wx_webviewctrls[sender]->GetId(),
1213 wxStringWithNSString( url ), target, true);
1215 if (webKitWindow && webKitWindow->GetEventHandler())
1216 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1218 if (thisEvent.IsVetoed())
1220 wx_webviewctrls[sender]->m_busy = false;
1229 - (void)webView:(WebView *)sender
1230 decidePolicyForNewWindowAction:(NSDictionary *)actionInformation
1231 request:(NSURLRequest *)request
1232 newFrameName:(NSString *)frameName
1233 decisionListener:(id < WebPolicyDecisionListener >)listener
1235 wxUnusedVar(actionInformation);
1237 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1238 NSString *url = [[request URL] absoluteString];
1239 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NEWWINDOW,
1240 wx_webviewctrls[sender]->GetId(),
1241 wxStringWithNSString( url ), "", true);
1243 if (webKitWindow && webKitWindow->GetEventHandler())
1244 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1250 #endif //wxUSE_WEBVIEW_WEBKIT