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 WebViewLoadDelegate : NSObject
300 wxWebViewWebKit* webKitWindow;
303 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
307 @interface WebViewPolicyDelegate : 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)
330 wxControl::Create(parent, winID, pos, size, style, wxDefaultValidator, name);
333 wxMacControl* peer = new wxMacControl(this);
335 HIWebViewCreate( peer->GetControlRefAddr() );
337 m_webView = (WebView*) HIWebViewGetWebView( peer->GetControlRef() );
339 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_3
340 if ( UMAGetSystemVersion() >= 0x1030 )
341 HIViewChangeFeatures( peer->GetControlRef() , kHIViewIsOpaque , 0 ) ;
343 InstallControlEventHandler(peer->GetControlRef(),
344 GetwxWebViewWebKitEventHandlerUPP(),
345 GetEventTypeCount(eventList), eventList, this,
346 (EventHandlerRef *)&m_webKitCtrlEventHandler);
349 NSRect r = wxOSXGetFrameForControl( this, pos , size ) ;
350 m_webView = [[WebView alloc] initWithFrame:r
351 frameName:@"webkitFrame"
352 groupName:@"webkitGroup"];
353 SetPeer(new wxWidgetCocoaImpl( this, m_webView ));
356 MacPostControlCreate(pos, size);
359 HIViewSetVisible( GetPeer()->GetControlRef(), true );
361 [m_webView setHidden:false];
365 // Register event listener interfaces
366 WebViewLoadDelegate* loadDelegate =
367 [[WebViewWebKitLoadDelegate alloc] initWithWxWindow: this];
369 [m_webView setFrameLoadDelegate:loadDelegate];
371 // this is used to veto page loads, etc.
372 WebViewPolicyDelegate* policyDelegate =
373 [[WebViewPolicyDelegate alloc] initWithWxWindow: this];
375 [m_webView setPolicyDelegate:policyDelegate];
381 wxWebViewWebKit::~wxWebViewWebKit()
383 WebViewLoadDelegate* loadDelegate = [m_webView frameLoadDelegate];
384 WebViewPolicyDelegate* policyDelegate = [m_webView policyDelegate];
385 [m_webView setFrameLoadDelegate: nil];
386 [m_webView setPolicyDelegate: nil];
389 [loadDelegate release];
392 [policyDelegate release];
395 // ----------------------------------------------------------------------------
397 // ----------------------------------------------------------------------------
399 bool wxWebViewWebKit::CanGoBack()
404 return [m_webView canGoBack];
407 bool wxWebViewWebKit::CanGoForward()
412 return [m_webView canGoForward];
415 void wxWebViewWebKit::GoBack()
420 [(WebView*)m_webView goBack];
423 void wxWebViewWebKit::GoForward()
428 [(WebView*)m_webView goForward];
431 void wxWebViewWebKit::Reload(wxWebViewReloadFlags flags)
436 if (flags & wxWEB_VIEW_RELOAD_NO_CACHE)
438 // TODO: test this indeed bypasses the cache
439 [[m_webView preferences] setUsesPageCache:NO];
440 [[m_webView mainFrame] reload];
441 [[m_webView preferences] setUsesPageCache:YES];
445 [[m_webView mainFrame] reload];
449 void wxWebViewWebKit::Stop()
454 [[m_webView mainFrame] stopLoading];
457 bool wxWebViewWebKit::CanGetPageSource()
462 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
463 return ( [[dataSource representation] canProvideDocumentSource] );
466 wxString wxWebViewWebKit::GetPageSource()
469 if (CanGetPageSource())
471 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
472 wxASSERT (dataSource != nil);
474 id<WebDocumentRepresentation> representation = [dataSource representation];
475 wxASSERT (representation != nil);
477 NSString* source = [representation documentSource];
480 return wxEmptyString;
483 return wxStringWithNSString( source );
486 return wxEmptyString;
489 bool wxWebViewWebKit::CanIncreaseTextSize()
494 if ([m_webView canMakeTextLarger])
500 void wxWebViewWebKit::IncreaseTextSize()
505 if (CanIncreaseTextSize())
506 [m_webView makeTextLarger:(WebView*)m_webView];
509 bool wxWebViewWebKit::CanDecreaseTextSize()
514 if ([m_webView canMakeTextSmaller])
520 void wxWebViewWebKit::DecreaseTextSize()
525 if (CanDecreaseTextSize())
526 [m_webView makeTextSmaller:(WebView*)m_webView];
529 void wxWebViewWebKit::Print()
532 // TODO: allow specifying the "show prompt" parameter in Print() ?
533 bool showPrompt = true;
538 id view = [[[m_webView mainFrame] frameView] documentView];
539 NSPrintOperation *op = [NSPrintOperation printOperationWithView:view
540 printInfo: [NSPrintInfo sharedPrintInfo]];
543 [op setShowsPrintPanel: showPrompt];
544 // in my tests, the progress bar always freezes and it stops the whole
545 // print operation. do not turn this to true unless there is a
546 // workaround for the bug.
547 [op setShowsProgressPanel: false];
553 void wxWebViewWebKit::SetEditable(bool enable)
558 [m_webView setEditable:enable ];
561 bool wxWebViewWebKit::IsEditable()
566 return [m_webView isEditable];
569 void wxWebViewWebKit::SetZoomType(wxWebViewZoomType zoomType)
571 // there is only one supported zoom type at the moment so this setter
572 // does nothing beyond checking sanity
573 wxASSERT(zoomType == wxWEB_VIEW_ZOOM_TYPE_TEXT);
576 wxWebViewZoomType wxWebViewWebKit::GetZoomType() const
578 // for now that's the only one that is supported
579 // FIXME: does the default zoom type change depending on webkit versions? :S
580 // Then this will be wrong
581 return wxWEB_VIEW_ZOOM_TYPE_TEXT;
584 bool wxWebViewWebKit::CanSetZoomType(wxWebViewZoomType type) const
588 // for now that's the only one that is supported
589 // TODO: I know recent versions of webkit support layout zoom too,
590 // check if we can support it
591 case wxWEB_VIEW_ZOOM_TYPE_TEXT:
599 int wxWebViewWebKit::GetScrollPos()
601 id result = [[m_webView windowScriptObject]
602 evaluateWebScript:@"document.body.scrollTop"];
603 return [result intValue];
606 void wxWebViewWebKit::SetScrollPos(int pos)
612 javascript.Printf(wxT("document.body.scrollTop = %d;"), pos);
613 [[m_webView windowScriptObject] evaluateWebScript:
614 (NSString*)wxNSStringWithWxString( javascript )];
617 wxString wxWebViewWebKit::GetSelectedText()
619 NSString* selection = [[m_webView selectedDOMRange] markupString];
620 if (!selection) return wxEmptyString;
622 return wxStringWithNSString(selection);
625 void wxWebViewWebKit::RunScript(const wxString& javascript)
630 [[m_webView windowScriptObject] evaluateWebScript:
631 (NSString*)wxNSStringWithWxString( javascript )];
634 void wxWebViewWebKit::OnSize(wxSizeEvent &event)
636 #if defined(__WXMAC_) && wxOSX_USE_CARBON
637 // This is a nasty hack because WebKit seems to lose its position when it is
638 // embedded in a control that is not itself the content view for a TLW.
639 // I put it in OnSize because these calcs are not perfect, and in fact are
640 // basically guesses based on reverse engineering, so it's best to give
641 // people the option of overriding OnSize with their own calcs if need be.
642 // I also left some test debugging print statements as a convenience if
643 // a(nother) problem crops up.
645 wxWindow* tlw = MacGetTopLevelWindow();
647 NSRect frame = [(WebView*)m_webView frame];
648 NSRect bounds = [(WebView*)m_webView bounds];
650 #if DEBUG_WEBKIT_SIZING
651 fprintf(stderr,"Carbon window x=%d, y=%d, width=%d, height=%d\n",
652 GetPosition().x, GetPosition().y, GetSize().x, GetSize().y);
653 fprintf(stderr, "Cocoa window frame x=%G, y=%G, width=%G, height=%G\n",
654 frame.origin.x, frame.origin.y,
655 frame.size.width, frame.size.height);
656 fprintf(stderr, "Cocoa window bounds x=%G, y=%G, width=%G, height=%G\n",
657 bounds.origin.x, bounds.origin.y,
658 bounds.size.width, bounds.size.height);
661 // This must be the case that Apple tested with, because well, in this one case
662 // we don't need to do anything! It just works. ;)
663 if (GetParent() == tlw) return;
665 // since we no longer use parent coordinates, we always want 0,0.
673 #if DEBUG_WEBKIT_SIZING
674 printf("Before conversion, origin is: x = %d, y = %d\n", x, y);
677 // NB: In most cases, when calling HIViewConvertRect, what people want is to
678 // use GetRootControl(), and this tripped me up at first. But in fact, what
679 // we want is the root view, because we need to make the y origin relative
680 // to the very top of the window, not its contents, since we later flip
681 // the y coordinate for Cocoa.
682 HIViewConvertRect (&rect, m_peer->GetControlRef(),
684 (WindowRef) MacGetTopLevelWindowRef()
687 x = (int)rect.origin.x;
688 y = (int)rect.origin.y;
690 #if DEBUG_WEBKIT_SIZING
691 printf("Moving Cocoa frame origin to: x = %d, y = %d\n", x, y);
695 //flip the y coordinate to convert to Cocoa coordinates
696 y = tlw->GetSize().y - ((GetSize().y) + y);
699 #if DEBUG_WEBKIT_SIZING
700 printf("y = %d after flipping value\n", y);
705 [(WebView*)m_webView setFrame:frame];
708 [(WebView*)m_webView display];
713 void wxWebViewWebKit::MacVisibilityChanged(){
714 #if defined(__WXMAC__) && wxOSX_USE_CARBON
715 bool isHidden = !IsControlVisible( GetPeer()->GetControlRef());
717 [(WebView*)m_webView display];
719 [m_webView setHidden:isHidden];
723 void wxWebViewWebKit::LoadUrl(const wxString& url)
725 [[m_webView mainFrame] loadRequest:[NSURLRequest requestWithURL:
726 [NSURL URLWithString:wxNSStringWithWxString(url)]]];
729 wxString wxWebViewWebKit::GetCurrentURL()
731 return wxStringWithNSString([m_webView mainFrameURL]);
734 wxString wxWebViewWebKit::GetCurrentTitle()
736 return wxStringWithNSString([m_webView mainFrameTitle]);
739 float wxWebViewWebKit::GetWebkitZoom()
741 return [m_webView textSizeMultiplier];
744 void wxWebViewWebKit::SetWebkitZoom(float zoom)
746 [m_webView setTextSizeMultiplier:zoom];
749 wxWebViewZoom wxWebViewWebKit::GetZoom()
751 float zoom = GetWebkitZoom();
753 // arbitrary way to map float zoom to our common zoom enum
756 return wxWEB_VIEW_ZOOM_TINY;
758 else if (zoom > 0.55 && zoom <= 0.85)
760 return wxWEB_VIEW_ZOOM_SMALL;
762 else if (zoom > 0.85 && zoom <= 1.15)
764 return wxWEB_VIEW_ZOOM_MEDIUM;
766 else if (zoom > 1.15 && zoom <= 1.45)
768 return wxWEB_VIEW_ZOOM_LARGE;
770 else if (zoom > 1.45)
772 return wxWEB_VIEW_ZOOM_LARGEST;
775 // to shut up compilers, this can never be reached logically
777 return wxWEB_VIEW_ZOOM_MEDIUM;
780 void wxWebViewWebKit::SetZoom(wxWebViewZoom zoom)
782 // arbitrary way to map our common zoom enum to float zoom
785 case wxWEB_VIEW_ZOOM_TINY:
789 case wxWEB_VIEW_ZOOM_SMALL:
793 case wxWEB_VIEW_ZOOM_MEDIUM:
797 case wxWEB_VIEW_ZOOM_LARGE:
801 case wxWEB_VIEW_ZOOM_LARGEST:
811 void wxWebViewWebKit::SetPage(const wxString& src, const wxString& baseUrl)
816 [[m_webView mainFrame] loadHTMLString:(NSString*)wxNSStringWithWxString(src)
817 baseURL:[NSURL URLWithString:
818 wxNSStringWithWxString( baseUrl )]];
821 void wxWebViewWebKit::Cut()
826 [(WebView*)m_webView cut:m_webView];
829 void wxWebViewWebKit::Copy()
834 [(WebView*)m_webView copy:m_webView];
837 void wxWebViewWebKit::Paste()
842 [(WebView*)m_webView paste:m_webView];
845 void wxWebViewWebKit::DeleteSelection()
850 [(WebView*)m_webView deleteSelection];
853 bool wxWebViewWebKit::HasSelection()
855 DOMRange* range = [m_webView selectedDOMRange];
866 void wxWebViewWebKit::ClearSelection()
868 //We use javascript as selection isn't exposed at the moment in webkit
869 RunScript("window.getSelection().removeAllRanges();");
872 void wxWebViewWebKit::SelectAll()
874 RunScript("window.getSelection().selectAllChildren(document.body);");
877 wxString wxWebViewWebKit::GetSelectedSource()
879 wxString script = ("var range = window.getSelection().getRangeAt(0);"
880 "var element = document.createElement('div');"
881 "element.appendChild(range.cloneContents());"
882 "return element.innerHTML;");
883 id result = [[m_webView windowScriptObject]
884 evaluateWebScript:wxNSStringWithWxString(script)];
885 return wxStringWithNSString([result stringValue]);
888 wxString wxWebViewWebKit::GetPageText()
890 id result = [[m_webView windowScriptObject]
891 evaluateWebScript:@"document.body.textContent"];
892 return wxStringWithNSString([result stringValue]);
895 void wxWebViewWebKit::EnableHistory(bool enable)
900 [m_webView setMaintainsBackForwardList:enable];
903 void wxWebViewWebKit::ClearHistory()
905 [m_webView setMaintainsBackForwardList:NO];
906 [m_webView setMaintainsBackForwardList:YES];
909 wxVector<wxSharedPtr<wxWebHistoryItem> > wxWebViewWebKit::GetBackwardHistory()
911 wxVector<wxSharedPtr<wxWebHistoryItem> > backhist;
912 WebBackForwardList* history = [m_webView backForwardList];
913 int count = [history backListCount];
914 for(int i = -count; i < 0; i++)
916 WebHistoryItem* item = [history itemAtIndex:i];
917 wxString url = wxStringWithNSString([item URLString]);
918 wxString title = wxStringWithNSString([item title]);
919 wxWebHistoryItem* wxitem = new wxWebHistoryItem(url, title);
920 wxitem->m_histItem = item;
921 wxSharedPtr<wxWebHistoryItem> itemptr(wxitem);
922 backhist.push_back(itemptr);
927 wxVector<wxSharedPtr<wxWebHistoryItem> > wxWebViewWebKit::GetForwardHistory()
929 wxVector<wxSharedPtr<wxWebHistoryItem> > forwardhist;
930 WebBackForwardList* history = [m_webView backForwardList];
931 int count = [history forwardListCount];
932 for(int i = 1; i <= count; i++)
934 WebHistoryItem* item = [history itemAtIndex:i];
935 wxString url = wxStringWithNSString([item URLString]);
936 wxString title = wxStringWithNSString([item title]);
937 wxWebHistoryItem* wxitem = new wxWebHistoryItem(url, title);
938 wxitem->m_histItem = item;
939 wxSharedPtr<wxWebHistoryItem> itemptr(wxitem);
940 forwardhist.push_back(itemptr);
945 void wxWebViewWebKit::LoadHistoryItem(wxSharedPtr<wxWebHistoryItem> item)
947 [m_webView goToBackForwardItem:item->m_histItem];
950 bool wxWebViewWebKit::CanUndo()
952 return [[m_webView undoManager] canUndo];
955 bool wxWebViewWebKit::CanRedo()
957 return [[m_webView undoManager] canRedo];
960 void wxWebViewWebKit::Undo()
962 [[m_webView undoManager] undo];
965 void wxWebViewWebKit::Redo()
967 [[m_webView undoManager] redo];
970 //------------------------------------------------------------
971 // Listener interfaces
972 //------------------------------------------------------------
974 // NB: I'm still tracking this down, but it appears the Cocoa window
975 // still has these events fired on it while the Carbon control is being
976 // destroyed. Therefore, we must be careful to check both the existence
977 // of the Carbon control and the event handler before firing events.
979 @implementation WebViewLoadDelegate
981 - initWithWxWindow: (wxWebViewWebKit*)inWindow
984 webKitWindow = inWindow; // non retained
988 - (void)webView:(WebView *)sender
989 didStartProvisionalLoadForFrame:(WebFrame *)frame
991 webKitWindow->m_busy = true;
994 - (void)webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame
996 webKitWindow->m_busy = true;
998 if (webKitWindow && frame == [sender mainFrame]){
999 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1000 wxString target = wxStringWithNSString([frame name]);
1001 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATED,
1002 webKitWindow->GetId(),
1003 wxStringWithNSString( url ),
1006 if (webKitWindow && webKitWindow->GetEventHandler())
1007 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1011 - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
1013 webKitWindow->m_busy = false;
1015 if (webKitWindow && frame == [sender mainFrame]){
1016 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1018 wxString target = wxStringWithNSString([frame name]);
1019 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_LOADED,
1020 webKitWindow->GetId(),
1021 wxStringWithNSString( url ),
1024 if (webKitWindow && webKitWindow->GetEventHandler())
1025 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1029 wxString nsErrorToWxHtmlError(NSError* error, wxWebNavigationError* out)
1031 *out = wxWEB_NAV_ERR_OTHER;
1033 if ([[error domain] isEqualToString:NSURLErrorDomain])
1035 switch ([error code])
1037 case NSURLErrorCannotFindHost:
1038 case NSURLErrorFileDoesNotExist:
1039 case NSURLErrorRedirectToNonExistentLocation:
1040 *out = wxWEB_NAV_ERR_NOT_FOUND;
1043 case NSURLErrorResourceUnavailable:
1044 case NSURLErrorHTTPTooManyRedirects:
1045 case NSURLErrorDataLengthExceedsMaximum:
1046 case NSURLErrorBadURL:
1047 case NSURLErrorFileIsDirectory:
1048 *out = wxWEB_NAV_ERR_REQUEST;
1051 case NSURLErrorTimedOut:
1052 case NSURLErrorDNSLookupFailed:
1053 case NSURLErrorNetworkConnectionLost:
1054 case NSURLErrorCannotConnectToHost:
1055 case NSURLErrorNotConnectedToInternet:
1056 //case NSURLErrorInternationalRoamingOff:
1057 //case NSURLErrorCallIsActive:
1058 //case NSURLErrorDataNotAllowed:
1059 *out = wxWEB_NAV_ERR_CONNECTION;
1062 case NSURLErrorCancelled:
1063 case NSURLErrorUserCancelledAuthentication:
1064 *out = wxWEB_NAV_ERR_USER_CANCELLED;
1067 case NSURLErrorCannotDecodeRawData:
1068 case NSURLErrorCannotDecodeContentData:
1069 case NSURLErrorBadServerResponse:
1070 case NSURLErrorCannotParseResponse:
1071 *out = wxWEB_NAV_ERR_REQUEST;
1074 case NSURLErrorUserAuthenticationRequired:
1075 case NSURLErrorSecureConnectionFailed:
1076 case NSURLErrorClientCertificateRequired:
1077 *out = wxWEB_NAV_ERR_AUTH;
1080 case NSURLErrorNoPermissionsToReadFile:
1081 *out = wxWEB_NAV_ERR_SECURITY;
1084 case NSURLErrorServerCertificateHasBadDate:
1085 case NSURLErrorServerCertificateUntrusted:
1086 case NSURLErrorServerCertificateHasUnknownRoot:
1087 case NSURLErrorServerCertificateNotYetValid:
1088 case NSURLErrorClientCertificateRejected:
1089 *out = wxWEB_NAV_ERR_CERTIFICATE;
1094 wxString message = wxStringWithNSString([error localizedDescription]);
1095 NSString* detail = [error localizedFailureReason];
1098 message = message + " (" + wxStringWithNSString(detail) + ")";
1103 - (void)webView:(WebView *)sender didFailLoadWithError:(NSError*) error
1104 forFrame:(WebFrame *)frame
1106 webKitWindow->m_busy = false;
1108 if (webKitWindow && frame == [sender mainFrame]){
1109 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1111 wxWebNavigationError type;
1112 wxString description = nsErrorToWxHtmlError(error, &type);
1113 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1114 webKitWindow->GetId(),
1115 wxStringWithNSString( url ),
1116 wxEmptyString, false);
1117 thisEvent.SetString(description);
1118 thisEvent.SetInt(type);
1120 if (webKitWindow && webKitWindow->GetEventHandler())
1122 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1127 - (void)webView:(WebView *)sender
1128 didFailProvisionalLoadWithError:(NSError*)error
1129 forFrame:(WebFrame *)frame
1131 webKitWindow->m_busy = false;
1133 if (webKitWindow && frame == [sender mainFrame]){
1134 NSString *url = [[[[frame provisionalDataSource] request] URL]
1137 wxWebNavigationError type;
1138 wxString description = nsErrorToWxHtmlError(error, &type);
1139 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1140 webKitWindow->GetId(),
1141 wxStringWithNSString( url ),
1142 wxEmptyString, false);
1143 thisEvent.SetString(description);
1144 thisEvent.SetInt(type);
1146 if (webKitWindow && webKitWindow->GetEventHandler())
1147 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1151 - (void)webView:(WebView *)sender didReceiveTitle:(NSString *)title
1152 forFrame:(WebFrame *)frame
1154 wxString target = wxStringWithNSString([frame name]);
1155 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_TITLE_CHANGED,
1156 webKitWindow->GetId(),
1157 webKitWindow->GetCurrentURL(),
1160 thisEvent.SetString(wxStringWithNSString(title));
1162 if (webKitWindow && webKitWindow->GetEventHandler())
1163 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1167 @implementation WebViewPolicyDelegate
1169 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1172 webKitWindow = inWindow; // non retained
1176 - (void)webView:(WebView *)sender
1177 decidePolicyForNavigationAction:(NSDictionary *)actionInformation
1178 request:(NSURLRequest *)request
1179 frame:(WebFrame *)frame
1180 decisionListener:(id<WebPolicyDecisionListener>)listener
1184 webKitWindow->m_busy = true;
1185 NSString *url = [[request URL] absoluteString];
1186 wxString target = wxStringWithNSString([frame name]);
1187 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATING,
1188 webKitWindow->GetId(),
1189 wxStringWithNSString( url ), target, true);
1191 if (webKitWindow && webKitWindow->GetEventHandler())
1192 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1194 if (thisEvent.IsVetoed())
1196 webKitWindow->m_busy = false;
1205 - (void)webView:(WebView *)sender
1206 decidePolicyForNewWindowAction:(NSDictionary *)actionInformation
1207 request:(NSURLRequest *)request
1208 newFrameName:(NSString *)frameName
1209 decisionListener:(id < WebPolicyDecisionListener >)listener
1211 wxUnusedVar(actionInformation);
1213 NSString *url = [[request URL] absoluteString];
1214 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NEWWINDOW,
1215 webKitWindow->GetId(),
1216 wxStringWithNSString( url ), "", true);
1218 if (webKitWindow && webKitWindow->GetEventHandler())
1219 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1225 #endif //wxUSE_WEBVIEW_WEBKIT