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