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 #define DEBUG_WEBKIT_SIZING 0
38 // ----------------------------------------------------------------------------
40 // ----------------------------------------------------------------------------
42 wxIMPLEMENT_DYNAMIC_CLASS(wxWebViewWebKit, wxWebView);
44 BEGIN_EVENT_TABLE(wxWebViewWebKit, wxControl)
45 #if defined(__WXMAC__) && wxOSX_USE_CARBON
46 EVT_SIZE(wxWebViewWebKit::OnSize)
50 #if defined(__WXOSX__) && wxOSX_USE_CARBON
52 // ----------------------------------------------------------------------------
53 // Carbon Events handlers
54 // ----------------------------------------------------------------------------
56 // prototype for function in src/osx/carbon/nonownedwnd.cpp
57 void SetupMouseEvent( wxMouseEvent &wxevent , wxMacCarbonEvent &cEvent );
59 static const EventTypeSpec eventList[] =
61 //{ kEventClassControl, kEventControlTrack } ,
62 { kEventClassMouse, kEventMouseUp },
63 { kEventClassMouse, kEventMouseDown },
64 { kEventClassMouse, kEventMouseMoved },
65 { kEventClassMouse, kEventMouseDragged },
67 { kEventClassKeyboard, kEventRawKeyDown } ,
68 { kEventClassKeyboard, kEventRawKeyRepeat } ,
69 { kEventClassKeyboard, kEventRawKeyUp } ,
70 { kEventClassKeyboard, kEventRawKeyModifiersChanged } ,
72 { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent } ,
73 { kEventClassTextInput, kEventTextInputUpdateActiveInputArea } ,
75 #if DEBUG_WEBKIT_SIZING == 1
76 { kEventClassControl, kEventControlBoundsChanged } ,
80 // mix this in from window.cpp
81 pascal OSStatus wxMacUnicodeTextEventHandler(EventHandlerCallRef handler,
82 EventRef event, void *data) ;
84 // NOTE: This is mostly taken from KeyboardEventHandler in toplevel.cpp, but
85 // that expects the data pointer is a top-level window, so I needed to change
86 // that in this case. However, once 2.8 is out, we should factor out the common
87 // logic among the two functions and merge them.
88 static pascal OSStatus wxWebKitKeyEventHandler(EventHandlerCallRef handler,
89 EventRef event, void *data)
91 OSStatus result = eventNotHandledErr ;
92 wxMacCarbonEvent cEvent( event ) ;
94 wxWebViewWebKit* thisWindow = (wxWebViewWebKit*) data ;
95 wxWindow* focus = thisWindow ;
97 unsigned char charCode ;
105 UInt32 when = EventTimeToTicks( GetEventTime( event ) ) ;
108 ByteCount dataSize = 0 ;
109 if ( GetEventParameter(event, kEventParamKeyUnicodes, typeUnicodeText,
110 NULL, 0 , &dataSize, NULL ) == noErr)
113 int numChars = dataSize / sizeof( UniChar) + 1;
115 UniChar* charBuf = buf ;
117 if ( numChars * 2 > 4 )
118 charBuf = new UniChar[ numChars ] ;
119 GetEventParameter(event, kEventParamKeyUnicodes, typeUnicodeText, NULL,
120 dataSize , NULL , charBuf) ;
121 charBuf[ numChars - 1 ] = 0;
123 #if SIZEOF_WCHAR_T == 2
124 uniChar = charBuf[0] ;
126 wxMBConvUTF16 converter ;
127 converter.MB2WC( uniChar , (const char*)charBuf , 2 ) ;
130 if ( numChars * 2 > 4 )
135 GetEventParameter(event, kEventParamKeyMacCharCodes, typeChar, NULL,
136 sizeof(char), NULL, &charCode );
137 GetEventParameter(event, kEventParamKeyCode, typeUInt32, NULL,
138 sizeof(UInt32), NULL, &keyCode );
139 GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, NULL,
140 sizeof(UInt32), NULL, &modifiers );
141 GetEventParameter(event, kEventParamMouseLocation, typeQDPoint, NULL,
142 sizeof(Point), NULL, &point );
144 UInt32 message = (keyCode << 8) + charCode;
145 switch ( GetEventKind( event ) )
147 case kEventRawKeyRepeat :
148 case kEventRawKeyDown :
150 WXEVENTREF formerEvent = wxTheApp->MacGetCurrentEvent() ;
151 WXEVENTHANDLERCALLREF formerHandler =
152 wxTheApp->MacGetCurrentEventHandlerCallRef() ;
154 wxTheApp->MacSetCurrentEvent( event , handler ) ;
155 if ( /* focus && */ wxTheApp->MacSendKeyDownEvent(
156 focus, message, modifiers, when, point.h, point.v, uniChar[0]))
160 wxTheApp->MacSetCurrentEvent( formerEvent , formerHandler ) ;
164 case kEventRawKeyUp :
165 if ( /* focus && */ wxTheApp->MacSendKeyUpEvent(
166 focus , message , modifiers , when , point.h , point.v , uniChar[0] ) )
172 case kEventRawKeyModifiersChanged :
174 wxKeyEvent event(wxEVT_KEY_DOWN);
176 event.m_shiftDown = modifiers & shiftKey;
177 event.m_controlDown = modifiers & controlKey;
178 event.m_altDown = modifiers & optionKey;
179 event.m_metaDown = modifiers & cmdKey;
184 event.m_uniChar = uniChar[0] ;
187 event.SetTimestamp(when);
188 event.SetEventObject(focus);
190 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & controlKey )
192 event.m_keyCode = WXK_CONTROL ;
193 event.SetEventType( ( modifiers & controlKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
194 focus->GetEventHandler()->ProcessEvent( event ) ;
196 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & shiftKey )
198 event.m_keyCode = WXK_SHIFT ;
199 event.SetEventType( ( modifiers & shiftKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
200 focus->GetEventHandler()->ProcessEvent( event ) ;
202 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & optionKey )
204 event.m_keyCode = WXK_ALT ;
205 event.SetEventType( ( modifiers & optionKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
206 focus->GetEventHandler()->ProcessEvent( event ) ;
208 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & cmdKey )
210 event.m_keyCode = WXK_COMMAND ;
211 event.SetEventType( ( modifiers & cmdKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
212 focus->GetEventHandler()->ProcessEvent( event ) ;
215 wxApp::s_lastModifiers = modifiers ;
226 static pascal OSStatus wxWebViewWebKitEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
228 OSStatus result = eventNotHandledErr ;
230 wxMacCarbonEvent cEvent( event ) ;
232 ControlRef controlRef ;
233 wxWebViewWebKit* thisWindow = (wxWebViewWebKit*) data ;
234 wxNonOwnedWindow* tlw = NULL;
236 tlw = thisWindow->MacGetTopLevelWindow();
238 cEvent.GetParameter( kEventParamDirectObject , &controlRef ) ;
240 wxWindow* currentMouseWindow = thisWindow ;
242 if ( wxApp::s_captureWindow )
243 currentMouseWindow = wxApp::s_captureWindow;
245 switch ( GetEventClass( event ) )
247 case kEventClassKeyboard:
249 result = wxWebKitKeyEventHandler(handler, event, data);
253 case kEventClassTextInput:
255 result = wxMacUnicodeTextEventHandler(handler, event, data);
259 case kEventClassMouse:
261 switch ( GetEventKind( event ) )
263 case kEventMouseDragged :
264 case kEventMouseMoved :
265 case kEventMouseDown :
268 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
269 SetupMouseEvent( wxevent , cEvent ) ;
271 currentMouseWindow->ScreenToClient( &wxevent.m_x , &wxevent.m_y ) ;
272 wxevent.SetEventObject( currentMouseWindow ) ;
273 wxevent.SetId( currentMouseWindow->GetId() ) ;
275 if ( currentMouseWindow->GetEventHandler()->ProcessEvent(wxevent) )
280 break; // this should enable WebKit to fire mouse dragged and mouse up events...
290 result = CallNextEventHandler(handler, event);
294 DEFINE_ONE_SHOT_HANDLER_GETTER( wxWebViewWebKitEventHandler )
298 @interface MyFrameLoadMonitor : NSObject
300 wxWebViewWebKit* webKitWindow;
303 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
307 @interface MyPolicyDelegate : NSObject
309 wxWebViewWebKit* webKitWindow;
312 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
316 // ----------------------------------------------------------------------------
317 // creation/destruction
318 // ----------------------------------------------------------------------------
320 bool wxWebViewWebKit::Create(wxWindow *parent,
322 const wxString& strURL,
324 const wxSize& size, long style,
325 const wxString& name)
329 wxControl::Create(parent, winID, pos, size, style, wxDefaultValidator, name);
332 m_peer = new wxMacControl(this);
334 HIWebViewCreate( m_peer->GetControlRefAddr() );
336 m_webView = (WebView*) HIWebViewGetWebView( m_peer->GetControlRef() );
338 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_3
339 if ( UMAGetSystemVersion() >= 0x1030 )
340 HIViewChangeFeatures( m_peer->GetControlRef() , kHIViewIsOpaque , 0 ) ;
342 InstallControlEventHandler(m_peer->GetControlRef(),
343 GetwxWebViewWebKitEventHandlerUPP(),
344 GetEventTypeCount(eventList), eventList, this,
345 (EventHandlerRef *)&m_webKitCtrlEventHandler);
347 NSRect r = wxOSXGetFrameForControl( this, pos , size ) ;
348 m_webView = [[WebView alloc] initWithFrame:r
349 frameName:@"webkitFrame"
350 groupName:@"webkitGroup"];
351 m_peer = new wxWidgetCocoaImpl( this, m_webView );
354 MacPostControlCreate(pos, size);
357 HIViewSetVisible( m_peer->GetControlRef(), true );
359 [m_webView setHidden:false];
363 // Register event listener interfaces
364 MyFrameLoadMonitor* myFrameLoadMonitor =
365 [[MyFrameLoadMonitor alloc] initWithWxWindow: this];
367 [m_webView setFrameLoadDelegate:myFrameLoadMonitor];
369 // this is used to veto page loads, etc.
370 MyPolicyDelegate* myPolicyDelegate =
371 [[MyPolicyDelegate alloc] initWithWxWindow: this];
373 [m_webView setPolicyDelegate:myPolicyDelegate];
379 wxWebViewWebKit::~wxWebViewWebKit()
381 MyFrameLoadMonitor* myFrameLoadMonitor = [m_webView frameLoadDelegate];
382 MyPolicyDelegate* myPolicyDelegate = [m_webView policyDelegate];
383 [m_webView setFrameLoadDelegate: nil];
384 [m_webView setPolicyDelegate: nil];
386 if (myFrameLoadMonitor)
387 [myFrameLoadMonitor release];
389 if (myPolicyDelegate)
390 [myPolicyDelegate release];
393 // ----------------------------------------------------------------------------
395 // ----------------------------------------------------------------------------
397 bool wxWebViewWebKit::CanGoBack()
402 return [m_webView canGoBack];
405 bool wxWebViewWebKit::CanGoForward()
410 return [m_webView canGoForward];
413 void wxWebViewWebKit::GoBack()
418 bool result = [(WebView*)m_webView goBack];
420 // TODO: return result (if it also exists in other backends...)
424 void wxWebViewWebKit::GoForward()
429 bool result = [(WebView*)m_webView goForward];
431 // TODO: return result (if it also exists in other backends...)
435 void wxWebViewWebKit::Reload(wxWebViewReloadFlags flags)
440 if (flags & wxWEB_VIEW_RELOAD_NO_CACHE)
442 // TODO: test this indeed bypasses the cache
443 [[m_webView preferences] setUsesPageCache:NO];
444 [[m_webView mainFrame] reload];
445 [[m_webView preferences] setUsesPageCache:YES];
449 [[m_webView mainFrame] reload];
453 void wxWebViewWebKit::Stop()
458 [[m_webView mainFrame] stopLoading];
461 bool wxWebViewWebKit::CanGetPageSource()
466 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
467 return ( [[dataSource representation] canProvideDocumentSource] );
470 wxString wxWebViewWebKit::GetPageSource()
473 if (CanGetPageSource())
475 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
476 wxASSERT (dataSource != nil);
478 id<WebDocumentRepresentation> representation = [dataSource representation];
479 wxASSERT (representation != nil);
481 NSString* source = [representation documentSource];
484 return wxEmptyString;
487 return wxStringWithNSString( source );
490 return wxEmptyString;
493 bool wxWebViewWebKit::CanIncreaseTextSize()
498 if ([m_webView canMakeTextLarger])
504 void wxWebViewWebKit::IncreaseTextSize()
509 if (CanIncreaseTextSize())
510 [m_webView makeTextLarger:(WebView*)m_webView];
513 bool wxWebViewWebKit::CanDecreaseTextSize()
518 if ([m_webView canMakeTextSmaller])
524 void wxWebViewWebKit::DecreaseTextSize()
529 if (CanDecreaseTextSize())
530 [m_webView makeTextSmaller:(WebView*)m_webView];
533 void wxWebViewWebKit::Print()
536 // TODO: allow specifying the "show prompt" parameter in Print() ?
537 bool showPrompt = true;
542 id view = [[[m_webView mainFrame] frameView] documentView];
543 NSPrintOperation *op = [NSPrintOperation printOperationWithView:view
544 printInfo: [NSPrintInfo sharedPrintInfo]];
547 [op setShowsPrintPanel: showPrompt];
548 // in my tests, the progress bar always freezes and it stops the whole
549 // print operation. do not turn this to true unless there is a
550 // workaround for the bug.
551 [op setShowsProgressPanel: false];
557 void wxWebViewWebKit::SetEditable(bool enable)
562 [m_webView setEditable:enable ];
565 bool wxWebViewWebKit::IsEditable()
570 return [m_webView isEditable];
573 void wxWebViewWebKit::SetZoomType(wxWebViewZoomType zoomType)
575 // there is only one supported zoom type at the moment so this setter
576 // does nothing beyond checking sanity
577 wxASSERT(zoomType == wxWEB_VIEW_ZOOM_TYPE_TEXT);
580 wxWebViewZoomType wxWebViewWebKit::GetZoomType() const
582 // for now that's the only one that is supported
583 // FIXME: does the default zoom type change depending on webkit versions? :S
584 // Then this will be wrong
585 return wxWEB_VIEW_ZOOM_TYPE_TEXT;
588 bool wxWebViewWebKit::CanSetZoomType(wxWebViewZoomType type) const
592 // for now that's the only one that is supported
593 // TODO: I know recent versions of webkit support layout zoom too,
594 // check if we can support it
595 case wxWEB_VIEW_ZOOM_TYPE_TEXT:
603 int wxWebViewWebKit::GetScrollPos()
605 id result = [[m_webView windowScriptObject]
606 evaluateWebScript:@"document.body.scrollTop"];
607 return [result intValue];
610 void wxWebViewWebKit::SetScrollPos(int pos)
616 javascript.Printf(wxT("document.body.scrollTop = %d;"), pos);
617 [[m_webView windowScriptObject] evaluateWebScript:
618 (NSString*)wxNSStringWithWxString( javascript )];
621 wxString wxWebViewWebKit::GetSelectedText()
623 NSString* selection = [[m_webView selectedDOMRange] markupString];
624 if (!selection) return wxEmptyString;
626 return wxStringWithNSString(selection);
629 void wxWebViewWebKit::RunScript(const wxString& javascript)
634 [[m_webView windowScriptObject] evaluateWebScript:
635 (NSString*)wxNSStringWithWxString( javascript )];
638 void wxWebViewWebKit::OnSize(wxSizeEvent &event)
640 #if defined(__WXMAC_) && wxOSX_USE_CARBON
641 // This is a nasty hack because WebKit seems to lose its position when it is
642 // embedded in a control that is not itself the content view for a TLW.
643 // I put it in OnSize because these calcs are not perfect, and in fact are
644 // basically guesses based on reverse engineering, so it's best to give
645 // people the option of overriding OnSize with their own calcs if need be.
646 // I also left some test debugging print statements as a convenience if
647 // a(nother) problem crops up.
649 wxWindow* tlw = MacGetTopLevelWindow();
651 NSRect frame = [(WebView*)m_webView frame];
652 NSRect bounds = [(WebView*)m_webView bounds];
654 #if DEBUG_WEBKIT_SIZING
655 fprintf(stderr,"Carbon window x=%d, y=%d, width=%d, height=%d\n",
656 GetPosition().x, GetPosition().y, GetSize().x, GetSize().y);
657 fprintf(stderr, "Cocoa window frame x=%G, y=%G, width=%G, height=%G\n",
658 frame.origin.x, frame.origin.y,
659 frame.size.width, frame.size.height);
660 fprintf(stderr, "Cocoa window bounds x=%G, y=%G, width=%G, height=%G\n",
661 bounds.origin.x, bounds.origin.y,
662 bounds.size.width, bounds.size.height);
665 // This must be the case that Apple tested with, because well, in this one case
666 // we don't need to do anything! It just works. ;)
667 if (GetParent() == tlw) return;
669 // since we no longer use parent coordinates, we always want 0,0.
677 #if DEBUG_WEBKIT_SIZING
678 printf("Before conversion, origin is: x = %d, y = %d\n", x, y);
681 // NB: In most cases, when calling HIViewConvertRect, what people want is to
682 // use GetRootControl(), and this tripped me up at first. But in fact, what
683 // we want is the root view, because we need to make the y origin relative
684 // to the very top of the window, not its contents, since we later flip
685 // the y coordinate for Cocoa.
686 HIViewConvertRect (&rect, m_peer->GetControlRef(),
688 (WindowRef) MacGetTopLevelWindowRef()
691 x = (int)rect.origin.x;
692 y = (int)rect.origin.y;
694 #if DEBUG_WEBKIT_SIZING
695 printf("Moving Cocoa frame origin to: x = %d, y = %d\n", x, y);
699 //flip the y coordinate to convert to Cocoa coordinates
700 y = tlw->GetSize().y - ((GetSize().y) + y);
703 #if DEBUG_WEBKIT_SIZING
704 printf("y = %d after flipping value\n", y);
709 [(WebView*)m_webView setFrame:frame];
712 [(WebView*)m_webView display];
717 void wxWebViewWebKit::MacVisibilityChanged(){
718 #if defined(__WXMAC__) && wxOSX_USE_CARBON
719 bool isHidden = !IsControlVisible( m_peer->GetControlRef());
721 [(WebView*)m_webView display];
723 [m_webView setHidden:isHidden];
727 void wxWebViewWebKit::LoadUrl(const wxString& url)
729 [[m_webView mainFrame] loadRequest:[NSURLRequest requestWithURL:
730 [NSURL URLWithString:wxNSStringWithWxString(url)]]];
733 wxString wxWebViewWebKit::GetCurrentURL()
735 return wxStringWithNSString([m_webView mainFrameURL]);
738 wxString wxWebViewWebKit::GetCurrentTitle()
740 return wxStringWithNSString([m_webView mainFrameTitle]);
743 float wxWebViewWebKit::GetWebkitZoom()
745 return [m_webView textSizeMultiplier];
748 void wxWebViewWebKit::SetWebkitZoom(float zoom)
750 [m_webView setTextSizeMultiplier:zoom];
753 wxWebViewZoom wxWebViewWebKit::GetZoom()
755 float zoom = GetWebkitZoom();
757 // arbitrary way to map float zoom to our common zoom enum
760 return wxWEB_VIEW_ZOOM_TINY;
762 else if (zoom > 0.55 && zoom <= 0.85)
764 return wxWEB_VIEW_ZOOM_SMALL;
766 else if (zoom > 0.85 && zoom <= 1.15)
768 return wxWEB_VIEW_ZOOM_MEDIUM;
770 else if (zoom > 1.15 && zoom <= 1.45)
772 return wxWEB_VIEW_ZOOM_LARGE;
774 else if (zoom > 1.45)
776 return wxWEB_VIEW_ZOOM_LARGEST;
779 // to shut up compilers, this can never be reached logically
781 return wxWEB_VIEW_ZOOM_MEDIUM;
784 void wxWebViewWebKit::SetZoom(wxWebViewZoom zoom)
786 // arbitrary way to map our common zoom enum to float zoom
789 case wxWEB_VIEW_ZOOM_TINY:
793 case wxWEB_VIEW_ZOOM_SMALL:
797 case wxWEB_VIEW_ZOOM_MEDIUM:
801 case wxWEB_VIEW_ZOOM_LARGE:
805 case wxWEB_VIEW_ZOOM_LARGEST:
815 void wxWebViewWebKit::SetPage(const wxString& src, const wxString& baseUrl)
820 [[m_webView mainFrame] loadHTMLString:(NSString*)wxNSStringWithWxString(src)
821 baseURL:[NSURL URLWithString:
822 wxNSStringWithWxString( baseUrl )]];
825 void wxWebViewWebKit::Cut()
830 [(WebView*)m_webView cut:m_webView];
833 void wxWebViewWebKit::Copy()
838 [(WebView*)m_webView copy:m_webView];
841 void wxWebViewWebKit::Paste()
846 [(WebView*)m_webView paste:m_webView];
849 void wxWebViewWebKit::DeleteSelection()
854 [(WebView*)m_webView deleteSelection];
857 bool wxWebViewWebKit::HasSelection()
859 DOMRange* range = [m_webView selectedDOMRange];
870 void wxWebViewWebKit::ClearSelection()
872 //We use javascript as selection isn't exposed at the moment in webkit
873 RunScript("window.getSelection().removeAllRanges();");
876 void wxWebViewWebKit::SelectAll()
878 RunScript("window.getSelection().selectAllChildren(document.body);");
881 wxString wxWebViewWebKit::GetSelectedSource()
883 wxString script = ("var range = window.getSelection().getRangeAt(0);"
884 "var element = document.createElement('div');"
885 "element.appendChild(range.cloneContents());"
886 "return element.innerHTML;");
887 id result = [[m_webView windowScriptObject]
888 evaluateWebScript:wxNSStringWithWxString(script)];
889 return wxStringWithNSString([result stringValue]);
892 wxString wxWebViewWebKit::GetPageText()
894 id result = [[m_webView windowScriptObject]
895 evaluateWebScript:@"document.body.textContent"];
896 return wxStringWithNSString([result stringValue]);
899 void wxWebViewWebKit::EnableHistory(bool enable)
904 [m_webView setMaintainsBackForwardList:enable];
907 void wxWebViewWebKit::ClearHistory()
909 [m_webView setMaintainsBackForwardList:NO];
910 [m_webView setMaintainsBackForwardList:YES];
913 wxVector<wxSharedPtr<wxWebHistoryItem> > wxWebViewWebKit::GetBackwardHistory()
915 wxVector<wxSharedPtr<wxWebHistoryItem> > backhist;
916 WebBackForwardList* history = [m_webView backForwardList];
917 int count = [history backListCount];
918 for(int i = -count; i < 0; i++)
920 WebHistoryItem* item = [history itemAtIndex:i];
921 wxString url = wxStringWithNSString([item URLString]);
922 wxString title = wxStringWithNSString([item title]);
923 wxWebHistoryItem* wxitem = new wxWebHistoryItem(url, title);
924 wxitem->m_histItem = item;
925 wxSharedPtr<wxWebHistoryItem> itemptr(wxitem);
926 backhist.push_back(itemptr);
931 wxVector<wxSharedPtr<wxWebHistoryItem> > wxWebViewWebKit::GetForwardHistory()
933 wxVector<wxSharedPtr<wxWebHistoryItem> > forwardhist;
934 WebBackForwardList* history = [m_webView backForwardList];
935 int count = [history forwardListCount];
936 for(int i = 1; i <= count; i++)
938 WebHistoryItem* item = [history itemAtIndex:i];
939 wxString url = wxStringWithNSString([item URLString]);
940 wxString title = wxStringWithNSString([item title]);
941 wxWebHistoryItem* wxitem = new wxWebHistoryItem(url, title);
942 wxitem->m_histItem = item;
943 wxSharedPtr<wxWebHistoryItem> itemptr(wxitem);
944 forwardhist.push_back(itemptr);
949 void wxWebViewWebKit::LoadHistoryItem(wxSharedPtr<wxWebHistoryItem> item)
951 [m_webView goToBackForwardItem:item->m_histItem];
954 bool wxWebViewWebKit::CanUndo()
956 return [[m_webView undoManager] canUndo];
959 bool wxWebViewWebKit::CanRedo()
961 return [[m_webView undoManager] canRedo];
964 void wxWebViewWebKit::Undo()
966 [[m_webView undoManager] undo];
969 void wxWebViewWebKit::Redo()
971 [[m_webView undoManager] redo];
974 //------------------------------------------------------------
975 // Listener interfaces
976 //------------------------------------------------------------
978 // NB: I'm still tracking this down, but it appears the Cocoa window
979 // still has these events fired on it while the Carbon control is being
980 // destroyed. Therefore, we must be careful to check both the existence
981 // of the Carbon control and the event handler before firing events.
983 @implementation MyFrameLoadMonitor
985 - initWithWxWindow: (wxWebViewWebKit*)inWindow
988 webKitWindow = inWindow; // non retained
992 - (void)webView:(WebView *)sender
993 didStartProvisionalLoadForFrame:(WebFrame *)frame
995 webKitWindow->m_busy = true;
998 - (void)webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame
1000 webKitWindow->m_busy = true;
1002 if (webKitWindow && frame == [sender mainFrame]){
1003 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1004 wxString target = wxStringWithNSString([frame name]);
1005 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATED,
1006 webKitWindow->GetId(),
1007 wxStringWithNSString( url ),
1010 if (webKitWindow && webKitWindow->GetEventHandler())
1011 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1015 - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
1017 webKitWindow->m_busy = false;
1019 if (webKitWindow && frame == [sender mainFrame]){
1020 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1022 wxString target = wxStringWithNSString([frame name]);
1023 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_LOADED,
1024 webKitWindow->GetId(),
1025 wxStringWithNSString( url ),
1028 if (webKitWindow && webKitWindow->GetEventHandler())
1029 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1033 wxString nsErrorToWxHtmlError(NSError* error, wxWebNavigationError* out)
1035 *out = wxWEB_NAV_ERR_OTHER;
1037 if ([[error domain] isEqualToString:NSURLErrorDomain])
1039 switch ([error code])
1041 case NSURLErrorCannotFindHost:
1042 case NSURLErrorFileDoesNotExist:
1043 case NSURLErrorRedirectToNonExistentLocation:
1044 *out = wxWEB_NAV_ERR_NOT_FOUND;
1047 case NSURLErrorResourceUnavailable:
1048 case NSURLErrorHTTPTooManyRedirects:
1049 case NSURLErrorDataLengthExceedsMaximum:
1050 case NSURLErrorBadURL:
1051 case NSURLErrorFileIsDirectory:
1052 *out = wxWEB_NAV_ERR_REQUEST;
1055 case NSURLErrorTimedOut:
1056 case NSURLErrorDNSLookupFailed:
1057 case NSURLErrorNetworkConnectionLost:
1058 case NSURLErrorCannotConnectToHost:
1059 case NSURLErrorNotConnectedToInternet:
1060 //case NSURLErrorInternationalRoamingOff:
1061 //case NSURLErrorCallIsActive:
1062 //case NSURLErrorDataNotAllowed:
1063 *out = wxWEB_NAV_ERR_CONNECTION;
1066 case NSURLErrorCancelled:
1067 case NSURLErrorUserCancelledAuthentication:
1068 *out = wxWEB_NAV_ERR_USER_CANCELLED;
1071 case NSURLErrorCannotDecodeRawData:
1072 case NSURLErrorCannotDecodeContentData:
1073 case NSURLErrorBadServerResponse:
1074 case NSURLErrorCannotParseResponse:
1075 *out = wxWEB_NAV_ERR_REQUEST;
1078 case NSURLErrorUserAuthenticationRequired:
1079 case NSURLErrorSecureConnectionFailed:
1080 case NSURLErrorClientCertificateRequired:
1081 *out = wxWEB_NAV_ERR_AUTH;
1084 case NSURLErrorNoPermissionsToReadFile:
1085 *out = wxWEB_NAV_ERR_SECURITY;
1088 case NSURLErrorServerCertificateHasBadDate:
1089 case NSURLErrorServerCertificateUntrusted:
1090 case NSURLErrorServerCertificateHasUnknownRoot:
1091 case NSURLErrorServerCertificateNotYetValid:
1092 case NSURLErrorClientCertificateRejected:
1093 *out = wxWEB_NAV_ERR_CERTIFICATE;
1098 wxString message = wxStringWithNSString([error localizedDescription]);
1099 NSString* detail = [error localizedFailureReason];
1102 message = message + " (" + wxStringWithNSString(detail) + ")";
1107 - (void)webView:(WebView *)sender didFailLoadWithError:(NSError*) error
1108 forFrame:(WebFrame *)frame
1110 webKitWindow->m_busy = false;
1112 if (webKitWindow && frame == [sender mainFrame]){
1113 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1115 wxWebNavigationError type;
1116 wxString description = nsErrorToWxHtmlError(error, &type);
1117 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1118 webKitWindow->GetId(),
1119 wxStringWithNSString( url ),
1120 wxEmptyString, false);
1121 thisEvent.SetString(description);
1122 thisEvent.SetInt(type);
1124 if (webKitWindow && webKitWindow->GetEventHandler())
1126 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1131 - (void)webView:(WebView *)sender
1132 didFailProvisionalLoadWithError:(NSError*)error
1133 forFrame:(WebFrame *)frame
1135 webKitWindow->m_busy = false;
1137 if (webKitWindow && frame == [sender mainFrame]){
1138 NSString *url = [[[[frame provisionalDataSource] request] URL]
1141 wxWebNavigationError type;
1142 wxString description = nsErrorToWxHtmlError(error, &type);
1143 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1144 webKitWindow->GetId(),
1145 wxStringWithNSString( url ),
1146 wxEmptyString, false);
1147 thisEvent.SetString(description);
1148 thisEvent.SetInt(type);
1150 if (webKitWindow && webKitWindow->GetEventHandler())
1151 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1155 - (void)webView:(WebView *)sender didReceiveTitle:(NSString *)title
1156 forFrame:(WebFrame *)frame
1158 wxString target = wxStringWithNSString([frame name]);
1159 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_TITLE_CHANGED,
1160 webKitWindow->GetId(),
1161 webKitWindow->GetCurrentURL(),
1164 thisEvent.SetString(wxStringWithNSString(title));
1166 if (webKitWindow && webKitWindow->GetEventHandler())
1167 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1171 @implementation MyPolicyDelegate
1173 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1176 webKitWindow = inWindow; // non retained
1180 - (void)webView:(WebView *)sender
1181 decidePolicyForNavigationAction:(NSDictionary *)actionInformation
1182 request:(NSURLRequest *)request
1183 frame:(WebFrame *)frame
1184 decisionListener:(id<WebPolicyDecisionListener>)listener
1188 webKitWindow->m_busy = true;
1189 NSString *url = [[request URL] absoluteString];
1190 wxString target = wxStringWithNSString([frame name]);
1191 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATING,
1192 webKitWindow->GetId(),
1193 wxStringWithNSString( url ), target, true);
1195 if (webKitWindow && webKitWindow->GetEventHandler())
1196 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1198 if (thisEvent.IsVetoed())
1200 webKitWindow->m_busy = false;
1209 - (void)webView:(WebView *)sender
1210 decidePolicyForNewWindowAction:(NSDictionary *)actionInformation
1211 request:(NSURLRequest *)request
1212 newFrameName:(NSString *)frameName
1213 decisionListener:(id < WebPolicyDecisionListener >)listener
1215 wxUnusedVar(actionInformation);
1217 NSString *url = [[request URL] absoluteString];
1218 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NEWWINDOW,
1219 webKitWindow->GetId(),
1220 wxStringWithNSString( url ), "", true);
1222 if (webKitWindow && webKitWindow->GetEventHandler())
1223 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1229 #endif //wxUSE_WEBVIEW_WEBKIT