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