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];
444 InternalLoadURL(strURL);
448 wxWebViewWebKit::~wxWebViewWebKit()
450 MyFrameLoadMonitor* myFrameLoadMonitor = [m_webView frameLoadDelegate];
451 MyPolicyDelegate* myPolicyDelegate = [m_webView policyDelegate];
452 [m_webView setFrameLoadDelegate: nil];
453 [m_webView setPolicyDelegate: nil];
455 if (myFrameLoadMonitor)
456 [myFrameLoadMonitor release];
458 if (myPolicyDelegate)
459 [myPolicyDelegate release];
462 // ----------------------------------------------------------------------------
464 // ----------------------------------------------------------------------------
466 void wxWebViewWebKit::InternalLoadURL(const wxString &url)
471 [[m_webView mainFrame] loadRequest:[NSURLRequest requestWithURL:
472 [NSURL URLWithString:wxNSStringWithWxString(url)]]];
475 bool wxWebViewWebKit::CanGoBack()
480 return [m_webView canGoBack];
483 bool wxWebViewWebKit::CanGoForward()
488 return [m_webView canGoForward];
491 void wxWebViewWebKit::GoBack()
496 bool result = [(WebView*)m_webView goBack];
498 // TODO: return result (if it also exists in other backends...)
502 void wxWebViewWebKit::GoForward()
507 bool result = [(WebView*)m_webView goForward];
509 // TODO: return result (if it also exists in other backends...)
513 void wxWebViewWebKit::Reload(wxWebViewReloadFlags flags)
518 if (flags & wxWEB_VIEW_RELOAD_NO_CACHE)
520 // TODO: test this indeed bypasses the cache
521 [[m_webView preferences] setUsesPageCache:NO];
522 [[m_webView mainFrame] reload];
523 [[m_webView preferences] setUsesPageCache:YES];
527 [[m_webView mainFrame] reload];
531 void wxWebViewWebKit::Stop()
536 [[m_webView mainFrame] stopLoading];
539 bool wxWebViewWebKit::CanGetPageSource()
544 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
545 return ( [[dataSource representation] canProvideDocumentSource] );
548 wxString wxWebViewWebKit::GetPageSource()
551 if (CanGetPageSource())
553 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
554 wxASSERT (dataSource != nil);
556 id<WebDocumentRepresentation> representation = [dataSource representation];
557 wxASSERT (representation != nil);
559 NSString* source = [representation documentSource];
562 return wxEmptyString;
565 return wxStringWithNSString( source );
568 return wxEmptyString;
571 bool wxWebViewWebKit::CanIncreaseTextSize()
576 if ([m_webView canMakeTextLarger])
582 void wxWebViewWebKit::IncreaseTextSize()
587 if (CanIncreaseTextSize())
588 [m_webView makeTextLarger:(WebView*)m_webView];
591 bool wxWebViewWebKit::CanDecreaseTextSize()
596 if ([m_webView canMakeTextSmaller])
602 void wxWebViewWebKit::DecreaseTextSize()
607 if (CanDecreaseTextSize())
608 [m_webView makeTextSmaller:(WebView*)m_webView];
611 void wxWebViewWebKit::Print()
614 // TODO: allow specifying the "show prompt" parameter in Print() ?
615 bool showPrompt = true;
620 id view = [[[m_webView mainFrame] frameView] documentView];
621 NSPrintOperation *op = [NSPrintOperation printOperationWithView:view
622 printInfo: [NSPrintInfo sharedPrintInfo]];
625 [op setShowsPrintPanel: showPrompt];
626 // in my tests, the progress bar always freezes and it stops the whole
627 // print operation. do not turn this to true unless there is a
628 // workaround for the bug.
629 [op setShowsProgressPanel: false];
635 void wxWebViewWebKit::SetEditable(bool enable)
640 [m_webView setEditable:enable ];
643 bool wxWebViewWebKit::IsEditable()
648 return [m_webView isEditable];
651 void wxWebViewWebKit::SetZoomType(wxWebViewZoomType zoomType)
653 // there is only one supported zoom type at the moment so this setter
654 // does nothing beyond checking sanity
655 wxASSERT(zoomType == wxWEB_VIEW_ZOOM_TYPE_TEXT);
658 wxWebViewZoomType wxWebViewWebKit::GetZoomType() const
660 // for now that's the only one that is supported
661 // FIXME: does the default zoom type change depending on webkit versions? :S
662 // Then this will be wrong
663 return wxWEB_VIEW_ZOOM_TYPE_TEXT;
666 bool wxWebViewWebKit::CanSetZoomType(wxWebViewZoomType type) const
670 // for now that's the only one that is supported
671 // TODO: I know recent versions of webkit support layout zoom too,
672 // check if we can support it
673 case wxWEB_VIEW_ZOOM_TYPE_TEXT:
681 int wxWebViewWebKit::GetScrollPos()
683 id result = [[m_webView windowScriptObject]
684 evaluateWebScript:@"document.body.scrollTop"];
685 return [result intValue];
688 void wxWebViewWebKit::SetScrollPos(int pos)
694 javascript.Printf(wxT("document.body.scrollTop = %d;"), pos);
695 [[m_webView windowScriptObject] evaluateWebScript:
696 (NSString*)wxNSStringWithWxString( javascript )];
699 wxString wxWebViewWebKit::GetSelectedText()
701 NSString* selection = [[m_webView selectedDOMRange] markupString];
702 if (!selection) return wxEmptyString;
704 return wxStringWithNSString(selection);
707 void wxWebViewWebKit::RunScript(const wxString& javascript)
712 [[m_webView windowScriptObject] evaluateWebScript:
713 (NSString*)wxNSStringWithWxString( javascript )];
716 void wxWebViewWebKit::OnSize(wxSizeEvent &event)
718 #if defined(__WXMAC_) && wxOSX_USE_CARBON
719 // This is a nasty hack because WebKit seems to lose its position when it is
720 // embedded in a control that is not itself the content view for a TLW.
721 // I put it in OnSize because these calcs are not perfect, and in fact are
722 // basically guesses based on reverse engineering, so it's best to give
723 // people the option of overriding OnSize with their own calcs if need be.
724 // I also left some test debugging print statements as a convenience if
725 // a(nother) problem crops up.
727 wxWindow* tlw = MacGetTopLevelWindow();
729 NSRect frame = [(WebView*)m_webView frame];
730 NSRect bounds = [(WebView*)m_webView bounds];
732 #if DEBUG_WEBKIT_SIZING
733 fprintf(stderr,"Carbon window x=%d, y=%d, width=%d, height=%d\n",
734 GetPosition().x, GetPosition().y, GetSize().x, GetSize().y);
735 fprintf(stderr, "Cocoa window frame x=%G, y=%G, width=%G, height=%G\n",
736 frame.origin.x, frame.origin.y,
737 frame.size.width, frame.size.height);
738 fprintf(stderr, "Cocoa window bounds x=%G, y=%G, width=%G, height=%G\n",
739 bounds.origin.x, bounds.origin.y,
740 bounds.size.width, bounds.size.height);
743 // This must be the case that Apple tested with, because well, in this one case
744 // we don't need to do anything! It just works. ;)
745 if (GetParent() == tlw) return;
747 // since we no longer use parent coordinates, we always want 0,0.
755 #if DEBUG_WEBKIT_SIZING
756 printf("Before conversion, origin is: x = %d, y = %d\n", x, y);
759 // NB: In most cases, when calling HIViewConvertRect, what people want is to
760 // use GetRootControl(), and this tripped me up at first. But in fact, what
761 // we want is the root view, because we need to make the y origin relative
762 // to the very top of the window, not its contents, since we later flip
763 // the y coordinate for Cocoa.
764 HIViewConvertRect (&rect, m_peer->GetControlRef(),
766 (WindowRef) MacGetTopLevelWindowRef()
769 x = (int)rect.origin.x;
770 y = (int)rect.origin.y;
772 #if DEBUG_WEBKIT_SIZING
773 printf("Moving Cocoa frame origin to: x = %d, y = %d\n", x, y);
777 //flip the y coordinate to convert to Cocoa coordinates
778 y = tlw->GetSize().y - ((GetSize().y) + y);
781 #if DEBUG_WEBKIT_SIZING
782 printf("y = %d after flipping value\n", y);
787 [(WebView*)m_webView setFrame:frame];
790 [(WebView*)m_webView display];
795 void wxWebViewWebKit::MacVisibilityChanged(){
796 #if defined(__WXMAC__) && wxOSX_USE_CARBON
797 bool isHidden = !IsControlVisible( m_peer->GetControlRef());
799 [(WebView*)m_webView display];
801 [m_webView setHidden:isHidden];
805 void wxWebViewWebKit::LoadUrl(const wxString& url)
807 InternalLoadURL(url);
810 wxString wxWebViewWebKit::GetCurrentURL()
812 return wxStringWithNSString([m_webView mainFrameURL]);
815 wxString wxWebViewWebKit::GetCurrentTitle()
817 return GetPageTitle();
820 float wxWebViewWebKit::GetWebkitZoom()
822 return [m_webView textSizeMultiplier];
825 void wxWebViewWebKit::SetWebkitZoom(float zoom)
827 [m_webView setTextSizeMultiplier:zoom];
830 wxWebViewZoom wxWebViewWebKit::GetZoom()
832 float zoom = GetWebkitZoom();
834 // arbitrary way to map float zoom to our common zoom enum
837 return wxWEB_VIEW_ZOOM_TINY;
839 else if (zoom > 0.55 && zoom <= 0.85)
841 return wxWEB_VIEW_ZOOM_SMALL;
843 else if (zoom > 0.85 && zoom <= 1.15)
845 return wxWEB_VIEW_ZOOM_MEDIUM;
847 else if (zoom > 1.15 && zoom <= 1.45)
849 return wxWEB_VIEW_ZOOM_LARGE;
851 else if (zoom > 1.45)
853 return wxWEB_VIEW_ZOOM_LARGEST;
856 // to shut up compilers, this can never be reached logically
858 return wxWEB_VIEW_ZOOM_MEDIUM;
861 void wxWebViewWebKit::SetZoom(wxWebViewZoom zoom)
863 // arbitrary way to map our common zoom enum to float zoom
866 case wxWEB_VIEW_ZOOM_TINY:
870 case wxWEB_VIEW_ZOOM_SMALL:
874 case wxWEB_VIEW_ZOOM_MEDIUM:
878 case wxWEB_VIEW_ZOOM_LARGE:
882 case wxWEB_VIEW_ZOOM_LARGEST:
892 void wxWebViewWebKit::SetPage(const wxString& src, const wxString& baseUrl)
897 [[m_webView mainFrame] loadHTMLString:(NSString*)wxNSStringWithWxString(src)
898 baseURL:[NSURL URLWithString:
899 wxNSStringWithWxString( baseUrl )]];
902 void wxWebViewWebKit::Cut()
907 [(WebView*)m_webView cut:m_webView];
910 void wxWebViewWebKit::Copy()
915 [(WebView*)m_webView copy:m_webView];
918 void wxWebViewWebKit::Paste()
923 [(WebView*)m_webView paste:m_webView];
926 void wxWebViewWebKit::DeleteSelection()
931 [(WebView*)m_webView deleteSelection];
934 bool wxWebViewWebKit::HasSelection()
936 DOMRange* range = [m_webView selectedDOMRange];
947 void wxWebViewWebKit::EnableHistory(bool enable)
952 [m_webView setMaintainsBackForwardList:enable];
955 void wxWebViewWebKit::ClearHistory()
957 [m_webView setMaintainsBackForwardList:NO];
958 [m_webView setMaintainsBackForwardList:YES];
961 wxVector<wxSharedPtr<wxWebHistoryItem> > wxWebViewWebKit::GetBackwardHistory()
963 wxVector<wxSharedPtr<wxWebHistoryItem> > backhist;
964 WebBackForwardList* history = [m_webView backForwardList];
965 int count = [history backListCount];
966 for(int i = -count; i < 0; i++)
968 WebHistoryItem* item = [history itemAtIndex:i];
969 wxString url = wxStringWithNSString([item URLString]);
970 wxString title = wxStringWithNSString([item title]);
971 wxWebHistoryItem* wxitem = new wxWebHistoryItem(url, title);
972 wxitem->m_histItem = item;
973 wxSharedPtr<wxWebHistoryItem> itemptr(wxitem);
974 backhist.push_back(itemptr);
979 wxVector<wxSharedPtr<wxWebHistoryItem> > wxWebViewWebKit::GetForwardHistory()
981 wxVector<wxSharedPtr<wxWebHistoryItem> > forwardhist;
982 WebBackForwardList* history = [m_webView backForwardList];
983 int count = [history forwardListCount];
984 for(int i = 1; i <= count; i++)
986 WebHistoryItem* item = [history itemAtIndex:i];
987 wxString url = wxStringWithNSString([item URLString]);
988 wxString title = wxStringWithNSString([item title]);
989 wxWebHistoryItem* wxitem = new wxWebHistoryItem(url, title);
990 wxitem->m_histItem = item;
991 wxSharedPtr<wxWebHistoryItem> itemptr(wxitem);
992 forwardhist.push_back(itemptr);
997 void wxWebViewWebKit::LoadHistoryItem(wxSharedPtr<wxWebHistoryItem> item)
999 [m_webView goToBackForwardItem:item->m_histItem];
1002 bool wxWebViewWebKit::CanUndo()
1004 return [[m_webView undoManager] canUndo];
1007 bool wxWebViewWebKit::CanRedo()
1009 return [[m_webView undoManager] canRedo];
1012 void wxWebViewWebKit::Undo()
1014 [[m_webView undoManager] undo];
1017 void wxWebViewWebKit::Redo()
1019 [[m_webView undoManager] redo];
1022 //------------------------------------------------------------
1023 // Listener interfaces
1024 //------------------------------------------------------------
1026 // NB: I'm still tracking this down, but it appears the Cocoa window
1027 // still has these events fired on it while the Carbon control is being
1028 // destroyed. Therefore, we must be careful to check both the existence
1029 // of the Carbon control and the event handler before firing events.
1031 @implementation MyFrameLoadMonitor
1033 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1036 webKitWindow = inWindow; // non retained
1040 - (void)webView:(WebView *)sender
1041 didStartProvisionalLoadForFrame:(WebFrame *)frame
1043 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1044 wx_webviewctrls[sender]->m_busy = true;
1047 - (void)webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame
1049 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1050 wx_webviewctrls[sender]->m_busy = true;
1052 if (webKitWindow && frame == [sender mainFrame]){
1053 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1054 wxString target = wxStringWithNSString([frame name]);
1055 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATED,
1056 wx_webviewctrls[sender]->GetId(),
1057 wxStringWithNSString( url ),
1060 if (webKitWindow && webKitWindow->GetEventHandler())
1061 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1065 - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
1067 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1068 wx_webviewctrls[sender]->m_busy = false;
1070 if (webKitWindow && frame == [sender mainFrame]){
1071 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1073 wxString target = wxStringWithNSString([frame name]);
1074 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_LOADED,
1075 wx_webviewctrls[sender]->GetId(),
1076 wxStringWithNSString( url ),
1079 if (webKitWindow && webKitWindow->GetEventHandler())
1080 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1084 wxString nsErrorToWxHtmlError(NSError* error, wxWebNavigationError* out)
1086 *out = wxWEB_NAV_ERR_OTHER;
1088 if ([[error domain] isEqualToString:NSURLErrorDomain])
1090 switch ([error code])
1092 case NSURLErrorCannotFindHost:
1093 case NSURLErrorFileDoesNotExist:
1094 case NSURLErrorRedirectToNonExistentLocation:
1095 *out = wxWEB_NAV_ERR_NOT_FOUND;
1098 case NSURLErrorResourceUnavailable:
1099 case NSURLErrorHTTPTooManyRedirects:
1100 case NSURLErrorDataLengthExceedsMaximum:
1101 case NSURLErrorBadURL:
1102 case NSURLErrorFileIsDirectory:
1103 *out = wxWEB_NAV_ERR_REQUEST;
1106 case NSURLErrorTimedOut:
1107 case NSURLErrorDNSLookupFailed:
1108 case NSURLErrorNetworkConnectionLost:
1109 case NSURLErrorCannotConnectToHost:
1110 case NSURLErrorNotConnectedToInternet:
1111 //case NSURLErrorInternationalRoamingOff:
1112 //case NSURLErrorCallIsActive:
1113 //case NSURLErrorDataNotAllowed:
1114 *out = wxWEB_NAV_ERR_CONNECTION;
1117 case NSURLErrorCancelled:
1118 case NSURLErrorUserCancelledAuthentication:
1119 *out = wxWEB_NAV_ERR_USER_CANCELLED;
1122 case NSURLErrorCannotDecodeRawData:
1123 case NSURLErrorCannotDecodeContentData:
1124 case NSURLErrorBadServerResponse:
1125 case NSURLErrorCannotParseResponse:
1126 *out = wxWEB_NAV_ERR_REQUEST;
1129 case NSURLErrorUserAuthenticationRequired:
1130 case NSURLErrorSecureConnectionFailed:
1131 case NSURLErrorClientCertificateRequired:
1132 *out = wxWEB_NAV_ERR_AUTH;
1135 case NSURLErrorNoPermissionsToReadFile:
1136 *out = wxWEB_NAV_ERR_SECURITY;
1139 case NSURLErrorServerCertificateHasBadDate:
1140 case NSURLErrorServerCertificateUntrusted:
1141 case NSURLErrorServerCertificateHasUnknownRoot:
1142 case NSURLErrorServerCertificateNotYetValid:
1143 case NSURLErrorClientCertificateRejected:
1144 *out = wxWEB_NAV_ERR_CERTIFICATE;
1149 wxString message = wxStringWithNSString([error localizedDescription]);
1150 NSString* detail = [error localizedFailureReason];
1153 message = message + " (" + wxStringWithNSString(detail) + ")";
1158 - (void)webView:(WebView *)sender didFailLoadWithError:(NSError*) error
1159 forFrame:(WebFrame *)frame
1161 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1162 wx_webviewctrls[sender]->m_busy = false;
1164 if (webKitWindow && frame == [sender mainFrame]){
1165 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1167 wxWebNavigationError type;
1168 wxString description = nsErrorToWxHtmlError(error, &type);
1169 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1170 wx_webviewctrls[sender]->GetId(),
1171 wxStringWithNSString( url ),
1172 wxEmptyString, false);
1173 thisEvent.SetString(description);
1174 thisEvent.SetInt(type);
1176 if (webKitWindow && webKitWindow->GetEventHandler())
1178 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1183 - (void)webView:(WebView *)sender
1184 didFailProvisionalLoadWithError:(NSError*)error
1185 forFrame:(WebFrame *)frame
1187 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1188 wx_webviewctrls[sender]->m_busy = false;
1190 if (webKitWindow && frame == [sender mainFrame]){
1191 NSString *url = [[[[frame provisionalDataSource] request] URL]
1194 wxWebNavigationError type;
1195 wxString description = nsErrorToWxHtmlError(error, &type);
1196 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1197 wx_webviewctrls[sender]->GetId(),
1198 wxStringWithNSString( url ),
1199 wxEmptyString, false);
1200 thisEvent.SetString(description);
1201 thisEvent.SetInt(type);
1203 if (webKitWindow && webKitWindow->GetEventHandler())
1204 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1208 - (void)webView:(WebView *)sender didReceiveTitle:(NSString *)title
1209 forFrame:(WebFrame *)frame
1211 if (webKitWindow && frame == [sender mainFrame])
1213 webKitWindow->SetPageTitle(wxStringWithNSString( title ));
1215 wxString target = wxStringWithNSString([frame name]);
1216 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_TITLE_CHANGED,
1217 wx_webviewctrls[sender]->GetId(),
1218 wx_webviewctrls[sender]->GetCurrentURL(),
1221 thisEvent.SetString(wxStringWithNSString(title));
1223 if (webKitWindow && webKitWindow->GetEventHandler())
1224 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1228 @implementation MyPolicyDelegate
1230 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1233 webKitWindow = inWindow; // non retained
1237 - (void)webView:(WebView *)sender
1238 decidePolicyForNavigationAction:(NSDictionary *)actionInformation
1239 request:(NSURLRequest *)request
1240 frame:(WebFrame *)frame
1241 decisionListener:(id<WebPolicyDecisionListener>)listener
1245 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1246 wx_webviewctrls[sender]->m_busy = true;
1247 NSString *url = [[request URL] absoluteString];
1248 wxString target = wxStringWithNSString([frame name]);
1249 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATING,
1250 wx_webviewctrls[sender]->GetId(),
1251 wxStringWithNSString( url ), target, true);
1253 if (webKitWindow && webKitWindow->GetEventHandler())
1254 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1256 if (thisEvent.IsVetoed())
1258 wx_webviewctrls[sender]->m_busy = false;
1267 - (void)webView:(WebView *)sender
1268 decidePolicyForNewWindowAction:(NSDictionary *)actionInformation
1269 request:(NSURLRequest *)request
1270 newFrameName:(NSString *)frameName
1271 decisionListener:(id < WebPolicyDecisionListener >)listener
1273 wxUnusedVar(actionInformation);
1275 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1276 NSString *url = [[request URL] absoluteString];
1277 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NEWWINDOW,
1278 wx_webviewctrls[sender]->GetId(),
1279 wxStringWithNSString( url ), "", true);
1281 if (webKitWindow && webKitWindow->GetEventHandler())
1282 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1288 #endif //wxUSE_WEBVIEW_WEBKIT