]> git.saurik.com Git - wxWidgets.git/blob - src/html/htmlctrl/webkit/webkit.mm
No real changes, just avoid overloaded virtual wxWebView::SetPage().
[wxWidgets.git] / src / html / htmlctrl / webkit / webkit.mm
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/html/htmlctrl/webkit/webkit.mm
3 // Purpose: wxWebKitCtrl - embeddable web kit control
4 // Author: Jethro Grassie / Kevin Ollivier
5 // Modified by:
6 // Created: 2004-4-16
7 // RCS-ID: $Id$
8 // Copyright: (c) Jethro Grassie / Kevin Ollivier
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // For compilers that support precompilation, includes "wx.h".
13 #include "wx/wxprec.h"
14 #include "wx/splitter.h"
15
16 #ifndef WX_PRECOMP
17 #include "wx/wx.h"
18 #endif
19
20 #if wxUSE_WEBKIT
21
22 #ifdef __WXCOCOA__
23 #include "wx/cocoa/autorelease.h"
24 #else
25 #include "wx/osx/private.h"
26
27 #include <WebKit/WebKit.h>
28 #include <WebKit/HIWebView.h>
29 #include <WebKit/CarbonUtils.h>
30 #endif
31
32 #include "wx/html/webkit.h"
33
34 #define DEBUG_WEBKIT_SIZING 0
35
36 extern WXDLLEXPORT_DATA(const char) wxWebKitCtrlNameStr[] = "webkitctrl";
37
38 // ----------------------------------------------------------------------------
39 // macros
40 // ----------------------------------------------------------------------------
41
42 IMPLEMENT_DYNAMIC_CLASS(wxWebKitCtrl, wxControl)
43
44 BEGIN_EVENT_TABLE(wxWebKitCtrl, wxControl)
45 #if defined(__WXMAC__) && wxOSX_USE_CARBON
46 EVT_SIZE(wxWebKitCtrl::OnSize)
47 #endif
48 END_EVENT_TABLE()
49
50 #if defined(__WXOSX__) && wxOSX_USE_CARBON
51
52 // ----------------------------------------------------------------------------
53 // Carbon Events handlers
54 // ----------------------------------------------------------------------------
55
56 // prototype for function in src/osx/carbon/nonownedwnd.cpp
57 void SetupMouseEvent( wxMouseEvent &wxevent , wxMacCarbonEvent &cEvent );
58
59 static const EventTypeSpec eventList[] =
60 {
61 //{ kEventClassControl, kEventControlTrack } ,
62 { kEventClassMouse, kEventMouseUp },
63 { kEventClassMouse, kEventMouseDown },
64 { kEventClassMouse, kEventMouseMoved },
65 { kEventClassMouse, kEventMouseDragged },
66
67 { kEventClassKeyboard, kEventRawKeyDown } ,
68 { kEventClassKeyboard, kEventRawKeyRepeat } ,
69 { kEventClassKeyboard, kEventRawKeyUp } ,
70 { kEventClassKeyboard, kEventRawKeyModifiersChanged } ,
71
72 { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent } ,
73 { kEventClassTextInput, kEventTextInputUpdateActiveInputArea } ,
74
75 #if DEBUG_WEBKIT_SIZING == 1
76 { kEventClassControl, kEventControlBoundsChanged } ,
77 #endif
78 };
79
80 // mix this in from window.cpp
81 pascal OSStatus wxMacUnicodeTextEventHandler( EventHandlerCallRef handler , EventRef event , void *data ) ;
82
83 // NOTE: This is mostly taken from KeyboardEventHandler in toplevel.cpp, but
84 // that expects the data pointer is a top-level window, so I needed to change
85 // that in this case. However, once 2.8 is out, we should factor out the common logic
86 // among the two functions and merge them.
87 static pascal OSStatus wxWebKitKeyEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
88 {
89 OSStatus result = eventNotHandledErr ;
90 wxMacCarbonEvent cEvent( event ) ;
91
92 wxWebKitCtrl* thisWindow = (wxWebKitCtrl*) data ;
93 wxWindow* focus = thisWindow ;
94
95 unsigned char charCode ;
96 wxChar uniChar[2] ;
97 uniChar[0] = 0;
98 uniChar[1] = 0;
99
100 UInt32 keyCode ;
101 UInt32 modifiers ;
102 Point point ;
103 UInt32 when = EventTimeToTicks( GetEventTime( event ) ) ;
104
105 #if wxUSE_UNICODE
106 ByteCount dataSize = 0 ;
107 if ( GetEventParameter( event, kEventParamKeyUnicodes, typeUnicodeText, NULL, 0 , &dataSize, NULL ) == noErr )
108 {
109 UniChar buf[2] ;
110 int numChars = dataSize / sizeof( UniChar) + 1;
111
112 UniChar* charBuf = buf ;
113
114 if ( numChars * 2 > 4 )
115 charBuf = new UniChar[ numChars ] ;
116 GetEventParameter( event, kEventParamKeyUnicodes, typeUnicodeText, NULL, dataSize , NULL , charBuf ) ;
117 charBuf[ numChars - 1 ] = 0;
118
119 #if SIZEOF_WCHAR_T == 2
120 uniChar = charBuf[0] ;
121 #else
122 wxMBConvUTF16 converter ;
123 converter.MB2WC( uniChar , (const char*)charBuf , 2 ) ;
124 #endif
125
126 if ( numChars * 2 > 4 )
127 delete[] charBuf ;
128 }
129 #endif
130
131 GetEventParameter( event, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(char), NULL, &charCode );
132 GetEventParameter( event, kEventParamKeyCode, typeUInt32, NULL, sizeof(UInt32), NULL, &keyCode );
133 GetEventParameter( event, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(UInt32), NULL, &modifiers );
134 GetEventParameter( event, kEventParamMouseLocation, typeQDPoint, NULL, sizeof(Point), NULL, &point );
135
136 UInt32 message = (keyCode << 8) + charCode;
137 switch ( GetEventKind( event ) )
138 {
139 case kEventRawKeyRepeat :
140 case kEventRawKeyDown :
141 {
142 WXEVENTREF formerEvent = wxTheApp->MacGetCurrentEvent() ;
143 WXEVENTHANDLERCALLREF formerHandler = wxTheApp->MacGetCurrentEventHandlerCallRef() ;
144 wxTheApp->MacSetCurrentEvent( event , handler ) ;
145 if ( /* focus && */ wxTheApp->MacSendKeyDownEvent(
146 focus , message , modifiers , when , point.h , point.v , uniChar[0] ) )
147 {
148 result = noErr ;
149 }
150 wxTheApp->MacSetCurrentEvent( formerEvent , formerHandler ) ;
151 }
152 break ;
153
154 case kEventRawKeyUp :
155 if ( /* focus && */ wxTheApp->MacSendKeyUpEvent(
156 focus , message , modifiers , when , point.h , point.v , uniChar[0] ) )
157 {
158 result = noErr ;
159 }
160 break ;
161
162 case kEventRawKeyModifiersChanged :
163 {
164 wxKeyEvent event(wxEVT_KEY_DOWN);
165
166 event.m_shiftDown = modifiers & shiftKey;
167 event.m_rawControlDown = modifiers & controlKey;
168 event.m_altDown = modifiers & optionKey;
169 event.m_controlDown = modifiers & cmdKey;
170 event.m_x = point.h;
171 event.m_y = point.v;
172
173 #if wxUSE_UNICODE
174 event.m_uniChar = uniChar[0] ;
175 #endif
176
177 event.SetTimestamp(when);
178 event.SetEventObject(focus);
179
180 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & controlKey )
181 {
182 event.m_keyCode = WXK_RAW_CONTROL ;
183 event.SetEventType( ( modifiers & controlKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
184 focus->GetEventHandler()->ProcessEvent( event ) ;
185 }
186 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & shiftKey )
187 {
188 event.m_keyCode = WXK_SHIFT ;
189 event.SetEventType( ( modifiers & shiftKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
190 focus->GetEventHandler()->ProcessEvent( event ) ;
191 }
192 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & optionKey )
193 {
194 event.m_keyCode = WXK_ALT ;
195 event.SetEventType( ( modifiers & optionKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
196 focus->GetEventHandler()->ProcessEvent( event ) ;
197 }
198 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & cmdKey )
199 {
200 event.m_keyCode = WXK_CONTROL ;
201 event.SetEventType( ( modifiers & cmdKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
202 focus->GetEventHandler()->ProcessEvent( event ) ;
203 }
204
205 wxApp::s_lastModifiers = modifiers ;
206 }
207 break ;
208
209 default:
210 break;
211 }
212
213 return result ;
214 }
215
216 static pascal OSStatus wxWebKitCtrlEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
217 {
218 OSStatus result = eventNotHandledErr ;
219
220 wxMacCarbonEvent cEvent( event ) ;
221
222 ControlRef controlRef ;
223 wxWebKitCtrl* thisWindow = (wxWebKitCtrl*) data ;
224 wxNonOwnedWindow* tlw = NULL;
225 if (thisWindow)
226 tlw = thisWindow->MacGetTopLevelWindow();
227
228 cEvent.GetParameter( kEventParamDirectObject , &controlRef ) ;
229
230 wxWindow* currentMouseWindow = thisWindow ;
231
232 if ( wxApp::s_captureWindow )
233 currentMouseWindow = wxApp::s_captureWindow;
234
235 switch ( GetEventClass( event ) )
236 {
237 case kEventClassKeyboard:
238 {
239 result = wxWebKitKeyEventHandler(handler, event, data);
240 break;
241 }
242
243 case kEventClassTextInput:
244 {
245 result = wxMacUnicodeTextEventHandler(handler, event, data);
246 break;
247 }
248
249 case kEventClassMouse:
250 {
251 switch ( GetEventKind( event ) )
252 {
253 case kEventMouseDragged :
254 case kEventMouseMoved :
255 case kEventMouseDown :
256 case kEventMouseUp :
257 {
258 wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
259 SetupMouseEvent( wxevent , cEvent ) ;
260
261 currentMouseWindow->ScreenToClient( &wxevent.m_x , &wxevent.m_y ) ;
262 wxevent.SetEventObject( currentMouseWindow ) ;
263 wxevent.SetId( currentMouseWindow->GetId() ) ;
264
265 if ( currentMouseWindow->GetEventHandler()->ProcessEvent(wxevent) )
266 {
267 result = noErr;
268 }
269
270 break; // this should enable WebKit to fire mouse dragged and mouse up events...
271 }
272 default :
273 break ;
274 }
275 }
276 default:
277 break;
278 }
279
280 result = CallNextEventHandler(handler, event);
281 return result ;
282 }
283
284 DEFINE_ONE_SHOT_HANDLER_GETTER( wxWebKitCtrlEventHandler )
285
286 #endif
287
288 // ----------------------------------------------------------------------------
289 // wxWebKit Events
290 // ----------------------------------------------------------------------------
291
292 IMPLEMENT_DYNAMIC_CLASS( wxWebKitStateChangedEvent, wxCommandEvent )
293
294 wxDEFINE_EVENT( wxEVT_WEBKIT_STATE_CHANGED, wxWebKitStateChangedEvent );
295
296 wxWebKitStateChangedEvent::wxWebKitStateChangedEvent( wxWindow* win )
297 {
298 SetEventType( wxEVT_WEBKIT_STATE_CHANGED);
299 if ( win )
300 {
301 SetEventObject( win );
302 SetId(win->GetId());
303 }
304 }
305
306 IMPLEMENT_DYNAMIC_CLASS( wxWebKitBeforeLoadEvent, wxCommandEvent )
307
308 wxDEFINE_EVENT( wxEVT_WEBKIT_BEFORE_LOAD, wxWebKitBeforeLoadEvent );
309
310 wxWebKitBeforeLoadEvent::wxWebKitBeforeLoadEvent( wxWindow* win )
311 {
312 m_cancelled = false;
313 SetEventType( wxEVT_WEBKIT_BEFORE_LOAD);
314 if ( win )
315 {
316 SetEventObject( win );
317 SetId(win->GetId());
318 }
319 }
320
321
322 IMPLEMENT_DYNAMIC_CLASS( wxWebKitNewWindowEvent, wxCommandEvent )
323
324 wxDEFINE_EVENT( wxEVT_WEBKIT_NEW_WINDOW, wxWebKitNewWindowEvent );
325
326 wxWebKitNewWindowEvent::wxWebKitNewWindowEvent( wxWindow* win )
327 {
328 SetEventType( wxEVT_WEBKIT_NEW_WINDOW);
329 if ( win )
330 {
331 SetEventObject( win );
332 SetId(win->GetId());
333 }
334 }
335
336
337
338 //---------------------------------------------------------
339 // helper functions for NSString<->wxString conversion
340 //---------------------------------------------------------
341
342 inline wxString wxStringWithNSString(NSString *nsstring)
343 {
344 #if wxUSE_UNICODE
345 return wxString([nsstring UTF8String], wxConvUTF8);
346 #else
347 return wxString([nsstring lossyCString]);
348 #endif // wxUSE_UNICODE
349 }
350
351 inline NSString* wxNSStringWithWxString(const wxString &wxstring)
352 {
353 #if wxUSE_UNICODE
354 return [NSString stringWithUTF8String: wxstring.mb_str(wxConvUTF8)];
355 #else
356 return [NSString stringWithCString: wxstring.c_str() length:wxstring.Len()];
357 #endif // wxUSE_UNICODE
358 }
359
360 inline int wxNavTypeFromWebNavType(int type){
361 if (type == WebNavigationTypeLinkClicked)
362 return wxWEBKIT_NAV_LINK_CLICKED;
363
364 if (type == WebNavigationTypeFormSubmitted)
365 return wxWEBKIT_NAV_FORM_SUBMITTED;
366
367 if (type == WebNavigationTypeBackForward)
368 return wxWEBKIT_NAV_BACK_NEXT;
369
370 if (type == WebNavigationTypeReload)
371 return wxWEBKIT_NAV_RELOAD;
372
373 if (type == WebNavigationTypeFormResubmitted)
374 return wxWEBKIT_NAV_FORM_RESUBMITTED;
375
376 return wxWEBKIT_NAV_OTHER;
377 }
378
379 @interface MyFrameLoadMonitor : NSObject
380 {
381 wxWebKitCtrl* webKitWindow;
382 }
383
384 - initWithWxWindow: (wxWebKitCtrl*)inWindow;
385
386 @end
387
388 @interface MyPolicyDelegate : NSObject
389 {
390 wxWebKitCtrl* webKitWindow;
391 }
392
393 - initWithWxWindow: (wxWebKitCtrl*)inWindow;
394
395 @end
396
397 // ----------------------------------------------------------------------------
398 // creation/destruction
399 // ----------------------------------------------------------------------------
400
401 bool wxWebKitCtrl::Create(wxWindow *parent,
402 wxWindowID winID,
403 const wxString& strURL,
404 const wxPoint& pos,
405 const wxSize& size, long style,
406 const wxValidator& validator,
407 const wxString& name)
408 {
409 m_currentURL = strURL;
410 //m_pageTitle = _("Untitled Page");
411
412 //still needed for wxCocoa??
413 /*
414 int width, height;
415 wxSize sizeInstance;
416 if (size.x == wxDefaultCoord || size.y == wxDefaultCoord)
417 {
418 m_parent->GetClientSize(&width, &height);
419 sizeInstance.x = width;
420 sizeInstance.y = height;
421 }
422 else
423 {
424 sizeInstance.x = size.x;
425 sizeInstance.y = size.y;
426 }
427 */
428 // now create and attach WebKit view...
429 DontCreatePeer();
430 #ifdef __WXCOCOA__
431 wxControl::Create(parent, m_windowID, pos, sizeInstance, style , validator , name);
432 SetSize(pos.x, pos.y, sizeInstance.x, sizeInstance.y);
433
434 wxTopLevelWindowCocoa *topWin = wxDynamicCast(this, wxTopLevelWindowCocoa);
435 NSWindow* nsWin = topWin->GetNSWindow();
436 NSRect rect;
437 rect.origin.x = pos.x;
438 rect.origin.y = pos.y;
439 rect.size.width = sizeInstance.x;
440 rect.size.height = sizeInstance.y;
441 m_webView = (WebView*)[[WebView alloc] initWithFrame:rect frameName:@"webkitFrame" groupName:@"webkitGroup"];
442 SetNSView(m_webView);
443 [m_cocoaNSView release];
444
445 if(m_parent) m_parent->CocoaAddChild(this);
446 SetInitialFrameRect(pos,sizeInstance);
447 #else
448 DontCreatePeer();
449 wxControl::Create(parent, winID, pos, size, style , validator , name);
450 #if wxOSX_USE_CARBON
451 wxMacControl* peer = new wxMacControl(this);
452 WebInitForCarbon();
453 HIWebViewCreate( peer->GetControlRefAddr() );
454
455 m_webView = (WebView*) HIWebViewGetWebView( peer->GetControlRef() );
456
457 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_3
458 if ( UMAGetSystemVersion() >= 0x1030 )
459 HIViewChangeFeatures( peer->GetControlRef() , kHIViewIsOpaque , 0 ) ;
460 #endif
461 InstallControlEventHandler( peer->GetControlRef() , GetwxWebKitCtrlEventHandlerUPP(),
462 GetEventTypeCount(eventList), eventList, this,
463 (EventHandlerRef *)&m_webKitCtrlEventHandler);
464
465 SetPeer(peer);
466 #else
467 NSRect r = wxOSXGetFrameForControl( this, pos , size ) ;
468 m_webView = [[WebView alloc] initWithFrame:r frameName:@"webkitFrame" groupName:@"webkitGroup"];
469
470 SetPeer(new wxWidgetCocoaImpl( this, m_webView ));
471 #endif
472 MacPostControlCreate(pos, size);
473 #if wxOSX_USE_CARBON
474 HIViewSetVisible( GetPeer()->GetControlRef(), true );
475 #endif
476 [m_webView setHidden:false];
477
478 #endif
479
480 // Register event listener interfaces
481 MyFrameLoadMonitor* myFrameLoadMonitor = [[MyFrameLoadMonitor alloc] initWithWxWindow: this];
482 [m_webView setFrameLoadDelegate:myFrameLoadMonitor];
483
484 // this is used to veto page loads, etc.
485 MyPolicyDelegate* myPolicyDelegate = [[MyPolicyDelegate alloc] initWithWxWindow: this];
486 [m_webView setPolicyDelegate:myPolicyDelegate];
487
488 LoadURL(m_currentURL);
489 return true;
490 }
491
492 wxWebKitCtrl::~wxWebKitCtrl()
493 {
494 MyFrameLoadMonitor* myFrameLoadMonitor = [m_webView frameLoadDelegate];
495 MyPolicyDelegate* myPolicyDelegate = [m_webView policyDelegate];
496 [m_webView setFrameLoadDelegate: nil];
497 [m_webView setPolicyDelegate: nil];
498
499 if (myFrameLoadMonitor)
500 [myFrameLoadMonitor release];
501
502 if (myPolicyDelegate)
503 [myPolicyDelegate release];
504 }
505
506 // ----------------------------------------------------------------------------
507 // public methods
508 // ----------------------------------------------------------------------------
509
510 void wxWebKitCtrl::LoadURL(const wxString &url)
511 {
512 if( !m_webView )
513 return;
514
515 [[m_webView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:wxNSStringWithWxString(url)]]];
516
517 m_currentURL = url;
518 }
519
520 bool wxWebKitCtrl::CanGoBack(){
521 if ( !m_webView )
522 return false;
523
524 return [m_webView canGoBack];
525 }
526
527 bool wxWebKitCtrl::CanGoForward(){
528 if ( !m_webView )
529 return false;
530
531 return [m_webView canGoForward];
532 }
533
534 bool wxWebKitCtrl::GoBack(){
535 if ( !m_webView )
536 return false;
537
538 bool result = [(WebView*)m_webView goBack];
539 return result;
540 }
541
542 bool wxWebKitCtrl::GoForward(){
543 if ( !m_webView )
544 return false;
545
546 bool result = [(WebView*)m_webView goForward];
547 return result;
548 }
549
550 void wxWebKitCtrl::Reload(){
551 if ( !m_webView )
552 return;
553
554 [[m_webView mainFrame] reload];
555 }
556
557 void wxWebKitCtrl::Stop(){
558 if ( !m_webView )
559 return;
560
561 [[m_webView mainFrame] stopLoading];
562 }
563
564 bool wxWebKitCtrl::CanGetPageSource(){
565 if ( !m_webView )
566 return false;
567
568 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
569 return ( [[dataSource representation] canProvideDocumentSource] );
570 }
571
572 wxString wxWebKitCtrl::GetPageSource(){
573
574 if (CanGetPageSource()){
575 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
576 return wxStringWithNSString( [[dataSource representation] documentSource] );
577 }
578
579 return wxEmptyString;
580 }
581
582 wxString wxWebKitCtrl::GetSelection(){
583 if ( !m_webView )
584 return wxEmptyString;
585
586 NSString* selectedText = [[m_webView selectedDOMRange] toString];
587 return wxStringWithNSString( selectedText );
588 }
589
590 bool wxWebKitCtrl::CanIncreaseTextSize(){
591 if ( !m_webView )
592 return false;
593
594 if ([m_webView canMakeTextLarger])
595 return true;
596 else
597 return false;
598 }
599
600 void wxWebKitCtrl::IncreaseTextSize(){
601 if ( !m_webView )
602 return;
603
604 if (CanIncreaseTextSize())
605 [m_webView makeTextLarger:(WebView*)m_webView];
606 }
607
608 bool wxWebKitCtrl::CanDecreaseTextSize(){
609 if ( !m_webView )
610 return false;
611
612 if ([m_webView canMakeTextSmaller])
613 return true;
614 else
615 return false;
616 }
617
618 void wxWebKitCtrl::DecreaseTextSize(){
619 if ( !m_webView )
620 return;
621
622 if (CanDecreaseTextSize())
623 [m_webView makeTextSmaller:(WebView*)m_webView];
624 }
625
626 void wxWebKitCtrl::SetPageSource(const wxString& source, const wxString& baseUrl){
627 if ( !m_webView )
628 return;
629
630 [[m_webView mainFrame] loadHTMLString:(NSString*)wxNSStringWithWxString( source ) baseURL:[NSURL URLWithString:wxNSStringWithWxString( baseUrl )]];
631
632 }
633
634 void wxWebKitCtrl::Print(bool showPrompt){
635 if ( !m_webView )
636 return;
637
638 id view = [[[m_webView mainFrame] frameView] documentView];
639 NSPrintOperation *op = [NSPrintOperation printOperationWithView:view printInfo: [NSPrintInfo sharedPrintInfo]];
640 if (showPrompt){
641 [op setShowsPrintPanel: showPrompt];
642 // in my tests, the progress bar always freezes and it stops the whole print operation.
643 // do not turn this to true unless there is a workaround for the bug.
644 [op setShowsProgressPanel: false];
645 }
646 // Print it.
647 [op runOperation];
648 }
649
650 void wxWebKitCtrl::MakeEditable(bool enable){
651 if ( !m_webView )
652 return;
653
654 [m_webView setEditable:enable ];
655 }
656
657 bool wxWebKitCtrl::IsEditable(){
658 if ( !m_webView )
659 return false;
660
661 return [m_webView isEditable];
662 }
663
664 int wxWebKitCtrl::GetScrollPos(){
665 id result = [[m_webView windowScriptObject] evaluateWebScript:@"document.body.scrollTop"];
666 return [result intValue];
667 }
668
669 void wxWebKitCtrl::SetScrollPos(int pos){
670 if ( !m_webView )
671 return;
672
673 wxString javascript;
674 javascript.Printf(wxT("document.body.scrollTop = %d;"), pos);
675 [[m_webView windowScriptObject] evaluateWebScript:(NSString*)wxNSStringWithWxString( javascript )];
676 }
677
678 wxString wxWebKitCtrl::RunScript(const wxString& javascript){
679 if ( !m_webView )
680 return wxEmptyString;
681
682 id result = [[m_webView windowScriptObject] evaluateWebScript:(NSString*)wxNSStringWithWxString( javascript )];
683
684 NSString* resultAsString;
685 if ([result isKindOfClass:[NSNumber class]]){
686 // __NSCFBoolean is a subclass of NSNumber
687 if (strcmp([result objCType], @encode(BOOL)) == 0){
688 if ([result boolValue])
689 resultAsString = @"true";
690 else
691 resultAsString = @"false";
692 }
693 else
694 resultAsString = [NSString stringWithFormat:@"%@", result];
695 }
696 else if ([result isKindOfClass:[NSString class]])
697 resultAsString = result;
698 else if ([result isKindOfClass:[WebScriptObject class]])
699 resultAsString = [result stringRepresentation];
700 else
701 return wxString(); // This can happen, see e.g. #12361.
702
703 return wxStringWithNSString( resultAsString );
704 }
705
706 void wxWebKitCtrl::OnSize(wxSizeEvent &event){
707 #if defined(__WXMAC__) && wxOSX_USE_CARBON
708 // This is a nasty hack because WebKit seems to lose its position when it is embedded
709 // in a control that is not itself the content view for a TLW.
710 // I put it in OnSize because these calcs are not perfect, and in fact are basically
711 // guesses based on reverse engineering, so it's best to give people the option of
712 // overriding OnSize with their own calcs if need be.
713 // I also left some test debugging print statements as a convenience if a(nother)
714 // problem crops up.
715
716 wxWindow* tlw = MacGetTopLevelWindow();
717
718 NSRect frame = [(WebView*)m_webView frame];
719 NSRect bounds = [(WebView*)m_webView bounds];
720
721 #if DEBUG_WEBKIT_SIZING
722 fprintf(stderr,"Carbon window x=%d, y=%d, width=%d, height=%d\n", GetPosition().x, GetPosition().y, GetSize().x, GetSize().y);
723 fprintf(stderr, "Cocoa window frame x=%G, y=%G, width=%G, height=%G\n", frame.origin.x, frame.origin.y, frame.size.width, frame.size.height);
724 fprintf(stderr, "Cocoa window bounds x=%G, y=%G, width=%G, height=%G\n", bounds.origin.x, bounds.origin.y, bounds.size.width, bounds.size.height);
725 #endif
726
727 // This must be the case that Apple tested with, because well, in this one case
728 // we don't need to do anything! It just works. ;)
729 if (GetParent() == tlw){
730 return;
731 }
732
733 // since we no longer use parent coordinates, we always want 0,0.
734 int x = 0;
735 int y = 0;
736
737 HIRect rect;
738 rect.origin.x = x;
739 rect.origin.y = y;
740
741 #if DEBUG_WEBKIT_SIZING
742 printf("Before conversion, origin is: x = %d, y = %d\n", x, y);
743 #endif
744
745 // NB: In most cases, when calling HIViewConvertRect, what people want is to use GetRootControl(),
746 // and this tripped me up at first. But in fact, what we want is the root view, because we need to
747 // make the y origin relative to the very top of the window, not its contents, since we later flip
748 // the y coordinate for Cocoa.
749 HIViewConvertRect (&rect, GetPeer()->GetControlRef(),
750 HIViewGetRoot( (WindowRef) MacGetTopLevelWindowRef() ) );
751
752 x = (int)rect.origin.x;
753 y = (int)rect.origin.y;
754
755 #if DEBUG_WEBKIT_SIZING
756 printf("Moving Cocoa frame origin to: x = %d, y = %d\n", x, y);
757 #endif
758
759 if (tlw){
760 //flip the y coordinate to convert to Cocoa coordinates
761 y = tlw->GetSize().y - ((GetSize().y) + y);
762 }
763
764 #if DEBUG_WEBKIT_SIZING
765 printf("y = %d after flipping value\n", y);
766 #endif
767
768 frame.origin.x = x;
769 frame.origin.y = y;
770 [(WebView*)m_webView setFrame:frame];
771
772 if (IsShown())
773 [(WebView*)m_webView display];
774 #endif
775 event.Skip();
776 }
777
778 void wxWebKitCtrl::MacVisibilityChanged(){
779 #if defined(__WXMAC__) && wxOSX_USE_CARBON
780 bool isHidden = !IsControlVisible( GetPeer()->GetControlRef());
781 if (!isHidden)
782 [(WebView*)m_webView display];
783
784 [m_webView setHidden:isHidden];
785 #endif
786 }
787
788 //------------------------------------------------------------
789 // Listener interfaces
790 //------------------------------------------------------------
791
792 // NB: I'm still tracking this down, but it appears the Cocoa window
793 // still has these events fired on it while the Carbon control is being
794 // destroyed. Therefore, we must be careful to check both the existence
795 // of the Carbon control and the event handler before firing events.
796
797 @implementation MyFrameLoadMonitor
798
799 - initWithWxWindow: (wxWebKitCtrl*)inWindow
800 {
801 self = [super init];
802 webKitWindow = inWindow; // non retained
803 return self;
804 }
805
806 - (void)webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame
807 {
808 if (webKitWindow && frame == [sender mainFrame]){
809 NSString *url = [[[[frame provisionalDataSource] request] URL] absoluteString];
810 wxWebKitStateChangedEvent thisEvent(webKitWindow);
811 thisEvent.SetState(wxWEBKIT_STATE_NEGOTIATING);
812 thisEvent.SetURL( wxStringWithNSString( url ) );
813 if (webKitWindow->GetEventHandler())
814 webKitWindow->GetEventHandler()->ProcessEvent( thisEvent );
815 }
816 }
817
818 - (void)webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame
819 {
820 if (webKitWindow && frame == [sender mainFrame]){
821 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
822 wxWebKitStateChangedEvent thisEvent(webKitWindow);
823 thisEvent.SetState(wxWEBKIT_STATE_TRANSFERRING);
824 thisEvent.SetURL( wxStringWithNSString( url ) );
825 if (webKitWindow->GetEventHandler())
826 webKitWindow->GetEventHandler()->ProcessEvent( thisEvent );
827 }
828 }
829
830 - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
831 {
832 if (webKitWindow && frame == [sender mainFrame]){
833 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
834 wxWebKitStateChangedEvent thisEvent(webKitWindow);
835 thisEvent.SetState(wxWEBKIT_STATE_STOP);
836 thisEvent.SetURL( wxStringWithNSString( url ) );
837 if (webKitWindow->GetEventHandler())
838 webKitWindow->GetEventHandler()->ProcessEvent( thisEvent );
839 }
840 }
841
842 - (void)webView:(WebView *)sender didFailLoadWithError:(NSError*) error forFrame:(WebFrame *)frame
843 {
844 wxUnusedVar(error);
845
846 if (webKitWindow && frame == [sender mainFrame]){
847 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
848 wxWebKitStateChangedEvent thisEvent(webKitWindow);
849 thisEvent.SetState(wxWEBKIT_STATE_FAILED);
850 thisEvent.SetURL( wxStringWithNSString( url ) );
851 if (webKitWindow->GetEventHandler())
852 webKitWindow->GetEventHandler()->ProcessEvent( thisEvent );
853 }
854 }
855
856 - (void)webView:(WebView *)sender didFailProvisionalLoadWithError:(NSError*) error forFrame:(WebFrame *)frame
857 {
858 wxUnusedVar(error);
859
860 if (webKitWindow && frame == [sender mainFrame]){
861 NSString *url = [[[[frame provisionalDataSource] request] URL] absoluteString];
862 wxWebKitStateChangedEvent thisEvent(webKitWindow);
863 thisEvent.SetState(wxWEBKIT_STATE_FAILED);
864 thisEvent.SetURL( wxStringWithNSString( url ) );
865 if (webKitWindow->GetEventHandler())
866 webKitWindow->GetEventHandler()->ProcessEvent( thisEvent );
867 }
868 }
869
870 - (void)webView:(WebView *)sender didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame
871 {
872 if (webKitWindow && frame == [sender mainFrame]){
873 webKitWindow->SetPageTitle(wxStringWithNSString( title ));
874 }
875 }
876 @end
877
878 @implementation MyPolicyDelegate
879
880 - initWithWxWindow: (wxWebKitCtrl*)inWindow
881 {
882 self = [super init];
883 webKitWindow = inWindow; // non retained
884 return self;
885 }
886
887 - (void)webView:(WebView *)sender decidePolicyForNavigationAction:(NSDictionary *)actionInformation request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener
888 {
889 wxUnusedVar(sender);
890 wxUnusedVar(frame);
891
892 wxWebKitBeforeLoadEvent thisEvent(webKitWindow);
893
894 // Get the navigation type.
895 NSNumber *n = [actionInformation objectForKey:WebActionNavigationTypeKey];
896 int actionType = [n intValue];
897 thisEvent.SetNavigationType( wxNavTypeFromWebNavType(actionType) );
898
899 NSString *url = [[request URL] absoluteString];
900 thisEvent.SetURL( wxStringWithNSString( url ) );
901
902 if (webKitWindow && webKitWindow->GetEventHandler())
903 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
904
905 if (thisEvent.IsCancelled())
906 [listener ignore];
907 else
908 [listener use];
909 }
910
911 - (void)webView:(WebView *)sender decidePolicyForNewWindowAction:(NSDictionary *)actionInformation request:(NSURLRequest *)request newFrameName:(NSString *)frameName decisionListener:(id < WebPolicyDecisionListener >)listener
912 {
913 wxUnusedVar(sender);
914 wxUnusedVar(actionInformation);
915 wxWebKitNewWindowEvent thisEvent(webKitWindow);
916
917 NSString *url = [[request URL] absoluteString];
918 thisEvent.SetURL( wxStringWithNSString( url ) );
919 thisEvent.SetTargetName( wxStringWithNSString( frameName ) );
920
921 if (webKitWindow && webKitWindow->GetEventHandler())
922 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
923
924 [listener use];
925 }
926 @end
927
928 #endif //wxUSE_WEBKIT