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