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)
358 //still needed for wxCocoa??
362 if (size.x == wxDefaultCoord || size.y == wxDefaultCoord)
364 m_parent->GetClientSize(&width, &height);
365 sizeInstance.x = width;
366 sizeInstance.y = height;
370 sizeInstance.x = size.x;
371 sizeInstance.y = size.y;
374 // now create and attach WebKit view...
376 wxControl::Create(parent, m_windowID, pos, sizeInstance, style, name);
377 SetSize(pos.x, pos.y, sizeInstance.x, sizeInstance.y);
379 wxTopLevelWindowCocoa *topWin = wxDynamicCast(this, wxTopLevelWindowCocoa);
380 NSWindow* nsWin = topWin->GetNSWindow();
382 rect.origin.x = pos.x;
383 rect.origin.y = pos.y;
384 rect.size.width = sizeInstance.x;
385 rect.size.height = sizeInstance.y;
386 m_webView = (WebView*)[[WebView alloc] initWithFrame:rect
387 frameName:@"webkitFrame"
388 groupName:@"webkitGroup"];
389 SetNSView(m_webView);
390 [m_cocoaNSView release];
392 if(m_parent) m_parent->CocoaAddChild(this);
393 SetInitialFrameRect(pos,sizeInstance);
395 wxControl::Create(parent, winID, pos, size, style, wxDefaultValidator, name);
398 m_peer = new wxMacControl(this);
400 HIWebViewCreate( m_peer->GetControlRefAddr() );
402 m_webView = (WebView*) HIWebViewGetWebView( m_peer->GetControlRef() );
404 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_3
405 if ( UMAGetSystemVersion() >= 0x1030 )
406 HIViewChangeFeatures( m_peer->GetControlRef() , kHIViewIsOpaque , 0 ) ;
408 InstallControlEventHandler(m_peer->GetControlRef(),
409 GetwxWebViewWebKitEventHandlerUPP(),
410 GetEventTypeCount(eventList), eventList, this,
411 (EventHandlerRef *)&m_webKitCtrlEventHandler);
413 NSRect r = wxOSXGetFrameForControl( this, pos , size ) ;
414 m_webView = [[WebView alloc] initWithFrame:r
415 frameName:@"webkitFrame"
416 groupName:@"webkitGroup"];
417 m_peer = new wxWidgetCocoaImpl( this, m_webView );
420 wx_webviewctrls[m_webView] = this;
422 MacPostControlCreate(pos, size);
425 HIViewSetVisible( m_peer->GetControlRef(), true );
427 [m_webView setHidden:false];
431 // Register event listener interfaces
432 MyFrameLoadMonitor* myFrameLoadMonitor =
433 [[MyFrameLoadMonitor alloc] initWithWxWindow: this];
435 [m_webView setFrameLoadDelegate:myFrameLoadMonitor];
437 // this is used to veto page loads, etc.
438 MyPolicyDelegate* myPolicyDelegate =
439 [[MyPolicyDelegate alloc] initWithWxWindow: this];
441 [m_webView setPolicyDelegate:myPolicyDelegate];
447 wxWebViewWebKit::~wxWebViewWebKit()
449 MyFrameLoadMonitor* myFrameLoadMonitor = [m_webView frameLoadDelegate];
450 MyPolicyDelegate* myPolicyDelegate = [m_webView policyDelegate];
451 [m_webView setFrameLoadDelegate: nil];
452 [m_webView setPolicyDelegate: nil];
454 if (myFrameLoadMonitor)
455 [myFrameLoadMonitor release];
457 if (myPolicyDelegate)
458 [myPolicyDelegate release];
461 // ----------------------------------------------------------------------------
463 // ----------------------------------------------------------------------------
465 bool wxWebViewWebKit::CanGoBack()
470 return [m_webView canGoBack];
473 bool wxWebViewWebKit::CanGoForward()
478 return [m_webView canGoForward];
481 void wxWebViewWebKit::GoBack()
486 bool result = [(WebView*)m_webView goBack];
488 // TODO: return result (if it also exists in other backends...)
492 void wxWebViewWebKit::GoForward()
497 bool result = [(WebView*)m_webView goForward];
499 // TODO: return result (if it also exists in other backends...)
503 void wxWebViewWebKit::Reload(wxWebViewReloadFlags flags)
508 if (flags & wxWEB_VIEW_RELOAD_NO_CACHE)
510 // TODO: test this indeed bypasses the cache
511 [[m_webView preferences] setUsesPageCache:NO];
512 [[m_webView mainFrame] reload];
513 [[m_webView preferences] setUsesPageCache:YES];
517 [[m_webView mainFrame] reload];
521 void wxWebViewWebKit::Stop()
526 [[m_webView mainFrame] stopLoading];
529 bool wxWebViewWebKit::CanGetPageSource()
534 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
535 return ( [[dataSource representation] canProvideDocumentSource] );
538 wxString wxWebViewWebKit::GetPageSource()
541 if (CanGetPageSource())
543 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
544 wxASSERT (dataSource != nil);
546 id<WebDocumentRepresentation> representation = [dataSource representation];
547 wxASSERT (representation != nil);
549 NSString* source = [representation documentSource];
552 return wxEmptyString;
555 return wxStringWithNSString( source );
558 return wxEmptyString;
561 bool wxWebViewWebKit::CanIncreaseTextSize()
566 if ([m_webView canMakeTextLarger])
572 void wxWebViewWebKit::IncreaseTextSize()
577 if (CanIncreaseTextSize())
578 [m_webView makeTextLarger:(WebView*)m_webView];
581 bool wxWebViewWebKit::CanDecreaseTextSize()
586 if ([m_webView canMakeTextSmaller])
592 void wxWebViewWebKit::DecreaseTextSize()
597 if (CanDecreaseTextSize())
598 [m_webView makeTextSmaller:(WebView*)m_webView];
601 void wxWebViewWebKit::Print()
604 // TODO: allow specifying the "show prompt" parameter in Print() ?
605 bool showPrompt = true;
610 id view = [[[m_webView mainFrame] frameView] documentView];
611 NSPrintOperation *op = [NSPrintOperation printOperationWithView:view
612 printInfo: [NSPrintInfo sharedPrintInfo]];
615 [op setShowsPrintPanel: showPrompt];
616 // in my tests, the progress bar always freezes and it stops the whole
617 // print operation. do not turn this to true unless there is a
618 // workaround for the bug.
619 [op setShowsProgressPanel: false];
625 void wxWebViewWebKit::SetEditable(bool enable)
630 [m_webView setEditable:enable ];
633 bool wxWebViewWebKit::IsEditable()
638 return [m_webView isEditable];
641 void wxWebViewWebKit::SetZoomType(wxWebViewZoomType zoomType)
643 // there is only one supported zoom type at the moment so this setter
644 // does nothing beyond checking sanity
645 wxASSERT(zoomType == wxWEB_VIEW_ZOOM_TYPE_TEXT);
648 wxWebViewZoomType wxWebViewWebKit::GetZoomType() const
650 // for now that's the only one that is supported
651 // FIXME: does the default zoom type change depending on webkit versions? :S
652 // Then this will be wrong
653 return wxWEB_VIEW_ZOOM_TYPE_TEXT;
656 bool wxWebViewWebKit::CanSetZoomType(wxWebViewZoomType type) const
660 // for now that's the only one that is supported
661 // TODO: I know recent versions of webkit support layout zoom too,
662 // check if we can support it
663 case wxWEB_VIEW_ZOOM_TYPE_TEXT:
671 int wxWebViewWebKit::GetScrollPos()
673 id result = [[m_webView windowScriptObject]
674 evaluateWebScript:@"document.body.scrollTop"];
675 return [result intValue];
678 void wxWebViewWebKit::SetScrollPos(int pos)
684 javascript.Printf(wxT("document.body.scrollTop = %d;"), pos);
685 [[m_webView windowScriptObject] evaluateWebScript:
686 (NSString*)wxNSStringWithWxString( javascript )];
689 wxString wxWebViewWebKit::GetSelectedText()
691 NSString* selection = [[m_webView selectedDOMRange] markupString];
692 if (!selection) return wxEmptyString;
694 return wxStringWithNSString(selection);
697 void wxWebViewWebKit::RunScript(const wxString& javascript)
702 [[m_webView windowScriptObject] evaluateWebScript:
703 (NSString*)wxNSStringWithWxString( javascript )];
706 void wxWebViewWebKit::OnSize(wxSizeEvent &event)
708 #if defined(__WXMAC_) && wxOSX_USE_CARBON
709 // This is a nasty hack because WebKit seems to lose its position when it is
710 // embedded in a control that is not itself the content view for a TLW.
711 // I put it in OnSize because these calcs are not perfect, and in fact are
712 // basically guesses based on reverse engineering, so it's best to give
713 // people the option of overriding OnSize with their own calcs if need be.
714 // I also left some test debugging print statements as a convenience if
715 // a(nother) problem crops up.
717 wxWindow* tlw = MacGetTopLevelWindow();
719 NSRect frame = [(WebView*)m_webView frame];
720 NSRect bounds = [(WebView*)m_webView bounds];
722 #if DEBUG_WEBKIT_SIZING
723 fprintf(stderr,"Carbon window x=%d, y=%d, width=%d, height=%d\n",
724 GetPosition().x, GetPosition().y, GetSize().x, GetSize().y);
725 fprintf(stderr, "Cocoa window frame x=%G, y=%G, width=%G, height=%G\n",
726 frame.origin.x, frame.origin.y,
727 frame.size.width, frame.size.height);
728 fprintf(stderr, "Cocoa window bounds x=%G, y=%G, width=%G, height=%G\n",
729 bounds.origin.x, bounds.origin.y,
730 bounds.size.width, bounds.size.height);
733 // This must be the case that Apple tested with, because well, in this one case
734 // we don't need to do anything! It just works. ;)
735 if (GetParent() == tlw) return;
737 // since we no longer use parent coordinates, we always want 0,0.
745 #if DEBUG_WEBKIT_SIZING
746 printf("Before conversion, origin is: x = %d, y = %d\n", x, y);
749 // NB: In most cases, when calling HIViewConvertRect, what people want is to
750 // use GetRootControl(), and this tripped me up at first. But in fact, what
751 // we want is the root view, because we need to make the y origin relative
752 // to the very top of the window, not its contents, since we later flip
753 // the y coordinate for Cocoa.
754 HIViewConvertRect (&rect, m_peer->GetControlRef(),
756 (WindowRef) MacGetTopLevelWindowRef()
759 x = (int)rect.origin.x;
760 y = (int)rect.origin.y;
762 #if DEBUG_WEBKIT_SIZING
763 printf("Moving Cocoa frame origin to: x = %d, y = %d\n", x, y);
767 //flip the y coordinate to convert to Cocoa coordinates
768 y = tlw->GetSize().y - ((GetSize().y) + y);
771 #if DEBUG_WEBKIT_SIZING
772 printf("y = %d after flipping value\n", y);
777 [(WebView*)m_webView setFrame:frame];
780 [(WebView*)m_webView display];
785 void wxWebViewWebKit::MacVisibilityChanged(){
786 #if defined(__WXMAC__) && wxOSX_USE_CARBON
787 bool isHidden = !IsControlVisible( m_peer->GetControlRef());
789 [(WebView*)m_webView display];
791 [m_webView setHidden:isHidden];
795 void wxWebViewWebKit::LoadUrl(const wxString& url)
797 [[m_webView mainFrame] loadRequest:[NSURLRequest requestWithURL:
798 [NSURL URLWithString:wxNSStringWithWxString(url)]]];
801 wxString wxWebViewWebKit::GetCurrentURL()
803 return wxStringWithNSString([m_webView mainFrameURL]);
806 wxString wxWebViewWebKit::GetCurrentTitle()
808 return wxStringWithNSString([m_webView mainFrameTitle]);
811 float wxWebViewWebKit::GetWebkitZoom()
813 return [m_webView textSizeMultiplier];
816 void wxWebViewWebKit::SetWebkitZoom(float zoom)
818 [m_webView setTextSizeMultiplier:zoom];
821 wxWebViewZoom wxWebViewWebKit::GetZoom()
823 float zoom = GetWebkitZoom();
825 // arbitrary way to map float zoom to our common zoom enum
828 return wxWEB_VIEW_ZOOM_TINY;
830 else if (zoom > 0.55 && zoom <= 0.85)
832 return wxWEB_VIEW_ZOOM_SMALL;
834 else if (zoom > 0.85 && zoom <= 1.15)
836 return wxWEB_VIEW_ZOOM_MEDIUM;
838 else if (zoom > 1.15 && zoom <= 1.45)
840 return wxWEB_VIEW_ZOOM_LARGE;
842 else if (zoom > 1.45)
844 return wxWEB_VIEW_ZOOM_LARGEST;
847 // to shut up compilers, this can never be reached logically
849 return wxWEB_VIEW_ZOOM_MEDIUM;
852 void wxWebViewWebKit::SetZoom(wxWebViewZoom zoom)
854 // arbitrary way to map our common zoom enum to float zoom
857 case wxWEB_VIEW_ZOOM_TINY:
861 case wxWEB_VIEW_ZOOM_SMALL:
865 case wxWEB_VIEW_ZOOM_MEDIUM:
869 case wxWEB_VIEW_ZOOM_LARGE:
873 case wxWEB_VIEW_ZOOM_LARGEST:
883 void wxWebViewWebKit::SetPage(const wxString& src, const wxString& baseUrl)
888 [[m_webView mainFrame] loadHTMLString:(NSString*)wxNSStringWithWxString(src)
889 baseURL:[NSURL URLWithString:
890 wxNSStringWithWxString( baseUrl )]];
893 void wxWebViewWebKit::Cut()
898 [(WebView*)m_webView cut:m_webView];
901 void wxWebViewWebKit::Copy()
906 [(WebView*)m_webView copy:m_webView];
909 void wxWebViewWebKit::Paste()
914 [(WebView*)m_webView paste:m_webView];
917 void wxWebViewWebKit::DeleteSelection()
922 [(WebView*)m_webView deleteSelection];
925 bool wxWebViewWebKit::HasSelection()
927 DOMRange* range = [m_webView selectedDOMRange];
938 void wxWebViewWebKit::EnableHistory(bool enable)
943 [m_webView setMaintainsBackForwardList:enable];
946 void wxWebViewWebKit::ClearHistory()
948 [m_webView setMaintainsBackForwardList:NO];
949 [m_webView setMaintainsBackForwardList:YES];
952 wxVector<wxSharedPtr<wxWebHistoryItem> > wxWebViewWebKit::GetBackwardHistory()
954 wxVector<wxSharedPtr<wxWebHistoryItem> > backhist;
955 WebBackForwardList* history = [m_webView backForwardList];
956 int count = [history backListCount];
957 for(int i = -count; i < 0; i++)
959 WebHistoryItem* item = [history itemAtIndex:i];
960 wxString url = wxStringWithNSString([item URLString]);
961 wxString title = wxStringWithNSString([item title]);
962 wxWebHistoryItem* wxitem = new wxWebHistoryItem(url, title);
963 wxitem->m_histItem = item;
964 wxSharedPtr<wxWebHistoryItem> itemptr(wxitem);
965 backhist.push_back(itemptr);
970 wxVector<wxSharedPtr<wxWebHistoryItem> > wxWebViewWebKit::GetForwardHistory()
972 wxVector<wxSharedPtr<wxWebHistoryItem> > forwardhist;
973 WebBackForwardList* history = [m_webView backForwardList];
974 int count = [history forwardListCount];
975 for(int i = 1; i <= count; i++)
977 WebHistoryItem* item = [history itemAtIndex:i];
978 wxString url = wxStringWithNSString([item URLString]);
979 wxString title = wxStringWithNSString([item title]);
980 wxWebHistoryItem* wxitem = new wxWebHistoryItem(url, title);
981 wxitem->m_histItem = item;
982 wxSharedPtr<wxWebHistoryItem> itemptr(wxitem);
983 forwardhist.push_back(itemptr);
988 void wxWebViewWebKit::LoadHistoryItem(wxSharedPtr<wxWebHistoryItem> item)
990 [m_webView goToBackForwardItem:item->m_histItem];
993 bool wxWebViewWebKit::CanUndo()
995 return [[m_webView undoManager] canUndo];
998 bool wxWebViewWebKit::CanRedo()
1000 return [[m_webView undoManager] canRedo];
1003 void wxWebViewWebKit::Undo()
1005 [[m_webView undoManager] undo];
1008 void wxWebViewWebKit::Redo()
1010 [[m_webView undoManager] redo];
1013 //------------------------------------------------------------
1014 // Listener interfaces
1015 //------------------------------------------------------------
1017 // NB: I'm still tracking this down, but it appears the Cocoa window
1018 // still has these events fired on it while the Carbon control is being
1019 // destroyed. Therefore, we must be careful to check both the existence
1020 // of the Carbon control and the event handler before firing events.
1022 @implementation MyFrameLoadMonitor
1024 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1027 webKitWindow = inWindow; // non retained
1031 - (void)webView:(WebView *)sender
1032 didStartProvisionalLoadForFrame:(WebFrame *)frame
1034 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1035 wx_webviewctrls[sender]->m_busy = true;
1038 - (void)webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame
1040 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1041 wx_webviewctrls[sender]->m_busy = true;
1043 if (webKitWindow && frame == [sender mainFrame]){
1044 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1045 wxString target = wxStringWithNSString([frame name]);
1046 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATED,
1047 wx_webviewctrls[sender]->GetId(),
1048 wxStringWithNSString( url ),
1051 if (webKitWindow && webKitWindow->GetEventHandler())
1052 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1056 - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
1058 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1059 wx_webviewctrls[sender]->m_busy = false;
1061 if (webKitWindow && frame == [sender mainFrame]){
1062 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1064 wxString target = wxStringWithNSString([frame name]);
1065 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_LOADED,
1066 wx_webviewctrls[sender]->GetId(),
1067 wxStringWithNSString( url ),
1070 if (webKitWindow && webKitWindow->GetEventHandler())
1071 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1075 wxString nsErrorToWxHtmlError(NSError* error, wxWebNavigationError* out)
1077 *out = wxWEB_NAV_ERR_OTHER;
1079 if ([[error domain] isEqualToString:NSURLErrorDomain])
1081 switch ([error code])
1083 case NSURLErrorCannotFindHost:
1084 case NSURLErrorFileDoesNotExist:
1085 case NSURLErrorRedirectToNonExistentLocation:
1086 *out = wxWEB_NAV_ERR_NOT_FOUND;
1089 case NSURLErrorResourceUnavailable:
1090 case NSURLErrorHTTPTooManyRedirects:
1091 case NSURLErrorDataLengthExceedsMaximum:
1092 case NSURLErrorBadURL:
1093 case NSURLErrorFileIsDirectory:
1094 *out = wxWEB_NAV_ERR_REQUEST;
1097 case NSURLErrorTimedOut:
1098 case NSURLErrorDNSLookupFailed:
1099 case NSURLErrorNetworkConnectionLost:
1100 case NSURLErrorCannotConnectToHost:
1101 case NSURLErrorNotConnectedToInternet:
1102 //case NSURLErrorInternationalRoamingOff:
1103 //case NSURLErrorCallIsActive:
1104 //case NSURLErrorDataNotAllowed:
1105 *out = wxWEB_NAV_ERR_CONNECTION;
1108 case NSURLErrorCancelled:
1109 case NSURLErrorUserCancelledAuthentication:
1110 *out = wxWEB_NAV_ERR_USER_CANCELLED;
1113 case NSURLErrorCannotDecodeRawData:
1114 case NSURLErrorCannotDecodeContentData:
1115 case NSURLErrorBadServerResponse:
1116 case NSURLErrorCannotParseResponse:
1117 *out = wxWEB_NAV_ERR_REQUEST;
1120 case NSURLErrorUserAuthenticationRequired:
1121 case NSURLErrorSecureConnectionFailed:
1122 case NSURLErrorClientCertificateRequired:
1123 *out = wxWEB_NAV_ERR_AUTH;
1126 case NSURLErrorNoPermissionsToReadFile:
1127 *out = wxWEB_NAV_ERR_SECURITY;
1130 case NSURLErrorServerCertificateHasBadDate:
1131 case NSURLErrorServerCertificateUntrusted:
1132 case NSURLErrorServerCertificateHasUnknownRoot:
1133 case NSURLErrorServerCertificateNotYetValid:
1134 case NSURLErrorClientCertificateRejected:
1135 *out = wxWEB_NAV_ERR_CERTIFICATE;
1140 wxString message = wxStringWithNSString([error localizedDescription]);
1141 NSString* detail = [error localizedFailureReason];
1144 message = message + " (" + wxStringWithNSString(detail) + ")";
1149 - (void)webView:(WebView *)sender didFailLoadWithError:(NSError*) error
1150 forFrame:(WebFrame *)frame
1152 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1153 wx_webviewctrls[sender]->m_busy = false;
1155 if (webKitWindow && frame == [sender mainFrame]){
1156 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1158 wxWebNavigationError type;
1159 wxString description = nsErrorToWxHtmlError(error, &type);
1160 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1161 wx_webviewctrls[sender]->GetId(),
1162 wxStringWithNSString( url ),
1163 wxEmptyString, false);
1164 thisEvent.SetString(description);
1165 thisEvent.SetInt(type);
1167 if (webKitWindow && webKitWindow->GetEventHandler())
1169 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1174 - (void)webView:(WebView *)sender
1175 didFailProvisionalLoadWithError:(NSError*)error
1176 forFrame:(WebFrame *)frame
1178 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1179 wx_webviewctrls[sender]->m_busy = false;
1181 if (webKitWindow && frame == [sender mainFrame]){
1182 NSString *url = [[[[frame provisionalDataSource] request] URL]
1185 wxWebNavigationError type;
1186 wxString description = nsErrorToWxHtmlError(error, &type);
1187 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1188 wx_webviewctrls[sender]->GetId(),
1189 wxStringWithNSString( url ),
1190 wxEmptyString, false);
1191 thisEvent.SetString(description);
1192 thisEvent.SetInt(type);
1194 if (webKitWindow && webKitWindow->GetEventHandler())
1195 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1199 - (void)webView:(WebView *)sender didReceiveTitle:(NSString *)title
1200 forFrame:(WebFrame *)frame
1202 wxString target = wxStringWithNSString([frame name]);
1203 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_TITLE_CHANGED,
1204 wx_webviewctrls[sender]->GetId(),
1205 wx_webviewctrls[sender]->GetCurrentURL(),
1208 thisEvent.SetString(wxStringWithNSString(title));
1210 if (webKitWindow && webKitWindow->GetEventHandler())
1211 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1215 @implementation MyPolicyDelegate
1217 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1220 webKitWindow = inWindow; // non retained
1224 - (void)webView:(WebView *)sender
1225 decidePolicyForNavigationAction:(NSDictionary *)actionInformation
1226 request:(NSURLRequest *)request
1227 frame:(WebFrame *)frame
1228 decisionListener:(id<WebPolicyDecisionListener>)listener
1232 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1233 wx_webviewctrls[sender]->m_busy = true;
1234 NSString *url = [[request URL] absoluteString];
1235 wxString target = wxStringWithNSString([frame name]);
1236 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATING,
1237 wx_webviewctrls[sender]->GetId(),
1238 wxStringWithNSString( url ), target, true);
1240 if (webKitWindow && webKitWindow->GetEventHandler())
1241 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1243 if (thisEvent.IsVetoed())
1245 wx_webviewctrls[sender]->m_busy = false;
1254 - (void)webView:(WebView *)sender
1255 decidePolicyForNewWindowAction:(NSDictionary *)actionInformation
1256 request:(NSURLRequest *)request
1257 newFrameName:(NSString *)frameName
1258 decisionListener:(id < WebPolicyDecisionListener >)listener
1260 wxUnusedVar(actionInformation);
1262 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1263 NSString *url = [[request URL] absoluteString];
1264 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NEWWINDOW,
1265 wx_webviewctrls[sender]->GetId(),
1266 wxStringWithNSString( url ), "", true);
1268 if (webKitWindow && webKitWindow->GetEventHandler())
1269 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1275 #endif //wxUSE_WEBVIEW_WEBKIT