]> git.saurik.com Git - wxWidgets.git/blob - src/osx/webview_webkit.mm
Add a WebHistory to the OSX WebKit backend and implement ClearHistory.
[wxWidgets.git] / src / osx / webview_webkit.mm
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
6 // Modified by:
7 // Created: 2004-4-16
8 // RCS-ID: $Id$
9 // Copyright: (c) Jethro Grassie / Kevin Ollivier / Marianne Gagnon
10 // Licence: wxWindows licence
11 /////////////////////////////////////////////////////////////////////////////
12
13 // http://developer.apple.com/mac/library/documentation/Cocoa/Reference/WebKit/Classes/WebView_Class/Reference/Reference.html
14
15 #include "wx/osx/webview_webkit.h"
16
17 #if wxUSE_WEBVIEW_WEBKIT && (defined(__WXOSX_COCOA__) \
18 || defined(__WXOSX_CARBON__))
19
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifndef WX_PRECOMP
24 #include "wx/wx.h"
25 #endif
26
27 #ifdef __WXCOCOA__
28 #include "wx/cocoa/autorelease.h"
29 #else
30 #include "wx/osx/private.h"
31
32 #include <WebKit/WebKit.h>
33 #include <WebKit/HIWebView.h>
34 #include <WebKit/CarbonUtils.h>
35 #endif
36
37 #include <Foundation/NSURLError.h>
38
39 // FIXME: find cleaner way to find the wxWidgets ID of a webview than this hack
40 #include <map>
41 std::map<WebView*, wxWebViewWebKit*> wx_webviewctrls;
42
43 #define DEBUG_WEBKIT_SIZING 0
44
45 // ----------------------------------------------------------------------------
46 // macros
47 // ----------------------------------------------------------------------------
48
49 wxIMPLEMENT_DYNAMIC_CLASS(wxWebViewWebKit, wxWebView);
50
51 BEGIN_EVENT_TABLE(wxWebViewWebKit, wxControl)
52 #if defined(__WXMAC__) && wxOSX_USE_CARBON
53 EVT_SIZE(wxWebViewWebKit::OnSize)
54 #endif
55 END_EVENT_TABLE()
56
57 #if defined(__WXOSX__) && wxOSX_USE_CARBON
58
59 // ----------------------------------------------------------------------------
60 // Carbon Events handlers
61 // ----------------------------------------------------------------------------
62
63 // prototype for function in src/osx/carbon/nonownedwnd.cpp
64 void SetupMouseEvent( wxMouseEvent &wxevent , wxMacCarbonEvent &cEvent );
65
66 static const EventTypeSpec eventList[] =
67 {
68 //{ kEventClassControl, kEventControlTrack } ,
69 { kEventClassMouse, kEventMouseUp },
70 { kEventClassMouse, kEventMouseDown },
71 { kEventClassMouse, kEventMouseMoved },
72 { kEventClassMouse, kEventMouseDragged },
73
74 { kEventClassKeyboard, kEventRawKeyDown } ,
75 { kEventClassKeyboard, kEventRawKeyRepeat } ,
76 { kEventClassKeyboard, kEventRawKeyUp } ,
77 { kEventClassKeyboard, kEventRawKeyModifiersChanged } ,
78
79 { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent } ,
80 { kEventClassTextInput, kEventTextInputUpdateActiveInputArea } ,
81
82 #if DEBUG_WEBKIT_SIZING == 1
83 { kEventClassControl, kEventControlBoundsChanged } ,
84 #endif
85 };
86
87 // mix this in from window.cpp
88 pascal OSStatus wxMacUnicodeTextEventHandler(EventHandlerCallRef handler,
89 EventRef event, void *data) ;
90
91 // NOTE: This is mostly taken from KeyboardEventHandler in toplevel.cpp, but
92 // that expects the data pointer is a top-level window, so I needed to change
93 // that in this case. However, once 2.8 is out, we should factor out the common
94 // logic among the two functions and merge them.
95 static pascal OSStatus wxWebKitKeyEventHandler(EventHandlerCallRef handler,
96 EventRef event, void *data)
97 {
98 OSStatus result = eventNotHandledErr ;
99 wxMacCarbonEvent cEvent( event ) ;
100
101 wxWebViewWebKit* thisWindow = (wxWebViewWebKit*) data ;
102 wxWindow* focus = thisWindow ;
103
104 unsigned char charCode ;
105 wxChar uniChar[2] ;
106 uniChar[0] = 0;
107 uniChar[1] = 0;
108
109 UInt32 keyCode ;
110 UInt32 modifiers ;
111 Point point ;
112 UInt32 when = EventTimeToTicks( GetEventTime( event ) ) ;
113
114 #if wxUSE_UNICODE
115 ByteCount dataSize = 0 ;
116 if ( GetEventParameter(event, kEventParamKeyUnicodes, typeUnicodeText,
117 NULL, 0 , &dataSize, NULL ) == noErr)
118 {
119 UniChar buf[2] ;
120 int numChars = dataSize / sizeof( UniChar) + 1;
121
122 UniChar* charBuf = buf ;
123
124 if ( numChars * 2 > 4 )
125 charBuf = new UniChar[ numChars ] ;
126 GetEventParameter(event, kEventParamKeyUnicodes, typeUnicodeText, NULL,
127 dataSize , NULL , charBuf) ;
128 charBuf[ numChars - 1 ] = 0;
129
130 #if SIZEOF_WCHAR_T == 2
131 uniChar = charBuf[0] ;
132 #else
133 wxMBConvUTF16 converter ;
134 converter.MB2WC( uniChar , (const char*)charBuf , 2 ) ;
135 #endif
136
137 if ( numChars * 2 > 4 )
138 delete[] charBuf ;
139 }
140 #endif
141
142 GetEventParameter(event, kEventParamKeyMacCharCodes, typeChar, NULL,
143 sizeof(char), NULL, &charCode );
144 GetEventParameter(event, kEventParamKeyCode, typeUInt32, NULL,
145 sizeof(UInt32), NULL, &keyCode );
146 GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, NULL,
147 sizeof(UInt32), NULL, &modifiers );
148 GetEventParameter(event, kEventParamMouseLocation, typeQDPoint, NULL,
149 sizeof(Point), NULL, &point );
150
151 UInt32 message = (keyCode << 8) + charCode;
152 switch ( GetEventKind( event ) )
153 {
154 case kEventRawKeyRepeat :
155 case kEventRawKeyDown :
156 {
157 WXEVENTREF formerEvent = wxTheApp->MacGetCurrentEvent() ;
158 WXEVENTHANDLERCALLREF formerHandler =
159 wxTheApp->MacGetCurrentEventHandlerCallRef() ;
160
161 wxTheApp->MacSetCurrentEvent( event , handler ) ;
162 if ( /* focus && */ wxTheApp->MacSendKeyDownEvent(
163 focus, message, modifiers, when, point.h, point.v, uniChar[0]))
164 {
165 result = noErr ;
166 }
167 wxTheApp->MacSetCurrentEvent( formerEvent , formerHandler ) ;
168 }
169 break ;
170
171 case kEventRawKeyUp :
172 if ( /* focus && */ wxTheApp->MacSendKeyUpEvent(
173 focus , message , modifiers , when , point.h , point.v , uniChar[0] ) )
174 {
175 result = noErr ;
176 }
177 break ;
178
179 case kEventRawKeyModifiersChanged :
180 {
181 wxKeyEvent event(wxEVT_KEY_DOWN);
182
183 event.m_shiftDown = modifiers & shiftKey;
184 event.m_controlDown = modifiers & controlKey;
185 event.m_altDown = modifiers & optionKey;
186 event.m_metaDown = modifiers & cmdKey;
187 event.m_x = point.h;
188 event.m_y = point.v;
189
190 #if wxUSE_UNICODE
191 event.m_uniChar = uniChar[0] ;
192 #endif
193
194 event.SetTimestamp(when);
195 event.SetEventObject(focus);
196
197 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & controlKey )
198 {
199 event.m_keyCode = WXK_CONTROL ;
200 event.SetEventType( ( modifiers & controlKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
201 focus->GetEventHandler()->ProcessEvent( event ) ;
202 }
203 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & shiftKey )
204 {
205 event.m_keyCode = WXK_SHIFT ;
206 event.SetEventType( ( modifiers & shiftKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
207 focus->GetEventHandler()->ProcessEvent( event ) ;
208 }
209 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & optionKey )
210 {
211 event.m_keyCode = WXK_ALT ;
212 event.SetEventType( ( modifiers & optionKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
213 focus->GetEventHandler()->ProcessEvent( event ) ;
214 }
215 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & cmdKey )
216 {
217 event.m_keyCode = WXK_COMMAND ;
218 event.SetEventType( ( modifiers & cmdKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
219 focus->GetEventHandler()->ProcessEvent( event ) ;
220 }
221
222 wxApp::s_lastModifiers = modifiers ;
223 }
224 break ;
225
226 default:
227 break;
228 }
229
230 return result ;
231 }
232
233 static pascal OSStatus wxWebViewWebKitEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
234 {
235 OSStatus result = eventNotHandledErr ;
236
237 wxMacCarbonEvent cEvent( event ) ;
238
239 ControlRef controlRef ;
240 wxWebViewWebKit* thisWindow = (wxWebViewWebKit*) data ;
241 wxNonOwnedWindow* tlw = NULL;
242 if (thisWindow)
243 tlw = thisWindow->MacGetTopLevelWindow();
244
245 cEvent.GetParameter( kEventParamDirectObject , &controlRef ) ;
246
247 wxWindow* currentMouseWindow = thisWindow ;
248
249 if ( wxApp::s_captureWindow )
250 currentMouseWindow = wxApp::s_captureWindow;
251
252 switch ( GetEventClass( event ) )
253 {
254 case kEventClassKeyboard:
255 {
256 result = wxWebKitKeyEventHandler(handler, event, data);
257 break;
258 }
259
260 case kEventClassTextInput:
261 {
262 result = wxMacUnicodeTextEventHandler(handler, event, data);
263 break;
264 }
265
266 case kEventClassMouse:
267 {
268 switch ( GetEventKind( event ) )
269 {
270 case kEventMouseDragged :
271 case kEventMouseMoved :
272 case kEventMouseDown :
273 case kEventMouseUp :
274 {
275 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
276 SetupMouseEvent( wxevent , cEvent ) ;
277
278 currentMouseWindow->ScreenToClient( &wxevent.m_x , &wxevent.m_y ) ;
279 wxevent.SetEventObject( currentMouseWindow ) ;
280 wxevent.SetId( currentMouseWindow->GetId() ) ;
281
282 if ( currentMouseWindow->GetEventHandler()->ProcessEvent(wxevent) )
283 {
284 result = noErr;
285 }
286
287 break; // this should enable WebKit to fire mouse dragged and mouse up events...
288 }
289 default :
290 break ;
291 }
292 }
293 default:
294 break;
295 }
296
297 result = CallNextEventHandler(handler, event);
298 return result ;
299 }
300
301 DEFINE_ONE_SHOT_HANDLER_GETTER( wxWebViewWebKitEventHandler )
302
303 #endif
304
305 //---------------------------------------------------------
306 // helper functions for NSString<->wxString conversion
307 //---------------------------------------------------------
308
309 inline wxString wxStringWithNSString(NSString *nsstring)
310 {
311 #if wxUSE_UNICODE
312 return wxString([nsstring UTF8String], wxConvUTF8);
313 #else
314 return wxString([nsstring lossyCString]);
315 #endif // wxUSE_UNICODE
316 }
317
318 inline NSString* wxNSStringWithWxString(const wxString &wxstring)
319 {
320 #if wxUSE_UNICODE
321 return [NSString stringWithUTF8String: wxstring.mb_str(wxConvUTF8)];
322 #else
323 return [NSString stringWithCString: wxstring.c_str() length:wxstring.Len()];
324 #endif // wxUSE_UNICODE
325 }
326
327 @interface MyFrameLoadMonitor : NSObject
328 {
329 wxWebViewWebKit* webKitWindow;
330 }
331
332 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
333
334 @end
335
336 @interface MyPolicyDelegate : NSObject
337 {
338 wxWebViewWebKit* webKitWindow;
339 }
340
341 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
342
343 @end
344
345 // ----------------------------------------------------------------------------
346 // creation/destruction
347 // ----------------------------------------------------------------------------
348
349 bool wxWebViewWebKit::Create(wxWindow *parent,
350 wxWindowID winID,
351 const wxString& strURL,
352 const wxPoint& pos,
353 const wxSize& size, long style,
354 const wxString& name)
355 {
356 m_busy = false;
357 //m_pageTitle = _("Untitled Page");
358
359 //still needed for wxCocoa??
360 /*
361 int width, height;
362 wxSize sizeInstance;
363 if (size.x == wxDefaultCoord || size.y == wxDefaultCoord)
364 {
365 m_parent->GetClientSize(&width, &height);
366 sizeInstance.x = width;
367 sizeInstance.y = height;
368 }
369 else
370 {
371 sizeInstance.x = size.x;
372 sizeInstance.y = size.y;
373 }
374 */
375 // now create and attach WebKit view...
376 #ifdef __WXCOCOA__
377 wxControl::Create(parent, m_windowID, pos, sizeInstance, style, name);
378 SetSize(pos.x, pos.y, sizeInstance.x, sizeInstance.y);
379
380 wxTopLevelWindowCocoa *topWin = wxDynamicCast(this, wxTopLevelWindowCocoa);
381 NSWindow* nsWin = topWin->GetNSWindow();
382 NSRect rect;
383 rect.origin.x = pos.x;
384 rect.origin.y = pos.y;
385 rect.size.width = sizeInstance.x;
386 rect.size.height = sizeInstance.y;
387 m_webView = (WebView*)[[WebView alloc] initWithFrame:rect
388 frameName:@"webkitFrame"
389 groupName:@"webkitGroup"];
390 SetNSView(m_webView);
391 [m_cocoaNSView release];
392
393 if(m_parent) m_parent->CocoaAddChild(this);
394 SetInitialFrameRect(pos,sizeInstance);
395 #else
396 wxControl::Create(parent, winID, pos, size, style, wxDefaultValidator, name);
397
398 #if wxOSX_USE_CARBON
399 m_peer = new wxMacControl(this);
400 WebInitForCarbon();
401 HIWebViewCreate( m_peer->GetControlRefAddr() );
402
403 m_webView = (WebView*) HIWebViewGetWebView( m_peer->GetControlRef() );
404
405 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_3
406 if ( UMAGetSystemVersion() >= 0x1030 )
407 HIViewChangeFeatures( m_peer->GetControlRef() , kHIViewIsOpaque , 0 ) ;
408 #endif
409 InstallControlEventHandler(m_peer->GetControlRef(),
410 GetwxWebViewWebKitEventHandlerUPP(),
411 GetEventTypeCount(eventList), eventList, this,
412 (EventHandlerRef *)&m_webKitCtrlEventHandler);
413 #else
414 NSRect r = wxOSXGetFrameForControl( this, pos , size ) ;
415 m_webView = [[WebView alloc] initWithFrame:r
416 frameName:@"webkitFrame"
417 groupName:@"webkitGroup"];
418 m_peer = new wxWidgetCocoaImpl( this, m_webView );
419 #endif
420
421 wx_webviewctrls[m_webView] = this;
422
423 MacPostControlCreate(pos, size);
424
425 #if wxOSX_USE_CARBON
426 HIViewSetVisible( m_peer->GetControlRef(), true );
427 #endif
428 [m_webView setHidden:false];
429
430 #endif
431
432 // Register event listener interfaces
433 MyFrameLoadMonitor* myFrameLoadMonitor =
434 [[MyFrameLoadMonitor alloc] initWithWxWindow: this];
435
436 [m_webView setFrameLoadDelegate:myFrameLoadMonitor];
437
438 // this is used to veto page loads, etc.
439 MyPolicyDelegate* myPolicyDelegate =
440 [[MyPolicyDelegate alloc] initWithWxWindow: this];
441
442 [m_webView setPolicyDelegate:myPolicyDelegate];
443
444 // add history
445 WebHistory* history = [[WebHistory alloc] init];
446 [WebHistory setOptionalSharedHistory:history];
447
448 InternalLoadURL(strURL);
449 return true;
450 }
451
452 wxWebViewWebKit::~wxWebViewWebKit()
453 {
454 MyFrameLoadMonitor* myFrameLoadMonitor = [m_webView frameLoadDelegate];
455 MyPolicyDelegate* myPolicyDelegate = [m_webView policyDelegate];
456 [m_webView setFrameLoadDelegate: nil];
457 [m_webView setPolicyDelegate: nil];
458
459 if (myFrameLoadMonitor)
460 [myFrameLoadMonitor release];
461
462 if (myPolicyDelegate)
463 [myPolicyDelegate release];
464 }
465
466 // ----------------------------------------------------------------------------
467 // public methods
468 // ----------------------------------------------------------------------------
469
470 void wxWebViewWebKit::InternalLoadURL(const wxString &url)
471 {
472 if( !m_webView )
473 return;
474
475 [[m_webView mainFrame] loadRequest:[NSURLRequest requestWithURL:
476 [NSURL URLWithString:wxNSStringWithWxString(url)]]];
477 }
478
479 bool wxWebViewWebKit::CanGoBack()
480 {
481 if ( !m_webView )
482 return false;
483
484 return [m_webView canGoBack];
485 }
486
487 bool wxWebViewWebKit::CanGoForward()
488 {
489 if ( !m_webView )
490 return false;
491
492 return [m_webView canGoForward];
493 }
494
495 void wxWebViewWebKit::GoBack()
496 {
497 if ( !m_webView )
498 return;
499
500 bool result = [(WebView*)m_webView goBack];
501
502 // TODO: return result (if it also exists in other backends...)
503 //return result;
504 }
505
506 void wxWebViewWebKit::GoForward()
507 {
508 if ( !m_webView )
509 return;
510
511 bool result = [(WebView*)m_webView goForward];
512
513 // TODO: return result (if it also exists in other backends...)
514 //return result;
515 }
516
517 void wxWebViewWebKit::Reload(wxWebViewReloadFlags flags)
518 {
519 if ( !m_webView )
520 return;
521
522 if (flags & wxWEB_VIEW_RELOAD_NO_CACHE)
523 {
524 // TODO: test this indeed bypasses the cache
525 [[m_webView preferences] setUsesPageCache:NO];
526 [[m_webView mainFrame] reload];
527 [[m_webView preferences] setUsesPageCache:YES];
528 }
529 else
530 {
531 [[m_webView mainFrame] reload];
532 }
533 }
534
535 void wxWebViewWebKit::Stop()
536 {
537 if ( !m_webView )
538 return;
539
540 [[m_webView mainFrame] stopLoading];
541 }
542
543 bool wxWebViewWebKit::CanGetPageSource()
544 {
545 if ( !m_webView )
546 return false;
547
548 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
549 return ( [[dataSource representation] canProvideDocumentSource] );
550 }
551
552 wxString wxWebViewWebKit::GetPageSource()
553 {
554
555 if (CanGetPageSource())
556 {
557 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
558 wxASSERT (dataSource != nil);
559
560 id<WebDocumentRepresentation> representation = [dataSource representation];
561 wxASSERT (representation != nil);
562
563 NSString* source = [representation documentSource];
564 if (source == nil)
565 {
566 return wxEmptyString;
567 }
568
569 return wxStringWithNSString( source );
570 }
571
572 return wxEmptyString;
573 }
574
575 bool wxWebViewWebKit::CanIncreaseTextSize()
576 {
577 if ( !m_webView )
578 return false;
579
580 if ([m_webView canMakeTextLarger])
581 return true;
582 else
583 return false;
584 }
585
586 void wxWebViewWebKit::IncreaseTextSize()
587 {
588 if ( !m_webView )
589 return;
590
591 if (CanIncreaseTextSize())
592 [m_webView makeTextLarger:(WebView*)m_webView];
593 }
594
595 bool wxWebViewWebKit::CanDecreaseTextSize()
596 {
597 if ( !m_webView )
598 return false;
599
600 if ([m_webView canMakeTextSmaller])
601 return true;
602 else
603 return false;
604 }
605
606 void wxWebViewWebKit::DecreaseTextSize()
607 {
608 if ( !m_webView )
609 return;
610
611 if (CanDecreaseTextSize())
612 [m_webView makeTextSmaller:(WebView*)m_webView];
613 }
614
615 void wxWebViewWebKit::Print()
616 {
617
618 // TODO: allow specifying the "show prompt" parameter in Print() ?
619 bool showPrompt = true;
620
621 if ( !m_webView )
622 return;
623
624 id view = [[[m_webView mainFrame] frameView] documentView];
625 NSPrintOperation *op = [NSPrintOperation printOperationWithView:view
626 printInfo: [NSPrintInfo sharedPrintInfo]];
627 if (showPrompt)
628 {
629 [op setShowsPrintPanel: showPrompt];
630 // in my tests, the progress bar always freezes and it stops the whole
631 // print operation. do not turn this to true unless there is a
632 // workaround for the bug.
633 [op setShowsProgressPanel: false];
634 }
635 // Print it.
636 [op runOperation];
637 }
638
639 void wxWebViewWebKit::SetEditable(bool enable)
640 {
641 if ( !m_webView )
642 return;
643
644 [m_webView setEditable:enable ];
645 }
646
647 bool wxWebViewWebKit::IsEditable()
648 {
649 if ( !m_webView )
650 return false;
651
652 return [m_webView isEditable];
653 }
654
655 void wxWebViewWebKit::SetZoomType(wxWebViewZoomType zoomType)
656 {
657 // there is only one supported zoom type at the moment so this setter
658 // does nothing beyond checking sanity
659 wxASSERT(zoomType == wxWEB_VIEW_ZOOM_TYPE_TEXT);
660 }
661
662 wxWebViewZoomType wxWebViewWebKit::GetZoomType() const
663 {
664 // for now that's the only one that is supported
665 // FIXME: does the default zoom type change depending on webkit versions? :S
666 // Then this will be wrong
667 return wxWEB_VIEW_ZOOM_TYPE_TEXT;
668 }
669
670 bool wxWebViewWebKit::CanSetZoomType(wxWebViewZoomType type) const
671 {
672 switch (type)
673 {
674 // for now that's the only one that is supported
675 // TODO: I know recent versions of webkit support layout zoom too,
676 // check if we can support it
677 case wxWEB_VIEW_ZOOM_TYPE_TEXT:
678 return true;
679
680 default:
681 return false;
682 }
683 }
684
685 int wxWebViewWebKit::GetScrollPos()
686 {
687 id result = [[m_webView windowScriptObject]
688 evaluateWebScript:@"document.body.scrollTop"];
689 return [result intValue];
690 }
691
692 void wxWebViewWebKit::SetScrollPos(int pos)
693 {
694 if ( !m_webView )
695 return;
696
697 wxString javascript;
698 javascript.Printf(wxT("document.body.scrollTop = %d;"), pos);
699 [[m_webView windowScriptObject] evaluateWebScript:
700 (NSString*)wxNSStringWithWxString( javascript )];
701 }
702
703 wxString wxWebViewWebKit::GetSelectedText()
704 {
705 NSString* selection = [[m_webView selectedDOMRange] markupString];
706 if (!selection) return wxEmptyString;
707
708 return wxStringWithNSString(selection);
709 }
710
711 void wxWebViewWebKit::RunScript(const wxString& javascript)
712 {
713 if ( !m_webView )
714 return;
715
716 [[m_webView windowScriptObject] evaluateWebScript:
717 (NSString*)wxNSStringWithWxString( javascript )];
718 }
719
720 void wxWebViewWebKit::OnSize(wxSizeEvent &event)
721 {
722 #if defined(__WXMAC_) && wxOSX_USE_CARBON
723 // This is a nasty hack because WebKit seems to lose its position when it is
724 // embedded in a control that is not itself the content view for a TLW.
725 // I put it in OnSize because these calcs are not perfect, and in fact are
726 // basically guesses based on reverse engineering, so it's best to give
727 // people the option of overriding OnSize with their own calcs if need be.
728 // I also left some test debugging print statements as a convenience if
729 // a(nother) problem crops up.
730
731 wxWindow* tlw = MacGetTopLevelWindow();
732
733 NSRect frame = [(WebView*)m_webView frame];
734 NSRect bounds = [(WebView*)m_webView bounds];
735
736 #if DEBUG_WEBKIT_SIZING
737 fprintf(stderr,"Carbon window x=%d, y=%d, width=%d, height=%d\n",
738 GetPosition().x, GetPosition().y, GetSize().x, GetSize().y);
739 fprintf(stderr, "Cocoa window frame x=%G, y=%G, width=%G, height=%G\n",
740 frame.origin.x, frame.origin.y,
741 frame.size.width, frame.size.height);
742 fprintf(stderr, "Cocoa window bounds x=%G, y=%G, width=%G, height=%G\n",
743 bounds.origin.x, bounds.origin.y,
744 bounds.size.width, bounds.size.height);
745 #endif
746
747 // This must be the case that Apple tested with, because well, in this one case
748 // we don't need to do anything! It just works. ;)
749 if (GetParent() == tlw) return;
750
751 // since we no longer use parent coordinates, we always want 0,0.
752 int x = 0;
753 int y = 0;
754
755 HIRect rect;
756 rect.origin.x = x;
757 rect.origin.y = y;
758
759 #if DEBUG_WEBKIT_SIZING
760 printf("Before conversion, origin is: x = %d, y = %d\n", x, y);
761 #endif
762
763 // NB: In most cases, when calling HIViewConvertRect, what people want is to
764 // use GetRootControl(), and this tripped me up at first. But in fact, what
765 // we want is the root view, because we need to make the y origin relative
766 // to the very top of the window, not its contents, since we later flip
767 // the y coordinate for Cocoa.
768 HIViewConvertRect (&rect, m_peer->GetControlRef(),
769 HIViewGetRoot(
770 (WindowRef) MacGetTopLevelWindowRef()
771 ));
772
773 x = (int)rect.origin.x;
774 y = (int)rect.origin.y;
775
776 #if DEBUG_WEBKIT_SIZING
777 printf("Moving Cocoa frame origin to: x = %d, y = %d\n", x, y);
778 #endif
779
780 if (tlw){
781 //flip the y coordinate to convert to Cocoa coordinates
782 y = tlw->GetSize().y - ((GetSize().y) + y);
783 }
784
785 #if DEBUG_WEBKIT_SIZING
786 printf("y = %d after flipping value\n", y);
787 #endif
788
789 frame.origin.x = x;
790 frame.origin.y = y;
791 [(WebView*)m_webView setFrame:frame];
792
793 if (IsShown())
794 [(WebView*)m_webView display];
795 event.Skip();
796 #endif
797 }
798
799 void wxWebViewWebKit::MacVisibilityChanged(){
800 #if defined(__WXMAC__) && wxOSX_USE_CARBON
801 bool isHidden = !IsControlVisible( m_peer->GetControlRef());
802 if (!isHidden)
803 [(WebView*)m_webView display];
804
805 [m_webView setHidden:isHidden];
806 #endif
807 }
808
809 void wxWebViewWebKit::LoadUrl(const wxString& url)
810 {
811 InternalLoadURL(url);
812 }
813
814 wxString wxWebViewWebKit::GetCurrentURL()
815 {
816 return wxStringWithNSString([m_webView mainFrameURL]);
817 }
818
819 wxString wxWebViewWebKit::GetCurrentTitle()
820 {
821 return GetPageTitle();
822 }
823
824 float wxWebViewWebKit::GetWebkitZoom()
825 {
826 return [m_webView textSizeMultiplier];
827 }
828
829 void wxWebViewWebKit::SetWebkitZoom(float zoom)
830 {
831 [m_webView setTextSizeMultiplier:zoom];
832 }
833
834 wxWebViewZoom wxWebViewWebKit::GetZoom()
835 {
836 float zoom = GetWebkitZoom();
837
838 // arbitrary way to map float zoom to our common zoom enum
839 if (zoom <= 0.55)
840 {
841 return wxWEB_VIEW_ZOOM_TINY;
842 }
843 else if (zoom > 0.55 && zoom <= 0.85)
844 {
845 return wxWEB_VIEW_ZOOM_SMALL;
846 }
847 else if (zoom > 0.85 && zoom <= 1.15)
848 {
849 return wxWEB_VIEW_ZOOM_MEDIUM;
850 }
851 else if (zoom > 1.15 && zoom <= 1.45)
852 {
853 return wxWEB_VIEW_ZOOM_LARGE;
854 }
855 else if (zoom > 1.45)
856 {
857 return wxWEB_VIEW_ZOOM_LARGEST;
858 }
859
860 // to shut up compilers, this can never be reached logically
861 wxASSERT(false);
862 return wxWEB_VIEW_ZOOM_MEDIUM;
863 }
864
865 void wxWebViewWebKit::SetZoom(wxWebViewZoom zoom)
866 {
867 // arbitrary way to map our common zoom enum to float zoom
868 switch (zoom)
869 {
870 case wxWEB_VIEW_ZOOM_TINY:
871 SetWebkitZoom(0.4f);
872 break;
873
874 case wxWEB_VIEW_ZOOM_SMALL:
875 SetWebkitZoom(0.7f);
876 break;
877
878 case wxWEB_VIEW_ZOOM_MEDIUM:
879 SetWebkitZoom(1.0f);
880 break;
881
882 case wxWEB_VIEW_ZOOM_LARGE:
883 SetWebkitZoom(1.3);
884 break;
885
886 case wxWEB_VIEW_ZOOM_LARGEST:
887 SetWebkitZoom(1.6);
888 break;
889
890 default:
891 wxASSERT(false);
892 }
893
894 }
895
896 void wxWebViewWebKit::SetPage(const wxString& src, const wxString& baseUrl)
897 {
898 if ( !m_webView )
899 return;
900
901 [[m_webView mainFrame] loadHTMLString:(NSString*)wxNSStringWithWxString(src)
902 baseURL:[NSURL URLWithString:
903 wxNSStringWithWxString( baseUrl )]];
904 }
905
906 void wxWebViewWebKit::Cut()
907 {
908 if ( !m_webView )
909 return;
910
911 [(WebView*)m_webView cut:m_webView];
912 }
913
914 void wxWebViewWebKit::Copy()
915 {
916 if ( !m_webView )
917 return;
918
919 [(WebView*)m_webView copy:m_webView];
920 }
921
922 void wxWebViewWebKit::Paste()
923 {
924 if ( !m_webView )
925 return;
926
927 [(WebView*)m_webView paste:m_webView];
928 }
929
930 void wxWebViewWebKit::DeleteSelection()
931 {
932 if ( !m_webView )
933 return;
934
935 [(WebView*)m_webView deleteSelection];
936 }
937
938 bool wxWebViewWebKit::HasSelection()
939 {
940 DOMRange* range = [m_webView selectedDOMRange];
941 if(!range)
942 {
943 return false;
944 }
945 else
946 {
947 return true;
948 }
949 }
950
951 void wxWebViewWebKit::EnableHistory(bool enable)
952 {
953 if ( !m_webView )
954 return;
955
956 [m_webView setMaintainsBackForwardList:enable];
957 }
958
959 void wxWebViewWebKit::ClearHistory()
960 {
961 [[WebHistory optionalSharedHistory] removeAllItems];
962 }
963
964 bool wxWebViewWebKit::CanUndo()
965 {
966 return [[m_webView undoManager] canUndo];
967 }
968
969 bool wxWebViewWebKit::CanRedo()
970 {
971 return [[m_webView undoManager] canRedo];
972 }
973
974 void wxWebViewWebKit::Undo()
975 {
976 [[m_webView undoManager] undo];
977 }
978
979 void wxWebViewWebKit::Redo()
980 {
981 [[m_webView undoManager] redo];
982 }
983
984 //------------------------------------------------------------
985 // Listener interfaces
986 //------------------------------------------------------------
987
988 // NB: I'm still tracking this down, but it appears the Cocoa window
989 // still has these events fired on it while the Carbon control is being
990 // destroyed. Therefore, we must be careful to check both the existence
991 // of the Carbon control and the event handler before firing events.
992
993 @implementation MyFrameLoadMonitor
994
995 - initWithWxWindow: (wxWebViewWebKit*)inWindow
996 {
997 [super init];
998 webKitWindow = inWindow; // non retained
999 return self;
1000 }
1001
1002 - (void)webView:(WebView *)sender
1003 didStartProvisionalLoadForFrame:(WebFrame *)frame
1004 {
1005 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1006 wx_webviewctrls[sender]->m_busy = true;
1007 }
1008
1009 - (void)webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame
1010 {
1011 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1012 wx_webviewctrls[sender]->m_busy = true;
1013
1014 if (webKitWindow && frame == [sender mainFrame]){
1015 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1016 wxString target = wxStringWithNSString([frame name]);
1017 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATED,
1018 wx_webviewctrls[sender]->GetId(),
1019 wxStringWithNSString( url ),
1020 target, false);
1021
1022 if (webKitWindow && webKitWindow->GetEventHandler())
1023 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1024 }
1025 }
1026
1027 - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
1028 {
1029 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1030 wx_webviewctrls[sender]->m_busy = false;
1031
1032 if (webKitWindow && frame == [sender mainFrame]){
1033 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1034
1035 wxString target = wxStringWithNSString([frame name]);
1036 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_LOADED,
1037 wx_webviewctrls[sender]->GetId(),
1038 wxStringWithNSString( url ),
1039 target, false);
1040
1041 if (webKitWindow && webKitWindow->GetEventHandler())
1042 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1043 }
1044 }
1045
1046 wxString nsErrorToWxHtmlError(NSError* error, wxWebNavigationError* out)
1047 {
1048 *out = wxWEB_NAV_ERR_OTHER;
1049
1050 if ([[error domain] isEqualToString:NSURLErrorDomain])
1051 {
1052 switch ([error code])
1053 {
1054 case NSURLErrorCannotFindHost:
1055 case NSURLErrorFileDoesNotExist:
1056 case NSURLErrorRedirectToNonExistentLocation:
1057 *out = wxWEB_NAV_ERR_NOT_FOUND;
1058 break;
1059
1060 case NSURLErrorResourceUnavailable:
1061 case NSURLErrorHTTPTooManyRedirects:
1062 case NSURLErrorDataLengthExceedsMaximum:
1063 case NSURLErrorBadURL:
1064 case NSURLErrorFileIsDirectory:
1065 *out = wxWEB_NAV_ERR_REQUEST;
1066 break;
1067
1068 case NSURLErrorTimedOut:
1069 case NSURLErrorDNSLookupFailed:
1070 case NSURLErrorNetworkConnectionLost:
1071 case NSURLErrorCannotConnectToHost:
1072 case NSURLErrorNotConnectedToInternet:
1073 //case NSURLErrorInternationalRoamingOff:
1074 //case NSURLErrorCallIsActive:
1075 //case NSURLErrorDataNotAllowed:
1076 *out = wxWEB_NAV_ERR_CONNECTION;
1077 break;
1078
1079 case NSURLErrorCancelled:
1080 case NSURLErrorUserCancelledAuthentication:
1081 *out = wxWEB_NAV_ERR_USER_CANCELLED;
1082 break;
1083
1084 case NSURLErrorCannotDecodeRawData:
1085 case NSURLErrorCannotDecodeContentData:
1086 case NSURLErrorBadServerResponse:
1087 case NSURLErrorCannotParseResponse:
1088 *out = wxWEB_NAV_ERR_REQUEST;
1089 break;
1090
1091 case NSURLErrorUserAuthenticationRequired:
1092 case NSURLErrorSecureConnectionFailed:
1093 case NSURLErrorClientCertificateRequired:
1094 *out = wxWEB_NAV_ERR_AUTH;
1095 break;
1096
1097 case NSURLErrorNoPermissionsToReadFile:
1098 *out = wxWEB_NAV_ERR_SECURITY;
1099 break;
1100
1101 case NSURLErrorServerCertificateHasBadDate:
1102 case NSURLErrorServerCertificateUntrusted:
1103 case NSURLErrorServerCertificateHasUnknownRoot:
1104 case NSURLErrorServerCertificateNotYetValid:
1105 case NSURLErrorClientCertificateRejected:
1106 *out = wxWEB_NAV_ERR_CERTIFICATE;
1107 break;
1108 }
1109 }
1110
1111 wxString message = wxStringWithNSString([error localizedDescription]);
1112 NSString* detail = [error localizedFailureReason];
1113 if (detail != NULL)
1114 {
1115 message = message + " (" + wxStringWithNSString(detail) + ")";
1116 }
1117 return message;
1118 }
1119
1120 - (void)webView:(WebView *)sender didFailLoadWithError:(NSError*) error
1121 forFrame:(WebFrame *)frame
1122 {
1123 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1124 wx_webviewctrls[sender]->m_busy = false;
1125
1126 if (webKitWindow && frame == [sender mainFrame]){
1127 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1128
1129 wxWebNavigationError type;
1130 wxString description = nsErrorToWxHtmlError(error, &type);
1131 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1132 wx_webviewctrls[sender]->GetId(),
1133 wxStringWithNSString( url ),
1134 wxEmptyString, false);
1135 thisEvent.SetString(description);
1136 thisEvent.SetInt(type);
1137
1138 if (webKitWindow && webKitWindow->GetEventHandler())
1139 {
1140 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1141 }
1142 }
1143 }
1144
1145 - (void)webView:(WebView *)sender
1146 didFailProvisionalLoadWithError:(NSError*)error
1147 forFrame:(WebFrame *)frame
1148 {
1149 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1150 wx_webviewctrls[sender]->m_busy = false;
1151
1152 if (webKitWindow && frame == [sender mainFrame]){
1153 NSString *url = [[[[frame provisionalDataSource] request] URL]
1154 absoluteString];
1155
1156 wxWebNavigationError type;
1157 wxString description = nsErrorToWxHtmlError(error, &type);
1158 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1159 wx_webviewctrls[sender]->GetId(),
1160 wxStringWithNSString( url ),
1161 wxEmptyString, false);
1162 thisEvent.SetString(description);
1163 thisEvent.SetInt(type);
1164
1165 if (webKitWindow && webKitWindow->GetEventHandler())
1166 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1167 }
1168 }
1169
1170 - (void)webView:(WebView *)sender didReceiveTitle:(NSString *)title
1171 forFrame:(WebFrame *)frame
1172 {
1173 if (webKitWindow && frame == [sender mainFrame])
1174 {
1175 webKitWindow->SetPageTitle(wxStringWithNSString( title ));
1176 }
1177 wxString target = wxStringWithNSString([frame name]);
1178 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_TITLE_CHANGED,
1179 wx_webviewctrls[sender]->GetId(),
1180 wx_webviewctrls[sender]->GetCurrentURL(),
1181 target, true);
1182
1183 thisEvent.SetString(wxStringWithNSString(title));
1184
1185 if (webKitWindow && webKitWindow->GetEventHandler())
1186 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1187 }
1188 @end
1189
1190 @implementation MyPolicyDelegate
1191
1192 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1193 {
1194 [super init];
1195 webKitWindow = inWindow; // non retained
1196 return self;
1197 }
1198
1199 - (void)webView:(WebView *)sender
1200 decidePolicyForNavigationAction:(NSDictionary *)actionInformation
1201 request:(NSURLRequest *)request
1202 frame:(WebFrame *)frame
1203 decisionListener:(id<WebPolicyDecisionListener>)listener
1204 {
1205 wxUnusedVar(frame);
1206
1207 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1208 wx_webviewctrls[sender]->m_busy = true;
1209 NSString *url = [[request URL] absoluteString];
1210 wxString target = wxStringWithNSString([frame name]);
1211 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATING,
1212 wx_webviewctrls[sender]->GetId(),
1213 wxStringWithNSString( url ), target, true);
1214
1215 if (webKitWindow && webKitWindow->GetEventHandler())
1216 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1217
1218 if (thisEvent.IsVetoed())
1219 {
1220 wx_webviewctrls[sender]->m_busy = false;
1221 [listener ignore];
1222 }
1223 else
1224 {
1225 [listener use];
1226 }
1227 }
1228
1229 - (void)webView:(WebView *)sender
1230 decidePolicyForNewWindowAction:(NSDictionary *)actionInformation
1231 request:(NSURLRequest *)request
1232 newFrameName:(NSString *)frameName
1233 decisionListener:(id < WebPolicyDecisionListener >)listener
1234 {
1235 wxUnusedVar(actionInformation);
1236
1237 wxASSERT(wx_webviewctrls.find(sender) != wx_webviewctrls.end());
1238 NSString *url = [[request URL] absoluteString];
1239 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NEWWINDOW,
1240 wx_webviewctrls[sender]->GetId(),
1241 wxStringWithNSString( url ), "", true);
1242
1243 if (webKitWindow && webKitWindow->GetEventHandler())
1244 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1245
1246 [listener ignore];
1247 }
1248 @end
1249
1250 #endif //wxUSE_WEBVIEW_WEBKIT