Don't eagerly set wxKeyEvent position fields.
[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 && 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 #include "wx/hashmap.h"
30 #include "wx/filesys.h"
31
32 #include <WebKit/WebKit.h>
33 #include <WebKit/HIWebView.h>
34 #include <WebKit/CarbonUtils.h>
35
36 #include <Foundation/NSURLError.h>
37
38 #define DEBUG_WEBKIT_SIZING 0
39
40 // ----------------------------------------------------------------------------
41 // macros
42 // ----------------------------------------------------------------------------
43
44 wxIMPLEMENT_DYNAMIC_CLASS(wxWebViewWebKit, wxWebView);
45
46 BEGIN_EVENT_TABLE(wxWebViewWebKit, wxControl)
47 #if defined(__WXMAC__) && wxOSX_USE_CARBON
48     EVT_SIZE(wxWebViewWebKit::OnSize)
49 #endif
50 END_EVENT_TABLE()
51
52 #if defined(__WXOSX__) && wxOSX_USE_CARBON
53
54 // ----------------------------------------------------------------------------
55 // Carbon Events handlers
56 // ----------------------------------------------------------------------------
57
58 // prototype for function in src/osx/carbon/nonownedwnd.cpp
59 void SetupMouseEvent( wxMouseEvent &wxevent , wxMacCarbonEvent &cEvent );
60
61 static const EventTypeSpec eventList[] =
62 {
63     //{ kEventClassControl, kEventControlTrack } ,
64     { kEventClassMouse, kEventMouseUp },
65     { kEventClassMouse, kEventMouseDown },
66     { kEventClassMouse, kEventMouseMoved },
67     { kEventClassMouse, kEventMouseDragged },
68
69     { kEventClassKeyboard, kEventRawKeyDown } ,
70     { kEventClassKeyboard, kEventRawKeyRepeat } ,
71     { kEventClassKeyboard, kEventRawKeyUp } ,
72     { kEventClassKeyboard, kEventRawKeyModifiersChanged } ,
73
74     { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent } ,
75     { kEventClassTextInput, kEventTextInputUpdateActiveInputArea } ,
76
77 #if DEBUG_WEBKIT_SIZING == 1
78     { kEventClassControl, kEventControlBoundsChanged } ,
79 #endif
80 };
81
82 // mix this in from window.cpp
83 pascal OSStatus wxMacUnicodeTextEventHandler(EventHandlerCallRef handler,
84                                              EventRef event, void *data) ;
85
86 // NOTE: This is mostly taken from KeyboardEventHandler in toplevel.cpp, but
87 // that expects the data pointer is a top-level window, so I needed to change
88 // that in this case. However, once 2.8 is out, we should factor out the common
89 // logic among the two functions and merge them.
90 static pascal OSStatus wxWebKitKeyEventHandler(EventHandlerCallRef handler,
91                                                EventRef event, void *data)
92 {
93     OSStatus result = eventNotHandledErr ;
94     wxMacCarbonEvent cEvent( event ) ;
95
96     wxWebViewWebKit* thisWindow = (wxWebViewWebKit*) data ;
97     wxWindow* focus = thisWindow ;
98
99     unsigned char charCode ;
100     wxChar uniChar[2] ;
101     uniChar[0] = 0;
102     uniChar[1] = 0;
103
104     UInt32 keyCode ;
105     UInt32 modifiers ;
106     UInt32 when = EventTimeToTicks( GetEventTime( event ) ) ;
107
108 #if wxUSE_UNICODE
109     ByteCount dataSize = 0 ;
110     if ( GetEventParameter(event, kEventParamKeyUnicodes, typeUnicodeText,
111                            NULL, 0 , &dataSize, NULL ) == noErr)
112     {
113         UniChar buf[2] ;
114         int numChars = dataSize / sizeof( UniChar) + 1;
115
116         UniChar* charBuf = buf ;
117
118         if ( numChars * 2 > 4 )
119             charBuf = new UniChar[ numChars ] ;
120         GetEventParameter(event, kEventParamKeyUnicodes, typeUnicodeText, NULL,
121                           dataSize , NULL , charBuf) ;
122         charBuf[ numChars - 1 ] = 0;
123
124 #if SIZEOF_WCHAR_T == 2
125         uniChar = charBuf[0] ;
126 #else
127         wxMBConvUTF16 converter ;
128         converter.MB2WC( uniChar , (const char*)charBuf , 2 ) ;
129 #endif
130
131         if ( numChars * 2 > 4 )
132             delete[] charBuf ;
133     }
134 #endif
135
136     GetEventParameter(event, kEventParamKeyMacCharCodes, typeChar, NULL,
137                       sizeof(char), NULL, &charCode );
138     GetEventParameter(event, kEventParamKeyCode, typeUInt32, NULL,
139                       sizeof(UInt32), NULL, &keyCode );
140     GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, NULL,
141                       sizeof(UInt32), NULL, &modifiers );
142
143     UInt32 message = (keyCode << 8) + charCode;
144     switch ( GetEventKind( event ) )
145     {
146         case kEventRawKeyRepeat :
147         case kEventRawKeyDown :
148         {
149             WXEVENTREF formerEvent = wxTheApp->MacGetCurrentEvent() ;
150             WXEVENTHANDLERCALLREF formerHandler =
151                 wxTheApp->MacGetCurrentEventHandlerCallRef() ;
152
153             wxTheApp->MacSetCurrentEvent( event , handler ) ;
154             if ( /* focus && */ wxTheApp->MacSendKeyDownEvent(
155                 focus, message, modifiers, when, uniChar[0]))
156             {
157                 result = noErr ;
158             }
159             wxTheApp->MacSetCurrentEvent( formerEvent , formerHandler ) ;
160         }
161         break ;
162
163         case kEventRawKeyUp :
164             if ( /* focus && */ wxTheApp->MacSendKeyUpEvent(
165                 focus , message , modifiers , when , uniChar[0] ) )
166             {
167                 result = noErr ;
168             }
169             break ;
170
171         case kEventRawKeyModifiersChanged :
172             {
173                 wxKeyEvent event(wxEVT_KEY_DOWN);
174
175                 event.m_shiftDown = modifiers & shiftKey;
176                 event.m_controlDown = modifiers & controlKey;
177                 event.m_altDown = modifiers & optionKey;
178                 event.m_metaDown = modifiers & cmdKey;
179
180 #if wxUSE_UNICODE
181                 event.m_uniChar = uniChar[0] ;
182 #endif
183
184                 event.SetTimestamp(when);
185                 event.SetEventObject(focus);
186
187                 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & controlKey )
188                 {
189                     event.m_keyCode = WXK_CONTROL ;
190                     event.SetEventType( ( modifiers & controlKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
191                     focus->GetEventHandler()->ProcessEvent( event ) ;
192                 }
193                 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & shiftKey )
194                 {
195                     event.m_keyCode = WXK_SHIFT ;
196                     event.SetEventType( ( modifiers & shiftKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
197                     focus->GetEventHandler()->ProcessEvent( event ) ;
198                 }
199                 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & optionKey )
200                 {
201                     event.m_keyCode = WXK_ALT ;
202                     event.SetEventType( ( modifiers & optionKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
203                     focus->GetEventHandler()->ProcessEvent( event ) ;
204                 }
205                 if ( /* focus && */ (modifiers ^ wxApp::s_lastModifiers ) & cmdKey )
206                 {
207                     event.m_keyCode = WXK_COMMAND ;
208                     event.SetEventType( ( modifiers & cmdKey ) ? wxEVT_KEY_DOWN : wxEVT_KEY_UP ) ;
209                     focus->GetEventHandler()->ProcessEvent( event ) ;
210                 }
211
212                 wxApp::s_lastModifiers = modifiers ;
213             }
214             break ;
215
216         default:
217             break;
218     }
219
220     return result ;
221 }
222
223 static pascal OSStatus wxWebViewWebKitEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
224 {
225     OSStatus result = eventNotHandledErr ;
226
227     wxMacCarbonEvent cEvent( event ) ;
228
229     ControlRef controlRef ;
230     wxWebViewWebKit* thisWindow = (wxWebViewWebKit*) data ;
231     wxNonOwnedWindow* tlw = NULL;
232     if (thisWindow)
233         tlw = thisWindow->MacGetTopLevelWindow();
234
235     cEvent.GetParameter( kEventParamDirectObject , &controlRef ) ;
236
237     wxWindow* currentMouseWindow = thisWindow ;
238
239     if ( wxApp::s_captureWindow )
240         currentMouseWindow = wxApp::s_captureWindow;
241
242     switch ( GetEventClass( event ) )
243     {
244         case kEventClassKeyboard:
245         {
246             result = wxWebKitKeyEventHandler(handler, event, data);
247             break;
248         }
249
250         case kEventClassTextInput:
251         {
252             result = wxMacUnicodeTextEventHandler(handler, event, data);
253             break;
254         }
255
256         case kEventClassMouse:
257         {
258             switch ( GetEventKind( event ) )
259             {
260                 case kEventMouseDragged :
261                 case kEventMouseMoved :
262                 case kEventMouseDown :
263                 case kEventMouseUp :
264                 {
265                     wxMouseEvent wxevent(wxEVT_LEFT_DOWN);
266                     SetupMouseEvent( wxevent , cEvent ) ;
267
268                     currentMouseWindow->ScreenToClient( &wxevent.m_x , &wxevent.m_y ) ;
269                     wxevent.SetEventObject( currentMouseWindow ) ;
270                     wxevent.SetId( currentMouseWindow->GetId() ) ;
271
272                     if ( currentMouseWindow->GetEventHandler()->ProcessEvent(wxevent) )
273                     {
274                         result = noErr;
275                     }
276
277                     break; // this should enable WebKit to fire mouse dragged and mouse up events...
278                 }
279                 default :
280                     break ;
281             }
282         }
283         default:
284             break;
285     }
286
287     result = CallNextEventHandler(handler, event);
288     return result ;
289 }
290
291 DEFINE_ONE_SHOT_HANDLER_GETTER( wxWebViewWebKitEventHandler )
292
293 #endif
294
295 @interface WebViewLoadDelegate : NSObject
296 {
297     wxWebViewWebKit* webKitWindow;
298 }
299
300 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
301
302 @end
303
304 @interface WebViewPolicyDelegate : NSObject
305 {
306     wxWebViewWebKit* webKitWindow;
307 }
308
309 - initWithWxWindow: (wxWebViewWebKit*)inWindow;
310
311 @end
312
313 //We use a hash to map scheme names to wxWebViewHandler
314 WX_DECLARE_STRING_HASH_MAP(wxSharedPtr<wxWebViewHandler>, wxStringToWebHandlerMap);
315
316 static wxStringToWebHandlerMap g_stringHandlerMap;
317
318 @interface WebViewCustomProtocol : NSURLProtocol
319 {
320 }
321 @end
322
323 // ----------------------------------------------------------------------------
324 // creation/destruction
325 // ----------------------------------------------------------------------------
326
327 bool wxWebViewWebKit::Create(wxWindow *parent,
328                                  wxWindowID winID,
329                                  const wxString& strURL,
330                                  const wxPoint& pos,
331                                  const wxSize& size, long style,
332                                  const wxString& name)
333 {
334     m_busy = false;
335
336     DontCreatePeer();
337     wxControl::Create(parent, winID, pos, size, style, wxDefaultValidator, name);
338
339 #if wxOSX_USE_CARBON
340     wxMacControl* peer = new wxMacControl(this);
341     WebInitForCarbon();
342     HIWebViewCreate( peer->GetControlRefAddr() );
343
344     m_webView = (WebView*) HIWebViewGetWebView( peer->GetControlRef() );
345
346 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_3
347     if ( UMAGetSystemVersion() >= 0x1030 )
348         HIViewChangeFeatures( peer->GetControlRef() , kHIViewIsOpaque , 0 ) ;
349 #endif
350     InstallControlEventHandler(peer->GetControlRef(),
351                                GetwxWebViewWebKitEventHandlerUPP(),
352                                GetEventTypeCount(eventList), eventList, this,
353                               (EventHandlerRef *)&m_webKitCtrlEventHandler);
354     SetPeer(peer);
355 #else
356     NSRect r = wxOSXGetFrameForControl( this, pos , size ) ;
357     m_webView = [[WebView alloc] initWithFrame:r
358                                      frameName:@"webkitFrame"
359                                      groupName:@"webkitGroup"];
360     SetPeer(new wxWidgetCocoaImpl( this, m_webView ));
361 #endif
362
363     MacPostControlCreate(pos, size);
364
365 #if wxOSX_USE_CARBON
366     HIViewSetVisible( GetPeer()->GetControlRef(), true );
367 #endif
368     [m_webView setHidden:false];
369
370
371
372     // Register event listener interfaces
373     WebViewLoadDelegate* loadDelegate =
374             [[WebViewLoadDelegate alloc] initWithWxWindow: this];
375
376     [m_webView setFrameLoadDelegate:loadDelegate];
377
378     // this is used to veto page loads, etc.
379     WebViewPolicyDelegate* policyDelegate =
380             [[WebViewPolicyDelegate alloc] initWithWxWindow: this];
381
382     [m_webView setPolicyDelegate:policyDelegate];
383
384     //Register our own class for custom scheme handling
385     [NSURLProtocol registerClass:[WebViewCustomProtocol class]];
386
387     LoadURL(strURL);
388     return true;
389 }
390
391 wxWebViewWebKit::~wxWebViewWebKit()
392 {
393     WebViewLoadDelegate* loadDelegate = [m_webView frameLoadDelegate];
394     WebViewPolicyDelegate* policyDelegate = [m_webView policyDelegate];
395     [m_webView setFrameLoadDelegate: nil];
396     [m_webView setPolicyDelegate: nil];
397
398     if (loadDelegate)
399         [loadDelegate release];
400
401     if (policyDelegate)
402         [policyDelegate release];
403 }
404
405 // ----------------------------------------------------------------------------
406 // public methods
407 // ----------------------------------------------------------------------------
408
409 bool wxWebViewWebKit::CanGoBack() const
410 {
411     if ( !m_webView )
412         return false;
413
414     return [m_webView canGoBack];
415 }
416
417 bool wxWebViewWebKit::CanGoForward() const
418 {
419     if ( !m_webView )
420         return false;
421
422     return [m_webView canGoForward];
423 }
424
425 void wxWebViewWebKit::GoBack()
426 {
427     if ( !m_webView )
428         return;
429
430     [(WebView*)m_webView goBack];
431 }
432
433 void wxWebViewWebKit::GoForward()
434 {
435     if ( !m_webView )
436         return;
437
438     [(WebView*)m_webView goForward];
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() const
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() const
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() const
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() const
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() const
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() const
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, GetPeer()->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( GetPeer()->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() const
740 {
741     return wxStringWithNSString([m_webView mainFrameURL]);
742 }
743
744 wxString wxWebViewWebKit::GetCurrentTitle() const
745 {
746     return wxStringWithNSString([m_webView mainFrameTitle]);
747 }
748
749 float wxWebViewWebKit::GetWebkitZoom() const
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() const
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::DoSetPage(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() const
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() const
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() const
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<wxWebViewHistoryItem> > wxWebViewWebKit::GetBackwardHistory()
920 {
921     wxVector<wxSharedPtr<wxWebViewHistoryItem> > 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         wxWebViewHistoryItem* wxitem = new wxWebViewHistoryItem(url, title);
930         wxitem->m_histItem = item;
931         wxSharedPtr<wxWebViewHistoryItem> itemptr(wxitem);
932         backhist.push_back(itemptr);
933     }
934     return backhist;
935 }
936
937 wxVector<wxSharedPtr<wxWebViewHistoryItem> > wxWebViewWebKit::GetForwardHistory()
938 {
939     wxVector<wxSharedPtr<wxWebViewHistoryItem> > 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         wxWebViewHistoryItem* wxitem = new wxWebViewHistoryItem(url, title);
948         wxitem->m_histItem = item;
949         wxSharedPtr<wxWebViewHistoryItem> itemptr(wxitem);
950         forwardhist.push_back(itemptr);
951     }
952     return forwardhist;
953 }
954
955 void wxWebViewWebKit::LoadHistoryItem(wxSharedPtr<wxWebViewHistoryItem> item)
956 {
957     [m_webView goToBackForwardItem:item->m_histItem];
958 }
959
960 bool wxWebViewWebKit::CanUndo() const
961 {
962     return [[m_webView undoManager] canUndo];
963 }
964
965 bool wxWebViewWebKit::CanRedo() const
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 void wxWebViewWebKit::RegisterHandler(wxSharedPtr<wxWebViewHandler> handler)
981 {
982     g_stringHandlerMap[handler->GetName()] = handler;
983 }
984
985 //------------------------------------------------------------
986 // Listener interfaces
987 //------------------------------------------------------------
988
989 // NB: I'm still tracking this down, but it appears the Cocoa window
990 // still has these events fired on it while the Carbon control is being
991 // destroyed. Therefore, we must be careful to check both the existence
992 // of the Carbon control and the event handler before firing events.
993
994 @implementation WebViewLoadDelegate
995
996 - initWithWxWindow: (wxWebViewWebKit*)inWindow
997 {
998     [super init];
999     webKitWindow = inWindow;    // non retained
1000     return self;
1001 }
1002
1003 - (void)webView:(WebView *)sender
1004     didStartProvisionalLoadForFrame:(WebFrame *)frame
1005 {
1006     webKitWindow->m_busy = true;
1007 }
1008
1009 - (void)webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame
1010 {
1011     webKitWindow->m_busy = true;
1012
1013     if (webKitWindow && frame == [sender mainFrame]){
1014         NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1015         wxString target = wxStringWithNSString([frame name]);
1016         wxWebViewEvent event(wxEVT_COMMAND_WEB_VIEW_NAVIGATED,
1017                              webKitWindow->GetId(),
1018                              wxStringWithNSString( url ),
1019                              target);
1020
1021         if (webKitWindow && webKitWindow->GetEventHandler())
1022             webKitWindow->GetEventHandler()->ProcessEvent(event);
1023     }
1024 }
1025
1026 - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
1027 {
1028     webKitWindow->m_busy = false;
1029
1030     if (webKitWindow && frame == [sender mainFrame]){
1031         NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1032
1033         wxString target = wxStringWithNSString([frame name]);
1034         wxWebViewEvent event(wxEVT_COMMAND_WEB_VIEW_LOADED,
1035                              webKitWindow->GetId(),
1036                              wxStringWithNSString( url ),
1037                              target);
1038
1039         if (webKitWindow && webKitWindow->GetEventHandler())
1040             webKitWindow->GetEventHandler()->ProcessEvent(event);
1041     }
1042 }
1043
1044 wxString nsErrorToWxHtmlError(NSError* error, wxWebViewNavigationError* out)
1045 {
1046     *out = wxWEB_NAV_ERR_OTHER;
1047
1048     if ([[error domain] isEqualToString:NSURLErrorDomain])
1049     {
1050         switch ([error code])
1051         {
1052             case NSURLErrorCannotFindHost:
1053             case NSURLErrorFileDoesNotExist:
1054             case NSURLErrorRedirectToNonExistentLocation:
1055                 *out = wxWEB_NAV_ERR_NOT_FOUND;
1056                 break;
1057
1058             case NSURLErrorResourceUnavailable:
1059             case NSURLErrorHTTPTooManyRedirects:
1060 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
1061             case NSURLErrorDataLengthExceedsMaximum:
1062 #endif
1063             case NSURLErrorBadURL:
1064             case NSURLErrorFileIsDirectory:
1065                 *out = wxWEB_NAV_ERR_REQUEST;
1066                 break;
1067
1068             case NSURLErrorTimedOut:
1069             case NSURLErrorDNSLookupFailed:
1070             case NSURLErrorNetworkConnectionLost:
1071             case NSURLErrorCannotConnectToHost:
1072             case NSURLErrorNotConnectedToInternet:
1073             //case NSURLErrorInternationalRoamingOff:
1074             //case NSURLErrorCallIsActive:
1075             //case NSURLErrorDataNotAllowed:
1076                 *out = wxWEB_NAV_ERR_CONNECTION;
1077                 break;
1078
1079             case NSURLErrorCancelled:
1080             case NSURLErrorUserCancelledAuthentication:
1081                 *out = wxWEB_NAV_ERR_USER_CANCELLED;
1082                 break;
1083
1084 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
1085             case NSURLErrorCannotDecodeRawData:
1086             case NSURLErrorCannotDecodeContentData:
1087             case NSURLErrorCannotParseResponse:
1088 #endif
1089             case NSURLErrorBadServerResponse:
1090                 *out = wxWEB_NAV_ERR_REQUEST;
1091                 break;
1092
1093             case NSURLErrorUserAuthenticationRequired:
1094             case NSURLErrorSecureConnectionFailed:
1095 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
1096             case NSURLErrorClientCertificateRequired:
1097 #endif
1098                 *out = wxWEB_NAV_ERR_AUTH;
1099                 break;
1100
1101             case NSURLErrorNoPermissionsToReadFile:
1102                                 *out = wxWEB_NAV_ERR_SECURITY;
1103                 break;
1104
1105             case NSURLErrorServerCertificateHasBadDate:
1106             case NSURLErrorServerCertificateUntrusted:
1107             case NSURLErrorServerCertificateHasUnknownRoot:
1108             case NSURLErrorServerCertificateNotYetValid:
1109             case NSURLErrorClientCertificateRejected:
1110                 *out = wxWEB_NAV_ERR_CERTIFICATE;
1111                 break;
1112         }
1113     }
1114
1115     wxString message = wxStringWithNSString([error localizedDescription]);
1116     NSString* detail = [error localizedFailureReason];
1117     if (detail != NULL)
1118     {
1119         message = message + " (" + wxStringWithNSString(detail) + ")";
1120     }
1121     return message;
1122 }
1123
1124 - (void)webView:(WebView *)sender didFailLoadWithError:(NSError*) error
1125         forFrame:(WebFrame *)frame
1126 {
1127     webKitWindow->m_busy = false;
1128
1129     if (webKitWindow && frame == [sender mainFrame]){
1130         NSString *url = [[[[frame dataSource] request] URL] absoluteString];
1131
1132         wxWebViewNavigationError type;
1133         wxString description = nsErrorToWxHtmlError(error, &type);
1134                 wxWebViewEvent event(wxEVT_COMMAND_WEB_VIEW_ERROR,
1135                                      webKitWindow->GetId(),
1136                              wxStringWithNSString( url ),
1137                              wxEmptyString);
1138                 event.SetString(description);
1139                 event.SetInt(type);
1140
1141                 if (webKitWindow && webKitWindow->GetEventHandler())
1142                 {
1143                         webKitWindow->GetEventHandler()->ProcessEvent(event);
1144                 }
1145     }
1146 }
1147
1148 - (void)webView:(WebView *)sender
1149         didFailProvisionalLoadWithError:(NSError*)error
1150                                forFrame:(WebFrame *)frame
1151 {
1152     webKitWindow->m_busy = false;
1153
1154     if (webKitWindow && frame == [sender mainFrame]){
1155         NSString *url = [[[[frame provisionalDataSource] request] URL]
1156                             absoluteString];
1157
1158                 wxWebViewNavigationError type;
1159         wxString description = nsErrorToWxHtmlError(error, &type);
1160                 wxWebViewEvent event(wxEVT_COMMAND_WEB_VIEW_ERROR,
1161                                      webKitWindow->GetId(),
1162                              wxStringWithNSString( url ),
1163                              wxEmptyString);
1164                 event.SetString(description);
1165                 event.SetInt(type);
1166
1167                 if (webKitWindow && webKitWindow->GetEventHandler())
1168                         webKitWindow->GetEventHandler()->ProcessEvent(event);
1169     }
1170 }
1171
1172 - (void)webView:(WebView *)sender didReceiveTitle:(NSString *)title
1173                                          forFrame:(WebFrame *)frame
1174 {
1175     wxString target = wxStringWithNSString([frame name]);
1176     wxWebViewEvent event(wxEVT_COMMAND_WEB_VIEW_TITLE_CHANGED,
1177                          webKitWindow->GetId(),
1178                          webKitWindow->GetCurrentURL(),
1179                          target);
1180
1181     event.SetString(wxStringWithNSString(title));
1182
1183     if (webKitWindow && webKitWindow->GetEventHandler())
1184         webKitWindow->GetEventHandler()->ProcessEvent(event);
1185 }
1186 @end
1187
1188 @implementation WebViewPolicyDelegate
1189
1190 - initWithWxWindow: (wxWebViewWebKit*)inWindow
1191 {
1192     [super init];
1193     webKitWindow = inWindow;    // non retained
1194     return self;
1195 }
1196
1197 - (void)webView:(WebView *)sender
1198         decidePolicyForNavigationAction:(NSDictionary *)actionInformation
1199                                 request:(NSURLRequest *)request
1200                                   frame:(WebFrame *)frame
1201                        decisionListener:(id<WebPolicyDecisionListener>)listener
1202 {
1203     wxUnusedVar(frame);
1204
1205     webKitWindow->m_busy = true;
1206     NSString *url = [[request URL] absoluteString];
1207     wxString target = wxStringWithNSString([frame name]);
1208     wxWebViewEvent event(wxEVT_COMMAND_WEB_VIEW_NAVIGATING,
1209                          webKitWindow->GetId(),
1210                          wxStringWithNSString( url ), target);
1211
1212     if (webKitWindow && webKitWindow->GetEventHandler())
1213         webKitWindow->GetEventHandler()->ProcessEvent(event);
1214
1215     if (!event.IsAllowed())
1216     {
1217         webKitWindow->m_busy = false;
1218         [listener ignore];
1219     }
1220     else
1221     {
1222         [listener use];
1223     }
1224 }
1225
1226 - (void)webView:(WebView *)sender
1227       decidePolicyForNewWindowAction:(NSDictionary *)actionInformation
1228                              request:(NSURLRequest *)request
1229                         newFrameName:(NSString *)frameName
1230                     decisionListener:(id < WebPolicyDecisionListener >)listener
1231 {
1232     wxUnusedVar(actionInformation);
1233
1234     NSString *url = [[request URL] absoluteString];
1235     wxWebViewEvent event(wxEVT_COMMAND_WEB_VIEW_NEWWINDOW,
1236                          webKitWindow->GetId(),
1237                          wxStringWithNSString( url ), "");
1238
1239     if (webKitWindow && webKitWindow->GetEventHandler())
1240         webKitWindow->GetEventHandler()->ProcessEvent(event);
1241
1242     [listener ignore];
1243 }
1244 @end
1245
1246 @implementation WebViewCustomProtocol
1247
1248 + (BOOL)canInitWithRequest:(NSURLRequest *)request
1249 {
1250     NSString *scheme = [[request URL] scheme];
1251
1252     wxStringToWebHandlerMap::const_iterator it;
1253     for( it = g_stringHandlerMap.begin(); it != g_stringHandlerMap.end(); ++it )
1254     {
1255         if(it->first.IsSameAs(wxStringWithNSString(scheme)))
1256         {
1257             return YES;
1258         }
1259     }
1260
1261         return NO;
1262 }
1263
1264 + (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
1265 {
1266     //We don't do any processing here as the wxWebViewHandler classes do it
1267     return request;
1268 }
1269
1270 - (void)startLoading
1271 {
1272     NSURLRequest *request = [self request];
1273         NSString* path = [[request URL] absoluteString];
1274
1275     wxString wxpath = wxStringWithNSString(path);
1276     wxString scheme = wxStringWithNSString([[request URL] scheme]);
1277     wxFSFile* file = g_stringHandlerMap[scheme]->GetFile(wxpath);
1278     size_t length = file->GetStream()->GetLength();
1279
1280
1281     NSURLResponse *response =  [[NSURLResponse alloc] initWithURL:[request URL]
1282                                            MIMEType:wxNSStringWithWxString(file->GetMimeType())
1283                                            expectedContentLength:length
1284                                            textEncodingName:nil];
1285
1286     //Load the data, we malloc it so it is tidied up properly
1287     void* buffer = malloc(length);
1288     file->GetStream()->Read(buffer, length);
1289     NSData *data = [[NSData alloc] initWithBytesNoCopy:buffer length:length];
1290
1291     id<NSURLProtocolClient> client = [self client];
1292
1293     //We do not support caching anything yet
1294         [client URLProtocol:self didReceiveResponse:response
1295             cacheStoragePolicy:NSURLCacheStorageNotAllowed];
1296
1297     //Set the data
1298         [client URLProtocol:self didLoadData:data];
1299
1300         //Notify that we have finished
1301         [client URLProtocolDidFinishLoading:self];
1302
1303         [response release];
1304 }
1305
1306 - (void)stopLoading
1307 {
1308
1309 }
1310
1311 @end
1312
1313 #endif //wxUSE_WEBVIEW && wxUSE_WEBVIEW_WEBKIT