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