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