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