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