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"
29 #include "wx/hashmap.h"
30 #include "wx/filesys.h"
32 #include <WebKit/WebKit.h>
33 #include <WebKit/HIWebView.h>
34 #include <WebKit/CarbonUtils.h>
36 #include <Foundation/NSURLError.h>
38 #define DEBUG_WEBKIT_SIZING 0
40 // ----------------------------------------------------------------------------
42 // ----------------------------------------------------------------------------
44 wxIMPLEMENT_DYNAMIC_CLASS(wxWebViewWebKit, wxWebView);
46 BEGIN_EVENT_TABLE(wxWebViewWebKit, wxControl)
47 #if defined(__WXMAC__) && wxOSX_USE_CARBON
48 EVT_SIZE(wxWebViewWebKit::OnSize)
52 #if defined(__WXOSX__) && wxOSX_USE_CARBON
54 // ----------------------------------------------------------------------------
55 // Carbon Events handlers
56 // ----------------------------------------------------------------------------
58 // prototype for function in src/osx/carbon/nonownedwnd.cpp
59 void SetupMouseEvent( wxMouseEvent &wxevent , wxMacCarbonEvent &cEvent );
61 static const EventTypeSpec eventList[] =
63 //{ kEventClassControl, kEventControlTrack } ,
64 { kEventClassMouse, kEventMouseUp },
65 { kEventClassMouse, kEventMouseDown },
66 { kEventClassMouse, kEventMouseMoved },
67 { kEventClassMouse, kEventMouseDragged },
69 { kEventClassKeyboard, kEventRawKeyDown } ,
70 { kEventClassKeyboard, kEventRawKeyRepeat } ,
71 { kEventClassKeyboard, kEventRawKeyUp } ,
72 { kEventClassKeyboard, kEventRawKeyModifiersChanged } ,
74 { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent } ,
75 { kEventClassTextInput, kEventTextInputUpdateActiveInputArea } ,
77 #if DEBUG_WEBKIT_SIZING == 1
78 { kEventClassControl, kEventControlBoundsChanged } ,
82 // mix this in from window.cpp
83 pascal OSStatus wxMacUnicodeTextEventHandler(EventHandlerCallRef handler,
84 EventRef event, void *data) ;
86 // NOTE: This is mostly taken from KeyboardEventHandler in toplevel.cpp, but
87 // that expects the data pointer is a top-level window, so I needed to change
88 // that in this case. However, once 2.8 is out, we should factor out the common
89 // logic among the two functions and merge them.
90 static pascal OSStatus wxWebKitKeyEventHandler(EventHandlerCallRef handler,
91 EventRef event, void *data)
93 OSStatus result = eventNotHandledErr ;
94 wxMacCarbonEvent cEvent( event ) ;
96 wxWebViewWebKit* thisWindow = (wxWebViewWebKit*) data ;
97 wxWindow* focus = thisWindow ;
99 unsigned char charCode ;
107 UInt32 when = EventTimeToTicks( GetEventTime( event ) ) ;
110 ByteCount dataSize = 0 ;
111 if ( GetEventParameter(event, kEventParamKeyUnicodes, typeUnicodeText,
112 NULL, 0 , &dataSize, NULL ) == noErr)
115 int numChars = dataSize / sizeof( UniChar) + 1;
117 UniChar* charBuf = buf ;
119 if ( numChars * 2 > 4 )
120 charBuf = new UniChar[ numChars ] ;
121 GetEventParameter(event, kEventParamKeyUnicodes, typeUnicodeText, NULL,
122 dataSize , NULL , charBuf) ;
123 charBuf[ numChars - 1 ] = 0;
125 #if SIZEOF_WCHAR_T == 2
126 uniChar = charBuf[0] ;
128 wxMBConvUTF16 converter ;
129 converter.MB2WC( uniChar , (const char*)charBuf , 2 ) ;
132 if ( numChars * 2 > 4 )
137 GetEventParameter(event, kEventParamKeyMacCharCodes, typeChar, NULL,
138 sizeof(char), NULL, &charCode );
139 GetEventParameter(event, kEventParamKeyCode, typeUInt32, NULL,
140 sizeof(UInt32), NULL, &keyCode );
141 GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, NULL,
142 sizeof(UInt32), NULL, &modifiers );
143 GetEventParameter(event, kEventParamMouseLocation, typeQDPoint, NULL,
144 sizeof(Point), NULL, &point );
146 UInt32 message = (keyCode << 8) + charCode;
147 switch ( GetEventKind( event ) )
149 case kEventRawKeyRepeat :
150 case kEventRawKeyDown :
152 WXEVENTREF formerEvent = wxTheApp->MacGetCurrentEvent() ;
153 WXEVENTHANDLERCALLREF formerHandler =
154 wxTheApp->MacGetCurrentEventHandlerCallRef() ;
156 wxTheApp->MacSetCurrentEvent( event , handler ) ;
157 if ( /* focus && */ wxTheApp->MacSendKeyDownEvent(
158 focus, message, modifiers, when, point.h, point.v, uniChar[0]))
162 wxTheApp->MacSetCurrentEvent( formerEvent , formerHandler ) ;
166 case kEventRawKeyUp :
167 if ( /* focus && */ wxTheApp->MacSendKeyUpEvent(
168 focus , message , modifiers , when , point.h , point.v , uniChar[0] ) )
174 case kEventRawKeyModifiersChanged :
176 wxKeyEvent event(wxEVT_KEY_DOWN);
178 event.m_shiftDown = modifiers & shiftKey;
179 event.m_controlDown = modifiers & controlKey;
180 event.m_altDown = modifiers & optionKey;
181 event.m_metaDown = modifiers & cmdKey;
186 event.m_uniChar = uniChar[0] ;
189 event.SetTimestamp(when);
190 event.SetEventObject(focus);
192 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & controlKey )
194 event.m_keyCode = WXK_CONTROL ;
195 event.SetEventType( ( modifiers & controlKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
196 focus->GetEventHandler()->ProcessEvent( event ) ;
198 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & shiftKey )
200 event.m_keyCode = WXK_SHIFT ;
201 event.SetEventType( ( modifiers & shiftKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
202 focus->GetEventHandler()->ProcessEvent( event ) ;
204 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & optionKey )
206 event.m_keyCode = WXK_ALT ;
207 event.SetEventType( ( modifiers & optionKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
208 focus->GetEventHandler()->ProcessEvent( event ) ;
210 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & cmdKey )
212 event.m_keyCode = WXK_COMMAND ;
213 event.SetEventType( ( modifiers & cmdKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
214 focus->GetEventHandler()->ProcessEvent( event ) ;
217 wxApp::s_lastModifiers = modifiers ;
228 static pascal OSStatus wxWebViewWebKitEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
230 OSStatus result = eventNotHandledErr ;
232 wxMacCarbonEvent cEvent( event ) ;
234 ControlRef controlRef ;
235 wxWebViewWebKit* thisWindow = (wxWebViewWebKit*) data ;
236 wxNonOwnedWindow* tlw = NULL;
238 tlw = thisWindow->MacGetTopLevelWindow();
240 cEvent.GetParameter( kEventParamDirectObject , &controlRef ) ;
242 wxWindow* currentMouseWindow = thisWindow ;
244 if ( wxApp::s_captureWindow )
245 currentMouseWindow = wxApp::s_captureWindow;
247 switch ( GetEventClass( event ) )
249 case kEventClassKeyboard:
251 result = wxWebKitKeyEventHandler(handler, event, data);
255 case kEventClassTextInput:
257 result = wxMacUnicodeTextEventHandler(handler, event, data);
261 case kEventClassMouse:
263 switch ( GetEventKind( event ) )
265 case kEventMouseDragged :
266 case kEventMouseMoved :
267 case kEventMouseDown :
270 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
271 SetupMouseEvent( wxevent , cEvent ) ;
273 currentMouseWindow->ScreenToClient( &wxevent.m_x , &wxevent.m_y ) ;
274 wxevent.SetEventObject( currentMouseWindow ) ;
275 wxevent.SetId( currentMouseWindow->GetId() ) ;
277 if ( currentMouseWindow->GetEventHandler()->ProcessEvent(wxevent) )
282 break; // this should enable WebKit to fire mouse dragged and mouse up events...
292 result = CallNextEventHandler(handler, event);
296 DEFINE_ONE_SHOT_HANDLER_GETTER( wxWebViewWebKitEventHandler )
300 @interface WebViewLoadDelegate : NSObject
302 wxWebViewWebKit* webKitWindow;
305 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
309 @interface WebViewPolicyDelegate : NSObject
311 wxWebViewWebKit* webKitWindow;
314 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
318 //We use a hash to map scheme names to wxWebHandlers
319 WX_DECLARE_STRING_HASH_MAP(wxSharedPtr<wxWebHandler>, wxStringToWebHandlerMap);
321 static wxStringToWebHandlerMap g_stringHandlerMap;
323 @interface WebViewCustomProtocol : NSURLProtocol
328 // ----------------------------------------------------------------------------
329 // creation/destruction
330 // ----------------------------------------------------------------------------
332 bool wxWebViewWebKit::Create(wxWindow *parent,
334 const wxString& strURL,
336 const wxSize& size, long style,
337 const wxString& name)
342 wxControl::Create(parent, winID, pos, size, style, wxDefaultValidator, name);
345 wxMacControl* peer = new wxMacControl(this);
347 HIWebViewCreate( peer->GetControlRefAddr() );
349 m_webView = (WebView*) HIWebViewGetWebView( peer->GetControlRef() );
351 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_3
352 if ( UMAGetSystemVersion() >= 0x1030 )
353 HIViewChangeFeatures( peer->GetControlRef() , kHIViewIsOpaque , 0 ) ;
355 InstallControlEventHandler(peer->GetControlRef(),
356 GetwxWebViewWebKitEventHandlerUPP(),
357 GetEventTypeCount(eventList), eventList, this,
358 (EventHandlerRef *)&m_webKitCtrlEventHandler);
361 NSRect r = wxOSXGetFrameForControl( this, pos , size ) ;
362 m_webView = [[WebView alloc] initWithFrame:r
363 frameName:@"webkitFrame"
364 groupName:@"webkitGroup"];
365 SetPeer(new wxWidgetCocoaImpl( this, m_webView ));
368 MacPostControlCreate(pos, size);
371 HIViewSetVisible( GetPeer()->GetControlRef(), true );
373 [m_webView setHidden:false];
377 // Register event listener interfaces
378 WebViewLoadDelegate* loadDelegate =
379 [[WebViewLoadDelegate alloc] initWithWxWindow: this];
381 [m_webView setFrameLoadDelegate:loadDelegate];
383 // this is used to veto page loads, etc.
384 WebViewPolicyDelegate* policyDelegate =
385 [[WebViewPolicyDelegate alloc] initWithWxWindow: this];
387 [m_webView setPolicyDelegate:policyDelegate];
389 //Register our own class for custom scheme handling
390 [NSURLProtocol registerClass:[WebViewCustomProtocol class]];
396 wxWebViewWebKit::~wxWebViewWebKit()
398 WebViewLoadDelegate* loadDelegate = [m_webView frameLoadDelegate];
399 WebViewPolicyDelegate* policyDelegate = [m_webView policyDelegate];
400 [m_webView setFrameLoadDelegate: nil];
401 [m_webView setPolicyDelegate: nil];
404 [loadDelegate release];
407 [policyDelegate release];
410 // ----------------------------------------------------------------------------
412 // ----------------------------------------------------------------------------
414 bool wxWebViewWebKit::CanGoBack()
419 return [m_webView canGoBack];
422 bool wxWebViewWebKit::CanGoForward()
427 return [m_webView canGoForward];
430 void wxWebViewWebKit::GoBack()
435 [(WebView*)m_webView goBack];
438 void wxWebViewWebKit::GoForward()
443 [(WebView*)m_webView goForward];
446 void wxWebViewWebKit::Reload(wxWebViewReloadFlags flags)
451 if (flags & wxWEB_VIEW_RELOAD_NO_CACHE)
453 // TODO: test this indeed bypasses the cache
454 [[m_webView preferences] setUsesPageCache:NO];
455 [[m_webView mainFrame] reload];
456 [[m_webView preferences] setUsesPageCache:YES];
460 [[m_webView mainFrame] reload];
464 void wxWebViewWebKit::Stop()
469 [[m_webView mainFrame] stopLoading];
472 bool wxWebViewWebKit::CanGetPageSource()
477 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
478 return ( [[dataSource representation] canProvideDocumentSource] );
481 wxString wxWebViewWebKit::GetPageSource()
484 if (CanGetPageSource())
486 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
487 wxASSERT (dataSource != nil);
489 id<WebDocumentRepresentation> representation = [dataSource representation];
490 wxASSERT (representation != nil);
492 NSString* source = [representation documentSource];
495 return wxEmptyString;
498 return wxStringWithNSString( source );
501 return wxEmptyString;
504 bool wxWebViewWebKit::CanIncreaseTextSize()
509 if ([m_webView canMakeTextLarger])
515 void wxWebViewWebKit::IncreaseTextSize()
520 if (CanIncreaseTextSize())
521 [m_webView makeTextLarger:(WebView*)m_webView];
524 bool wxWebViewWebKit::CanDecreaseTextSize()
529 if ([m_webView canMakeTextSmaller])
535 void wxWebViewWebKit::DecreaseTextSize()
540 if (CanDecreaseTextSize())
541 [m_webView makeTextSmaller:(WebView*)m_webView];
544 void wxWebViewWebKit::Print()
547 // TODO: allow specifying the "show prompt" parameter in Print() ?
548 bool showPrompt = true;
553 id view = [[[m_webView mainFrame] frameView] documentView];
554 NSPrintOperation *op = [NSPrintOperation printOperationWithView:view
555 printInfo: [NSPrintInfo sharedPrintInfo]];
558 [op setShowsPrintPanel: showPrompt];
559 // in my tests, the progress bar always freezes and it stops the whole
560 // print operation. do not turn this to true unless there is a
561 // workaround for the bug.
562 [op setShowsProgressPanel: false];
568 void wxWebViewWebKit::SetEditable(bool enable)
573 [m_webView setEditable:enable ];
576 bool wxWebViewWebKit::IsEditable()
581 return [m_webView isEditable];
584 void wxWebViewWebKit::SetZoomType(wxWebViewZoomType zoomType)
586 // there is only one supported zoom type at the moment so this setter
587 // does nothing beyond checking sanity
588 wxASSERT(zoomType == wxWEB_VIEW_ZOOM_TYPE_TEXT);
591 wxWebViewZoomType wxWebViewWebKit::GetZoomType() const
593 // for now that's the only one that is supported
594 // FIXME: does the default zoom type change depending on webkit versions? :S
595 // Then this will be wrong
596 return wxWEB_VIEW_ZOOM_TYPE_TEXT;
599 bool wxWebViewWebKit::CanSetZoomType(wxWebViewZoomType type) const
603 // for now that's the only one that is supported
604 // TODO: I know recent versions of webkit support layout zoom too,
605 // check if we can support it
606 case wxWEB_VIEW_ZOOM_TYPE_TEXT:
614 int wxWebViewWebKit::GetScrollPos()
616 id result = [[m_webView windowScriptObject]
617 evaluateWebScript:@"document.body.scrollTop"];
618 return [result intValue];
621 void wxWebViewWebKit::SetScrollPos(int pos)
627 javascript.Printf(wxT("document.body.scrollTop = %d;"), pos);
628 [[m_webView windowScriptObject] evaluateWebScript:
629 (NSString*)wxNSStringWithWxString( javascript )];
632 wxString wxWebViewWebKit::GetSelectedText()
634 NSString* selection = [[m_webView selectedDOMRange] markupString];
635 if (!selection) return wxEmptyString;
637 return wxStringWithNSString(selection);
640 void wxWebViewWebKit::RunScript(const wxString& javascript)
645 [[m_webView windowScriptObject] evaluateWebScript:
646 (NSString*)wxNSStringWithWxString( javascript )];
649 void wxWebViewWebKit::OnSize(wxSizeEvent &event)
651 #if defined(__WXMAC_) && wxOSX_USE_CARBON
652 // This is a nasty hack because WebKit seems to lose its position when it is
653 // embedded in a control that is not itself the content view for a TLW.
654 // I put it in OnSize because these calcs are not perfect, and in fact are
655 // basically guesses based on reverse engineering, so it's best to give
656 // people the option of overriding OnSize with their own calcs if need be.
657 // I also left some test debugging print statements as a convenience if
658 // a(nother) problem crops up.
660 wxWindow* tlw = MacGetTopLevelWindow();
662 NSRect frame = [(WebView*)m_webView frame];
663 NSRect bounds = [(WebView*)m_webView bounds];
665 #if DEBUG_WEBKIT_SIZING
666 fprintf(stderr,"Carbon window x=%d, y=%d, width=%d, height=%d\n",
667 GetPosition().x, GetPosition().y, GetSize().x, GetSize().y);
668 fprintf(stderr, "Cocoa window frame x=%G, y=%G, width=%G, height=%G\n",
669 frame.origin.x, frame.origin.y,
670 frame.size.width, frame.size.height);
671 fprintf(stderr, "Cocoa window bounds x=%G, y=%G, width=%G, height=%G\n",
672 bounds.origin.x, bounds.origin.y,
673 bounds.size.width, bounds.size.height);
676 // This must be the case that Apple tested with, because well, in this one case
677 // we don't need to do anything! It just works. ;)
678 if (GetParent() == tlw) return;
680 // since we no longer use parent coordinates, we always want 0,0.
688 #if DEBUG_WEBKIT_SIZING
689 printf("Before conversion, origin is: x = %d, y = %d\n", x, y);
692 // NB: In most cases, when calling HIViewConvertRect, what people want is to
693 // use GetRootControl(), and this tripped me up at first. But in fact, what
694 // we want is the root view, because we need to make the y origin relative
695 // to the very top of the window, not its contents, since we later flip
696 // the y coordinate for Cocoa.
697 HIViewConvertRect (&rect, m_peer->GetControlRef(),
699 (WindowRef) MacGetTopLevelWindowRef()
702 x = (int)rect.origin.x;
703 y = (int)rect.origin.y;
705 #if DEBUG_WEBKIT_SIZING
706 printf("Moving Cocoa frame origin to: x = %d, y = %d\n", x, y);
710 //flip the y coordinate to convert to Cocoa coordinates
711 y = tlw->GetSize().y - ((GetSize().y) + y);
714 #if DEBUG_WEBKIT_SIZING
715 printf("y = %d after flipping value\n", y);
720 [(WebView*)m_webView setFrame:frame];
723 [(WebView*)m_webView display];
728 void wxWebViewWebKit::MacVisibilityChanged(){
729 #if defined(__WXMAC__) && wxOSX_USE_CARBON
730 bool isHidden = !IsControlVisible( GetPeer()->GetControlRef());
732 [(WebView*)m_webView display];
734 [m_webView setHidden:isHidden];
738 void wxWebViewWebKit::LoadUrl(const wxString& url)
740 [[m_webView mainFrame] loadRequest:[NSURLRequest requestWithURL:
741 [NSURL URLWithString:wxNSStringWithWxString(url)]]];
744 wxString wxWebViewWebKit::GetCurrentURL()
746 return wxStringWithNSString([m_webView mainFrameURL]);
749 wxString wxWebViewWebKit::GetCurrentTitle()
751 return wxStringWithNSString([m_webView mainFrameTitle]);
754 float wxWebViewWebKit::GetWebkitZoom()
756 return [m_webView textSizeMultiplier];
759 void wxWebViewWebKit::SetWebkitZoom(float zoom)
761 [m_webView setTextSizeMultiplier:zoom];
764 wxWebViewZoom wxWebViewWebKit::GetZoom()
766 float zoom = GetWebkitZoom();
768 // arbitrary way to map float zoom to our common zoom enum
771 return wxWEB_VIEW_ZOOM_TINY;
773 else if (zoom > 0.55 && zoom <= 0.85)
775 return wxWEB_VIEW_ZOOM_SMALL;
777 else if (zoom > 0.85 && zoom <= 1.15)
779 return wxWEB_VIEW_ZOOM_MEDIUM;
781 else if (zoom > 1.15 && zoom <= 1.45)
783 return wxWEB_VIEW_ZOOM_LARGE;
785 else if (zoom > 1.45)
787 return wxWEB_VIEW_ZOOM_LARGEST;
790 // to shut up compilers, this can never be reached logically
792 return wxWEB_VIEW_ZOOM_MEDIUM;
795 void wxWebViewWebKit::SetZoom(wxWebViewZoom zoom)
797 // arbitrary way to map our common zoom enum to float zoom
800 case wxWEB_VIEW_ZOOM_TINY:
804 case wxWEB_VIEW_ZOOM_SMALL:
808 case wxWEB_VIEW_ZOOM_MEDIUM:
812 case wxWEB_VIEW_ZOOM_LARGE:
816 case wxWEB_VIEW_ZOOM_LARGEST:
826 void wxWebViewWebKit::SetPage(const wxString& src, const wxString& baseUrl)
831 [[m_webView mainFrame] loadHTMLString:(NSString*)wxNSStringWithWxString(src)
832 baseURL:[NSURL URLWithString:
833 wxNSStringWithWxString( baseUrl )]];
836 void wxWebViewWebKit::Cut()
841 [(WebView*)m_webView cut:m_webView];
844 void wxWebViewWebKit::Copy()
849 [(WebView*)m_webView copy:m_webView];
852 void wxWebViewWebKit::Paste()
857 [(WebView*)m_webView paste:m_webView];
860 void wxWebViewWebKit::DeleteSelection()
865 [(WebView*)m_webView deleteSelection];
868 bool wxWebViewWebKit::HasSelection()
870 DOMRange* range = [m_webView selectedDOMRange];
881 void wxWebViewWebKit::ClearSelection()
883 //We use javascript as selection isn't exposed at the moment in webkit
884 RunScript("window.getSelection().removeAllRanges();");
887 void wxWebViewWebKit::SelectAll()
889 RunScript("window.getSelection().selectAllChildren(document.body);");
892 wxString wxWebViewWebKit::GetSelectedSource()
894 wxString script = ("var range = window.getSelection().getRangeAt(0);"
895 "var element = document.createElement('div');"
896 "element.appendChild(range.cloneContents());"
897 "return element.innerHTML;");
898 id result = [[m_webView windowScriptObject]
899 evaluateWebScript:wxNSStringWithWxString(script)];
900 return wxStringWithNSString([result stringValue]);
903 wxString wxWebViewWebKit::GetPageText()
905 id result = [[m_webView windowScriptObject]
906 evaluateWebScript:@"document.body.textContent"];
907 return wxStringWithNSString([result stringValue]);
910 void wxWebViewWebKit::EnableHistory(bool enable)
915 [m_webView setMaintainsBackForwardList:enable];
918 void wxWebViewWebKit::ClearHistory()
920 [m_webView setMaintainsBackForwardList:NO];
921 [m_webView setMaintainsBackForwardList:YES];
924 wxVector<wxSharedPtr<wxWebHistoryItem> > wxWebViewWebKit::GetBackwardHistory()
926 wxVector<wxSharedPtr<wxWebHistoryItem> > backhist;
927 WebBackForwardList* history = [m_webView backForwardList];
928 int count = [history backListCount];
929 for(int i = -count; i < 0; i++)
931 WebHistoryItem* item = [history itemAtIndex:i];
932 wxString url = wxStringWithNSString([item URLString]);
933 wxString title = wxStringWithNSString([item title]);
934 wxWebHistoryItem* wxitem = new wxWebHistoryItem(url, title);
935 wxitem->m_histItem = item;
936 wxSharedPtr<wxWebHistoryItem> itemptr(wxitem);
937 backhist.push_back(itemptr);
942 wxVector<wxSharedPtr<wxWebHistoryItem> > wxWebViewWebKit::GetForwardHistory()
944 wxVector<wxSharedPtr<wxWebHistoryItem> > forwardhist;
945 WebBackForwardList* history = [m_webView backForwardList];
946 int count = [history forwardListCount];
947 for(int i = 1; i <= count; i++)
949 WebHistoryItem* item = [history itemAtIndex:i];
950 wxString url = wxStringWithNSString([item URLString]);
951 wxString title = wxStringWithNSString([item title]);
952 wxWebHistoryItem* wxitem = new wxWebHistoryItem(url, title);
953 wxitem->m_histItem = item;
954 wxSharedPtr<wxWebHistoryItem> itemptr(wxitem);
955 forwardhist.push_back(itemptr);
960 void wxWebViewWebKit::LoadHistoryItem(wxSharedPtr<wxWebHistoryItem> item)
962 [m_webView goToBackForwardItem:item->m_histItem];
965 bool wxWebViewWebKit::CanUndo()
967 return [[m_webView undoManager] canUndo];
970 bool wxWebViewWebKit::CanRedo()
972 return [[m_webView undoManager] canRedo];
975 void wxWebViewWebKit::Undo()
977 [[m_webView undoManager] undo];
980 void wxWebViewWebKit::Redo()
982 [[m_webView undoManager] redo];
985 void wxWebViewWebKit::RegisterHandler(wxSharedPtr<wxWebHandler> handler)
987 g_stringHandlerMap[handler->GetName()] = handler;
990 //------------------------------------------------------------
991 // Listener interfaces
992 //------------------------------------------------------------
994 // NB: I'm still tracking this down, but it appears the Cocoa window
995 // still has these events fired on it while the Carbon control is being
996 // destroyed. Therefore, we must be careful to check both the existence
997 // of the Carbon control and the event handler before firing events.
999 @implementation WebViewLoadDelegate
1001 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1004 webKitWindow = inWindow; // non retained
1008 - (void)webView:(WebView *)sender
1009 didStartProvisionalLoadForFrame:(WebFrame *)frame
1011 webKitWindow->m_busy = true;
1014 - (void)webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame
1016 webKitWindow->m_busy = true;
1018 if (webKitWindow && frame == [sender mainFrame]){
1019 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1020 wxString target = wxStringWithNSString([frame name]);
1021 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATED,
1022 webKitWindow->GetId(),
1023 wxStringWithNSString( url ),
1026 if (webKitWindow && webKitWindow->GetEventHandler())
1027 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1031 - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
1033 webKitWindow->m_busy = false;
1035 if (webKitWindow && frame == [sender mainFrame]){
1036 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1038 wxString target = wxStringWithNSString([frame name]);
1039 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_LOADED,
1040 webKitWindow->GetId(),
1041 wxStringWithNSString( url ),
1044 if (webKitWindow && webKitWindow->GetEventHandler())
1045 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1049 wxString nsErrorToWxHtmlError(NSError* error, wxWebNavigationError* out)
1051 *out = wxWEB_NAV_ERR_OTHER;
1053 if ([[error domain] isEqualToString:NSURLErrorDomain])
1055 switch ([error code])
1057 case NSURLErrorCannotFindHost:
1058 case NSURLErrorFileDoesNotExist:
1059 case NSURLErrorRedirectToNonExistentLocation:
1060 *out = wxWEB_NAV_ERR_NOT_FOUND;
1063 case NSURLErrorResourceUnavailable:
1064 case NSURLErrorHTTPTooManyRedirects:
1065 case NSURLErrorDataLengthExceedsMaximum:
1066 case NSURLErrorBadURL:
1067 case NSURLErrorFileIsDirectory:
1068 *out = wxWEB_NAV_ERR_REQUEST;
1071 case NSURLErrorTimedOut:
1072 case NSURLErrorDNSLookupFailed:
1073 case NSURLErrorNetworkConnectionLost:
1074 case NSURLErrorCannotConnectToHost:
1075 case NSURLErrorNotConnectedToInternet:
1076 //case NSURLErrorInternationalRoamingOff:
1077 //case NSURLErrorCallIsActive:
1078 //case NSURLErrorDataNotAllowed:
1079 *out = wxWEB_NAV_ERR_CONNECTION;
1082 case NSURLErrorCancelled:
1083 case NSURLErrorUserCancelledAuthentication:
1084 *out = wxWEB_NAV_ERR_USER_CANCELLED;
1087 case NSURLErrorCannotDecodeRawData:
1088 case NSURLErrorCannotDecodeContentData:
1089 case NSURLErrorBadServerResponse:
1090 case NSURLErrorCannotParseResponse:
1091 *out = wxWEB_NAV_ERR_REQUEST;
1094 case NSURLErrorUserAuthenticationRequired:
1095 case NSURLErrorSecureConnectionFailed:
1096 case NSURLErrorClientCertificateRequired:
1097 *out = wxWEB_NAV_ERR_AUTH;
1100 case NSURLErrorNoPermissionsToReadFile:
1101 *out = wxWEB_NAV_ERR_SECURITY;
1104 case NSURLErrorServerCertificateHasBadDate:
1105 case NSURLErrorServerCertificateUntrusted:
1106 case NSURLErrorServerCertificateHasUnknownRoot:
1107 case NSURLErrorServerCertificateNotYetValid:
1108 case NSURLErrorClientCertificateRejected:
1109 *out = wxWEB_NAV_ERR_CERTIFICATE;
1114 wxString message = wxStringWithNSString([error localizedDescription]);
1115 NSString* detail = [error localizedFailureReason];
1118 message = message + " (" + wxStringWithNSString(detail) + ")";
1123 - (void)webView:(WebView *)sender didFailLoadWithError:(NSError*) error
1124 forFrame:(WebFrame *)frame
1126 webKitWindow->m_busy = false;
1128 if (webKitWindow && frame == [sender mainFrame]){
1129 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1131 wxWebNavigationError type;
1132 wxString description = nsErrorToWxHtmlError(error, &type);
1133 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1134 webKitWindow->GetId(),
1135 wxStringWithNSString( url ),
1136 wxEmptyString, false);
1137 thisEvent.SetString(description);
1138 thisEvent.SetInt(type);
1140 if (webKitWindow && webKitWindow->GetEventHandler())
1142 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1147 - (void)webView:(WebView *)sender
1148 didFailProvisionalLoadWithError:(NSError*)error
1149 forFrame:(WebFrame *)frame
1151 webKitWindow->m_busy = false;
1153 if (webKitWindow && frame == [sender mainFrame]){
1154 NSString *url = [[[[frame provisionalDataSource] request] URL]
1157 wxWebNavigationError type;
1158 wxString description = nsErrorToWxHtmlError(error, &type);
1159 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1160 webKitWindow->GetId(),
1161 wxStringWithNSString( url ),
1162 wxEmptyString, false);
1163 thisEvent.SetString(description);
1164 thisEvent.SetInt(type);
1166 if (webKitWindow && webKitWindow->GetEventHandler())
1167 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1171 - (void)webView:(WebView *)sender didReceiveTitle:(NSString *)title
1172 forFrame:(WebFrame *)frame
1174 wxString target = wxStringWithNSString([frame name]);
1175 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_TITLE_CHANGED,
1176 webKitWindow->GetId(),
1177 webKitWindow->GetCurrentURL(),
1180 thisEvent.SetString(wxStringWithNSString(title));
1182 if (webKitWindow && webKitWindow->GetEventHandler())
1183 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1187 @implementation WebViewPolicyDelegate
1189 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1192 webKitWindow = inWindow; // non retained
1196 - (void)webView:(WebView *)sender
1197 decidePolicyForNavigationAction:(NSDictionary *)actionInformation
1198 request:(NSURLRequest *)request
1199 frame:(WebFrame *)frame
1200 decisionListener:(id<WebPolicyDecisionListener>)listener
1204 webKitWindow->m_busy = true;
1205 NSString *url = [[request URL] absoluteString];
1206 wxString target = wxStringWithNSString([frame name]);
1207 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATING,
1208 webKitWindow->GetId(),
1209 wxStringWithNSString( url ), target, true);
1211 if (webKitWindow && webKitWindow->GetEventHandler())
1212 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1214 if (thisEvent.IsVetoed())
1216 webKitWindow->m_busy = false;
1225 - (void)webView:(WebView *)sender
1226 decidePolicyForNewWindowAction:(NSDictionary *)actionInformation
1227 request:(NSURLRequest *)request
1228 newFrameName:(NSString *)frameName
1229 decisionListener:(id < WebPolicyDecisionListener >)listener
1231 wxUnusedVar(actionInformation);
1233 NSString *url = [[request URL] absoluteString];
1234 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NEWWINDOW,
1235 webKitWindow->GetId(),
1236 wxStringWithNSString( url ), "", true);
1238 if (webKitWindow && webKitWindow->GetEventHandler())
1239 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1245 @implementation WebViewCustomProtocol
1247 + (BOOL)canInitWithRequest:(NSURLRequest *)request
1249 NSString *scheme = [[request URL] scheme];
1251 wxStringToWebHandlerMap::const_iterator it;
1252 for( it = g_stringHandlerMap.begin(); it != g_stringHandlerMap.end(); ++it )
1254 if(it->first.IsSameAs(wxStringWithNSString(scheme)))
1263 + (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
1265 //We don't do any processing here as the wxWebHandler classes do it
1269 - (void)startLoading
1271 NSURLRequest *request = [self request];
1272 NSString* path = [[request URL] absoluteString];
1274 wxString wxpath = wxStringWithNSString(path);
1275 wxString scheme = wxStringWithNSString([[request URL] scheme]);
1276 wxFSFile* file = g_stringHandlerMap[scheme]->GetFile(wxpath);
1277 size_t length = file->GetStream()->GetLength();
1280 NSURLResponse *response = [[NSURLResponse alloc] initWithURL:[request URL]
1281 MIMEType:wxNSStringWithWxString(file->GetMimeType())
1282 expectedContentLength:length
1283 textEncodingName:nil];
1285 //Load the data, we malloc it so it is tidied up properly
1286 void* buffer = malloc(length);
1287 file->GetStream()->Read(buffer, length);
1288 NSData *data = [[NSData alloc] initWithBytesNoCopy:buffer length:length];
1290 id<NSURLProtocolClient> client = [self client];
1292 //We do not support caching anything yet
1293 [client URLProtocol:self didReceiveResponse:response
1294 cacheStoragePolicy:NSURLCacheStorageNotAllowed];
1297 [client URLProtocol:self didLoadData:data];
1299 //Notify that we have finished
1300 [client URLProtocolDidFinishLoading:self];
1312 #endif //wxUSE_WEBVIEW_WEBKIT