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 [(WebView*)m_webView goBack];
421 void wxWebViewWebKit::GoForward()
426 [(WebView*)m_webView goForward];
429 void wxWebViewWebKit::Reload(wxWebViewReloadFlags flags)
434 if (flags & wxWEB_VIEW_RELOAD_NO_CACHE)
436 // TODO: test this indeed bypasses the cache
437 [[m_webView preferences] setUsesPageCache:NO];
438 [[m_webView mainFrame] reload];
439 [[m_webView preferences] setUsesPageCache:YES];
443 [[m_webView mainFrame] reload];
447 void wxWebViewWebKit::Stop()
452 [[m_webView mainFrame] stopLoading];
455 bool wxWebViewWebKit::CanGetPageSource()
460 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
461 return ( [[dataSource representation] canProvideDocumentSource] );
464 wxString wxWebViewWebKit::GetPageSource()
467 if (CanGetPageSource())
469 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
470 wxASSERT (dataSource != nil);
472 id<WebDocumentRepresentation> representation = [dataSource representation];
473 wxASSERT (representation != nil);
475 NSString* source = [representation documentSource];
478 return wxEmptyString;
481 return wxStringWithNSString( source );
484 return wxEmptyString;
487 bool wxWebViewWebKit::CanIncreaseTextSize()
492 if ([m_webView canMakeTextLarger])
498 void wxWebViewWebKit::IncreaseTextSize()
503 if (CanIncreaseTextSize())
504 [m_webView makeTextLarger:(WebView*)m_webView];
507 bool wxWebViewWebKit::CanDecreaseTextSize()
512 if ([m_webView canMakeTextSmaller])
518 void wxWebViewWebKit::DecreaseTextSize()
523 if (CanDecreaseTextSize())
524 [m_webView makeTextSmaller:(WebView*)m_webView];
527 void wxWebViewWebKit::Print()
530 // TODO: allow specifying the "show prompt" parameter in Print() ?
531 bool showPrompt = true;
536 id view = [[[m_webView mainFrame] frameView] documentView];
537 NSPrintOperation *op = [NSPrintOperation printOperationWithView:view
538 printInfo: [NSPrintInfo sharedPrintInfo]];
541 [op setShowsPrintPanel: showPrompt];
542 // in my tests, the progress bar always freezes and it stops the whole
543 // print operation. do not turn this to true unless there is a
544 // workaround for the bug.
545 [op setShowsProgressPanel: false];
551 void wxWebViewWebKit::SetEditable(bool enable)
556 [m_webView setEditable:enable ];
559 bool wxWebViewWebKit::IsEditable()
564 return [m_webView isEditable];
567 void wxWebViewWebKit::SetZoomType(wxWebViewZoomType zoomType)
569 // there is only one supported zoom type at the moment so this setter
570 // does nothing beyond checking sanity
571 wxASSERT(zoomType == wxWEB_VIEW_ZOOM_TYPE_TEXT);
574 wxWebViewZoomType wxWebViewWebKit::GetZoomType() const
576 // for now that's the only one that is supported
577 // FIXME: does the default zoom type change depending on webkit versions? :S
578 // Then this will be wrong
579 return wxWEB_VIEW_ZOOM_TYPE_TEXT;
582 bool wxWebViewWebKit::CanSetZoomType(wxWebViewZoomType type) const
586 // for now that's the only one that is supported
587 // TODO: I know recent versions of webkit support layout zoom too,
588 // check if we can support it
589 case wxWEB_VIEW_ZOOM_TYPE_TEXT:
597 int wxWebViewWebKit::GetScrollPos()
599 id result = [[m_webView windowScriptObject]
600 evaluateWebScript:@"document.body.scrollTop"];
601 return [result intValue];
604 void wxWebViewWebKit::SetScrollPos(int pos)
610 javascript.Printf(wxT("document.body.scrollTop = %d;"), pos);
611 [[m_webView windowScriptObject] evaluateWebScript:
612 (NSString*)wxNSStringWithWxString( javascript )];
615 wxString wxWebViewWebKit::GetSelectedText()
617 NSString* selection = [[m_webView selectedDOMRange] markupString];
618 if (!selection) return wxEmptyString;
620 return wxStringWithNSString(selection);
623 void wxWebViewWebKit::RunScript(const wxString& javascript)
628 [[m_webView windowScriptObject] evaluateWebScript:
629 (NSString*)wxNSStringWithWxString( javascript )];
632 void wxWebViewWebKit::OnSize(wxSizeEvent &event)
634 #if defined(__WXMAC_) && wxOSX_USE_CARBON
635 // This is a nasty hack because WebKit seems to lose its position when it is
636 // embedded in a control that is not itself the content view for a TLW.
637 // I put it in OnSize because these calcs are not perfect, and in fact are
638 // basically guesses based on reverse engineering, so it's best to give
639 // people the option of overriding OnSize with their own calcs if need be.
640 // I also left some test debugging print statements as a convenience if
641 // a(nother) problem crops up.
643 wxWindow* tlw = MacGetTopLevelWindow();
645 NSRect frame = [(WebView*)m_webView frame];
646 NSRect bounds = [(WebView*)m_webView bounds];
648 #if DEBUG_WEBKIT_SIZING
649 fprintf(stderr,"Carbon window x=%d, y=%d, width=%d, height=%d\n",
650 GetPosition().x, GetPosition().y, GetSize().x, GetSize().y);
651 fprintf(stderr, "Cocoa window frame x=%G, y=%G, width=%G, height=%G\n",
652 frame.origin.x, frame.origin.y,
653 frame.size.width, frame.size.height);
654 fprintf(stderr, "Cocoa window bounds x=%G, y=%G, width=%G, height=%G\n",
655 bounds.origin.x, bounds.origin.y,
656 bounds.size.width, bounds.size.height);
659 // This must be the case that Apple tested with, because well, in this one case
660 // we don't need to do anything! It just works. ;)
661 if (GetParent() == tlw) return;
663 // since we no longer use parent coordinates, we always want 0,0.
671 #if DEBUG_WEBKIT_SIZING
672 printf("Before conversion, origin is: x = %d, y = %d\n", x, y);
675 // NB: In most cases, when calling HIViewConvertRect, what people want is to
676 // use GetRootControl(), and this tripped me up at first. But in fact, what
677 // we want is the root view, because we need to make the y origin relative
678 // to the very top of the window, not its contents, since we later flip
679 // the y coordinate for Cocoa.
680 HIViewConvertRect (&rect, m_peer->GetControlRef(),
682 (WindowRef) MacGetTopLevelWindowRef()
685 x = (int)rect.origin.x;
686 y = (int)rect.origin.y;
688 #if DEBUG_WEBKIT_SIZING
689 printf("Moving Cocoa frame origin to: x = %d, y = %d\n", x, y);
693 //flip the y coordinate to convert to Cocoa coordinates
694 y = tlw->GetSize().y - ((GetSize().y) + y);
697 #if DEBUG_WEBKIT_SIZING
698 printf("y = %d after flipping value\n", y);
703 [(WebView*)m_webView setFrame:frame];
706 [(WebView*)m_webView display];
711 void wxWebViewWebKit::MacVisibilityChanged(){
712 #if defined(__WXMAC__) && wxOSX_USE_CARBON
713 bool isHidden = !IsControlVisible( m_peer->GetControlRef());
715 [(WebView*)m_webView display];
717 [m_webView setHidden:isHidden];
721 void wxWebViewWebKit::LoadUrl(const wxString& url)
723 [[m_webView mainFrame] loadRequest:[NSURLRequest requestWithURL:
724 [NSURL URLWithString:wxNSStringWithWxString(url)]]];
727 wxString wxWebViewWebKit::GetCurrentURL()
729 return wxStringWithNSString([m_webView mainFrameURL]);
732 wxString wxWebViewWebKit::GetCurrentTitle()
734 return wxStringWithNSString([m_webView mainFrameTitle]);
737 float wxWebViewWebKit::GetWebkitZoom()
739 return [m_webView textSizeMultiplier];
742 void wxWebViewWebKit::SetWebkitZoom(float zoom)
744 [m_webView setTextSizeMultiplier:zoom];
747 wxWebViewZoom wxWebViewWebKit::GetZoom()
749 float zoom = GetWebkitZoom();
751 // arbitrary way to map float zoom to our common zoom enum
754 return wxWEB_VIEW_ZOOM_TINY;
756 else if (zoom > 0.55 && zoom <= 0.85)
758 return wxWEB_VIEW_ZOOM_SMALL;
760 else if (zoom > 0.85 && zoom <= 1.15)
762 return wxWEB_VIEW_ZOOM_MEDIUM;
764 else if (zoom > 1.15 && zoom <= 1.45)
766 return wxWEB_VIEW_ZOOM_LARGE;
768 else if (zoom > 1.45)
770 return wxWEB_VIEW_ZOOM_LARGEST;
773 // to shut up compilers, this can never be reached logically
775 return wxWEB_VIEW_ZOOM_MEDIUM;
778 void wxWebViewWebKit::SetZoom(wxWebViewZoom zoom)
780 // arbitrary way to map our common zoom enum to float zoom
783 case wxWEB_VIEW_ZOOM_TINY:
787 case wxWEB_VIEW_ZOOM_SMALL:
791 case wxWEB_VIEW_ZOOM_MEDIUM:
795 case wxWEB_VIEW_ZOOM_LARGE:
799 case wxWEB_VIEW_ZOOM_LARGEST:
809 void wxWebViewWebKit::SetPage(const wxString& src, const wxString& baseUrl)
814 [[m_webView mainFrame] loadHTMLString:(NSString*)wxNSStringWithWxString(src)
815 baseURL:[NSURL URLWithString:
816 wxNSStringWithWxString( baseUrl )]];
819 void wxWebViewWebKit::Cut()
824 [(WebView*)m_webView cut:m_webView];
827 void wxWebViewWebKit::Copy()
832 [(WebView*)m_webView copy:m_webView];
835 void wxWebViewWebKit::Paste()
840 [(WebView*)m_webView paste:m_webView];
843 void wxWebViewWebKit::DeleteSelection()
848 [(WebView*)m_webView deleteSelection];
851 bool wxWebViewWebKit::HasSelection()
853 DOMRange* range = [m_webView selectedDOMRange];
864 void wxWebViewWebKit::ClearSelection()
866 //We use javascript as selection isn't exposed at the moment in webkit
867 RunScript("window.getSelection().removeAllRanges();");
870 void wxWebViewWebKit::SelectAll()
872 RunScript("window.getSelection().selectAllChildren(document.body);");
875 wxString wxWebViewWebKit::GetSelectedSource()
877 wxString script = ("var range = window.getSelection().getRangeAt(0);"
878 "var element = document.createElement('div');"
879 "element.appendChild(range.cloneContents());"
880 "return element.innerHTML;");
881 id result = [[m_webView windowScriptObject]
882 evaluateWebScript:wxNSStringWithWxString(script)];
883 return wxStringWithNSString([result stringValue]);
886 wxString wxWebViewWebKit::GetPageText()
888 id result = [[m_webView windowScriptObject]
889 evaluateWebScript:@"document.body.textContent"];
890 return wxStringWithNSString([result stringValue]);
893 void wxWebViewWebKit::EnableHistory(bool enable)
898 [m_webView setMaintainsBackForwardList:enable];
901 void wxWebViewWebKit::ClearHistory()
903 [m_webView setMaintainsBackForwardList:NO];
904 [m_webView setMaintainsBackForwardList:YES];
907 wxVector<wxSharedPtr<wxWebHistoryItem> > wxWebViewWebKit::GetBackwardHistory()
909 wxVector<wxSharedPtr<wxWebHistoryItem> > backhist;
910 WebBackForwardList* history = [m_webView backForwardList];
911 int count = [history backListCount];
912 for(int i = -count; i < 0; i++)
914 WebHistoryItem* item = [history itemAtIndex:i];
915 wxString url = wxStringWithNSString([item URLString]);
916 wxString title = wxStringWithNSString([item title]);
917 wxWebHistoryItem* wxitem = new wxWebHistoryItem(url, title);
918 wxitem->m_histItem = item;
919 wxSharedPtr<wxWebHistoryItem> itemptr(wxitem);
920 backhist.push_back(itemptr);
925 wxVector<wxSharedPtr<wxWebHistoryItem> > wxWebViewWebKit::GetForwardHistory()
927 wxVector<wxSharedPtr<wxWebHistoryItem> > forwardhist;
928 WebBackForwardList* history = [m_webView backForwardList];
929 int count = [history forwardListCount];
930 for(int i = 1; i <= count; i++)
932 WebHistoryItem* item = [history itemAtIndex:i];
933 wxString url = wxStringWithNSString([item URLString]);
934 wxString title = wxStringWithNSString([item title]);
935 wxWebHistoryItem* wxitem = new wxWebHistoryItem(url, title);
936 wxitem->m_histItem = item;
937 wxSharedPtr<wxWebHistoryItem> itemptr(wxitem);
938 forwardhist.push_back(itemptr);
943 void wxWebViewWebKit::LoadHistoryItem(wxSharedPtr<wxWebHistoryItem> item)
945 [m_webView goToBackForwardItem:item->m_histItem];
948 bool wxWebViewWebKit::CanUndo()
950 return [[m_webView undoManager] canUndo];
953 bool wxWebViewWebKit::CanRedo()
955 return [[m_webView undoManager] canRedo];
958 void wxWebViewWebKit::Undo()
960 [[m_webView undoManager] undo];
963 void wxWebViewWebKit::Redo()
965 [[m_webView undoManager] redo];
968 //------------------------------------------------------------
969 // Listener interfaces
970 //------------------------------------------------------------
972 // NB: I'm still tracking this down, but it appears the Cocoa window
973 // still has these events fired on it while the Carbon control is being
974 // destroyed. Therefore, we must be careful to check both the existence
975 // of the Carbon control and the event handler before firing events.
977 @implementation MyFrameLoadMonitor
979 - initWithWxWindow: (wxWebViewWebKit*)inWindow
982 webKitWindow = inWindow; // non retained
986 - (void)webView:(WebView *)sender
987 didStartProvisionalLoadForFrame:(WebFrame *)frame
989 webKitWindow->m_busy = true;
992 - (void)webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame
994 webKitWindow->m_busy = true;
996 if (webKitWindow && frame == [sender mainFrame]){
997 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
998 wxString target = wxStringWithNSString([frame name]);
999 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATED,
1000 webKitWindow->GetId(),
1001 wxStringWithNSString( url ),
1004 if (webKitWindow && webKitWindow->GetEventHandler())
1005 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1009 - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
1011 webKitWindow->m_busy = false;
1013 if (webKitWindow && frame == [sender mainFrame]){
1014 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1016 wxString target = wxStringWithNSString([frame name]);
1017 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_LOADED,
1018 webKitWindow->GetId(),
1019 wxStringWithNSString( url ),
1022 if (webKitWindow && webKitWindow->GetEventHandler())
1023 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1027 wxString nsErrorToWxHtmlError(NSError* error, wxWebNavigationError* out)
1029 *out = wxWEB_NAV_ERR_OTHER;
1031 if ([[error domain] isEqualToString:NSURLErrorDomain])
1033 switch ([error code])
1035 case NSURLErrorCannotFindHost:
1036 case NSURLErrorFileDoesNotExist:
1037 case NSURLErrorRedirectToNonExistentLocation:
1038 *out = wxWEB_NAV_ERR_NOT_FOUND;
1041 case NSURLErrorResourceUnavailable:
1042 case NSURLErrorHTTPTooManyRedirects:
1043 case NSURLErrorDataLengthExceedsMaximum:
1044 case NSURLErrorBadURL:
1045 case NSURLErrorFileIsDirectory:
1046 *out = wxWEB_NAV_ERR_REQUEST;
1049 case NSURLErrorTimedOut:
1050 case NSURLErrorDNSLookupFailed:
1051 case NSURLErrorNetworkConnectionLost:
1052 case NSURLErrorCannotConnectToHost:
1053 case NSURLErrorNotConnectedToInternet:
1054 //case NSURLErrorInternationalRoamingOff:
1055 //case NSURLErrorCallIsActive:
1056 //case NSURLErrorDataNotAllowed:
1057 *out = wxWEB_NAV_ERR_CONNECTION;
1060 case NSURLErrorCancelled:
1061 case NSURLErrorUserCancelledAuthentication:
1062 *out = wxWEB_NAV_ERR_USER_CANCELLED;
1065 case NSURLErrorCannotDecodeRawData:
1066 case NSURLErrorCannotDecodeContentData:
1067 case NSURLErrorBadServerResponse:
1068 case NSURLErrorCannotParseResponse:
1069 *out = wxWEB_NAV_ERR_REQUEST;
1072 case NSURLErrorUserAuthenticationRequired:
1073 case NSURLErrorSecureConnectionFailed:
1074 case NSURLErrorClientCertificateRequired:
1075 *out = wxWEB_NAV_ERR_AUTH;
1078 case NSURLErrorNoPermissionsToReadFile:
1079 *out = wxWEB_NAV_ERR_SECURITY;
1082 case NSURLErrorServerCertificateHasBadDate:
1083 case NSURLErrorServerCertificateUntrusted:
1084 case NSURLErrorServerCertificateHasUnknownRoot:
1085 case NSURLErrorServerCertificateNotYetValid:
1086 case NSURLErrorClientCertificateRejected:
1087 *out = wxWEB_NAV_ERR_CERTIFICATE;
1092 wxString message = wxStringWithNSString([error localizedDescription]);
1093 NSString* detail = [error localizedFailureReason];
1096 message = message + " (" + wxStringWithNSString(detail) + ")";
1101 - (void)webView:(WebView *)sender didFailLoadWithError:(NSError*) error
1102 forFrame:(WebFrame *)frame
1104 webKitWindow->m_busy = false;
1106 if (webKitWindow && frame == [sender mainFrame]){
1107 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1109 wxWebNavigationError type;
1110 wxString description = nsErrorToWxHtmlError(error, &type);
1111 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1112 webKitWindow->GetId(),
1113 wxStringWithNSString( url ),
1114 wxEmptyString, false);
1115 thisEvent.SetString(description);
1116 thisEvent.SetInt(type);
1118 if (webKitWindow && webKitWindow->GetEventHandler())
1120 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1125 - (void)webView:(WebView *)sender
1126 didFailProvisionalLoadWithError:(NSError*)error
1127 forFrame:(WebFrame *)frame
1129 webKitWindow->m_busy = false;
1131 if (webKitWindow && frame == [sender mainFrame]){
1132 NSString *url = [[[[frame provisionalDataSource] request] URL]
1135 wxWebNavigationError type;
1136 wxString description = nsErrorToWxHtmlError(error, &type);
1137 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1138 webKitWindow->GetId(),
1139 wxStringWithNSString( url ),
1140 wxEmptyString, false);
1141 thisEvent.SetString(description);
1142 thisEvent.SetInt(type);
1144 if (webKitWindow && webKitWindow->GetEventHandler())
1145 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1149 - (void)webView:(WebView *)sender didReceiveTitle:(NSString *)title
1150 forFrame:(WebFrame *)frame
1152 wxString target = wxStringWithNSString([frame name]);
1153 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_TITLE_CHANGED,
1154 webKitWindow->GetId(),
1155 webKitWindow->GetCurrentURL(),
1158 thisEvent.SetString(wxStringWithNSString(title));
1160 if (webKitWindow && webKitWindow->GetEventHandler())
1161 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1165 @implementation MyPolicyDelegate
1167 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1170 webKitWindow = inWindow; // non retained
1174 - (void)webView:(WebView *)sender
1175 decidePolicyForNavigationAction:(NSDictionary *)actionInformation
1176 request:(NSURLRequest *)request
1177 frame:(WebFrame *)frame
1178 decisionListener:(id<WebPolicyDecisionListener>)listener
1182 webKitWindow->m_busy = true;
1183 NSString *url = [[request URL] absoluteString];
1184 wxString target = wxStringWithNSString([frame name]);
1185 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATING,
1186 webKitWindow->GetId(),
1187 wxStringWithNSString( url ), target, true);
1189 if (webKitWindow && webKitWindow->GetEventHandler())
1190 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1192 if (thisEvent.IsVetoed())
1194 webKitWindow->m_busy = false;
1203 - (void)webView:(WebView *)sender
1204 decidePolicyForNewWindowAction:(NSDictionary *)actionInformation
1205 request:(NSURLRequest *)request
1206 newFrameName:(NSString *)frameName
1207 decisionListener:(id < WebPolicyDecisionListener >)listener
1209 wxUnusedVar(actionInformation);
1211 NSString *url = [[request URL] absoluteString];
1212 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NEWWINDOW,
1213 webKitWindow->GetId(),
1214 wxStringWithNSString( url ), "", true);
1216 if (webKitWindow && webKitWindow->GetEventHandler())
1217 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1223 #endif //wxUSE_WEBVIEW_WEBKIT