]> git.saurik.com Git - wxWidgets.git/blob - src/osx/webview_webkit.mm
Remove some out of date comments.
[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 wxControl::Create(parent, winID, pos, size, style, wxDefaultValidator, name);
330
331 #if wxOSX_USE_CARBON
332 m_peer = new wxMacControl(this);
333 WebInitForCarbon();
334 HIWebViewCreate( m_peer->GetControlRefAddr() );
335
336 m_webView = (WebView*) HIWebViewGetWebView( m_peer->GetControlRef() );
337
338 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_3
339 if ( UMAGetSystemVersion() >= 0x1030 )
340 HIViewChangeFeatures( m_peer->GetControlRef() , kHIViewIsOpaque , 0 ) ;
341 #endif
342 InstallControlEventHandler(m_peer->GetControlRef(),
343 GetwxWebViewWebKitEventHandlerUPP(),
344 GetEventTypeCount(eventList), eventList, this,
345 (EventHandlerRef *)&m_webKitCtrlEventHandler);
346 #else
347 NSRect r = wxOSXGetFrameForControl( this, pos , size ) ;
348 m_webView = [[WebView alloc] initWithFrame:r
349 frameName:@"webkitFrame"
350 groupName:@"webkitGroup"];
351 m_peer = new wxWidgetCocoaImpl( this, m_webView );
352 #endif
353
354 MacPostControlCreate(pos, size);
355
356 #if wxOSX_USE_CARBON
357 HIViewSetVisible( m_peer->GetControlRef(), true );
358 #endif
359 [m_webView setHidden:false];
360
361
362
363 // Register event listener interfaces
364 MyFrameLoadMonitor* myFrameLoadMonitor =
365 [[MyFrameLoadMonitor alloc] initWithWxWindow: this];
366
367 [m_webView setFrameLoadDelegate:myFrameLoadMonitor];
368
369 // this is used to veto page loads, etc.
370 MyPolicyDelegate* myPolicyDelegate =
371 [[MyPolicyDelegate alloc] initWithWxWindow: this];
372
373 [m_webView setPolicyDelegate:myPolicyDelegate];
374
375 LoadUrl(strURL);
376 return true;
377 }
378
379 wxWebViewWebKit::~wxWebViewWebKit()
380 {
381 MyFrameLoadMonitor* myFrameLoadMonitor = [m_webView frameLoadDelegate];
382 MyPolicyDelegate* myPolicyDelegate = [m_webView policyDelegate];
383 [m_webView setFrameLoadDelegate: nil];
384 [m_webView setPolicyDelegate: nil];
385
386 if (myFrameLoadMonitor)
387 [myFrameLoadMonitor release];
388
389 if (myPolicyDelegate)
390 [myPolicyDelegate release];
391 }
392
393 // ----------------------------------------------------------------------------
394 // public methods
395 // ----------------------------------------------------------------------------
396
397 bool wxWebViewWebKit::CanGoBack()
398 {
399 if ( !m_webView )
400 return false;
401
402 return [m_webView canGoBack];
403 }
404
405 bool wxWebViewWebKit::CanGoForward()
406 {
407 if ( !m_webView )
408 return false;
409
410 return [m_webView canGoForward];
411 }
412
413 void wxWebViewWebKit::GoBack()
414 {
415 if ( !m_webView )
416 return;
417
418 [(WebView*)m_webView goBack];
419 }
420
421 void wxWebViewWebKit::GoForward()
422 {
423 if ( !m_webView )
424 return;
425
426 [(WebView*)m_webView goForward];
427 }
428
429 void wxWebViewWebKit::Reload(wxWebViewReloadFlags flags)
430 {
431 if ( !m_webView )
432 return;
433
434 if (flags & wxWEB_VIEW_RELOAD_NO_CACHE)
435 {
436 // TODO: test this indeed bypasses the cache
437 [[m_webView preferences] setUsesPageCache:NO];
438 [[m_webView mainFrame] reload];
439 [[m_webView preferences] setUsesPageCache:YES];
440 }
441 else
442 {
443 [[m_webView mainFrame] reload];
444 }
445 }
446
447 void wxWebViewWebKit::Stop()
448 {
449 if ( !m_webView )
450 return;
451
452 [[m_webView mainFrame] stopLoading];
453 }
454
455 bool wxWebViewWebKit::CanGetPageSource()
456 {
457 if ( !m_webView )
458 return false;
459
460 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
461 return ( [[dataSource representation] canProvideDocumentSource] );
462 }
463
464 wxString wxWebViewWebKit::GetPageSource()
465 {
466
467 if (CanGetPageSource())
468 {
469 WebDataSource* dataSource = [[m_webView mainFrame] dataSource];
470 wxASSERT (dataSource != nil);
471
472 id<WebDocumentRepresentation> representation = [dataSource representation];
473 wxASSERT (representation != nil);
474
475 NSString* source = [representation documentSource];
476 if (source == nil)
477 {
478 return wxEmptyString;
479 }
480
481 return wxStringWithNSString( source );
482 }
483
484 return wxEmptyString;
485 }
486
487 bool wxWebViewWebKit::CanIncreaseTextSize()
488 {
489 if ( !m_webView )
490 return false;
491
492 if ([m_webView canMakeTextLarger])
493 return true;
494 else
495 return false;
496 }
497
498 void wxWebViewWebKit::IncreaseTextSize()
499 {
500 if ( !m_webView )
501 return;
502
503 if (CanIncreaseTextSize())
504 [m_webView makeTextLarger:(WebView*)m_webView];
505 }
506
507 bool wxWebViewWebKit::CanDecreaseTextSize()
508 {
509 if ( !m_webView )
510 return false;
511
512 if ([m_webView canMakeTextSmaller])
513 return true;
514 else
515 return false;
516 }
517
518 void wxWebViewWebKit::DecreaseTextSize()
519 {
520 if ( !m_webView )
521 return;
522
523 if (CanDecreaseTextSize())
524 [m_webView makeTextSmaller:(WebView*)m_webView];
525 }
526
527 void wxWebViewWebKit::Print()
528 {
529
530 // TODO: allow specifying the "show prompt" parameter in Print() ?
531 bool showPrompt = true;
532
533 if ( !m_webView )
534 return;
535
536 id view = [[[m_webView mainFrame] frameView] documentView];
537 NSPrintOperation *op = [NSPrintOperation printOperationWithView:view
538 printInfo: [NSPrintInfo sharedPrintInfo]];
539 if (showPrompt)
540 {
541 [op setShowsPrintPanel: showPrompt];
542 // in my tests, the progress bar always freezes and it stops the whole
543 // print operation. do not turn this to true unless there is a
544 // workaround for the bug.
545 [op setShowsProgressPanel: false];
546 }
547 // Print it.
548 [op runOperation];
549 }
550
551 void wxWebViewWebKit::SetEditable(bool enable)
552 {
553 if ( !m_webView )
554 return;
555
556 [m_webView setEditable:enable ];
557 }
558
559 bool wxWebViewWebKit::IsEditable()
560 {
561 if ( !m_webView )
562 return false;
563
564 return [m_webView isEditable];
565 }
566
567 void wxWebViewWebKit::SetZoomType(wxWebViewZoomType zoomType)
568 {
569 // there is only one supported zoom type at the moment so this setter
570 // does nothing beyond checking sanity
571 wxASSERT(zoomType == wxWEB_VIEW_ZOOM_TYPE_TEXT);
572 }
573
574 wxWebViewZoomType wxWebViewWebKit::GetZoomType() const
575 {
576 // for now that's the only one that is supported
577 // FIXME: does the default zoom type change depending on webkit versions? :S
578 // Then this will be wrong
579 return wxWEB_VIEW_ZOOM_TYPE_TEXT;
580 }
581
582 bool wxWebViewWebKit::CanSetZoomType(wxWebViewZoomType type) const
583 {
584 switch (type)
585 {
586 // for now that's the only one that is supported
587 // TODO: I know recent versions of webkit support layout zoom too,
588 // check if we can support it
589 case wxWEB_VIEW_ZOOM_TYPE_TEXT:
590 return true;
591
592 default:
593 return false;
594 }
595 }
596
597 int wxWebViewWebKit::GetScrollPos()
598 {
599 id result = [[m_webView windowScriptObject]
600 evaluateWebScript:@"document.body.scrollTop"];
601 return [result intValue];
602 }
603
604 void wxWebViewWebKit::SetScrollPos(int pos)
605 {
606 if ( !m_webView )
607 return;
608
609 wxString javascript;
610 javascript.Printf(wxT("document.body.scrollTop = %d;"), pos);
611 [[m_webView windowScriptObject] evaluateWebScript:
612 (NSString*)wxNSStringWithWxString( javascript )];
613 }
614
615 wxString wxWebViewWebKit::GetSelectedText()
616 {
617 NSString* selection = [[m_webView selectedDOMRange] markupString];
618 if (!selection) return wxEmptyString;
619
620 return wxStringWithNSString(selection);
621 }
622
623 void wxWebViewWebKit::RunScript(const wxString& javascript)
624 {
625 if ( !m_webView )
626 return;
627
628 [[m_webView windowScriptObject] evaluateWebScript:
629 (NSString*)wxNSStringWithWxString( javascript )];
630 }
631
632 void wxWebViewWebKit::OnSize(wxSizeEvent &event)
633 {
634 #if defined(__WXMAC_) && wxOSX_USE_CARBON
635 // This is a nasty hack because WebKit seems to lose its position when it is
636 // embedded in a control that is not itself the content view for a TLW.
637 // I put it in OnSize because these calcs are not perfect, and in fact are
638 // basically guesses based on reverse engineering, so it's best to give
639 // people the option of overriding OnSize with their own calcs if need be.
640 // I also left some test debugging print statements as a convenience if
641 // a(nother) problem crops up.
642
643 wxWindow* tlw = MacGetTopLevelWindow();
644
645 NSRect frame = [(WebView*)m_webView frame];
646 NSRect bounds = [(WebView*)m_webView bounds];
647
648 #if DEBUG_WEBKIT_SIZING
649 fprintf(stderr,"Carbon window x=%d, y=%d, width=%d, height=%d\n",
650 GetPosition().x, GetPosition().y, GetSize().x, GetSize().y);
651 fprintf(stderr, "Cocoa window frame x=%G, y=%G, width=%G, height=%G\n",
652 frame.origin.x, frame.origin.y,
653 frame.size.width, frame.size.height);
654 fprintf(stderr, "Cocoa window bounds x=%G, y=%G, width=%G, height=%G\n",
655 bounds.origin.x, bounds.origin.y,
656 bounds.size.width, bounds.size.height);
657 #endif
658
659 // This must be the case that Apple tested with, because well, in this one case
660 // we don't need to do anything! It just works. ;)
661 if (GetParent() == tlw) return;
662
663 // since we no longer use parent coordinates, we always want 0,0.
664 int x = 0;
665 int y = 0;
666
667 HIRect rect;
668 rect.origin.x = x;
669 rect.origin.y = y;
670
671 #if DEBUG_WEBKIT_SIZING
672 printf("Before conversion, origin is: x = %d, y = %d\n", x, y);
673 #endif
674
675 // NB: In most cases, when calling HIViewConvertRect, what people want is to
676 // use GetRootControl(), and this tripped me up at first. But in fact, what
677 // we want is the root view, because we need to make the y origin relative
678 // to the very top of the window, not its contents, since we later flip
679 // the y coordinate for Cocoa.
680 HIViewConvertRect (&rect, m_peer->GetControlRef(),
681 HIViewGetRoot(
682 (WindowRef) MacGetTopLevelWindowRef()
683 ));
684
685 x = (int)rect.origin.x;
686 y = (int)rect.origin.y;
687
688 #if DEBUG_WEBKIT_SIZING
689 printf("Moving Cocoa frame origin to: x = %d, y = %d\n", x, y);
690 #endif
691
692 if (tlw){
693 //flip the y coordinate to convert to Cocoa coordinates
694 y = tlw->GetSize().y - ((GetSize().y) + y);
695 }
696
697 #if DEBUG_WEBKIT_SIZING
698 printf("y = %d after flipping value\n", y);
699 #endif
700
701 frame.origin.x = x;
702 frame.origin.y = y;
703 [(WebView*)m_webView setFrame:frame];
704
705 if (IsShown())
706 [(WebView*)m_webView display];
707 event.Skip();
708 #endif
709 }
710
711 void wxWebViewWebKit::MacVisibilityChanged(){
712 #if defined(__WXMAC__) && wxOSX_USE_CARBON
713 bool isHidden = !IsControlVisible( m_peer->GetControlRef());
714 if (!isHidden)
715 [(WebView*)m_webView display];
716
717 [m_webView setHidden:isHidden];
718 #endif
719 }
720
721 void wxWebViewWebKit::LoadUrl(const wxString& url)
722 {
723 [[m_webView mainFrame] loadRequest:[NSURLRequest requestWithURL:
724 [NSURL URLWithString:wxNSStringWithWxString(url)]]];
725 }
726
727 wxString wxWebViewWebKit::GetCurrentURL()
728 {
729 return wxStringWithNSString([m_webView mainFrameURL]);
730 }
731
732 wxString wxWebViewWebKit::GetCurrentTitle()
733 {
734 return wxStringWithNSString([m_webView mainFrameTitle]);
735 }
736
737 float wxWebViewWebKit::GetWebkitZoom()
738 {
739 return [m_webView textSizeMultiplier];
740 }
741
742 void wxWebViewWebKit::SetWebkitZoom(float zoom)
743 {
744 [m_webView setTextSizeMultiplier:zoom];
745 }
746
747 wxWebViewZoom wxWebViewWebKit::GetZoom()
748 {
749 float zoom = GetWebkitZoom();
750
751 // arbitrary way to map float zoom to our common zoom enum
752 if (zoom <= 0.55)
753 {
754 return wxWEB_VIEW_ZOOM_TINY;
755 }
756 else if (zoom > 0.55 && zoom <= 0.85)
757 {
758 return wxWEB_VIEW_ZOOM_SMALL;
759 }
760 else if (zoom > 0.85 && zoom <= 1.15)
761 {
762 return wxWEB_VIEW_ZOOM_MEDIUM;
763 }
764 else if (zoom > 1.15 && zoom <= 1.45)
765 {
766 return wxWEB_VIEW_ZOOM_LARGE;
767 }
768 else if (zoom > 1.45)
769 {
770 return wxWEB_VIEW_ZOOM_LARGEST;
771 }
772
773 // to shut up compilers, this can never be reached logically
774 wxASSERT(false);
775 return wxWEB_VIEW_ZOOM_MEDIUM;
776 }
777
778 void wxWebViewWebKit::SetZoom(wxWebViewZoom zoom)
779 {
780 // arbitrary way to map our common zoom enum to float zoom
781 switch (zoom)
782 {
783 case wxWEB_VIEW_ZOOM_TINY:
784 SetWebkitZoom(0.4f);
785 break;
786
787 case wxWEB_VIEW_ZOOM_SMALL:
788 SetWebkitZoom(0.7f);
789 break;
790
791 case wxWEB_VIEW_ZOOM_MEDIUM:
792 SetWebkitZoom(1.0f);
793 break;
794
795 case wxWEB_VIEW_ZOOM_LARGE:
796 SetWebkitZoom(1.3);
797 break;
798
799 case wxWEB_VIEW_ZOOM_LARGEST:
800 SetWebkitZoom(1.6);
801 break;
802
803 default:
804 wxASSERT(false);
805 }
806
807 }
808
809 void wxWebViewWebKit::SetPage(const wxString& src, const wxString& baseUrl)
810 {
811 if ( !m_webView )
812 return;
813
814 [[m_webView mainFrame] loadHTMLString:(NSString*)wxNSStringWithWxString(src)
815 baseURL:[NSURL URLWithString:
816 wxNSStringWithWxString( baseUrl )]];
817 }
818
819 void wxWebViewWebKit::Cut()
820 {
821 if ( !m_webView )
822 return;
823
824 [(WebView*)m_webView cut:m_webView];
825 }
826
827 void wxWebViewWebKit::Copy()
828 {
829 if ( !m_webView )
830 return;
831
832 [(WebView*)m_webView copy:m_webView];
833 }
834
835 void wxWebViewWebKit::Paste()
836 {
837 if ( !m_webView )
838 return;
839
840 [(WebView*)m_webView paste:m_webView];
841 }
842
843 void wxWebViewWebKit::DeleteSelection()
844 {
845 if ( !m_webView )
846 return;
847
848 [(WebView*)m_webView deleteSelection];
849 }
850
851 bool wxWebViewWebKit::HasSelection()
852 {
853 DOMRange* range = [m_webView selectedDOMRange];
854 if(!range)
855 {
856 return false;
857 }
858 else
859 {
860 return true;
861 }
862 }
863
864 void wxWebViewWebKit::ClearSelection()
865 {
866 //We use javascript as selection isn't exposed at the moment in webkit
867 RunScript("window.getSelection().removeAllRanges();");
868 }
869
870 void wxWebViewWebKit::SelectAll()
871 {
872 RunScript("window.getSelection().selectAllChildren(document.body);");
873 }
874
875 wxString wxWebViewWebKit::GetSelectedSource()
876 {
877 wxString script = ("var range = window.getSelection().getRangeAt(0);"
878 "var element = document.createElement('div');"
879 "element.appendChild(range.cloneContents());"
880 "return element.innerHTML;");
881 id result = [[m_webView windowScriptObject]
882 evaluateWebScript:wxNSStringWithWxString(script)];
883 return wxStringWithNSString([result stringValue]);
884 }
885
886 wxString wxWebViewWebKit::GetPageText()
887 {
888 id result = [[m_webView windowScriptObject]
889 evaluateWebScript:@"document.body.textContent"];
890 return wxStringWithNSString([result stringValue]);
891 }
892
893 void wxWebViewWebKit::EnableHistory(bool enable)
894 {
895 if ( !m_webView )
896 return;
897
898 [m_webView setMaintainsBackForwardList:enable];
899 }
900
901 void wxWebViewWebKit::ClearHistory()
902 {
903 [m_webView setMaintainsBackForwardList:NO];
904 [m_webView setMaintainsBackForwardList:YES];
905 }
906
907 wxVector<wxSharedPtr<wxWebHistoryItem> > wxWebViewWebKit::GetBackwardHistory()
908 {
909 wxVector<wxSharedPtr<wxWebHistoryItem> > backhist;
910 WebBackForwardList* history = [m_webView backForwardList];
911 int count = [history backListCount];
912 for(int i = -count; i < 0; i++)
913 {
914 WebHistoryItem* item = [history itemAtIndex:i];
915 wxString url = wxStringWithNSString([item URLString]);
916 wxString title = wxStringWithNSString([item title]);
917 wxWebHistoryItem* wxitem = new wxWebHistoryItem(url, title);
918 wxitem->m_histItem = item;
919 wxSharedPtr<wxWebHistoryItem> itemptr(wxitem);
920 backhist.push_back(itemptr);
921 }
922 return backhist;
923 }
924
925 wxVector<wxSharedPtr<wxWebHistoryItem> > wxWebViewWebKit::GetForwardHistory()
926 {
927 wxVector<wxSharedPtr<wxWebHistoryItem> > forwardhist;
928 WebBackForwardList* history = [m_webView backForwardList];
929 int count = [history forwardListCount];
930 for(int i = 1; i <= count; i++)
931 {
932 WebHistoryItem* item = [history itemAtIndex:i];
933 wxString url = wxStringWithNSString([item URLString]);
934 wxString title = wxStringWithNSString([item title]);
935 wxWebHistoryItem* wxitem = new wxWebHistoryItem(url, title);
936 wxitem->m_histItem = item;
937 wxSharedPtr<wxWebHistoryItem> itemptr(wxitem);
938 forwardhist.push_back(itemptr);
939 }
940 return forwardhist;
941 }
942
943 void wxWebViewWebKit::LoadHistoryItem(wxSharedPtr<wxWebHistoryItem> item)
944 {
945 [m_webView goToBackForwardItem:item->m_histItem];
946 }
947
948 bool wxWebViewWebKit::CanUndo()
949 {
950 return [[m_webView undoManager] canUndo];
951 }
952
953 bool wxWebViewWebKit::CanRedo()
954 {
955 return [[m_webView undoManager] canRedo];
956 }
957
958 void wxWebViewWebKit::Undo()
959 {
960 [[m_webView undoManager] undo];
961 }
962
963 void wxWebViewWebKit::Redo()
964 {
965 [[m_webView undoManager] redo];
966 }
967
968 //------------------------------------------------------------
969 // Listener interfaces
970 //------------------------------------------------------------
971
972 // NB: I'm still tracking this down, but it appears the Cocoa window
973 // still has these events fired on it while the Carbon control is being
974 // destroyed. Therefore, we must be careful to check both the existence
975 // of the Carbon control and the event handler before firing events.
976
977 @implementation MyFrameLoadMonitor
978
979 - initWithWxWindow: (wxWebViewWebKit*)inWindow
980 {
981 [super init];
982 webKitWindow = inWindow; // non retained
983 return self;
984 }
985
986 - (void)webView:(WebView *)sender
987 didStartProvisionalLoadForFrame:(WebFrame *)frame
988 {
989 webKitWindow->m_busy = true;
990 }
991
992 - (void)webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame
993 {
994 webKitWindow->m_busy = true;
995
996 if (webKitWindow && frame == [sender mainFrame]){
997 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
998 wxString target = wxStringWithNSString([frame name]);
999 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATED,
1000 webKitWindow->GetId(),
1001 wxStringWithNSString( url ),
1002 target, false);
1003
1004 if (webKitWindow && webKitWindow->GetEventHandler())
1005 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1006 }
1007 }
1008
1009 - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
1010 {
1011 webKitWindow->m_busy = false;
1012
1013 if (webKitWindow && frame == [sender mainFrame]){
1014 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1015
1016 wxString target = wxStringWithNSString([frame name]);
1017 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_LOADED,
1018 webKitWindow->GetId(),
1019 wxStringWithNSString( url ),
1020 target, false);
1021
1022 if (webKitWindow && webKitWindow->GetEventHandler())
1023 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1024 }
1025 }
1026
1027 wxString nsErrorToWxHtmlError(NSError* error, wxWebNavigationError* out)
1028 {
1029 *out = wxWEB_NAV_ERR_OTHER;
1030
1031 if ([[error domain] isEqualToString:NSURLErrorDomain])
1032 {
1033 switch ([error code])
1034 {
1035 case NSURLErrorCannotFindHost:
1036 case NSURLErrorFileDoesNotExist:
1037 case NSURLErrorRedirectToNonExistentLocation:
1038 *out = wxWEB_NAV_ERR_NOT_FOUND;
1039 break;
1040
1041 case NSURLErrorResourceUnavailable:
1042 case NSURLErrorHTTPTooManyRedirects:
1043 case NSURLErrorDataLengthExceedsMaximum:
1044 case NSURLErrorBadURL:
1045 case NSURLErrorFileIsDirectory:
1046 *out = wxWEB_NAV_ERR_REQUEST;
1047 break;
1048
1049 case NSURLErrorTimedOut:
1050 case NSURLErrorDNSLookupFailed:
1051 case NSURLErrorNetworkConnectionLost:
1052 case NSURLErrorCannotConnectToHost:
1053 case NSURLErrorNotConnectedToInternet:
1054 //case NSURLErrorInternationalRoamingOff:
1055 //case NSURLErrorCallIsActive:
1056 //case NSURLErrorDataNotAllowed:
1057 *out = wxWEB_NAV_ERR_CONNECTION;
1058 break;
1059
1060 case NSURLErrorCancelled:
1061 case NSURLErrorUserCancelledAuthentication:
1062 *out = wxWEB_NAV_ERR_USER_CANCELLED;
1063 break;
1064
1065 case NSURLErrorCannotDecodeRawData:
1066 case NSURLErrorCannotDecodeContentData:
1067 case NSURLErrorBadServerResponse:
1068 case NSURLErrorCannotParseResponse:
1069 *out = wxWEB_NAV_ERR_REQUEST;
1070 break;
1071
1072 case NSURLErrorUserAuthenticationRequired:
1073 case NSURLErrorSecureConnectionFailed:
1074 case NSURLErrorClientCertificateRequired:
1075 *out = wxWEB_NAV_ERR_AUTH;
1076 break;
1077
1078 case NSURLErrorNoPermissionsToReadFile:
1079 *out = wxWEB_NAV_ERR_SECURITY;
1080 break;
1081
1082 case NSURLErrorServerCertificateHasBadDate:
1083 case NSURLErrorServerCertificateUntrusted:
1084 case NSURLErrorServerCertificateHasUnknownRoot:
1085 case NSURLErrorServerCertificateNotYetValid:
1086 case NSURLErrorClientCertificateRejected:
1087 *out = wxWEB_NAV_ERR_CERTIFICATE;
1088 break;
1089 }
1090 }
1091
1092 wxString message = wxStringWithNSString([error localizedDescription]);
1093 NSString* detail = [error localizedFailureReason];
1094 if (detail != NULL)
1095 {
1096 message = message + " (" + wxStringWithNSString(detail) + ")";
1097 }
1098 return message;
1099 }
1100
1101 - (void)webView:(WebView *)sender didFailLoadWithError:(NSError*) error
1102 forFrame:(WebFrame *)frame
1103 {
1104 webKitWindow->m_busy = false;
1105
1106 if (webKitWindow && frame == [sender mainFrame]){
1107 NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1108
1109 wxWebNavigationError type;
1110 wxString description = nsErrorToWxHtmlError(error, &type);
1111 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1112 webKitWindow->GetId(),
1113 wxStringWithNSString( url ),
1114 wxEmptyString, false);
1115 thisEvent.SetString(description);
1116 thisEvent.SetInt(type);
1117
1118 if (webKitWindow && webKitWindow->GetEventHandler())
1119 {
1120 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1121 }
1122 }
1123 }
1124
1125 - (void)webView:(WebView *)sender
1126 didFailProvisionalLoadWithError:(NSError*)error
1127 forFrame:(WebFrame *)frame
1128 {
1129 webKitWindow->m_busy = false;
1130
1131 if (webKitWindow && frame == [sender mainFrame]){
1132 NSString *url = [[[[frame provisionalDataSource] request] URL]
1133 absoluteString];
1134
1135 wxWebNavigationError type;
1136 wxString description = nsErrorToWxHtmlError(error, &type);
1137 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_ERROR,
1138 webKitWindow->GetId(),
1139 wxStringWithNSString( url ),
1140 wxEmptyString, false);
1141 thisEvent.SetString(description);
1142 thisEvent.SetInt(type);
1143
1144 if (webKitWindow && webKitWindow->GetEventHandler())
1145 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1146 }
1147 }
1148
1149 - (void)webView:(WebView *)sender didReceiveTitle:(NSString *)title
1150 forFrame:(WebFrame *)frame
1151 {
1152 wxString target = wxStringWithNSString([frame name]);
1153 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_TITLE_CHANGED,
1154 webKitWindow->GetId(),
1155 webKitWindow->GetCurrentURL(),
1156 target, true);
1157
1158 thisEvent.SetString(wxStringWithNSString(title));
1159
1160 if (webKitWindow && webKitWindow->GetEventHandler())
1161 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1162 }
1163 @end
1164
1165 @implementation MyPolicyDelegate
1166
1167 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1168 {
1169 [super init];
1170 webKitWindow = inWindow; // non retained
1171 return self;
1172 }
1173
1174 - (void)webView:(WebView *)sender
1175 decidePolicyForNavigationAction:(NSDictionary *)actionInformation
1176 request:(NSURLRequest *)request
1177 frame:(WebFrame *)frame
1178 decisionListener:(id<WebPolicyDecisionListener>)listener
1179 {
1180 wxUnusedVar(frame);
1181
1182 webKitWindow->m_busy = true;
1183 NSString *url = [[request URL] absoluteString];
1184 wxString target = wxStringWithNSString([frame name]);
1185 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NAVIGATING,
1186 webKitWindow->GetId(),
1187 wxStringWithNSString( url ), target, true);
1188
1189 if (webKitWindow && webKitWindow->GetEventHandler())
1190 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1191
1192 if (thisEvent.IsVetoed())
1193 {
1194 webKitWindow->m_busy = false;
1195 [listener ignore];
1196 }
1197 else
1198 {
1199 [listener use];
1200 }
1201 }
1202
1203 - (void)webView:(WebView *)sender
1204 decidePolicyForNewWindowAction:(NSDictionary *)actionInformation
1205 request:(NSURLRequest *)request
1206 newFrameName:(NSString *)frameName
1207 decisionListener:(id < WebPolicyDecisionListener >)listener
1208 {
1209 wxUnusedVar(actionInformation);
1210
1211 NSString *url = [[request URL] absoluteString];
1212 wxWebNavigationEvent thisEvent(wxEVT_COMMAND_WEB_VIEW_NEWWINDOW,
1213 webKitWindow->GetId(),
1214 wxStringWithNSString( url ), "", true);
1215
1216 if (webKitWindow && webKitWindow->GetEventHandler())
1217 webKitWindow->GetEventHandler()->ProcessEvent(thisEvent);
1218
1219 [listener ignore];
1220 }
1221 @end
1222
1223 #endif //wxUSE_WEBVIEW_WEBKIT