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"
27 #include "wx/osx/private.h"
28 #include "wx/cocoa/string.h"
30 #include <WebKit/WebKit.h>
31 #include <WebKit/HIWebView.h>
32 #include <WebKit/CarbonUtils.h>
34 #include <Foundation/NSURLError.h>
36 // FIXME: find cleaner way to find the wxWidgets ID of a webview than this hack
38 std::map<WebView*, wxWebViewWebKit*> wx_webviewctrls;
40 #define DEBUG_WEBKIT_SIZING 0
42 // ----------------------------------------------------------------------------
44 // ----------------------------------------------------------------------------
46 wxIMPLEMENT_DYNAMIC_CLASS(wxWebViewWebKit, wxWebView);
48 BEGIN_EVENT_TABLE(wxWebViewWebKit, wxControl)
49 #if defined(__WXMAC__) && wxOSX_USE_CARBON
50 EVT_SIZE(wxWebViewWebKit::OnSize)
54 #if defined(__WXOSX__) && wxOSX_USE_CARBON
56 // ----------------------------------------------------------------------------
57 // Carbon Events handlers
58 // ----------------------------------------------------------------------------
60 // prototype for function in src/osx/carbon/nonownedwnd.cpp
61 void SetupMouseEvent( wxMouseEvent &wxevent , wxMacCarbonEvent &cEvent );
63 static const EventTypeSpec eventList[] =
65 //{ kEventClassControl, kEventControlTrack } ,
66 { kEventClassMouse, kEventMouseUp },
67 { kEventClassMouse, kEventMouseDown },
68 { kEventClassMouse, kEventMouseMoved },
69 { kEventClassMouse, kEventMouseDragged },
71 { kEventClassKeyboard, kEventRawKeyDown } ,
72 { kEventClassKeyboard, kEventRawKeyRepeat } ,
73 { kEventClassKeyboard, kEventRawKeyUp } ,
74 { kEventClassKeyboard, kEventRawKeyModifiersChanged } ,
76 { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent } ,
77 { kEventClassTextInput, kEventTextInputUpdateActiveInputArea } ,
79 #if DEBUG_WEBKIT_SIZING == 1
80 { kEventClassControl, kEventControlBoundsChanged } ,
84 // mix this in from window.cpp
85 pascal OSStatus wxMacUnicodeTextEventHandler(EventHandlerCallRef handler,
86 EventRef event, void *data) ;
88 // NOTE: This is mostly taken from KeyboardEventHandler in toplevel.cpp, but
89 // that expects the data pointer is a top-level window, so I needed to change
90 // that in this case. However, once 2.8 is out, we should factor out the common
91 // logic among the two functions and merge them.
92 static pascal OSStatus wxWebKitKeyEventHandler(EventHandlerCallRef handler,
93 EventRef event, void *data)
95 OSStatus result = eventNotHandledErr ;
96 wxMacCarbonEvent cEvent( event ) ;
98 wxWebViewWebKit* thisWindow = (wxWebViewWebKit*) data ;
99 wxWindow* focus = thisWindow ;
101 unsigned char charCode ;
109 UInt32 when = EventTimeToTicks( GetEventTime( event ) ) ;
112 ByteCount dataSize = 0 ;
113 if ( GetEventParameter(event, kEventParamKeyUnicodes, typeUnicodeText,
114 NULL, 0 , &dataSize, NULL ) == noErr)
117 int numChars = dataSize / sizeof( UniChar) + 1;
119 UniChar* charBuf = buf ;
121 if ( numChars * 2 > 4 )
122 charBuf = new UniChar[ numChars ] ;
123 GetEventParameter(event, kEventParamKeyUnicodes, typeUnicodeText, NULL,
124 dataSize , NULL , charBuf) ;
125 charBuf[ numChars - 1 ] = 0;
127 #if SIZEOF_WCHAR_T == 2
128 uniChar = charBuf[0] ;
130 wxMBConvUTF16 converter ;
131 converter.MB2WC( uniChar , (const char*)charBuf , 2 ) ;
134 if ( numChars * 2 > 4 )
139 GetEventParameter(event, kEventParamKeyMacCharCodes, typeChar, NULL,
140 sizeof(char), NULL, &charCode );
141 GetEventParameter(event, kEventParamKeyCode, typeUInt32, NULL,
142 sizeof(UInt32), NULL, &keyCode );
143 GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, NULL,
144 sizeof(UInt32), NULL, &modifiers );
145 GetEventParameter(event, kEventParamMouseLocation, typeQDPoint, NULL,
146 sizeof(Point), NULL, &point );
148 UInt32 message = (keyCode << 8) + charCode;
149 switch ( GetEventKind( event ) )
151 case kEventRawKeyRepeat :
152 case kEventRawKeyDown :
154 WXEVENTREF formerEvent = wxTheApp->MacGetCurrentEvent() ;
155 WXEVENTHANDLERCALLREF formerHandler =
156 wxTheApp->MacGetCurrentEventHandlerCallRef() ;
158 wxTheApp->MacSetCurrentEvent( event , handler ) ;
159 if ( /* focus && */ wxTheApp->MacSendKeyDownEvent(
160 focus, message, modifiers, when, point.h, point.v, uniChar[0]))
164 wxTheApp->MacSetCurrentEvent( formerEvent , formerHandler ) ;
168 case kEventRawKeyUp :
169 if ( /* focus && */ wxTheApp->MacSendKeyUpEvent(
170 focus , message , modifiers , when , point.h , point.v , uniChar[0] ) )
176 case kEventRawKeyModifiersChanged :
178 wxKeyEvent event(wxEVT_KEY_DOWN);
180 event.m_shiftDown = modifiers & shiftKey;
181 event.m_controlDown = modifiers & controlKey;
182 event.m_altDown = modifiers & optionKey;
183 event.m_metaDown = modifiers & cmdKey;
188 event.m_uniChar = uniChar[0] ;
191 event.SetTimestamp(when);
192 event.SetEventObject(focus);
194 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & controlKey )
196 event.m_keyCode = WXK_CONTROL ;
197 event.SetEventType( ( modifiers & controlKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
198 focus->GetEventHandler()->ProcessEvent( event ) ;
200 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & shiftKey )
202 event.m_keyCode = WXK_SHIFT ;
203 event.SetEventType( ( modifiers & shiftKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
204 focus->GetEventHandler()->ProcessEvent( event ) ;
206 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & optionKey )
208 event.m_keyCode = WXK_ALT ;
209 event.SetEventType( ( modifiers & optionKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
210 focus->GetEventHandler()->ProcessEvent( event ) ;
212 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & cmdKey )
214 event.m_keyCode = WXK_COMMAND ;
215 event.SetEventType( ( modifiers & cmdKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
216 focus->GetEventHandler()->ProcessEvent( event ) ;
219 wxApp::s_lastModifiers = modifiers ;
230 static pascal OSStatus wxWebViewWebKitEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
232 OSStatus result = eventNotHandledErr ;
234 wxMacCarbonEvent cEvent( event ) ;
236 ControlRef controlRef ;
237 wxWebViewWebKit* thisWindow = (wxWebViewWebKit*) data ;
238 wxNonOwnedWindow* tlw = NULL;
240 tlw = thisWindow->MacGetTopLevelWindow();
242 cEvent.GetParameter( kEventParamDirectObject , &controlRef ) ;
244 wxWindow* currentMouseWindow = thisWindow ;
246 if ( wxApp::s_captureWindow )
247 currentMouseWindow = wxApp::s_captureWindow;
249 switch ( GetEventClass( event ) )
251 case kEventClassKeyboard:
253 result = wxWebKitKeyEventHandler(handler, event, data);
257 case kEventClassTextInput:
259 result = wxMacUnicodeTextEventHandler(handler, event, data);
263 case kEventClassMouse:
265 switch ( GetEventKind( event ) )
267 case kEventMouseDragged :
268 case kEventMouseMoved :
269 case kEventMouseDown :
272 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
273 SetupMouseEvent( wxevent , cEvent ) ;
275 currentMouseWindow->ScreenToClient( &wxevent.m_x , &wxevent.m_y ) ;
276 wxevent.SetEventObject( currentMouseWindow ) ;
277 wxevent.SetId( currentMouseWindow->GetId() ) ;
279 if ( currentMouseWindow->GetEventHandler()->ProcessEvent(wxevent) )
284 break; // this should enable WebKit to fire mouse dragged and mouse up events...
294 result = CallNextEventHandler(handler, event);
298 DEFINE_ONE_SHOT_HANDLER_GETTER( wxWebViewWebKitEventHandler )
302 @interface MyFrameLoadMonitor : NSObject
304 wxWebViewWebKit* webKitWindow;
307 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
311 @interface MyPolicyDelegate : NSObject
313 wxWebViewWebKit* webKitWindow;
316 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
320 // ----------------------------------------------------------------------------
321 // creation/destruction
322 // ----------------------------------------------------------------------------
324 bool wxWebViewWebKit::Create(wxWindow *parent,
326 const wxString& strURL,
328 const wxSize& size, long style,
329 const wxString& name)
333 wxControl::Create(parent, winID, pos, size, style, wxDefaultValidator, name);
336 m_peer = new wxMacControl(this);
338 HIWebViewCreate( m_peer->GetControlRefAddr() );
340 m_webView = (WebView*) HIWebViewGetWebView( m_peer->GetControlRef() );
342 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_3
343 if ( UMAGetSystemVersion() >= 0x1030 )
344 HIViewChangeFeatures( m_peer->GetControlRef() , kHIViewIsOpaque , 0 ) ;
346 InstallControlEventHandler(m_peer->GetControlRef(),
347 GetwxWebViewWebKitEventHandlerUPP(),
348 GetEventTypeCount(eventList), eventList, this,
349 (EventHandlerRef *)&m_webKitCtrlEventHandler);
351 NSRect r = wxOSXGetFrameForControl( this, pos , size ) ;
352 m_webView = [[WebView alloc] initWithFrame:r
353 frameName:@"webkitFrame"
354 groupName:@"webkitGroup"];
355 m_peer = new wxWidgetCocoaImpl( this, m_webView );
358 wx_webviewctrls[m_webView] = this;
360 MacPostControlCreate(pos, size);
363 HIViewSetVisible( m_peer->GetControlRef(), true );
365 [m_webView setHidden:false];
369 // Register event listener interfaces
370 MyFrameLoadMonitor* myFrameLoadMonitor =
371 [[MyFrameLoadMonitor alloc] initWithWxWindow: this];
373 [m_webView setFrameLoadDelegate:myFrameLoadMonitor];
375 // this is used to veto page loads, etc.
376 MyPolicyDelegate* myPolicyDelegate =
377 [[MyPolicyDelegate alloc] initWithWxWindow: this];
379 [m_webView setPolicyDelegate:myPolicyDelegate];
385 wxWebViewWebKit::~wxWebViewWebKit()
387 MyFrameLoadMonitor* myFrameLoadMonitor = [m_webView frameLoadDelegate];
388 MyPolicyDelegate* myPolicyDelegate = [m_webView policyDelegate];
389 [m_webView setFrameLoadDelegate: nil];
390 [m_webView setPolicyDelegate: nil];
392 if (myFrameLoadMonitor)
393 [myFrameLoadMonitor release];
395 if (myPolicyDelegate)
396 [myPolicyDelegate release];
399 // ----------------------------------------------------------------------------
401 // ----------------------------------------------------------------------------
403 bool wxWebViewWebKit::CanGoBack()
408 return [m_webView canGoBack];
411 bool wxWebViewWebKit::CanGoForward()
416 return [m_webView canGoForward];
419 void wxWebViewWebKit::GoBack()
424 bool result = [(WebView*)m_webView goBack];
426 // TODO: return result (if it also exists in other backends...)
430 void wxWebViewWebKit::GoForward()
435 bool result = [(WebView*)m_webView goForward];
437 // TODO: return result (if it also exists in other backends...)
441 void wxWebViewWebKit::Reload(wxWebViewReloadFlags flags)
446 if (flags & wxWEB_VIEW_RELOAD_NO_CACHE)
448 // TODO: test this indeed bypasses the cache
449 [[m_webView preferences] setUsesPageCache:NO];
450 [[m_webView mainFrame] reload];
451 [[m_webView preferences] setUsesPageCache:YES];
455 [[m_webView mainFrame] reload];
459 void wxWebViewWebKit::Stop()
464 [[m_webView mainFrame] stopLoading];
467 bool wxWebViewWebKit::CanGetPageSource()
472 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
473 return ( [[dataSource representation] canProvideDocumentSource] );
476 wxString wxWebViewWebKit::GetPageSource()
479 if (CanGetPageSource())
481 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
482 wxASSERT (dataSource != nil);
484 id<WebDocumentRepresentation> representation = [dataSource representation];
485 wxASSERT (representation != nil);
487 NSString* source = [representation documentSource];
490 return wxEmptyString;
493 return wxStringWithNSString( source );
496 return wxEmptyString;
499 bool wxWebViewWebKit::CanIncreaseTextSize()
504 if ([m_webView canMakeTextLarger])
510 void wxWebViewWebKit::IncreaseTextSize()
515 if (CanIncreaseTextSize())
516 [m_webView makeTextLarger:(WebView*)m_webView];
519 bool wxWebViewWebKit::CanDecreaseTextSize()
524 if ([m_webView canMakeTextSmaller])
530 void wxWebViewWebKit::DecreaseTextSize()
535 if (CanDecreaseTextSize())
536 [m_webView makeTextSmaller:(WebView*)m_webView];
539 void wxWebViewWebKit::Print()
542 // TODO: allow specifying the "show prompt" parameter in Print() ?
543 bool showPrompt = true;
548 id view = [[[m_webView mainFrame] frameView] documentView];
549 NSPrintOperation *op = [NSPrintOperation printOperationWithView:view
550 printInfo: [NSPrintInfo sharedPrintInfo]];
553 [op setShowsPrintPanel: showPrompt];
554 // in my tests, the progress bar always freezes and it stops the whole
555 // print operation. do not turn this to true unless there is a
556 // workaround for the bug.
557 [op setShowsProgressPanel: false];
563 void wxWebViewWebKit::SetEditable(bool enable)
568 [m_webView setEditable:enable ];
571 bool wxWebViewWebKit::IsEditable()
576 return [m_webView isEditable];
579 void wxWebViewWebKit::SetZoomType(wxWebViewZoomType zoomType)
581 // there is only one supported zoom type at the moment so this setter
582 // does nothing beyond checking sanity
583 wxASSERT(zoomType == wxWEB_VIEW_ZOOM_TYPE_TEXT);
586 wxWebViewZoomType wxWebViewWebKit::GetZoomType() const
588 // for now that's the only one that is supported
589 // FIXME: does the default zoom type change depending on webkit versions? :S
590 // Then this will be wrong
591 return wxWEB_VIEW_ZOOM_TYPE_TEXT;
594 bool wxWebViewWebKit::CanSetZoomType(wxWebViewZoomType type) const
598 // for now that's the only one that is supported
599 // TODO: I know recent versions of webkit support layout zoom too,
600 // check if we can support it
601 case wxWEB_VIEW_ZOOM_TYPE_TEXT:
609 int wxWebViewWebKit::GetScrollPos()
611 id result = [[m_webView windowScriptObject]
612 evaluateWebScript:@"document.body.scrollTop"];
613 return [result intValue];
616 void wxWebViewWebKit::SetScrollPos(int pos)
622 javascript.Printf(wxT("document.body.scrollTop = %d;"), pos);
623 [[m_webView windowScriptObject] evaluateWebScript:
624 (NSString*)wxNSStringWithWxString( javascript )];
627 wxString wxWebViewWebKit::GetSelectedText()
629 NSString* selection = [[m_webView selectedDOMRange] markupString];
630 if (!selection) return wxEmptyString;
632 return wxStringWithNSString(selection);
635 void wxWebViewWebKit::RunScript(const wxString& javascript)
640 [[m_webView windowScriptObject] evaluateWebScript:
641 (NSString*)wxNSStringWithWxString( javascript )];
644 void wxWebViewWebKit::OnSize(wxSizeEvent &event)
646 #if defined(__WXMAC_) && wxOSX_USE_CARBON
647 // This is a nasty hack because WebKit seems to lose its position when it is
648 // embedded in a control that is not itself the content view for a TLW.
649 // I put it in OnSize because these calcs are not perfect, and in fact are
650 // basically guesses based on reverse engineering, so it's best to give
651 // people the option of overriding OnSize with their own calcs if need be.
652 // I also left some test debugging print statements as a convenience if
653 // a(nother) problem crops up.
655 wxWindow* tlw = MacGetTopLevelWindow();
657 NSRect frame = [(WebView*)m_webView frame];
658 NSRect bounds = [(WebView*)m_webView bounds];
660 #if DEBUG_WEBKIT_SIZING
661 fprintf(stderr,"Carbon window x=%d, y=%d, width=%d, height=%d\n",
662 GetPosition().x, GetPosition().y, GetSize().x, GetSize().y);
663 fprintf(stderr, "Cocoa window frame x=%G, y=%G, width=%G, height=%G\n",
664 frame.origin.x, frame.origin.y,
665 frame.size.width, frame.size.height);
666 fprintf(stderr, "Cocoa window bounds x=%G, y=%G, width=%G, height=%G\n",
667 bounds.origin.x, bounds.origin.y,
668 bounds.size.width, bounds.size.height);
671 // This must be the case that Apple tested with, because well, in this one case
672 // we don't need to do anything! It just works. ;)
673 if (GetParent() == tlw) return;
675 // since we no longer use parent coordinates, we always want 0,0.
683 #if DEBUG_WEBKIT_SIZING
684 printf("Before conversion, origin is: x = %d, y = %d\n", x, y);
687 // NB: In most cases, when calling HIViewConvertRect, what people want is to
688 // use GetRootControl(), and this tripped me up at first. But in fact, what
689 // we want is the root view, because we need to make the y origin relative
690 // to the very top of the window, not its contents, since we later flip
691 // the y coordinate for Cocoa.
692 HIViewConvertRect (&rect, m_peer->GetControlRef(),
694 (WindowRef) MacGetTopLevelWindowRef()
697 x = (int)rect.origin.x;
698 y = (int)rect.origin.y;
700 #if DEBUG_WEBKIT_SIZING
701 printf("Moving Cocoa frame origin to: x = %d, y = %d\n", x, y);
705 //flip the y coordinate to convert to Cocoa coordinates
706 y = tlw->GetSize().y - ((GetSize().y) + y);
709 #if DEBUG_WEBKIT_SIZING
710 printf("y = %d after flipping value\n", y);
715 [(WebView*)m_webView setFrame:frame];
718 [(WebView*)m_webView display];
723 void wxWebViewWebKit::MacVisibilityChanged(){
724 #if defined(__WXMAC__) && wxOSX_USE_CARBON
725 bool isHidden = !IsControlVisible( m_peer->GetControlRef());
727 [(WebView*)m_webView display];
729 [m_webView setHidden:isHidden];
733 void wxWebViewWebKit::LoadUrl(const wxString& url)
735 [[m_webView mainFrame] loadRequest:[NSURLRequest requestWithURL:
736 [NSURL URLWithString:wxNSStringWithWxString(url)]]];
739 wxString wxWebViewWebKit::GetCurrentURL()
741 return wxStringWithNSString([m_webView mainFrameURL]);
744 wxString wxWebViewWebKit::GetCurrentTitle()
746 return wxStringWithNSString([m_webView mainFrameTitle]);
749 float wxWebViewWebKit::GetWebkitZoom()
751 return [m_webView textSizeMultiplier];
754 void wxWebViewWebKit::SetWebkitZoom(float zoom)
756 [m_webView setTextSizeMultiplier:zoom];
759 wxWebViewZoom wxWebViewWebKit::GetZoom()
761 float zoom = GetWebkitZoom();
763 // arbitrary way to map float zoom to our common zoom enum
766 return wxWEB_VIEW_ZOOM_TINY;
768 else if (zoom > 0.55 && zoom <= 0.85)
770 return wxWEB_VIEW_ZOOM_SMALL;
772 else if (zoom > 0.85 && zoom <= 1.15)
774 return wxWEB_VIEW_ZOOM_MEDIUM;
776 else if (zoom > 1.15 && zoom <= 1.45)
778 return wxWEB_VIEW_ZOOM_LARGE;
780 else if (zoom > 1.45)
782 return wxWEB_VIEW_ZOOM_LARGEST;
785 // to shut up compilers, this can never be reached logically
787 return wxWEB_VIEW_ZOOM_MEDIUM;
790 void wxWebViewWebKit::SetZoom(wxWebViewZoom zoom)
792 // arbitrary way to map our common zoom enum to float zoom
795 case wxWEB_VIEW_ZOOM_TINY:
799 case wxWEB_VIEW_ZOOM_SMALL:
803 case wxWEB_VIEW_ZOOM_MEDIUM:
807 case wxWEB_VIEW_ZOOM_LARGE:
811 case wxWEB_VIEW_ZOOM_LARGEST:
821 void wxWebViewWebKit::SetPage(const wxString& src, const wxString& baseUrl)
826 [[m_webView mainFrame] loadHTMLString:(NSString*)wxNSStringWithWxString(src)
827 baseURL:[NSURL URLWithString:
828 wxNSStringWithWxString( baseUrl )]];
831 void wxWebViewWebKit::Cut()
836 [(WebView*)m_webView cut:m_webView];
839 void wxWebViewWebKit::Copy()
844 [(WebView*)m_webView copy:m_webView];
847 void wxWebViewWebKit::Paste()
852 [(WebView*)m_webView paste:m_webView];
855 void wxWebViewWebKit::DeleteSelection()
860 [(WebView*)m_webView deleteSelection];
863 bool wxWebViewWebKit::HasSelection()
865 DOMRange* range = [m_webView selectedDOMRange];
876 void wxWebViewWebKit::ClearSelection()
878 //We use javascript as selection isn't exposed at the moment in webkit
879 RunScript("window.getSelection().removeAllRanges();");
882 void wxWebViewWebKit::SelectAll()
884 RunScript("window.getSelection().selectAllChildren(document.body);");
887 wxString wxWebViewWebKit::GetSelectedSource()
889 wxString script = ("var range = window.getSelection().getRangeAt(0);"
890 "var element = document.createElement('div');"
891 "element.appendChild(range.cloneContents());"
892 "return element.innerHTML;");
893 id result = [[m_webView windowScriptObject]
894 evaluateWebScript:wxNSStringWithWxString(script)];
895 return wxStringWithNSString([result stringValue]);
898 wxString wxWebViewWebKit::GetPageText()
900 id result = [[m_webView windowScriptObject]
901 evaluateWebScript:@"document.body.textContent"];
902 return wxStringWithNSString([result stringValue]);
905 void wxWebViewWebKit::EnableHistory(bool enable)
910 [m_webView setMaintainsBackForwardList:enable];
913 void wxWebViewWebKit::ClearHistory()
915 [m_webView setMaintainsBackForwardList:NO];
916 [m_webView setMaintainsBackForwardList:YES];
919 wxVector<wxSharedPtr<wxWebHistoryItem> > wxWebViewWebKit::GetBackwardHistory()
921 wxVector<wxSharedPtr<wxWebHistoryItem> > backhist;
922 WebBackForwardList* history = [m_webView backForwardList];
923 int count = [history backListCount];
924 for(int i = -count; i < 0; i++)
926 WebHistoryItem* item = [history itemAtIndex:i];
927 wxString url = wxStringWithNSString([item URLString]);
928 wxString title = wxStringWithNSString([item title]);
929 wxWebHistoryItem* wxitem = new wxWebHistoryItem(url, title);
930 wxitem->m_histItem = item;
931 wxSharedPtr<wxWebHistoryItem> itemptr(wxitem);
932 backhist.push_back(itemptr);
937 wxVector<wxSharedPtr<wxWebHistoryItem> > wxWebViewWebKit::GetForwardHistory()
939 wxVector<wxSharedPtr<wxWebHistoryItem> > forwardhist;
940 WebBackForwardList* history = [m_webView backForwardList];
941 int count = [history forwardListCount];
942 for(int i = 1; i <= count; i++)
944 WebHistoryItem* item = [history itemAtIndex:i];
945 wxString url = wxStringWithNSString([item URLString]);
946 wxString title = wxStringWithNSString([item title]);
947 wxWebHistoryItem* wxitem = new wxWebHistoryItem(url, title);
948 wxitem->m_histItem = item;
949 wxSharedPtr<wxWebHistoryItem> itemptr(wxitem);
950 forwardhist.push_back(itemptr);
955 void wxWebViewWebKit::LoadHistoryItem(wxSharedPtr<wxWebHistoryItem> item)
957 [m_webView goToBackForwardItem:item->m_histItem];
960 bool wxWebViewWebKit::CanUndo()
962 return [[m_webView undoManager] canUndo];
965 bool wxWebViewWebKit::CanRedo()
967 return [[m_webView undoManager] canRedo];
970 void wxWebViewWebKit::Undo()
972 [[m_webView undoManager] undo];
975 void wxWebViewWebKit::Redo()
977 [[m_webView undoManager] redo];
980 //------------------------------------------------------------
981 // Listener interfaces
982 //------------------------------------------------------------
984 // NB: I'm still tracking this down, but it appears the Cocoa window
985 // still has these events fired on it while the Carbon control is being
986 // destroyed. Therefore, we must be careful to check both the existence
987 // of the Carbon control and the event handler before firing events.
989 @implementation MyFrameLoadMonitor
991 - initWithWxWindow: (wxWebViewWebKit*)inWindow
994 webKitWindow = inWindow; // non retained
998 - (void)webView:(WebView *)sender
999 didStartProvisionalLoadForFrame:(WebFrame *)frame
1001 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1002 wx_webviewctrls[sender]->m_busy = true;
1005 - (void)webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame
1007 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1008 wx_webviewctrls[sender]->m_busy = true;
1010 if (webKitWindow && frame == [sender mainFrame]){
1011 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1012 wxString target = wxStringWithNSString([frame name]);
1013 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATED,
1014 wx_webviewctrls[sender]->GetId(),
1015 wxStringWithNSString( url ),
1018 if (webKitWindow && webKitWindow->GetEventHandler())
1019 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1023 - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
1025 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1026 wx_webviewctrls[sender]->m_busy = false;
1028 if (webKitWindow && frame == [sender mainFrame]){
1029 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1031 wxString target = wxStringWithNSString([frame name]);
1032 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_LOADED,
1033 wx_webviewctrls[sender]->GetId(),
1034 wxStringWithNSString( url ),
1037 if (webKitWindow && webKitWindow->GetEventHandler())
1038 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1042 wxString nsErrorToWxHtmlError(NSError* error, wxWebNavigationError* out)
1044 *out = wxWEB_NAV_ERR_OTHER;
1046 if ([[error domain] isEqualToString:NSURLErrorDomain])
1048 switch ([error code])
1050 case NSURLErrorCannotFindHost:
1051 case NSURLErrorFileDoesNotExist:
1052 case NSURLErrorRedirectToNonExistentLocation:
1053 *out = wxWEB_NAV_ERR_NOT_FOUND;
1056 case NSURLErrorResourceUnavailable:
1057 case NSURLErrorHTTPTooManyRedirects:
1058 case NSURLErrorDataLengthExceedsMaximum:
1059 case NSURLErrorBadURL:
1060 case NSURLErrorFileIsDirectory:
1061 *out = wxWEB_NAV_ERR_REQUEST;
1064 case NSURLErrorTimedOut:
1065 case NSURLErrorDNSLookupFailed:
1066 case NSURLErrorNetworkConnectionLost:
1067 case NSURLErrorCannotConnectToHost:
1068 case NSURLErrorNotConnectedToInternet:
1069 //case NSURLErrorInternationalRoamingOff:
1070 //case NSURLErrorCallIsActive:
1071 //case NSURLErrorDataNotAllowed:
1072 *out = wxWEB_NAV_ERR_CONNECTION;
1075 case NSURLErrorCancelled:
1076 case NSURLErrorUserCancelledAuthentication:
1077 *out = wxWEB_NAV_ERR_USER_CANCELLED;
1080 case NSURLErrorCannotDecodeRawData:
1081 case NSURLErrorCannotDecodeContentData:
1082 case NSURLErrorBadServerResponse:
1083 case NSURLErrorCannotParseResponse:
1084 *out = wxWEB_NAV_ERR_REQUEST;
1087 case NSURLErrorUserAuthenticationRequired:
1088 case NSURLErrorSecureConnectionFailed:
1089 case NSURLErrorClientCertificateRequired:
1090 *out = wxWEB_NAV_ERR_AUTH;
1093 case NSURLErrorNoPermissionsToReadFile:
1094 *out = wxWEB_NAV_ERR_SECURITY;
1097 case NSURLErrorServerCertificateHasBadDate:
1098 case NSURLErrorServerCertificateUntrusted:
1099 case NSURLErrorServerCertificateHasUnknownRoot:
1100 case NSURLErrorServerCertificateNotYetValid:
1101 case NSURLErrorClientCertificateRejected:
1102 *out = wxWEB_NAV_ERR_CERTIFICATE;
1107 wxString message = wxStringWithNSString([error localizedDescription]);
1108 NSString* detail = [error localizedFailureReason];
1111 message = message + " (" + wxStringWithNSString(detail) + ")";
1116 - (void)webView:(WebView *)sender didFailLoadWithError:(NSError*) error
1117 forFrame:(WebFrame *)frame
1119 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1120 wx_webviewctrls[sender]->m_busy = false;
1122 if (webKitWindow && frame == [sender mainFrame]){
1123 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1125 wxWebNavigationError type;
1126 wxString description = nsErrorToWxHtmlError(error, &type);
1127 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1128 wx_webviewctrls[sender]->GetId(),
1129 wxStringWithNSString( url ),
1130 wxEmptyString, false);
1131 thisEvent.SetString(description);
1132 thisEvent.SetInt(type);
1134 if (webKitWindow && webKitWindow->GetEventHandler())
1136 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1141 - (void)webView:(WebView *)sender
1142 didFailProvisionalLoadWithError:(NSError*)error
1143 forFrame:(WebFrame *)frame
1145 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1146 wx_webviewctrls[sender]->m_busy = false;
1148 if (webKitWindow && frame == [sender mainFrame]){
1149 NSString *url = [[[[frame provisionalDataSource] request] URL]
1152 wxWebNavigationError type;
1153 wxString description = nsErrorToWxHtmlError(error, &type);
1154 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1155 wx_webviewctrls[sender]->GetId(),
1156 wxStringWithNSString( url ),
1157 wxEmptyString, false);
1158 thisEvent.SetString(description);
1159 thisEvent.SetInt(type);
1161 if (webKitWindow && webKitWindow->GetEventHandler())
1162 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1166 - (void)webView:(WebView *)sender didReceiveTitle:(NSString *)title
1167 forFrame:(WebFrame *)frame
1169 wxString target = wxStringWithNSString([frame name]);
1170 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_TITLE_CHANGED,
1171 wx_webviewctrls[sender]->GetId(),
1172 wx_webviewctrls[sender]->GetCurrentURL(),
1175 thisEvent.SetString(wxStringWithNSString(title));
1177 if (webKitWindow && webKitWindow->GetEventHandler())
1178 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1182 @implementation MyPolicyDelegate
1184 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1187 webKitWindow = inWindow; // non retained
1191 - (void)webView:(WebView *)sender
1192 decidePolicyForNavigationAction:(NSDictionary *)actionInformation
1193 request:(NSURLRequest *)request
1194 frame:(WebFrame *)frame
1195 decisionListener:(id<WebPolicyDecisionListener>)listener
1199 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1200 wx_webviewctrls[sender]->m_busy = true;
1201 NSString *url = [[request URL] absoluteString];
1202 wxString target = wxStringWithNSString([frame name]);
1203 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATING,
1204 wx_webviewctrls[sender]->GetId(),
1205 wxStringWithNSString( url ), target, true);
1207 if (webKitWindow && webKitWindow->GetEventHandler())
1208 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1210 if (thisEvent.IsVetoed())
1212 wx_webviewctrls[sender]->m_busy = false;
1221 - (void)webView:(WebView *)sender
1222 decidePolicyForNewWindowAction:(NSDictionary *)actionInformation
1223 request:(NSURLRequest *)request
1224 newFrameName:(NSString *)frameName
1225 decisionListener:(id < WebPolicyDecisionListener >)listener
1227 wxUnusedVar(actionInformation);
1229 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1230 NSString *url = [[request URL] absoluteString];
1231 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NEWWINDOW,
1232 wx_webviewctrls[sender]->GetId(),
1233 wxStringWithNSString( url ), "", true);
1235 if (webKitWindow && webKitWindow->GetEventHandler())
1236 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1242 #endif //wxUSE_WEBVIEW_WEBKIT