Logo ROOT   6.08/02
Reference Guide
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
QuartzWindow.mm
Go to the documentation of this file.
1 // @(#)root/graf2d:$Id$
2 // Author: Timur Pocheptsov 16/02/2012
3 
4 /*************************************************************************
5  * Copyright (C) 1995-2012, Rene Brun and Fons Rademakers. *
6  * All rights reserved. *
7  * *
8  * For the licensing terms see $ROOTSYS/LICENSE. *
9  * For the list of contributors see $ROOTSYS/README/CREDITS. *
10  *************************************************************************/
11 
12 //#define DEBUG_ROOT_COCOA
13 
14 //#define NDEBUG
15 
16 #ifdef DEBUG_ROOT_COCOA
17 #include <iostream>
18 #include <fstream>
19 
20 #include "TClass.h"
21 #endif
22 
23 #include <algorithm>
24 #include <stdexcept>
25 #include <cassert>
26 #include <vector>
27 
28 #include <Availability.h>
29 
30 #include "ROOTOpenGLView.h"
31 #include "CocoaConstants.h"
32 #include "QuartzWindow.h"
33 #include "QuartzPixmap.h"
34 #include "QuartzUtils.h"
35 #include "CocoaUtils.h"
36 #include "RConfigure.h"
37 #include "X11Colors.h"
38 #include "X11Buffer.h"
39 #include "TGWindow.h"
40 #include "TGClient.h"
41 #include "TSystem.h"
42 #include "TGCocoa.h"
43 
44 
45 namespace ROOT {
46 namespace MacOSX {
47 namespace X11 {
48 
49 #pragma mark - Create a window or a view.
50 
51 //______________________________________________________________________________
53  UInt_t clss, void */*visual*/, SetWindowAttributes_t *attr, UInt_t)
54 {
55  using namespace Details;
56 
57  NSRect winRect = {};
58  winRect.origin.x = GlobalXROOTToCocoa(x);
59  winRect.origin.y = GlobalYROOTToCocoa(y + h);
60  winRect.size.width = w;
61  winRect.size.height = h;
62 
63  const NSUInteger styleMask = kTitledWindowMask | kClosableWindowMask |
65 
66  QuartzWindow * const newWindow = [[QuartzWindow alloc] initWithContentRect : winRect
67  styleMask : styleMask
68  backing : NSBackingStoreBuffered
69  defer : YES
70  windowAttributes : attr];
71  if (!newWindow)
72  throw std::runtime_error("CreateTopLevelWindow failed");
73 
74  newWindow.fDepth = depth;
75  newWindow.fClass = clss;
76 
77  return newWindow;
78 }
79 
80 //______________________________________________________________________________
81 QuartzView *CreateChildView(QuartzView * /*parent*/, Int_t x, Int_t y, UInt_t w, UInt_t h, UInt_t /*border*/, Int_t /*depth*/,
82  UInt_t /*clss*/, void * /*visual*/, SetWindowAttributes_t *attr, UInt_t /*wtype*/)
83 {
84  NSRect viewRect = {};
85  viewRect.origin.x = x;
86  viewRect.origin.y = y;
87  viewRect.size.width = w;
88  viewRect.size.height = h;
89 
90  QuartzView * const view = [[QuartzView alloc] initWithFrame : viewRect windowAttributes : attr];
91  if (!view)
92  throw std::runtime_error("CreateChildView failed");
93 
94  return view;
95 }
96 
97 #pragma mark - root window (does not really exist, it's our desktop built of all screens).
98 
99 //______________________________________________________________________________
101 {
102  //'root' window does not exist, but we can request its attributes.
103  assert(attr != 0 && "GetRootWindowAttributes, parameter 'attr' is null");
104 
105 
106  NSArray * const screens = [NSScreen screens];
107  assert(screens != nil && "screens array is nil");
108  NSScreen * const mainScreen = [screens objectAtIndex : 0];
109  assert(mainScreen != nil && "screen with index 0 is nil");
110 
111  *attr = WindowAttributes_t();
112 
113  assert(dynamic_cast<TGCocoa *>(gVirtualX) &&
114  "GetRootWindowAttributes, gVirtualX is either null or has a wrong type");
115 
116  TGCocoa * const gCocoa = static_cast<TGCocoa *>(gVirtualX);
117 
118  const Rectangle &frame = gCocoa->GetDisplayGeometry();
119 
120  attr->fX = 0;
121  attr->fY = 0;
122  attr->fWidth = frame.fWidth;
123  attr->fHeight = frame.fHeight;
124  attr->fBorderWidth = 0;
125  attr->fYourEventMask = 0;
126  attr->fAllEventMasks = 0;//???
127 
128  attr->fDepth = NSBitsPerPixelFromDepth([mainScreen depth]);
129  attr->fVisual = 0;
130  attr->fRoot = 0;
131 }
132 
133 
134 #pragma mark - Coordinate conversions.
135 
136 //______________________________________________________________________________
137 NSPoint ConvertPointFromBaseToScreen(NSWindow *window, NSPoint windowPoint)
138 {
139  assert(window != nil && "ConvertPointFromBaseToScreen, parameter 'window' is nil");
140 
141  //I have no idea why apple deprecated function for a point conversion and requires rect conversion,
142  //point conversion seems to produce wrong results with HiDPI.
143 
144  NSRect tmpRect = {};
145  tmpRect.origin = windowPoint;
146  tmpRect.size = NSMakeSize(1., 1.);//This is strange size :) But if they require rect, 0,0 - will not work?
147  tmpRect = [window convertRectToScreen : tmpRect];
148 
149  return tmpRect.origin;
150 }
151 
152 //______________________________________________________________________________
153 NSPoint ConvertPointFromScreenToBase(NSPoint screenPoint, NSWindow *window)
154 {
155  assert(window != nil && "ConvertPointFromScreenToBase, parameter 'window' is nil");
156 
157  //I have no idea why apple deprecated function for a point conversion and requires rect conversion,
158  //point conversion seems to produce wrong results with HiDPI.
159 
160  NSRect tmpRect = {};
161  tmpRect.origin = screenPoint;
162  tmpRect.size = NSMakeSize(1., 1.);
163  tmpRect = [window convertRectFromScreen : tmpRect];
164 
165  return tmpRect.origin;
166 }
167 
168 //______________________________________________________________________________
169 int GlobalYCocoaToROOT(CGFloat yCocoa)
170 {
171  //We can have several physical displays and thus several NSScreens in some arbitrary order.
172  //With Cocoa, some screens can have negative coordinates - to the left ro down to the primary
173  //screen (whatever it means). With X11 (XQuartz) though it's always 0,0.
174 
175  assert(dynamic_cast<TGCocoa *>(gVirtualX) != 0 &&
176  "GlobalYCocoaToROOT, gVirtualX is either nul or has a wrong type");
177 
178  const Rectangle frame = ((TGCocoa *)gVirtualX)->GetDisplayGeometry();
179 
180  return int(frame.fHeight - (yCocoa - frame.fY));
181 }
182 
183 //______________________________________________________________________________
184 int GlobalXCocoaToROOT(CGFloat xCocoa)
185 {
186  assert(dynamic_cast<TGCocoa *>(gVirtualX) != 0 &&
187  "GlobalXCocoaToROOT, gVirtualX is either nul or has a wrong type");
188  const Rectangle frame = ((TGCocoa *)gVirtualX)->GetDisplayGeometry();
189  //With X11 coordinate space always starts from 0, 0
190  return int(xCocoa - frame.fX);
191 }
192 
193 //______________________________________________________________________________
194 int GlobalYROOTToCocoa(CGFloat yROOT)
195 {
196  assert(dynamic_cast<TGCocoa *>(gVirtualX) != 0 &&
197  "GlobalYROOTToCocoa, gVirtualX is either nul or has a wrong type");
198  const Rectangle frame = ((TGCocoa *)gVirtualX)->GetDisplayGeometry();
199 
200  return int(frame.fY + (frame.fHeight - yROOT));
201 }
202 
203 //______________________________________________________________________________
204 int GlobalXROOTToCocoa(CGFloat xROOT)
205 {
206  assert(dynamic_cast<TGCocoa *>(gVirtualX) != 0 &&
207  "GlobalXROOTToCocoa, gVirtualX is either nul or has a wrong type");
208  const Rectangle frame = ((TGCocoa *)gVirtualX)->GetDisplayGeometry();
209  //With X11 coordinate space always starts from 0, 0
210  return int(frame.fX + xROOT);
211 }
212 
213 //______________________________________________________________________________
214 int LocalYCocoaToROOT(NSView<X11Window> *parentView, CGFloat yCocoa)
215 {
216  assert(parentView != nil && "LocalYCocoaToROOT, parent view is nil");
217 
218  return int(parentView.frame.size.height - yCocoa);
219 }
220 
221 //______________________________________________________________________________
222 int LocalYROOTToCocoa(NSView<X11Window> *parentView, CGFloat yROOT)
223 {
224  //:)
225  assert(parentView != nil && "LocalYROOTToCocoa, parent view is nil");
226 
227  return int(parentView.frame.size.height - yROOT);
228 }
229 
230 
231 //______________________________________________________________________________
232 int LocalYROOTToCocoa(NSObject<X11Drawable> *drawable, CGFloat yROOT)
233 {
234  //:)
235  assert(drawable != nil && "LocalYROOTToCocoa, drawable is nil");
236 
237  return int(drawable.fHeight - yROOT);
238 }
239 
240 //______________________________________________________________________________
241 NSPoint TranslateToScreen(NSView<X11Window> *from, NSPoint point)
242 {
243  assert(from != nil && "TranslateToScreen, parameter 'from' is nil");
244 
245  const NSPoint winPoint = [from convertPoint : point toView : nil];
246 
247  NSPoint screenPoint = ConvertPointFromBaseToScreen([from window], winPoint);
248  screenPoint.x = GlobalXCocoaToROOT(screenPoint.x);
249  screenPoint.y = GlobalYCocoaToROOT(screenPoint.y);
250 
251  return screenPoint;
252 }
253 
254 //______________________________________________________________________________
255 NSPoint TranslateFromScreen(NSPoint point, NSView<X11Window> *to)
256 {
257  assert(to != nil && "TranslateFromScreen, parameter 'to' is nil");
258 
259  point.x = GlobalXROOTToCocoa(point.x);
260  point.y = GlobalYROOTToCocoa(point.y);
261  point = ConvertPointFromScreenToBase(point, [to window]);
262 
263  return [to convertPoint : point fromView : nil];
264 }
265 
266 //______________________________________________________________________________
267 NSPoint TranslateCoordinates(NSView<X11Window> *from, NSView<X11Window> *to, NSPoint sourcePoint)
268 {
269  //Both views are valid.
270  assert(from != nil && "TranslateCoordinates, parameter 'from' is nil");
271  assert(to != nil && "TranslateCoordinates, parameter 'to' is nil");
272 
273  if ([from window] == [to window]) {
274  //Both views are in the same window.
275  return [to convertPoint : sourcePoint fromView : from];
276  } else {
277  //May be, I can do it in one call, but it's not obvious for me
278  //what is 'pixel aligned backing store coordinates' and
279  //if they are the same as screen coordinates.
280 
281  //Many thanks to Apple for deprecated functions!!!
282 
283  const NSPoint win1Point = [from convertPoint : sourcePoint toView : nil];
284  const NSPoint screenPoint = ConvertPointFromBaseToScreen([from window], win1Point);
285  const NSPoint win2Point = ConvertPointFromScreenToBase(screenPoint, [to window]);
286 
287  return [to convertPoint : win2Point fromView : nil];
288  }
289 }
290 
291 //______________________________________________________________________________
292 bool ScreenPointIsInView(NSView<X11Window> *view, Int_t x, Int_t y)
293 {
294  assert(view != nil && "ScreenPointIsInView, parameter 'view' is nil");
295 
296  NSPoint point = {};
297  point.x = x, point.y = y;
298  point = TranslateFromScreen(point, view);
299  const NSRect viewFrame = view.frame;
300 
301  if (point.x < 0 || point.x > viewFrame.size.width)
302  return false;
303  if (point.y < 0 || point.y > viewFrame.size.height)
304  return false;
305 
306  return true;
307 }
308 
309 #pragma mark - Different FindView/Window functions iterating on the ROOT's windows/views.
310 
311 //______________________________________________________________________________
313 {
314  //array's counter is increased, all object in array are also retained.
315  const Util::AutoreleasePool pool;
316 
317  NSArray * const orderedWindows = [NSApp orderedWindows];
318  for (NSWindow *window in orderedWindows) {
319  if (![window isKindOfClass : [QuartzWindow class]])
320  continue;
321  QuartzWindow * const qw = (QuartzWindow *)window;
322  if (qw.fIsDeleted)//Because of reference counting this can happen.
323  continue;
324  //Check if point is inside.
325  if (ScreenPointIsInView(qw.fContentView, x, y))
326  return qw;
327  }
328 
329  return nil;
330 }
331 
332 //______________________________________________________________________________
333 NSView<X11Window> *FindDNDAwareViewInPoint(NSArray *children, Window_t dragWinID,
334  Window_t inputWinID, Int_t x, Int_t y, Int_t maxDepth)
335 {
336  assert(children != nil && "FindDNDAwareViewInPoint, parameter 'children' is nil");
337 
338  if (maxDepth <= 0)
339  return nil;
340 
341  NSEnumerator * const reverseEnumerator = [children reverseObjectEnumerator];
342  for (NSView<X11Window> *child in reverseEnumerator) {
343  if (!ScreenPointIsInView(child, x, y))
344  continue;
345  if (child.fIsDNDAware && child.fID != dragWinID && child.fID != inputWinID)
346  return child;//got it!
347 
348  NSView<X11Window> * const testView = FindDNDAwareViewInPoint([child subviews], dragWinID,
349  inputWinID, x, y, maxDepth - 1);
350  if (testView)
351  return testView;
352  }
353 
354  return nil;
355 }
356 
357 //______________________________________________________________________________
358 NSView<X11Window> *FindDNDAwareViewInPoint(NSView *parentView, Window_t dragWinID, Window_t inputWinID,
359  Int_t x, Int_t y, Int_t maxDepth)
360 {
361  //X and Y are ROOT's screen coordinates (Y is inverted).
362  if (maxDepth <= 0)
363  return nil;
364 
365  const Util::AutoreleasePool pool;
366 
367  if (!parentView) {//Start from the screen as a 'root' window.
368  NSArray * const orderedWindows = [NSApp orderedWindows];
369  for (NSWindow *window in orderedWindows) {
370  if (![window isKindOfClass : [QuartzWindow class]])
371  continue;
372  QuartzWindow * const qw = (QuartzWindow *)window;
373 
374  if (qw.fIsDeleted)//Because of reference counting this can happen.
375  continue;
376 
377  if (qw.fMapState != kIsViewable)
378  continue;
379 
380  //First, check this view itself, my be we found what we need already.
381  NSView<X11Window> *testView = qw.fContentView;
382  if (!ScreenPointIsInView(testView, x, y))
383  continue;
384 
385  if (testView.fIsDNDAware && testView.fID != dragWinID && testView.fID != inputWinID)
386  return testView;
387 
388  //Recursive part, check children.
389  NSArray * const children = [testView subviews];
390  testView = FindDNDAwareViewInPoint(children, dragWinID, inputWinID, x, y, maxDepth - 1);
391  if (testView)
392  return testView;
393  }
394 
395  //We did not find anything for 'root' window as parent.
396  return nil;
397  } else {
398  //Parent view is tested already (or should not be tested at all, check children.
399  return FindDNDAwareViewInPoint([parentView subviews], dragWinID, inputWinID, x, y, maxDepth);
400  }
401 }
402 
403 //______________________________________________________________________________
405 {
406  const Util::AutoreleasePool pool;
407 
408  NSArray * const orderedWindows = [NSApp orderedWindows];
409  for (NSWindow *nsWindow in orderedWindows) {
410  if (![nsWindow isKindOfClass : [QuartzWindow class]])
411  continue;
412 
413  QuartzWindow * const qWindow = (QuartzWindow *)nsWindow;
414 
415  if (qWindow.fIsDeleted)//Because of reference counting this can happen.
416  continue;
417 
418  if (qWindow.fMapState != kIsViewable)//Can it be false and still in this array???
419  continue;
420 
421  const NSPoint mousePosition = [qWindow mouseLocationOutsideOfEventStream];
422  const NSSize windowSize = qWindow.frame.size;
423  if (mousePosition.x >= 0 && mousePosition.x <= windowSize.width &&
424  mousePosition.y >= 0 && mousePosition.y <= windowSize.height)
425  return qWindow;
426  }
427 
428  return nil;
429 }
430 
431 //______________________________________________________________________________
432 NSView<X11Window> *FindViewUnderPointer()
433 {
434  //TODO: call FindViewInPoint using cursor screen coordiantes.
435  const Util::AutoreleasePool pool;
436 
437  if (QuartzWindow *topLevel = FindWindowUnderPointer()) {
438  const NSPoint mousePosition = [topLevel mouseLocationOutsideOfEventStream];
439  return (NSView<X11Window> *)[[topLevel contentView] hitTest : mousePosition];
440  }
441 
442  return nil;
443 }
444 
445 //______________________________________________________________________________
447 {
448  //FindWindowForPointerEvent is required because due to grabs
449  //the receiver of the event can be different from the actual
450  //window under cursor.
451 
452  assert(pointerEvent != nil &&
453  "FindWindowForPointerEvent, parameter 'pointerEvent' is nil");
454 
455  const Util::AutoreleasePool pool;
456 
457  NSArray * const orderedWindows = [NSApp orderedWindows];
458  for (NSWindow *nsWindow in orderedWindows) {
459  if (![nsWindow isKindOfClass : [QuartzWindow class]])
460  continue;
461 
462  QuartzWindow * const qWindow = (QuartzWindow *)nsWindow;
463 
464  if (qWindow.fIsDeleted)//Because of reference counting this can happen.
465  continue;
466 
467  //Can it be false and still in this array???
468  if (qWindow.fMapState != kIsViewable)
469  continue;
470 
471  NSPoint mousePosition = [pointerEvent locationInWindow];
472  //The event has a window, so position is in this window's coordinate system,
473  //convert it into screen point first.
474  if ([pointerEvent window]) {
475  //convertBaseToScreen is deprecated.
476  //mousePosition = [[pointerEvent window] convertBaseToScreen : mousePosition];
477  mousePosition = ConvertPointFromBaseToScreen([pointerEvent window], mousePosition);
478  }
479 
480  //convertScreenToBase is deprecated.
481  //mousePosition = [qWindow convertScreenToBase : mousePosition];
482  mousePosition = ConvertPointFromScreenToBase(mousePosition, qWindow);
483 
484  const NSSize windowSize = qWindow.frame.size;
485  if (mousePosition.x >= 0 && mousePosition.x <= windowSize.width &&
486  mousePosition.y >= 0 && mousePosition.y <= windowSize.height)
487  return qWindow;
488  }
489 
490  return nil;
491 }
492 
493 //______________________________________________________________________________
494 NSView<X11Window> *FindViewForPointerEvent(NSEvent *pointerEvent)
495 {
496  //FindViewForPointerEvent is required because of grabs - the receiver of the
497  //event can be different from the actual window under cursor.
498 
499  assert(pointerEvent != nil &&
500  "FindViewForPointerEvent, parameter 'pointerEvent' is nil");
501 
502  const Util::AutoreleasePool pool;
503 
504  if (QuartzWindow *topLevel = FindWindowForPointerEvent(pointerEvent)) {
505  NSPoint mousePosition = [pointerEvent locationInWindow];
506  if ([pointerEvent window])
507  mousePosition = ConvertPointFromBaseToScreen([pointerEvent window], mousePosition);
508 
509  //convertScreenToBase is deprecated.
510  //mousePosition = [topLevel convertScreenToBase : mousePosition];
511  mousePosition = ConvertPointFromScreenToBase(mousePosition, topLevel);
512 
513  return (NSView<X11Window> *)[[topLevel contentView] hitTest : mousePosition];
514  }
515 
516  return nil;
517 }
518 
519 #pragma mark - Downscale image ("reading color bits" on retina macs).
520 
521 //Hoho, we support C++11?? Let's return by value then!!!
522 std::vector<unsigned char> DownscaledImageData(unsigned w, unsigned h, CGImageRef image)
523 {
524  assert(w != 0 && h != 0 && "DownscaledImageData, invalid geometry");
525  assert(image != nullptr && "DonwscaledImageData, invalid parameter 'image'");
526 
527  std::vector<unsigned char> result;
528  try {
529  result.resize(w * h * 4);
530  } catch (const std::bad_alloc &) {
531  //TODO: check that 'resize' has no side effects in case of exception.
532  NSLog(@"DownscaledImageData, memory allocation failed");
533  return result;
534  }
535 
536  //TODO: device RGB? should it be generic?
537  const Util::CFScopeGuard<CGColorSpaceRef> colorSpace(CGColorSpaceCreateDeviceRGB());//[1]
538  if (!colorSpace.Get()) {
539  NSLog(@"DownscaledImageData, CGColorSpaceCreateDeviceRGB failed");
540  return result;
541  }
542 
543  Util::CFScopeGuard<CGContextRef> ctx(CGBitmapContextCreateWithData(&result[0], w, h, 8,
544  w * 4, colorSpace.Get(),
545  kCGImageAlphaPremultipliedLast, NULL, 0));
546  if (!ctx.Get()) {
547  NSLog(@"DownscaledImageData, CGBitmapContextCreateWithData failed");
548  return result;
549  }
550 
551  CGContextDrawImage(ctx.Get(), CGRectMake(0, 0, w, h), image);
552 
553  return result;
554 }
555 
556 #pragma mark - "Focus management" - just make another window key window.
557 
558 //______________________________________________________________________________
560 {
561  //XQuartz (and other X11
562  if (![NSApp isActive])
563  return;
564 
565  const Util::AutoreleasePool pool;
566 
567  NSArray * const orderedWindows = [NSApp orderedWindows];
568  for (NSWindow *nsWindow in orderedWindows) {
569  if (![nsWindow isKindOfClass : [QuartzWindow class]])
570  continue;
571 
572  QuartzWindow * const qWindow = (QuartzWindow *)nsWindow;
573 
574  if (qWindow.fIsDeleted || qWindow.fMapState != kIsViewable || qWindow.fID == winID)
575  continue;
576 
577  if (qWindow.fContentView.fOverrideRedirect)
578  continue;
579 
580  [qWindow makeKeyAndOrderFront : qWindow];
581  break;
582  }
583 }
584 
585 #pragma mark - 'shape mask' - to create a window with arbitrary (probably non-rectangle) shape.
586 
587 //______________________________________________________________________________
588 void ClipToShapeMask(NSView<X11Window> *view, CGContextRef ctx)
589 {
590  assert(view != nil && "ClipToShapeMask, parameter 'view' is nil");
591  assert(ctx != 0 && "ClipToShapeMask, parameter 'ctx' is null");
592 
593  QuartzWindow * const topLevelParent = view.fQuartzWindow;
594  assert(topLevelParent.fShapeCombineMask != nil &&
595  "ClipToShapeMask, fShapeCombineMask is nil on a top-level window");
596  assert(topLevelParent.fShapeCombineMask.fImage != 0 &&
597  "ClipToShapeMask, shape mask is null");
598 
599  //Important: shape mask should have the same width and height as
600  //a top-level window. In ROOT it does not :( Say hello to visual artifacts.
601 
602  //Attach clip mask to the context.
603  if (!view.fParentView) {
604  //'view' is a top-level view.
605  const CGRect clipRect = CGRectMake(0, 0, topLevelParent.fShapeCombineMask.fWidth,
606  topLevelParent.fShapeCombineMask.fHeight);
607  CGContextClipToMask(ctx, clipRect, topLevelParent.fShapeCombineMask.fImage);
608  } else {
609  NSRect clipRect = view.frame;
610  //More complex case: 'self' is a child view, we have to create a subimage from shape mask.
611  clipRect.origin = [view.fParentView convertPoint : clipRect.origin
612  toView : [view window].contentView];
613  clipRect.origin.y = X11::LocalYROOTToCocoa((NSView<X11Window> *)[view window].contentView,
614  clipRect.origin.y + clipRect.size.height);
615 
616  if (AdjustCropArea(topLevelParent.fShapeCombineMask, clipRect)) {
618  clipImageGuard(CGImageCreateWithImageInRect(topLevelParent.fShapeCombineMask.fImage,
619  NSRectToCGRect(clipRect)));
620  clipRect.origin = NSPoint();
621  CGContextClipToMask(ctx, NSRectToCGRect(clipRect), clipImageGuard.Get());
622  } else {
623  //View is invisible.
624  CGRect rect = {};
625  CGContextClipToRect(ctx, rect);
626  }
627  }
628 }
629 
630 #pragma mark - Window's geometry and attributes.
631 
632 //______________________________________________________________________________
633 void SetWindowAttributes(const SetWindowAttributes_t *attr, NSObject<X11Window> *window)
634 {
635  assert(attr != 0 && "SetWindowAttributes, parameter 'attr' is null");
636  assert(window != nil && "SetWindowAttributes, parameter 'window' is nil");
637 
638  const Mask_t mask = attr->fMask;
639 
640  if (mask & kWABackPixel)
641  window.fBackgroundPixel = attr->fBackgroundPixel;
642 
643  if (mask & kWAEventMask)
644  window.fEventMask = attr->fEventMask;
645 
646  if (mask & kWABitGravity)
647  window.fBitGravity = attr->fBitGravity;
648 
649  if (mask & kWAWinGravity)
650  window.fWinGravity = attr->fWinGravity;
651 
652  //TODO: More attributes to set -
653  //cursor for example, etc.
654  if (mask & kWAOverrideRedirect) {
655  //This is quite a special case.
656  //TODO: Must be checked yet, if I understand this correctly!
657  if ([(NSObject *)window isKindOfClass : [QuartzWindow class]]) {
658  QuartzWindow * const qw = (QuartzWindow *)window;
659  [qw setStyleMask : Details::kBorderlessWindowMask];
660  [qw setAlphaValue : 0.95];
661  }
662 
663  window.fOverrideRedirect = YES;
664  }
665 }
666 
667 //______________________________________________________________________________
668 void GetWindowGeometry(NSObject<X11Window> *win, WindowAttributes_t *dst)
669 {
670  assert(win != nil && "GetWindowGeometry, parameter 'win' is nil");
671  assert(dst != 0 && "GetWindowGeometry, parameter 'dst' is null");
672 
673  dst->fX = win.fX;
674  dst->fY = win.fY;
675 
676  dst->fWidth = win.fWidth;
677  dst->fHeight = win.fHeight;
678 }
679 
680 //______________________________________________________________________________
681 void GetWindowAttributes(NSObject<X11Window> *window, WindowAttributes_t *dst)
682 {
683  assert(window != nil && "GetWindowAttributes, parameter 'window' is nil");
684  assert(dst != 0 && "GetWindowAttributes, parameter 'attr' is null");
685 
686  *dst = WindowAttributes_t();
687 
688  //fX, fY, fWidth, fHeight.
689  GetWindowGeometry(window, dst);
690 
691  //Actually, most of them are not used by GUI.
692  dst->fBorderWidth = 0;
693  dst->fDepth = window.fDepth;
694  //Dummy value.
695  dst->fVisual = 0;
696  //Dummy value.
697  dst->fRoot = 0;
698  dst->fClass = window.fClass;
699  dst->fBitGravity = window.fBitGravity;
700  dst->fWinGravity = window.fWinGravity;
701  //Dummy value.
702  dst->fBackingStore = kAlways;//??? CHECK
703  dst->fBackingPlanes = 0;
704 
705  //Dummy value.
706  dst->fBackingPixel = 0;
707 
708  dst->fSaveUnder = 0;
709 
710  //Dummy value.
711  dst->fColormap = 0;
712  //Dummy value.
713  dst->fMapInstalled = kTRUE;
714 
715  dst->fMapState = window.fMapState;
716 
717  dst->fAllEventMasks = window.fEventMask;
718  dst->fYourEventMask = window.fEventMask;
719 
720  //Not used by GUI.
721  //dst->fDoNotPropagateMask
722 
723  dst->fOverrideRedirect = window.fOverrideRedirect;
724  //Dummy value.
725  dst->fScreen = 0;
726 }
727 
728 //With Apple's poor man's objective C/C++ + "brilliant" Cocoa you never know, what should be
729 //the linkage of callback functions, API + language dialects == MESS. I declare/define this comparators here
730 //as having "C++" linkage. If one good day clang will start to complane, I'll have to change this.
731 
732 #pragma mark - Comparators (I need them when changing a window's z-order).
733 
734 //______________________________________________________________________________
735 // SDK 10.11 and above ...
736 #ifdef MAC_OS_X_VERSION_10_11
737 NSComparisonResult CompareViewsToLower(__kindof NSView *view1, __kindof NSView *view2, void *context)
738 #else
739 NSComparisonResult CompareViewsToLower(id view1, id view2, void *context)
740 #endif
741 {
742  id topView = (id)context;
743  if (view1 == topView)
744  return NSOrderedAscending;
745  if (view2 == topView)
746  return NSOrderedDescending;
747 
748  return NSOrderedSame;
749 }
750 
751 //______________________________________________________________________________
752 // SDK 10.11 and above ...
753 #ifdef MAC_OS_X_VERSION_10_11
754 NSComparisonResult CompareViewsToRaise(__kindof NSView *view1, __kindof NSView *view2, void *context)
755 #else
756 NSComparisonResult CompareViewsToRaise(id view1, id view2, void *context)
757 #endif
758 {
759  id topView = (id)context;
760  if (view1 == topView)
761  return NSOrderedDescending;
762  if (view2 == topView)
763  return NSOrderedAscending;
764 
765  return NSOrderedSame;
766 }
767 
768 #pragma mark - Cursor's area.
769 
770 //______________________________________________________________________________
771 NSPoint GetCursorHotStop(NSImage *image, ECursor cursor)
772 {
773  assert(image != nil && "CursroHotSpot, parameter 'image' is nil");
774 
775  const NSSize imageSize = image.size;
776 
777  if (cursor == kArrowRight)
778  return NSMakePoint(imageSize.width, imageSize.height / 2);
779 
780  return NSMakePoint(imageSize.width / 2, imageSize.height / 2);
781 }
782 
783 //______________________________________________________________________________
784 NSCursor *CreateCustomCursor(ECursor currentCursor)
785 {
786  // Returns auto-released cursor object.
787  const char *pngFileName = 0;
788 
789  switch (currentCursor) {
790  case kMove:
791  pngFileName = "move_cursor.png";
792  break;
793  case kArrowHor:
794  pngFileName = "hor_arrow_cursor.png";
795  break;
796  case kArrowVer:
797  pngFileName = "ver_arrow_cursor.png";
798  break;
799  case kArrowRight:
800  pngFileName = "right_arrow_cursor.png";
801  break;
802  case kRotate:
803  pngFileName = "rotate.png";
804  break;
805  case kBottomLeft:
806  case kTopRight:
807  pngFileName = "top_right_cursor.png";
808  break;
809  case kTopLeft:
810  case kBottomRight:
811  pngFileName = "top_left_cursor.png";
812  break;
813  default:;
814  }
815 
816  if (pngFileName) {
817  const char * const path = gSystem->Which(TROOT::GetIconPath(), pngFileName, kReadPermission);
818  const Util::ScopedArray<const char> arrayGuard(path);
819 
820  if (!path || path[0] == 0) {
821  //File was not found.
822  return nil;
823  }
824 
825  NSString *nsPath = [NSString stringWithFormat : @"%s", path];//in autorelease pool.
826  NSImage * const cursorImage = [[NSImage alloc] initWithContentsOfFile : nsPath];
827 
828  if (!cursorImage)
829  return nil;
830 
831  const NSPoint hotSpot(X11::GetCursorHotStop(cursorImage, currentCursor));
832  NSCursor * const customCursor = [[[NSCursor alloc] initWithImage : cursorImage
833  hotSpot : hotSpot] autorelease];
834 
835  [cursorImage release];
836 
837  return customCursor;
838  }
839 
840  return nil;
841 }
842 
843 //______________________________________________________________________________
844 NSCursor *CreateCursor(ECursor currentCursor)
845 {
846  // Returns auto-released cursor object.
847 
848  //Cursors from TVirtaulX:
849  // kBottomLeft, kBottomRight, kTopLeft, kTopRight,
850  // kBottomSide, kLeftSide, kTopSide, kRightSide,
851  // kMove, kCross, kArrowHor, kArrowVer,
852  // kHand, kRotate, kPointer, kArrowRight,
853  // kCaret, kWatch
854 
855  NSCursor *cursor = nil;
856  switch (currentCursor) {
857  case kCross:
858  cursor = [NSCursor crosshairCursor];
859  break;
860  case kPointer:
861  cursor = [NSCursor arrowCursor];
862  break;
863  case kHand:
864  cursor = [NSCursor openHandCursor];
865  break;
866  case kLeftSide:
867  cursor = [NSCursor resizeLeftCursor];
868  break;
869  case kRightSide:
870  cursor = [NSCursor resizeRightCursor];
871  break;
872  case kTopSide:
873  cursor = [NSCursor resizeUpCursor];
874  break;
875  case kBottomSide:
876  cursor = [NSCursor resizeDownCursor];
877  break;
878  case kCaret:
879  cursor = [NSCursor IBeamCursor];
880  break;
881  case kRotate:
882  case kWatch:
883  default:
884  cursor = CreateCustomCursor(currentCursor);
885  }
886 
887  return cursor;
888 }
889 
890 //TGTextView/TGHtml is a very special window: it's a TGCompositeFrame,
891 //which has TGCompositeFrame inside (TGViewFrame). This TGViewFrame
892 //delegates Expose events to its parent, and parent tries to draw
893 //inside a TGViewFrame. This does not work with default
894 //QuartzView -drawRect/TGCocoa. So I need a trick to identify
895 //this special window.
896 
897 //TODO: possibly refactor these functions in a more generic way - not
898 //to have two separate versions for text and html.
899 
900 
901 #pragma mark - Workarounds for a text view and its descendants.
902 
903 //______________________________________________________________________________
904 bool ViewIsTextView(unsigned viewID)
905 {
906  const TGWindow * const window = gClient->GetWindowById(viewID);
907  if (!window)
908  return false;
909  return window->InheritsFrom("TGTextView");
910 }
911 
912 //______________________________________________________________________________
913 bool ViewIsTextView(NSView<X11Window> *view)
914 {
915  assert(view != nil && "ViewIsTextView, parameter 'view' is nil");
916 
917  return ViewIsTextView(view.fID);
918 }
919 
920 //______________________________________________________________________________
921 bool ViewIsTextViewFrame(NSView<X11Window> *view, bool checkParent)
922 {
923  assert(view != nil && "ViewIsTextViewFrame, parameter 'view' is nil");
924 
925  const TGWindow * const window = gClient->GetWindowById(view.fID);
926  if (!window)
927  return false;
928 
929  if (!window->InheritsFrom("TGViewFrame"))
930  return false;
931 
932  if (!checkParent)
933  return true;
934 
935  if (!view.fParentView)
936  return false;
937 
938  return ViewIsTextView(view.fParentView);
939 }
940 
941 //______________________________________________________________________________
942 bool ViewIsHtmlView(unsigned viewID)
943 {
944  const TGWindow * const window = gClient->GetWindowById(viewID);
945  if (!window)
946  return false;
947  return window->InheritsFrom("TGHtml");
948 }
949 
950 //______________________________________________________________________________
951 bool ViewIsHtmlView(NSView<X11Window> *view)
952 {
953  assert(view != nil && "ViewIsHtmlView, parameter 'view' is nil");
954 
955  return ViewIsHtmlView(view.fID);
956 }
957 
958 //______________________________________________________________________________
959 bool ViewIsHtmlViewFrame(NSView<X11Window> *view, bool checkParent)
960 {
961  //
962  assert(view != nil && "ViewIsHtmlViewFrame, parameter 'view' is nil");
963 
964  const TGWindow * const window = gClient->GetWindowById(view.fID);
965  if (!window)
966  return false;
967 
968  if (!window->InheritsFrom("TGViewFrame"))
969  return false;
970 
971  if (!checkParent)
972  return true;
973 
974  if (!view.fParentView)
975  return false;
976 
977  return ViewIsHtmlView(view.fParentView);
978 }
979 
980 //______________________________________________________________________________
981 NSView<X11Window> *FrameForTextView(NSView<X11Window> *textView)
982 {
983  assert(textView != nil && "FrameForTextView, parameter 'textView' is nil");
984 
985  for (NSView<X11Window> *child in [textView subviews]) {
986  if (ViewIsTextViewFrame(child, false))
987  return child;
988  }
989 
990  return nil;
991 }
992 
993 //______________________________________________________________________________
994 NSView<X11Window> *FrameForHtmlView(NSView<X11Window> *htmlView)
995 {
996  assert(htmlView != nil && "FrameForHtmlView, parameter 'htmlView' is nil");
997 
998  for (NSView<X11Window> *child in [htmlView subviews]) {
999  if (ViewIsHtmlViewFrame(child, false))
1000  return child;
1001  }
1002 
1003  return nil;
1004 }
1005 
1006 #pragma mark - Workarounds for 'paint out of paint events'.
1007 
1008 //______________________________________________________________________________
1009 bool LockFocus(NSView<X11Window> *view)
1010 {
1011  assert(view != nil && "LockFocus, parameter 'view' is nil");
1012  assert([view isKindOfClass : [QuartzView class]] &&
1013  "LockFocus, QuartzView is expected");
1014 
1015  if ([view lockFocusIfCanDraw]) {
1016  NSGraphicsContext *nsContext = [NSGraphicsContext currentContext];
1017  assert(nsContext != nil && "LockFocus, currentContext is nil");
1018  CGContextRef currContext = (CGContextRef)[nsContext graphicsPort];
1019  assert(currContext != 0 && "LockFocus, graphicsPort is null");//remove this assert?
1020 
1021  ((QuartzView *)view).fContext = currContext;
1022 
1023  return true;
1024  }
1025 
1026  return false;
1027 }
1028 
1029 //______________________________________________________________________________
1030 void UnlockFocus(NSView<X11Window> *view)
1031 {
1032  assert(view != nil && "UnlockFocus, parameter 'view' is nil");
1033  assert([view isKindOfClass : [QuartzView class]] &&
1034  "UnlockFocus, QuartzView is expected");
1035 
1036  [view unlockFocus];
1037  ((QuartzView *)view).fContext = 0;
1038 }
1039 
1040 }//X11
1041 }//MacOSX
1042 }//ROOT
1043 
1044 namespace Quartz = ROOT::Quartz;
1045 namespace Util = ROOT::MacOSX::Util;
1046 namespace X11 = ROOT::MacOSX::X11;
1047 namespace Details = ROOT::MacOSX::Details;
1048 
1049 #ifdef DEBUG_ROOT_COCOA
1050 
1051 #pragma mark - 'loggers'.
1052 
1053 namespace {
1054 
1055 //______________________________________________________________________________
1056 void log_attributes(const SetWindowAttributes_t *attr, unsigned winID)
1057 {
1058  //This function is loggin requests, at the moment I can not set all
1059  //of these attributes, so I first have to check, what is actually
1060  //requested by ROOT.
1061  static std::ofstream logfile("win_attr.txt");
1062 
1063  const Mask_t mask = attr->fMask;
1064  if (mask & kWABackPixmap)
1065  logfile<<"win "<<winID<<": BackPixmap\n";
1066  if (mask & kWABackPixel)
1067  logfile<<"win "<<winID<<": BackPixel\n";
1068  if (mask & kWABorderPixmap)
1069  logfile<<"win "<<winID<<": BorderPixmap\n";
1070  if (mask & kWABorderPixel)
1071  logfile<<"win "<<winID<<": BorderPixel\n";
1072  if (mask & kWABorderWidth)
1073  logfile<<"win "<<winID<<": BorderWidth\n";
1074  if (mask & kWABitGravity)
1075  logfile<<"win "<<winID<<": BitGravity\n";
1076  if (mask & kWAWinGravity)
1077  logfile<<"win "<<winID<<": WinGravity\n";
1078  if (mask & kWABackingStore)
1079  logfile<<"win "<<winID<<": BackingStore\n";
1080  if (mask & kWABackingPlanes)
1081  logfile<<"win "<<winID<<": BackingPlanes\n";
1082  if (mask & kWABackingPixel)
1083  logfile<<"win "<<winID<<": BackingPixel\n";
1084  if (mask & kWAOverrideRedirect)
1085  logfile<<"win "<<winID<<": OverrideRedirect\n";
1086  if (mask & kWASaveUnder)
1087  logfile<<"win "<<winID<<": SaveUnder\n";
1088  if (mask & kWAEventMask)
1089  logfile<<"win "<<winID<<": EventMask\n";
1090  if (mask & kWADontPropagate)
1091  logfile<<"win "<<winID<<": DontPropagate\n";
1092  if (mask & kWAColormap)
1093  logfile<<"win "<<winID<<": Colormap\n";
1094  if (mask & kWACursor)
1095  logfile<<"win "<<winID<<": Cursor\n";
1096 }
1097 
1098 //______________________________________________________________________________
1099 void print_mask_info(ULong_t mask)
1100 {
1101  if (mask & kButtonPressMask)
1102  NSLog(@"button press mask");
1103  if (mask & kButtonReleaseMask)
1104  NSLog(@"button release mask");
1105  if (mask & kExposureMask)
1106  NSLog(@"exposure mask");
1107  if (mask & kPointerMotionMask)
1108  NSLog(@"pointer motion mask");
1109  if (mask & kButtonMotionMask)
1110  NSLog(@"button motion mask");
1111  if (mask & kEnterWindowMask)
1112  NSLog(@"enter notify mask");
1113  if (mask & kLeaveWindowMask)
1114  NSLog(@"leave notify mask");
1115 }
1116 
1117 }
1118 #endif
1119 
1120 
1121 @implementation QuartzWindow
1122 
1123 @synthesize fMainWindow;
1124 @synthesize fHasFocus;
1125 
1126 #pragma mark - QuartzWindow's life cycle.
1127 
1128 //______________________________________________________________________________
1129 - (id) initWithContentRect : (NSRect) contentRect styleMask : (NSUInteger) windowStyle
1130  backing : (NSBackingStoreType) bufferingType defer : (BOOL) deferCreation
1131  windowAttributes : (const SetWindowAttributes_t *) attr
1132 {
1133  self = [super initWithContentRect : contentRect styleMask : windowStyle
1134  backing : bufferingType defer : deferCreation];
1135 
1136  if (self) {
1137  //ROOT's not able to draw GUI concurrently, thanks to global variables and gVirtualX itself.
1138  [self setAllowsConcurrentViewDrawing : NO];
1139 
1140  self.delegate = self;
1141  //create content view here.
1142  NSRect contentViewRect = contentRect;
1143  contentViewRect.origin.x = 0.f;
1144  contentViewRect.origin.y = 0.f;
1145 
1146  //TODO: OpenGL view can not be content of our QuartzWindow, check if
1147  //this is a problem for ROOT.
1148  fContentView = [[QuartzView alloc] initWithFrame : contentViewRect windowAttributes : 0];
1149 
1150  [self setContentView : fContentView];
1151 
1152  [fContentView release];
1153  fDelayedTransient = NO;
1154 
1155  if (attr)
1156  X11::SetWindowAttributes(attr, self);
1157 
1158  fIsDeleted = NO;
1159  fHasFocus = NO;
1160  }
1161 
1162  return self;
1163 }
1164 
1165 //______________________________________________________________________________
1166 - (id) initWithGLView : (ROOTOpenGLView *) glView
1167 {
1168  using namespace Details;
1169 
1170  assert(glView != nil && "-initWithGLView, parameter 'glView' is nil");
1171 
1172  const NSUInteger styleMask = kTitledWindowMask | kClosableWindowMask |
1174 
1175  NSRect contentRect = glView.frame;
1176  contentRect.origin = NSPoint();
1177 
1178  self = [super initWithContentRect : contentRect styleMask : styleMask
1179  backing : NSBackingStoreBuffered defer : NO];
1180 
1181  if (self) {
1182  //ROOT's not able to draw GUI concurrently, thanks to global variables and gVirtualX itself.
1183  [self setAllowsConcurrentViewDrawing : NO];
1184  self.delegate = self;
1185  fContentView = glView;
1186  [self setContentView : fContentView];
1187  fDelayedTransient = NO;
1188  fIsDeleted = NO;
1189  fHasFocus = NO;
1190  }
1191 
1192  return self;
1193 }
1194 
1195 //______________________________________________________________________________
1197 {
1198  [fShapeCombineMask release];
1199  [super dealloc];
1200 }
1201 
1202 //______________________________________________________________________________
1203 - (BOOL) fIsDeleted
1204 {
1205  return fIsDeleted;
1206 }
1207 
1208 //______________________________________________________________________________
1209 - (void) setContentView:(NSView *)cv
1210 {
1211  [super setContentView:cv];
1212  if ([cv isKindOfClass:[QuartzView class]])
1213  fContentView = (QuartzView *)cv;
1214  else
1215  fContentView = nil;
1216 }
1217 
1218 //______________________________________________________________________________
1219 - (void) setFIsDeleted : (BOOL) deleted
1220 {
1221  fIsDeleted = deleted;
1222 }
1223 
1224 #pragma mark - Forwaring: I want to forward a lot of property setters/getters to the content view.
1225 
1226 //______________________________________________________________________________
1227 - (void) forwardInvocation : (NSInvocation *) anInvocation
1228 {
1229  if (!fContentView)
1230  return;
1231 
1232  if ([fContentView respondsToSelector : [anInvocation selector]]) {
1233  [anInvocation invokeWithTarget : fContentView];
1234  } else {
1235  [super forwardInvocation : anInvocation];
1236  }
1237 }
1238 
1239 //______________________________________________________________________________
1240 - (NSMethodSignature*) methodSignatureForSelector : (SEL) selector
1241 {
1242  NSMethodSignature *signature = [super methodSignatureForSelector : selector];
1243 
1244  if (!signature) {
1245  if (fContentView)
1246  signature = [fContentView methodSignatureForSelector : selector];
1247  }
1248 
1249  return signature;
1250 }
1251 
1252 //______________________________________________________________________________
1253 - (void) addTransientWindow : (QuartzWindow *) window
1254 {
1255  //Transient window: all the popups (menus, dialogs, popups, comboboxes, etc.)
1256  //always should be on the top of its 'parent' window.
1257  //To enforce this ordering, I have to connect such windows with parent/child
1258  //relation (it's not the same as a view hierarchy - both child and parent
1259  //windows are top-level windows).
1260 
1261  assert(window != nil && "-addTransientWindow:, parameter 'window' is nil");
1262 
1263  window.fMainWindow = self;
1264 
1265  if (window.fMapState != kIsViewable) {
1266  //If I add it as child, it'll immediately make a window visible
1267  //and this thing sucks.
1268  window.fDelayedTransient = YES;
1269  } else {
1270  [self addChildWindow : window ordered : NSWindowAbove];
1271  window.fDelayedTransient = NO;
1272  }
1273 }
1274 
1275 //______________________________________________________________________________
1276 - (void) makeKeyAndOrderFront : (id) sender
1277 {
1278 #pragma unused(sender)
1279 
1280  //The more I know Cocoa, the less I like it.
1281  //Window behavior between spaces is a total mess.
1282  //Set the window to join all spaces.
1283 #ifdef MAC_OS_X_VERSION_10_9
1284  [self setCollectionBehavior : NSWindowCollectionBehaviorMoveToActiveSpace];
1285 #else
1286  [self setCollectionBehavior : NSWindowCollectionBehaviorCanJoinAllSpaces];
1287 #endif
1288  //now bring it to the front, it will appear on the active space.
1289  [super makeKeyAndOrderFront : self];
1290  //then reset the collection behavior to default, so the window
1291  [self setCollectionBehavior : NSWindowCollectionBehaviorDefault];
1292 }
1293 
1294 //______________________________________________________________________________
1295 - (void) setFDelayedTransient : (BOOL) d
1296 {
1297  fDelayedTransient = d;
1298 }
1299 
1300 //______________________________________________________________________________
1302 {
1303  return fShapeCombineMask;
1304 }
1305 
1306 //______________________________________________________________________________
1307 - (void) setFShapeCombineMask : (QuartzImage *) mask
1308 {
1309  if (mask != fShapeCombineMask) {
1310  [fShapeCombineMask release];
1311  if (mask) {
1312  fShapeCombineMask = [mask retain];
1313 
1314  //TODO: Check window's shadow???
1315  }
1316  }
1317 }
1318 
1319 #pragma mark - X11Drawable's protocol.
1320 
1321 //______________________________________________________________________________
1322 - (BOOL) fIsPixmap
1323 {
1324  //Never.
1325  return NO;
1326 }
1327 
1328 //______________________________________________________________________________
1330 {
1331  //Never.
1332  return NO;
1333 }
1334 
1335 //______________________________________________________________________________
1336 - (int) fX
1337 {
1338  return X11::GlobalXCocoaToROOT(self.frame.origin.x);
1339 }
1340 
1341 //______________________________________________________________________________
1342 - (int) fY
1343 {
1344  return X11::GlobalYCocoaToROOT(self.frame.origin.y + self.frame.size.height);
1345 }
1346 
1347 //______________________________________________________________________________
1348 - (unsigned) fWidth
1349 {
1350  return self.frame.size.width;
1351 }
1352 
1353 //______________________________________________________________________________
1354 - (unsigned) fHeight
1355 {
1356  //NSWindow's frame (height component) also includes title-bar.
1357  //So I have to use content view's height.
1358  //Obviously, there is a "hole" == 22 pixels.
1359  assert(fContentView != nil && "-fHeight:, content view is nil");
1360 
1361  return fContentView.frame.size.height;
1362 }
1363 
1364 //______________________________________________________________________________
1365 - (void) setDrawableSize : (NSSize) newSize
1366 {
1367  //Can not simply do self.frame.size = newSize.
1368  assert(!(newSize.width < 0) && "-setDrawableSize:, width is negative");
1369  assert(!(newSize.height < 0) && "-setDrawableSize:, height is negative");
1370 
1371  NSRect frame = self.frame;
1372  //dY is potentially a titlebar height.
1373  const CGFloat dY = fContentView ? frame.size.height - fContentView.frame.size.height : 0.;
1374  //Adjust the frame.
1375  frame.origin.y = frame.origin.y + frame.size.height - newSize.height - dY;
1376  frame.size = newSize;
1377  frame.size.height += dY;
1378  [self setFrame : frame display : YES];
1379 }
1380 
1381 //______________________________________________________________________________
1382 - (void) setX : (int) x Y : (int) y width : (unsigned) w height : (unsigned) h
1383 {
1384  NSSize newSize = {};
1385  newSize.width = w;
1386  newSize.height = h;
1387  [self setContentSize : newSize];
1388 
1389  //Check how this is affected by title bar's height.
1390  NSPoint topLeft = {};
1391  topLeft.x = X11::GlobalXROOTToCocoa(x);
1392  topLeft.y = X11::GlobalYROOTToCocoa(y);
1393 
1394  [self setFrameTopLeftPoint : topLeft];
1395 }
1396 
1397 //______________________________________________________________________________
1398 - (void) setX : (int) x Y : (int) y
1399 {
1400  NSPoint topLeft = {};
1401  topLeft.x = X11::GlobalXROOTToCocoa(x);
1402  topLeft.y = X11::GlobalYROOTToCocoa(y);
1403 
1404  [self setFrameTopLeftPoint : topLeft];
1405 }
1406 
1407 //______________________________________________________________________________
1408 - (void) copy : (NSObject<X11Drawable> *) src area : (X11::Rectangle) area withMask : (QuartzImage *) mask
1409  clipOrigin : (X11::Point) clipXY toPoint : (X11::Point) dstPoint
1410 {
1411  if (!fContentView)
1412  return;
1413 
1414  [fContentView copy : src area : area withMask : mask clipOrigin : clipXY toPoint : dstPoint];
1415 }
1416 
1417 //______________________________________________________________________________
1418 - (unsigned char *) readColorBits : (X11::Rectangle) area
1419 {
1420  if (!fContentView)
1421  return nullptr;
1422 
1423  return [fContentView readColorBits : area];
1424 }
1425 
1426 #pragma mark - X11Window protocol's implementation.
1427 
1428 //______________________________________________________________________________
1429 - (QuartzView *) fParentView
1430 {
1431  return nil;
1432 }
1433 
1434 //______________________________________________________________________________
1435 - (void) setFParentView : (QuartzView *) parent
1436 {
1437 #pragma unused(parent)
1438 }
1439 
1440 //______________________________________________________________________________
1441 - (NSView<X11Window> *) fContentView
1442 {
1443  return fContentView;
1444 }
1445 
1446 //______________________________________________________________________________
1448 {
1449  return self;
1450 }
1451 
1452 //... many forwards to fContentView.
1453 
1454 //______________________________________________________________________________
1455 - (void) setFBackgroundPixel : (unsigned long) backgroundColor
1456 {
1457  if (!fContentView)
1458  return;
1459 
1460  if (!fShapeCombineMask) {
1461  CGFloat rgba[] = {0., 0., 0., 1.};
1462  X11::PixelToRGB(backgroundColor, rgba);
1463 
1464  [self setBackgroundColor : [NSColor colorWithColorSpace : [NSColorSpace deviceRGBColorSpace] components : rgba count : 4]];
1465  }
1466 
1467  fContentView.fBackgroundPixel = backgroundColor;
1468 }
1469 
1470 //______________________________________________________________________________
1471 - (unsigned long) fBackgroundPixel
1472 {
1473  if (!fContentView)
1474  return 0;
1475 
1477 }
1478 
1479 //______________________________________________________________________________
1480 - (int) fMapState
1481 {
1482  //Top-level window can be only kIsViewable or kIsUnmapped (not unviewable).
1483  if (!fContentView)
1484  return kIsUnmapped;
1485 
1486  if ([fContentView isHidden])
1487  return kIsUnmapped;
1488 
1489  return kIsViewable;
1490 }
1491 
1492 //______________________________________________________________________________
1493 - (void) addChild : (NSView<X11Window> *) child
1494 {
1495  assert(child != nil && "-addChild:, parameter 'child' is nil");
1496 
1497  if (!fContentView) {
1498  //This can happen only in case of re-parent operation.
1499  assert([child isKindOfClass : [QuartzView class]] &&
1500  "-addChild: gl view in a top-level window as content view is not supported");
1501 
1502  fContentView = (QuartzView *)child;
1503  [self setContentView : child];
1504  fContentView.fParentView = nil;
1505  } else
1506  [fContentView addChild : child];
1507 }
1508 
1509 //______________________________________________________________________________
1510 - (void) getAttributes : (WindowAttributes_t *) attr
1511 {
1512  if (!fContentView)
1513  return;
1514 
1515  assert(attr && "-getAttributes:, parameter 'attr' is nil");
1516 
1517  X11::GetWindowAttributes(self, attr);
1518 }
1519 
1520 //______________________________________________________________________________
1521 - (void) setAttributes : (const SetWindowAttributes_t *) attr
1522 {
1523  assert(attr != 0 && "-setAttributes:, parameter 'attr' is null");
1524 
1525 #ifdef DEBUG_ROOT_COCOA
1526  log_attributes(attr, self.fID);
1527 #endif
1528 
1529  X11::SetWindowAttributes(attr, self);
1530 }
1531 
1532 //______________________________________________________________________________
1534 {
1535  if (!fContentView)
1536  return;
1537 
1538  const Util::AutoreleasePool pool;
1539 
1540  [fContentView setHidden : NO];
1541  [self makeKeyAndOrderFront : self];
1543 
1544  if (fDelayedTransient) {
1545  fDelayedTransient = NO;
1546  [fMainWindow addChildWindow : self ordered : NSWindowAbove];
1547  }
1548 }
1549 
1550 //______________________________________________________________________________
1552 {
1553  if (!fContentView)
1554  return;
1555 
1556  const Util::AutoreleasePool pool;
1557 
1558  [fContentView setHidden : NO];
1559  [self makeKeyAndOrderFront : self];
1561 
1562  if (fDelayedTransient) {
1563  fDelayedTransient = NO;
1564  [fMainWindow addChildWindow : self ordered : NSWindowAbove];
1565  }
1566 }
1567 
1568 //______________________________________________________________________________
1570 {
1571  if (!fContentView)
1572  return;
1573 
1574  const Util::AutoreleasePool pool;
1575 
1578 }
1579 
1580 //______________________________________________________________________________
1582 {
1583  if (!fContentView)
1584  return;
1585 
1586  [fContentView setHidden : YES];
1587  [self orderOut : self];
1588 
1589  if (fMainWindow && !fDelayedTransient) {
1590  [fMainWindow removeChildWindow : self];
1591  fMainWindow = nil;
1592  }
1593 }
1594 
1595 #pragma mark - Events.
1596 
1597 //______________________________________________________________________________
1598 - (void) sendEvent : (NSEvent *) theEvent
1599 {
1600  //With XQuartz, if you open a menu and try to move a window without closing this menu,
1601  //window does not move, menu closes, and after that you can start draggin a window again.
1602  //With Cocoa I can not do such a thing (window WILL move), but still can report button release event
1603  //to close a menu.
1604  if (!fContentView)
1605  return;
1606 
1607  if (theEvent.type == Details::kLeftMouseDown || theEvent.type == Details::kRightMouseDown) {
1608  bool generateFakeRelease = false;
1609 
1610  const NSPoint windowPoint = [theEvent locationInWindow];
1611 
1612  if (windowPoint.x <= 4 || windowPoint.x >= self.fWidth - 4)
1613  generateFakeRelease = true;
1614 
1615  if (windowPoint.y <= 4 || windowPoint.y >= self.fHeight - 4)
1616  generateFakeRelease = true;
1617 
1618  const NSPoint viewPoint = [fContentView convertPoint : windowPoint fromView : nil];
1619 
1620  if (viewPoint.y <= 0 && windowPoint.y >= 0)
1621  generateFakeRelease = true;
1622 
1623  assert(dynamic_cast<TGCocoa *>(gVirtualX) != 0 &&
1624  "-sendEvent:, gVirtualX is either null or not of TGCocoa type");
1625 
1626  TGCocoa * const vx = static_cast<TGCocoa *>(gVirtualX);
1627  if (vx->GetEventTranslator()->HasPointerGrab() && generateFakeRelease) {
1629  theEvent.type == Details::kLeftMouseDown ?
1630  kButton1 : kButton3);
1631  //Yes, ignore this event completely (this means, you are not able to immediately start
1632  //resizing a window, if some popup is open. Actually, this is more or less
1633  //the same as with XQuartz and X11 version.
1634  return;
1635  }
1636  }
1637 
1638  [super sendEvent : theEvent];
1639 }
1640 
1641 #pragma mark - NSWindowDelegate's methods.
1642 
1643 //______________________________________________________________________________
1644 - (BOOL) windowShouldClose : (id) sender
1645 {
1646 #pragma unused(sender)
1647  if (!fContentView)
1648  return NO;
1649 
1650  //TODO: check this!!! Children are
1651  //transient windows and ROOT does not handle
1652  //such a deletion properly, noop then:
1653  //you can not close some window, if there is a
1654  //modal dialog above.
1655  if ([[self childWindows] count])
1656  return NO;
1657 
1658  //Prepare client message for a window.
1659  Event_t closeEvent = {};
1660  closeEvent.fWindow = fContentView.fID;
1661  closeEvent.fType = kClientMessage;
1662  closeEvent.fFormat = 32;//Taken from GUI classes.
1663  closeEvent.fHandle = TGCocoa::fgDeleteWindowAtom;
1664  closeEvent.fUser[0] = TGCocoa::fgDeleteWindowAtom;
1665  //Place it into the queue.
1666  assert(dynamic_cast<TGCocoa *>(gVirtualX) != 0 &&
1667  "-windowShouldClose:, gVirtualX is either null or has a type different from TGCocoa");
1668  ((TGCocoa *)gVirtualX)->SendEvent(fContentView.fID, &closeEvent);
1669 
1670  //Do not let AppKit to close a window,
1671  //ROOT will do.
1672  return NO;
1673 }
1674 
1675 //______________________________________________________________________________
1676 - (void) windowDidBecomeKey : (NSNotification *) aNotification
1677 {
1678 #pragma unused(aNotification)
1679 
1680  if (!fContentView)
1681  return;
1682 
1684  fHasFocus = YES;
1685  //
1686  assert(dynamic_cast<TGCocoa *>(gVirtualX) != 0 &&
1687  "-windowDidBecomeKey:, gVirtualX is null or not of TGCocoa type");
1688  TGCocoa * const vx = static_cast<TGCocoa *>(gVirtualX);
1690  }
1691 }
1692 
1693 
1694 //______________________________________________________________________________
1695 - (void) windowDidResignKey : (NSNotification *) aNotification
1696 {
1697 #pragma unused(aNotification)
1698  fHasFocus = NO;
1699 }
1700 
1701 @end
1702 
1703 #pragma mark - Passive key grab info.
1704 
1705 @implementation PassiveKeyGrab
1706 
1707 //______________________________________________________________________________
1708 - (id) initWithKey : (unichar) keyCode modifiers : (NSUInteger) modifiers
1709 {
1710  if (self = [super init]) {
1711  fKeyCode = keyCode;
1712  fModifiers = modifiers;
1713  }
1714 
1715  return self;
1716 }
1717 
1718 //______________________________________________________________________________
1719 - (BOOL) matchKey : (unichar) keyCode modifiers : (NSUInteger) modifiers
1720 {
1721  return keyCode == fKeyCode && modifiers == fModifiers;
1722 }
1723 
1724 //______________________________________________________________________________
1725 - (BOOL) matchKey : (unichar) keyCode
1726 {
1727  return keyCode == fKeyCode;
1728 }
1729 
1730 //______________________________________________________________________________
1731 - (unichar) fKeyCode
1732 {
1733  return fKeyCode;
1734 }
1735 
1736 //______________________________________________________________________________
1737 - (NSUInteger) fModifiers
1738 {
1739  return fModifiers;
1740 }
1741 
1742 @end
1743 
1744 #pragma mark - X11 property emulation.
1745 
1746 @interface QuartzWindowProperty : NSObject {
1747  NSData *fPropertyData;
1748  Atom_t fType;
1749  unsigned fFormat;
1750 }
1751 
1752 @property (nonatomic, readonly) Atom_t fType;
1753 
1754 @end
1755 
1756 @implementation QuartzWindowProperty
1757 
1758 @synthesize fType;
1759 
1760 //______________________________________________________________________________
1761 - (id) initWithData : (unsigned char *) data size : (unsigned) dataSize type : (Atom_t) type format : (unsigned) format
1762 {
1763  if (self = [super init]) {
1764  //Memory is zero-initialized, but just to make it explicit:
1765  fPropertyData = nil;
1766  fType = 0;
1767  fFormat = 0;
1768 
1769  [self resetPropertyData : data size : dataSize type : type format : format];
1770  }
1771 
1772  return self;
1773 }
1774 
1775 //______________________________________________________________________________
1776 - (void) dealloc
1777 {
1778  [fPropertyData release];
1779 
1780  [super dealloc];
1781 }
1782 
1783 //______________________________________________________________________________
1784 - (void) resetPropertyData : (unsigned char *) data size : (unsigned) dataSize
1785  type : (Atom_t) type format : (unsigned) format
1786 {
1787  [fPropertyData release];
1788 
1789  fFormat = format;
1790  if (format == 16)
1791  dataSize *= 2;
1792  else if (format == 32)
1793  dataSize *= 4;
1794 
1795  fPropertyData = [[NSData dataWithBytes : data length : dataSize] retain];
1796 
1797  fType = type;
1798 }
1799 
1800 //______________________________________________________________________________
1801 - (NSData *) fPropertyData
1802 {
1803  return fPropertyData;
1804 }
1805 
1806 //______________________________________________________________________________
1807 - (unsigned) fFormat
1808 {
1809  return fFormat;
1810 }
1811 
1812 @end
1813 
1814 #pragma mark - QuartzView.
1815 
1816 //
1817 //QuartzView is a children view (also is a content view for a top-level QuartzWindow).
1818 //
1819 
1820 @implementation QuartzView
1821 
1822 @synthesize fID;
1823 @synthesize fContext;
1824 /////////////////////
1825 //SetWindowAttributes_t/WindowAttributes_t
1826 @synthesize fEventMask;
1827 @synthesize fClass;
1828 @synthesize fDepth;
1829 @synthesize fBitGravity;
1830 @synthesize fWinGravity;
1831 @synthesize fBackgroundPixel;
1832 @synthesize fOverrideRedirect;
1833 //SetWindowAttributes_t/WindowAttributes_t
1834 /////////////////////
1835 @synthesize fHasFocus;
1836 @synthesize fParentView;
1837 
1838 @synthesize fPassiveGrabButton;
1839 @synthesize fPassiveGrabEventMask;
1840 @synthesize fPassiveGrabKeyModifiers;
1841 @synthesize fActiveGrabEventMask;
1842 @synthesize fPassiveGrabOwnerEvents;
1843 @synthesize fSnapshotDraw;
1844 @synthesize fCurrentCursor;
1845 @synthesize fIsDNDAware;
1846 
1847 #pragma mark - Lifetime.
1848 
1849 //______________________________________________________________________________
1850 - (id) initWithFrame : (NSRect) frame windowAttributes : (const SetWindowAttributes_t *)attr
1851 {
1852  if (self = [super initWithFrame : frame]) {
1853  //Make this explicit (though memory is zero initialized).
1854  fBackBuffer = nil;
1855  fID = 0;
1856 
1857  //Passive grab parameters.
1858  fPassiveGrabButton = -1;//0 is kAnyButton.
1861 
1862  fPassiveKeyGrabs = [[NSMutableArray alloc] init];
1863 
1864  [self setCanDrawConcurrently : NO];
1865 
1866  [self setHidden : YES];
1867  //Actually, check if view need this.
1868  //
1869  if (attr)
1870  X11::SetWindowAttributes(attr, self);
1871 
1873  fX11Properties = [[NSMutableDictionary alloc] init];
1874 
1877  fActiveGrabOwnerEvents = YES;
1878  }
1879 
1880  return self;
1881 }
1882 
1883 //______________________________________________________________________________
1884 - (void) dealloc
1885 {
1886  [fBackBuffer release];
1887  [fPassiveKeyGrabs release];
1888  [fX11Properties release];
1889  [fBackgroundPixmap release];
1890  [super dealloc];
1891 }
1892 
1893 #pragma mark - Tracking area.
1894 
1895 //Tracking area is required to ... track mouse motion events inside a view.
1896 
1897 //______________________________________________________________________________
1898 - (void) updateTrackingAreas
1899 {
1900  [super updateTrackingAreas];
1901 
1902  if (!fID)
1903  return;
1904 
1905  const Util::AutoreleasePool pool;
1906 
1907  if (NSArray *trackingArray = [self trackingAreas]) {
1908  const NSUInteger size = [trackingArray count];
1909  for (NSUInteger i = 0; i < size; ++i) {
1910  NSTrackingArea * const t = [trackingArray objectAtIndex : i];
1911  [self removeTrackingArea : t];
1912  }
1913  }
1914 
1915  const NSUInteger trackerOptions = NSTrackingMouseMoved | NSTrackingMouseEnteredAndExited |
1916  NSTrackingActiveInActiveApp | NSTrackingInVisibleRect |
1917  NSTrackingEnabledDuringMouseDrag | NSTrackingCursorUpdate;
1918 
1919  NSRect frame = {};
1920  frame.size.width = self.fWidth;
1921  frame.size.height = self.fHeight;
1922 
1923  NSTrackingArea * const tracker = [[NSTrackingArea alloc] initWithRect : frame
1924  options : trackerOptions owner : self userInfo : nil];
1925  [self addTrackingArea : tracker];
1926  [tracker release];
1927 }
1928 
1929 //______________________________________________________________________________
1930 - (void) updateTrackingAreasAfterRaise
1931 {
1932  [self updateTrackingAreas];
1933 
1934  for (QuartzView *childView in [self subviews])
1935  [childView updateTrackingAreasAfterRaise];
1936 }
1937 
1938 #pragma mark - X11Drawable protocol.
1939 
1940 //______________________________________________________________________________
1941 - (BOOL) fIsPixmap
1942 {
1943  return NO;
1944 }
1945 
1946 //______________________________________________________________________________
1948 {
1949  return NO;
1950 }
1951 
1952 //______________________________________________________________________________
1953 - (int) fX
1954 {
1955  return self.frame.origin.x;
1956 }
1957 
1958 //______________________________________________________________________________
1959 - (int) fY
1960 {
1961  return self.frame.origin.y;
1962 }
1963 
1964 //______________________________________________________________________________
1965 - (unsigned) fWidth
1966 {
1967  return self.frame.size.width;
1968 }
1969 
1970 //______________________________________________________________________________
1971 - (unsigned) fHeight
1972 {
1973  return self.frame.size.height;
1974 }
1975 
1976 //______________________________________________________________________________
1977 - (void) setDrawableSize : (NSSize) newSize
1978 {
1979  assert(!(newSize.width < 0) && "-setDrawableSize, width is negative");
1980  assert(!(newSize.height < 0) && "-setDrawableSize, height is negative");
1981 
1982  //This will cause redraw(?)
1983 
1984  //In X11, resize changes the size, but upper-left corner is not changed.
1985  //In Cocoa, bottom-left is fixed.
1986  NSRect frame = self.frame;
1987  frame.size = newSize;
1988 
1989  self.frame = frame;
1990 }
1991 
1992 //______________________________________________________________________________
1993 - (void) setX : (int) x Y : (int) y width : (unsigned) w height : (unsigned) h
1994 {
1995  NSRect newFrame = {};
1996  newFrame.origin.x = x;
1997  newFrame.origin.y = y;
1998  newFrame.size.width = w;
1999  newFrame.size.height = h;
2000 
2001  self.frame = newFrame;
2002 }
2003 
2004 //______________________________________________________________________________
2005 - (void) setX : (int) x Y : (int) y
2006 {
2007  NSRect newFrame = self.frame;
2008  newFrame.origin.x = x;
2009  newFrame.origin.y = y;
2010 
2011  self.frame = newFrame;
2012 }
2013 
2014 //______________________________________________________________________________
2015 - (void) copyImage : (QuartzImage *) srcImage area : (X11::Rectangle) area
2016  withMask : (QuartzImage *) mask clipOrigin : (X11::Point) clipXY
2017  toPoint : (X11::Point) dstPoint
2018 {
2019  //Check parameters.
2020  assert(srcImage != nil &&
2021  "-copyImage:area:withMask:clipOrigin:toPoint:, parameter 'srcImage' is nil");
2022  assert(srcImage.fImage != nil &&
2023  "-copyImage:area:withMask:clipOrigin:toPoint:, srcImage.fImage is nil");
2024 
2025  //Check self.
2026  assert(self.fContext != 0 &&
2027  "-copyImage:area:withMask:clipOrigin:toPoint:, self.fContext is null");
2028 
2029  if (!X11::AdjustCropArea(srcImage, area)) {
2030  NSLog(@"QuartzView: -copyImage:area:withMask:clipOrigin:toPoint:,"
2031  " srcRect and copyRect do not intersect");
2032  return;
2033  }
2034 
2035  //No RAII for subImage, since it can be really subimage or image itself and
2036  //in these cases there is no need to release image.
2037  CGImageRef subImage = 0;
2038  bool needSubImage = false;
2039  if (area.fX || area.fY || area.fWidth != srcImage.fWidth || area.fHeight != srcImage.fHeight) {
2040  needSubImage = true;
2041  subImage = X11::CreateSubImage(srcImage, area);
2042  if (!subImage) {
2043  NSLog(@"QuartzView: -copyImage:area:withMask:clipOrigin:toPoint:,"
2044  " subimage creation failed");
2045  return;
2046  }
2047  } else
2048  subImage = srcImage.fImage;
2049 
2050  //Save context state.
2051  const Quartz::CGStateGuard ctxGuard(self.fContext);
2052 
2053  //Scale and translate to undo isFlipped.
2054  CGContextTranslateCTM(self.fContext, 0., self.fHeight);
2055  CGContextScaleCTM(self.fContext, 1., -1.);
2056  //Set clip mask on a context.
2057 
2058  if (mask) {
2059  assert(mask.fImage != nil &&
2060  "-copyImage:area:withMask:clipOrigin:toPoint:, mask.fImage is nil");
2061  assert(CGImageIsMask(mask.fImage) == true &&
2062  "-copyImage:area:withMask:clipOrigin:toPoint:, mask.fImage is not a mask");
2063  //clipXY.fY = X11::LocalYROOTToCocoa(self, clipXY.fY + mask.fHeight);
2064  const CGFloat clipY = X11::LocalYROOTToCocoa(self, CGFloat(clipXY.fY) + mask.fHeight);
2065  //const CGRect clipRect = CGRectMake(clipXY.fX, clipXY.fY, mask.fWidth, mask.fHeight);
2066  const CGRect clipRect = CGRectMake(clipXY.fX, clipY, mask.fWidth, mask.fHeight);
2067  CGContextClipToMask(self.fContext, clipRect, mask.fImage);
2068  }
2069 
2070  //Convert from X11 to Cocoa (as soon as we scaled y * -1).
2071  //dstPoint.fY = X11::LocalYROOTToCocoa(self, dstPoint.fY + area.fHeight);
2072  const CGFloat dstY = X11::LocalYROOTToCocoa(self, CGFloat(dstPoint.fY) + area.fHeight);
2073  //const CGRect imageRect = CGRectMake(dstPoint.fX, dstPoint.fY, area.fWidth, area.fHeight);
2074  const CGRect imageRect = CGRectMake(dstPoint.fX, dstY, area.fWidth, area.fHeight);
2075  CGContextDrawImage(self.fContext, imageRect, subImage);
2076 
2077  if (needSubImage)
2078  CGImageRelease(subImage);
2079 }
2080 
2081 //______________________________________________________________________________
2082 - (void) copyView : (QuartzView *) srcView area : (X11::Rectangle) area toPoint : (X11::Point) dstPoint
2083 {
2084  //To copy one "window" to another "window", I have to ask source QuartzView to draw intself into
2085  //bitmap, and copy this bitmap into the destination view.
2086 
2087  //TODO: this code must be tested, with all possible cases.
2088 
2089  assert(srcView != nil && "-copyView:area:toPoint:, parameter 'srcView' is nil");
2090 
2091  const NSRect frame = [srcView frame];
2092  //imageRep is in autorelease pool now.
2093  NSBitmapImageRep * const imageRep = [srcView bitmapImageRepForCachingDisplayInRect : frame];
2094  if (!imageRep) {
2095  NSLog(@"QuartzView: -copyView:area:toPoint failed");
2096  return;
2097  }
2098 
2099  assert(srcView != nil && "-copyView:area:toPoint:, parameter 'srcView' is nil");
2100  assert(self.fContext != 0 && "-copyView:area:toPoint, self.fContext is null");
2101 
2102  //It can happen, that src and self are the same.
2103  //cacheDisplayInRect calls drawRect with bitmap context
2104  //(and this will reset self.fContext: I have to save/restore it.
2105  CGContextRef ctx = srcView.fContext;
2106  srcView.fSnapshotDraw = YES;
2107  [srcView cacheDisplayInRect : frame toBitmapImageRep : imageRep];
2108  srcView.fSnapshotDraw = NO;
2109  srcView.fContext = ctx;
2110 
2111  const CGRect subImageRect = CGRectMake(area.fX, area.fY, area.fWidth, area.fHeight);
2112  const Util::CFScopeGuard<CGImageRef> subImage(CGImageCreateWithImageInRect(imageRep.CGImage, subImageRect));
2113 
2114  if (!subImage.Get()) {
2115  NSLog(@"QuartzView: -copyView:area:toPoint, CGImageCreateWithImageInRect failed");
2116  return;
2117  }
2118 
2119  const Quartz::CGStateGuard ctxGuard(self.fContext);
2120  const CGRect imageRect = CGRectMake(dstPoint.fX,
2121  [self visibleRect].size.height - (CGFloat(dstPoint.fY) + area.fHeight),
2122  area.fWidth, area.fHeight);
2123 
2124  CGContextTranslateCTM(self.fContext, 0., [self visibleRect].size.height);
2125  CGContextScaleCTM(self.fContext, 1., -1.);
2126 
2127  CGContextDrawImage(self.fContext, imageRect, subImage.Get());
2128 }
2129 
2130 //______________________________________________________________________________
2131 - (void) copyPixmap : (QuartzPixmap *) srcPixmap area : (X11::Rectangle) area
2132  withMask : (QuartzImage *) mask clipOrigin : (X11::Point) clipXY toPoint : (X11::Point) dstPoint
2133 {
2134  //Check parameters.
2135  assert(srcPixmap != nil && "-copyPixmap:area:withMask:clipOrigin:toPoint:, parameter 'srcPixmap' is nil");
2136 
2137  if (!X11::AdjustCropArea(srcPixmap, area)) {
2138  NSLog(@"QuartzView: -copyPixmap:area:withMask:clipOrigin:toPoint,"
2139  " no intersection between pixmap rectangle and cropArea");
2140  return;
2141  }
2142 
2143  //Check self.
2144  assert(self.fContext != 0 &&
2145  "-copyPixmap:area:withMask:clipOrigin:toPoint:, self.fContext is null");
2146 
2147  //Save context state.
2148  const Quartz::CGStateGuard ctxGuard(self.fContext);
2149 
2150  CGContextTranslateCTM(self.fContext, 0., self.frame.size.height);//???
2151  CGContextScaleCTM(self.fContext, 1., -1.);
2152 
2153  const Util::CFScopeGuard<CGImageRef> imageFromPixmap([srcPixmap createImageFromPixmap]);
2154  assert(imageFromPixmap.Get() != 0 &&
2155  "-copyPixmap:area:withMask:clipOrigin:toPoint:, createImageFromPixmap failed");
2156 
2157  CGImageRef subImage = 0;
2158  bool needSubImage = false;
2159  if (area.fX || area.fY || area.fWidth != srcPixmap.fWidth || area.fHeight != srcPixmap.fHeight) {
2160  needSubImage = true;
2161  const CGRect subImageRect = CGRectMake(area.fX, area.fY, area.fHeight, area.fWidth);
2162  subImage = CGImageCreateWithImageInRect(imageFromPixmap.Get(), subImageRect);
2163  if (!subImage) {
2164  NSLog(@"QuartzView: -copyImage:area:withMask:clipOrigin:toPoint:,"
2165  " subimage creation failed");
2166  return;
2167  }
2168  } else
2169  subImage = imageFromPixmap.Get();
2170 
2171  if (mask) {
2172  assert(mask.fImage != nil &&
2173  "-copyPixmap:area:withMask:clipOrigin:toPoint:, mask.fImage is nil");
2174  assert(CGImageIsMask(mask.fImage) == true &&
2175  "-copyPixmap:area:withMask:clipOrigin:toPoint:, mask.fImage is not a mask");
2176 
2177  //clipXY.fY = X11::LocalYROOTToCocoa(self, clipXY.fY + mask.fHeight);
2178  const CGFloat clipY = X11::LocalYROOTToCocoa(self, CGFloat(clipXY.fY) + mask.fHeight);
2179  //const CGRect clipRect = CGRectMake(clipXY.fX, clipXY.fY, mask.fWidth, mask.fHeight);
2180  const CGRect clipRect = CGRectMake(clipXY.fX, clipY, mask.fWidth, mask.fHeight);
2181  CGContextClipToMask(self.fContext, clipRect, mask.fImage);
2182  }
2183 
2184  //dstPoint.fY = X11::LocalYCocoaToROOT(self, dstPoint.fY + area.fHeight);
2185  const CGFloat dstY = X11::LocalYCocoaToROOT(self, CGFloat(dstPoint.fY) + area.fHeight);
2186  const CGRect imageRect = CGRectMake(dstPoint.fX, dstY, area.fWidth, area.fHeight);
2187  CGContextDrawImage(self.fContext, imageRect, imageFromPixmap.Get());
2188 
2189  if (needSubImage)
2190  CGImageRelease(subImage);
2191 }
2192 
2193 
2194 //______________________________________________________________________________
2195 - (void) copyImage : (QuartzImage *) srcImage area : (X11::Rectangle) area
2196  toPoint : (X11::Point) dstPoint
2197 {
2198  assert(srcImage != nil && "-copyImage:area:toPoint:, parameter 'srcImage' is nil");
2199  assert(srcImage.fImage != nil && "-copyImage:area:toPoint:, srcImage.fImage is nil");
2200  assert(self.fContext != 0 && "-copyImage:area:toPoint:, fContext is null");
2201 
2202  if (!X11::AdjustCropArea(srcImage, area)) {
2203  NSLog(@"QuartzView: -copyImage:area:toPoint, image and copy area do not intersect");
2204  return;
2205  }
2206 
2207  CGImageRef subImage = 0;
2208  bool needSubImage = false;
2209  if (area.fX || area.fY || area.fWidth != srcImage.fWidth || area.fHeight != srcImage.fHeight) {
2210  needSubImage = true;
2211  subImage = X11::CreateSubImage(srcImage, area);
2212  if (!subImage) {
2213  NSLog(@"QuartzView: -copyImage:area:toPoint:, subimage creation failed");
2214  return;
2215  }
2216  } else
2217  subImage = srcImage.fImage;
2218 
2219  const Quartz::CGStateGuard ctxGuard(self.fContext);
2220 
2221  CGContextTranslateCTM(self.fContext, 0., self.fHeight);
2222  CGContextScaleCTM(self.fContext, 1., -1.);
2223 
2224  //dstPoint.fY = X11::LocalYCocoaToROOT(self, dstPoint.fY + area.fHeight);
2225  const CGFloat dstY = X11::LocalYCocoaToROOT(self, CGFloat(dstPoint.fY) + area.fHeight);
2226  //const CGRect imageRect = CGRectMake(dstPoint.fX, dstPoint.fY, area.fWidth, area.fHeight);
2227  const CGRect imageRect = CGRectMake(dstPoint.fX, dstY, area.fWidth, area.fHeight);
2228  CGContextDrawImage(self.fContext, imageRect, subImage);
2229 
2230  if (needSubImage)
2231  CGImageRelease(subImage);
2232 }
2233 
2234 //______________________________________________________________________________
2235 - (void) copy : (NSObject<X11Drawable> *) src area : (X11::Rectangle) area
2236  withMask : (QuartzImage *)mask clipOrigin : (X11::Point) clipXY toPoint : (X11::Point) dstPoint
2237 {
2238  assert(src != nil && "-copy:area:withMask:clipOrigin:toPoint:, parameter 'src' is nil");
2239  assert(area.fWidth && area.fHeight && "-copy:area:withMask:clipOrigin:toPoint:, area to copy is empty");
2240 
2241  if ([src isKindOfClass : [QuartzWindow class]]) {
2242  //Forget about mask (can I have it???)
2243  QuartzWindow * const qw = (QuartzWindow *)src;
2244  //Will not work with OpenGL.
2245  [self copyView : (QuartzView *)qw.fContentView area : area toPoint : dstPoint];
2246  } else if ([src isKindOfClass : [QuartzView class]]) {
2247  //Forget about mask (can I have it???)
2248  [self copyView : (QuartzView *)src area : area toPoint : dstPoint];
2249  } else if ([src isKindOfClass : [QuartzPixmap class]]) {
2250  [self copyPixmap : (QuartzPixmap *)src area : area withMask : mask clipOrigin : clipXY toPoint : dstPoint];
2251  } else if ([src isKindOfClass : [QuartzImage class]]) {
2252  [self copyImage : (QuartzImage *)src area : area withMask : mask clipOrigin : clipXY toPoint : dstPoint];
2253  } else {
2254  assert(0 && "-copy:area:withMask:clipOrigin:toPoint:, src is of unknown type");
2255  }
2256 }
2257 
2258 //______________________________________________________________________________
2259 - (unsigned char *) readColorBits : (X11::Rectangle) area
2260 {
2261  //This is quite a bad idea - to read pixels back from a view,
2262  //but our GUI does exactly this. In case of Cocoa it's expensive
2263  //and not guaranteed to work.
2264 
2265  assert(area.fWidth && area.fHeight && "-readColorBits:, area to copy is empty");
2266 
2267  //int, not unsigned or something - to keep it simple.
2268  const NSRect visRect = [self visibleRect];
2269  const X11::Rectangle srcRect(int(visRect.origin.x), int(visRect.origin.y),
2270  unsigned(visRect.size.width), unsigned(visRect.size.height));
2271 
2272  if (!X11::AdjustCropArea(srcRect, area)) {
2273  NSLog(@"QuartzView: -readColorBits:, visible rect of view and copy area do not intersect");
2274  return nullptr;
2275  }
2276 
2277  //imageRep is autoreleased.
2278  NSBitmapImageRep * const imageRep = [self bitmapImageRepForCachingDisplayInRect : visRect];
2279  if (!imageRep) {
2280  NSLog(@"QuartzView: -readColorBits:, bitmapImageRepForCachingDisplayInRect failed");
2281  return nullptr;
2282  }
2283 
2284  CGContextRef ctx = self.fContext; //Save old context if any.
2285  [self cacheDisplayInRect : visRect toBitmapImageRep : imageRep];
2286  self.fContext = ctx; //Restore old context.
2287  //
2288  const NSInteger bitsPerPixel = [imageRep bitsPerPixel];
2289  //TODO: ohhh :(((
2290  assert(bitsPerPixel == 32 && "-readColorBits:, no alpha channel???");
2291  const NSInteger bytesPerRow = [imageRep bytesPerRow];
2292  unsigned dataWidth = bytesPerRow / (bitsPerPixel / 8);//assume an octet :(
2293 
2294  unsigned char *srcData = nullptr;
2295  std::vector<unsigned char> downscaled;
2296  if ([[NSScreen mainScreen] backingScaleFactor] > 1 && imageRep.CGImage) {
2297  downscaled = X11::DownscaledImageData(area.fWidth, area.fHeight, imageRep.CGImage);
2298  if (downscaled.size())
2299  srcData = &downscaled[0];
2300  dataWidth = area.fWidth;
2301  } else
2302  srcData = [imageRep bitmapData];
2303 
2304  if (!srcData) {
2305  NSLog(@"QuartzView: -readColorBits:, failed to obtain backing store contents");
2306  return nullptr;
2307  }
2308 
2309  //We have a source data now. Let's allocate buffer for ROOT's GUI and convert source data.
2310  unsigned char *data = nullptr;
2311 
2312  try {
2313  data = new unsigned char[area.fWidth * area.fHeight * 4];//bgra?
2314  } catch (const std::bad_alloc &) {
2315  NSLog(@"QuartzView: -readColorBits:, memory allocation failed");
2316  return nullptr;
2317  }
2318 
2319  unsigned char *dstPixel = data;
2320  const unsigned char *line = srcData + area.fY * dataWidth * 4;
2321  const unsigned char *srcPixel = line + area.fX * 4;
2322 
2323  for (unsigned i = 0; i < area.fHeight; ++i) {
2324  for (unsigned j = 0; j < area.fWidth; ++j, srcPixel += 4, dstPixel += 4) {
2325  dstPixel[0] = srcPixel[2];
2326  dstPixel[1] = srcPixel[1];
2327  dstPixel[2] = srcPixel[0];
2328  dstPixel[3] = srcPixel[3];
2329  }
2330 
2331  line += dataWidth * 4;
2332  srcPixel = line + area.fX * 4;
2333  }
2334 
2335  return data;
2336 }
2337 
2338 //______________________________________________________________________________
2339 - (void) setFBackgroundPixmap : (QuartzImage *) pixmap
2340 {
2341  if (fBackgroundPixmap != pixmap) {
2342  [fBackgroundPixmap release];
2343  if (pixmap)
2344  fBackgroundPixmap = [pixmap retain];
2345  else
2346  fBackgroundPixmap = nil;
2347  }
2348 }
2349 
2350 //______________________________________________________________________________
2352 {
2353  //I do not autorelease, screw this idiom!
2354 
2355  return fBackgroundPixmap;
2356 }
2357 
2358 //______________________________________________________________________________
2359 - (int) fMapState
2360 {
2361  if ([self isHidden])
2362  return kIsUnmapped;
2363 
2364  for (QuartzView *parent = fParentView; parent; parent = parent.fParentView) {
2365  if ([parent isHidden])
2366  return kIsUnviewable;
2367  }
2368 
2369  return kIsViewable;
2370 }
2371 
2372 //______________________________________________________________________________
2373 - (BOOL) fHasFocus
2374 {
2375  //With the latest update clang became a bit more stupid.
2376  //Let's write a stupid useless cargo cult code
2377  //to make IT SHUT THE F... UP.
2378  (void)fHasFocus;
2379  return NO;
2380 }
2381 
2382 //______________________________________________________________________________
2383 - (void) setFHasFocus : (BOOL) focus
2384 {
2385 #pragma unused(focus)
2386  //With the latest update clang became a bit more stupid.
2387  //Let's write a stupid useless cargo cult code
2388  //to make IT SHUT THE F... UP.
2389  (void)fHasFocus;
2390 }
2391 
2392 //______________________________________________________________________________
2394 {
2395  return fBackBuffer;//No autorelease, I know the object's lifetime myself.
2396 }
2397 
2398 //______________________________________________________________________________
2399 - (void) setFBackBuffer : (QuartzPixmap *) backBuffer
2400 {
2401  if (fBackBuffer != backBuffer) {
2402  [fBackBuffer release];
2403 
2404  if (backBuffer)
2405  fBackBuffer = [backBuffer retain];
2406  else
2407  fBackBuffer = nil;
2408  }
2409 }
2410 
2411 //______________________________________________________________________________
2412 - (NSView<X11Window> *) fContentView
2413 {
2414  return self;
2415 }
2416 
2417 //______________________________________________________________________________
2419 {
2420  return (QuartzWindow *)[self window];
2421 }
2422 
2423 //______________________________________________________________________________
2425 {
2427 }
2428 
2429 //______________________________________________________________________________
2431 {
2433 }
2434 
2435 //______________________________________________________________________________
2436 - (void) activateGrab : (unsigned) eventMask ownerEvents : (BOOL) ownerEvents
2437 {
2439  fActiveGrabEventMask = eventMask;
2440  fActiveGrabOwnerEvents = ownerEvents;
2441 }
2442 
2443 //______________________________________________________________________________
2445 {
2448  fActiveGrabOwnerEvents = YES;
2449 }
2450 
2451 //______________________________________________________________________________
2452 - (BOOL) acceptsCrossingEvents : (unsigned) eventMask
2453 {
2454  bool accepts = fEventMask & eventMask;
2455 
2456  //In ROOT passive grabs are always with owner_events == true.
2458  accepts = accepts || (fPassiveGrabEventMask & eventMask);
2459 
2462  accepts = accepts || (fActiveGrabOwnerEvents & eventMask);
2463  else
2464  accepts = fActiveGrabOwnerEvents & eventMask;
2465  }
2466 
2467  return accepts;
2468 }
2469 
2470 //______________________________________________________________________________
2471 - (void) addChild : (NSView<X11Window> *) child
2472 {
2473  assert(child != nil && "-addChild:, parameter 'child' is nil");
2474 
2475  [self addSubview : child];
2476  child.fParentView = self;
2477 }
2478 
2479 //______________________________________________________________________________
2480 - (void) getAttributes : (WindowAttributes_t *) attr
2481 {
2482  assert(attr != 0 && "-getAttributes:, parameter 'attr' is null");
2483 
2484  X11::GetWindowAttributes(self, attr);
2485 }
2486 
2487 //______________________________________________________________________________
2488 - (void) setAttributes : (const SetWindowAttributes_t *)attr
2489 {
2490  assert(attr != 0 && "-setAttributes:, parameter 'attr' is null");
2491 
2492 #ifdef DEBUG_ROOT_COCOA
2493  log_attributes(attr, fID);
2494 #endif
2495 
2496  X11::SetWindowAttributes(attr, self);
2497 }
2498 
2499 //______________________________________________________________________________
2501 {
2502  //Move view to the top of subviews.
2503  QuartzView * const parent = fParentView;
2504  [self removeFromSuperview];
2505  [parent addSubview : self];
2506  [self setHidden : NO];
2507 }
2508 
2509 //______________________________________________________________________________
2511 {
2512  [self setHidden : NO];
2513 }
2514 
2515 //______________________________________________________________________________
2517 {
2518  for (QuartzView * v in [self subviews])
2519  [v setHidden : NO];
2520 }
2521 
2522 //______________________________________________________________________________
2524 {
2525  [self setHidden : YES];
2526 }
2527 
2528 //______________________________________________________________________________
2530 {
2531  return fIsOverlapped;
2532 }
2533 
2534 //______________________________________________________________________________
2535 - (void) setOverlapped : (BOOL) overlap
2536 {
2537  fIsOverlapped = overlap;
2538  for (NSView<X11Window> *child in [self subviews])
2539  [child setOverlapped : overlap];
2540 }
2541 
2542 //______________________________________________________________________________
2544 {
2545  //Now, I can not remove window and add it ...
2546  //For example, if you click on a tab, this:
2547  //1. Creates (potentially) a passive button grab
2548  //2. Raises this tab - changes the window order.
2549  //3. On a button release - grab is release.
2550  //The tough problem is, if I remove a view from subviews
2551  //and add it ... it will never receve the
2552  //release event thus a grab will 'hang' on
2553  //view leading to bugs and artifacts.
2554  //So instead I have to ... SORT!!!!!
2555 
2556  using namespace X11;//Comparators.
2557 
2558  for (QuartzView *sibling in [fParentView subviews]) {
2559  if (self == sibling)
2560  continue;
2561  if ([sibling isHidden])
2562  continue;
2563 
2564  if (NSEqualRects(sibling.frame, self.frame)) {
2565  [sibling setOverlapped : YES];
2566  [sibling setHidden : YES];
2567  }
2568  }
2569 
2570  [self setOverlapped : NO];
2571  //
2572  [self setHidden : NO];
2573  //
2574  [fParentView sortSubviewsUsingFunction : CompareViewsToRaise context : (void *)self];
2575  //
2576  [self updateTrackingAreasAfterRaise];
2577  //
2578  [self setNeedsDisplay : YES];
2579 }
2580 
2581 //______________________________________________________________________________
2583 {
2584  //See comment about sorting in -raiseWindow.
2585 
2586  using namespace X11;
2587 
2588  NSEnumerator * const reverseEnumerator = [[fParentView subviews] reverseObjectEnumerator];
2589  for (QuartzView *sibling in reverseEnumerator) {
2590  if (sibling == self)
2591  continue;
2592 
2593  //TODO: equal test is not good :) I have a baaad feeling about this ;)
2594  if (NSEqualRects(sibling.frame, self.frame)) {
2595  [sibling setOverlapped : NO];
2596  //
2597  [sibling setHidden : NO];
2598  //
2599  [sibling setNeedsDisplay : YES];
2600  [self setOverlapped : YES];
2601  //
2602  [self setHidden : YES];
2603  //
2604  break;
2605  }
2606  }
2607 
2608  [fParentView sortSubviewsUsingFunction : CompareViewsToLower context : (void*)self];
2609 }
2610 
2611 //______________________________________________________________________________
2612 - (BOOL) isFlipped
2613 {
2614  //Now view's placement, geometry, moving and resizing can be
2615  //done with ROOT's (X11) coordinates without conversion - we're are 'flipped'.
2616  return YES;
2617 }
2618 
2619 //______________________________________________________________________________
2621 {
2622  if (self.fMapState == kIsViewable || fIsOverlapped == YES) {
2624  assert(dynamic_cast<TGCocoa *>(gVirtualX) &&
2625  "-configureNotifyTree, gVirtualX is either null or has type different from TGCocoa");
2626  TGCocoa * const vx = static_cast<TGCocoa *>(gVirtualX);
2627  vx->GetEventTranslator()->GenerateConfigureNotifyEvent(self, self.frame);
2628  }
2629 
2630  for (NSView<X11Window> *v in [self subviews])
2631  [v configureNotifyTree];
2632  }
2633 }
2634 
2635 #pragma mark - Key grabs.
2636 
2637 //______________________________________________________________________________
2638 - (void) addPassiveKeyGrab : (unichar) keyCode modifiers : (NSUInteger) modifiers
2639 {
2640  [self removePassiveKeyGrab : keyCode modifiers : modifiers];
2641  PassiveKeyGrab * const newGrab = [[PassiveKeyGrab alloc] initWithKey : keyCode
2642  modifiers : modifiers];
2643  [fPassiveKeyGrabs addObject : newGrab];
2644  [newGrab release];
2645 }
2646 
2647 //______________________________________________________________________________
2648 - (void) removePassiveKeyGrab : (unichar) keyCode modifiers : (NSUInteger) modifiers
2649 {
2650  const NSUInteger count = [fPassiveKeyGrabs count];
2651  for (NSUInteger i = 0; i < count; ++i) {
2652  PassiveKeyGrab *grab = [fPassiveKeyGrabs objectAtIndex : i];
2653  if ([grab matchKey : keyCode modifiers : modifiers]) {
2654  [fPassiveKeyGrabs removeObjectAtIndex : i];
2655  break;
2656  }
2657  }
2658 }
2659 
2660 //______________________________________________________________________________
2661 - (PassiveKeyGrab *) findPassiveKeyGrab : (unichar) keyCode modifiers : (NSUInteger) modifiers
2662 {
2663  NSEnumerator * const enumerator = [fPassiveKeyGrabs objectEnumerator];
2664  while (PassiveKeyGrab *grab = (PassiveKeyGrab *)[enumerator nextObject]) {
2665  if ([grab matchKey : keyCode modifiers : modifiers])
2666  return grab;
2667  }
2668 
2669  return nil;
2670 }
2671 
2672 //______________________________________________________________________________
2673 - (PassiveKeyGrab *) findPassiveKeyGrab : (unichar) keyCode
2674 {
2675  //Do not check modifiers.
2676  NSEnumerator * const enumerator = [fPassiveKeyGrabs objectEnumerator];
2677  while (PassiveKeyGrab *grab = (PassiveKeyGrab *)[enumerator nextObject]) {
2678  if ([grab matchKey : keyCode])
2679  return grab;
2680  }
2681 
2682  return nil;
2683 }
2684 
2685 #pragma mark - Painting mechanics.
2686 
2687 //______________________________________________________________________________
2688 - (void) drawRect : (NSRect) dirtyRect
2689 {
2690 #pragma unused(dirtyRect)
2691 
2692  using namespace X11;
2693 
2694  if (fID) {
2695  if (TGWindow * const window = gClient->GetWindowById(fID)) {
2696  //It's never painted, parent renders child. true == check the parent also.
2697  if (ViewIsTextViewFrame(self, true) ||ViewIsHtmlViewFrame(self, true))
2698  return;
2699 
2700  NSGraphicsContext * const nsContext = [NSGraphicsContext currentContext];
2701  assert(nsContext != nil && "-drawRect:, currentContext returned nil");
2702 
2703  TGCocoa * const vx = (TGCocoa *)gVirtualX;
2704  vx->CocoaDrawON();
2705 
2706  fContext = (CGContextRef)[nsContext graphicsPort];
2707  assert(fContext != 0 && "-drawRect:, graphicsPort returned null");
2708 
2709  const Quartz::CGStateGuard ctxGuard(fContext);
2710 
2711  //Non-rectangular windows.
2714 
2715  if (window->InheritsFrom("TGContainer"))//It always has an ExposureMask.
2716  vx->GetEventTranslator()->GenerateExposeEvent(self, [self visibleRect]);
2717 
2718  if (fEventMask & kExposureMask) {
2719  if (ViewIsTextView(self)) {
2720  //Send Expose event, using child view (this is how it's done in GUI :( ).
2721  NSView<X11Window> * const viewFrame = FrameForTextView(self);
2722  if (viewFrame)//Now we set fExposedRegion for TGView.
2723  vx->GetEventTranslator()->GenerateExposeEvent(viewFrame, [viewFrame visibleRect]);
2724  }
2725 
2726  if (ViewIsHtmlView(self)) {
2727  NSView<X11Window> *const viewFrame = FrameForHtmlView(self);
2728  if (viewFrame)
2729  vx->GetEventTranslator()->GenerateExposeEvent(viewFrame, [viewFrame visibleRect]);
2730  }
2731 
2732  //Ask ROOT's widget/window to draw itself.
2733  gClient->NeedRedraw(window, kTRUE);
2734 
2735  if (!fSnapshotDraw && !ViewIsTextView(self) && !ViewIsHtmlView(self)) {
2736  //If Cocoa repaints widget, cancel all ROOT's "outside of paint event"
2737  //rendering into this widget ... Except it's a text view :)
2738  gClient->CancelRedraw(window);
2739  vx->GetCommandBuffer()->RemoveGraphicsOperationsForWindow(fID);
2740  }
2741  }
2742 
2743  if (fBackBuffer) {
2744  //Very "special" window.
2745  const X11::Rectangle copyArea(0, 0, fBackBuffer.fWidth, fBackBuffer.fHeight);
2746  [self copy : fBackBuffer area : copyArea withMask : nil
2747  clipOrigin : X11::Point() toPoint : X11::Point()];
2748  }
2749 
2750  vx->CocoaDrawOFF();
2751 #ifdef DEBUG_ROOT_COCOA
2752  CGContextSetRGBStrokeColor(fContext, 1., 0., 0., 1.);
2753  CGContextStrokeRect(fContext, dirtyRect);
2754 #endif
2755 
2756  fContext = 0;
2757  } else {
2758 #ifdef DEBUG_ROOT_COCOA
2759  NSLog(@"QuartzView: -drawRect: method, no window for id %u was found", fID);
2760 #endif
2761  }
2762  }
2763 }
2764 
2765 #pragma mark - Geometry.
2766 
2767 //______________________________________________________________________________
2768 - (void) setFrame : (NSRect) newFrame
2769 {
2770  //In case of TBrowser, setFrame started infinite recursion:
2771  //HandleConfigure for embedded main frame emits signal, slot
2772  //calls layout, layout calls setFrame -> HandleConfigure and etc. etc.
2773  if (NSEqualRects(newFrame, self.frame))
2774  return;
2775 
2776  [super setFrame : newFrame];
2777 }
2778 
2779 //______________________________________________________________________________
2780 - (void) setFrameSize : (NSSize) newSize
2781 {
2782  //Check, if setFrameSize calls setFrame.
2783 
2784  [super setFrameSize : newSize];
2785 
2786  if ((fEventMask & kStructureNotifyMask) && (self.fMapState == kIsViewable || fIsOverlapped == YES)) {
2787  assert(dynamic_cast<TGCocoa *>(gVirtualX) != 0 &&
2788  "setFrameSize:, gVirtualX is either null or has a type, different from TGCocoa");
2789  TGCocoa * const vx = static_cast<TGCocoa *>(gVirtualX);
2790  vx->GetEventTranslator()->GenerateConfigureNotifyEvent(self, self.frame);
2791  }
2792 
2793  [self setNeedsDisplay : YES];//?
2794 }
2795 
2796 #pragma mark - Event handling.
2797 
2798 //______________________________________________________________________________
2799 - (void) mouseDown : (NSEvent *) theEvent
2800 {
2801  assert(fID != 0 && "-mouseDown:, fID is 0");
2802 
2803  assert(dynamic_cast<TGCocoa *>(gVirtualX) != 0 &&
2804  "-mouseDown:, gVirtualX is either null or has a type, different from TGCocoa");
2805  TGCocoa * const vx = static_cast<TGCocoa *>(gVirtualX);
2806  vx->GetEventTranslator()->GenerateButtonPressEvent(self, theEvent, kButton1);
2807 }
2808 
2809 //______________________________________________________________________________
2810 - (void) scrollWheel : (NSEvent*) theEvent
2811 {
2812  assert(fID != 0 && "-scrollWheel:, fID is 0");
2813 
2814 
2815  assert(dynamic_cast<TGCocoa *>(gVirtualX) != 0 &&
2816  "-scrollWheel:, gVirtualX is either null or has a type, different from TGCocoa");
2817 
2818  TGCocoa * const vx = static_cast<TGCocoa *>(gVirtualX);
2819  const CGFloat deltaY = [theEvent deltaY];
2820  if (deltaY < 0) {
2821  vx->GetEventTranslator()->GenerateButtonPressEvent(self, theEvent, kButton5);
2822  vx->GetEventTranslator()->GenerateButtonReleaseEvent(self, theEvent, kButton5);
2823  } else if (deltaY > 0) {
2824  vx->GetEventTranslator()->GenerateButtonPressEvent(self, theEvent, kButton4);
2825  vx->GetEventTranslator()->GenerateButtonReleaseEvent(self, theEvent, kButton4);
2826  }
2827 }
2828 
2829 #ifdef DEBUG_ROOT_COCOA
2830 //______________________________________________________________________________
2831 - (void) printViewInformation
2832 {
2833  assert(fID != 0 && "-printWindowInformation, fID is 0");
2834  const TGWindow * const window = gClient->GetWindowById(fID);
2835  assert(window != 0 && "printWindowInformation, window not found");
2836 
2837  NSLog(@"-----------------View %u info:---------------------", fID);
2838  NSLog(@"ROOT's window class is %s", window->IsA()->GetName());
2839  NSLog(@"event mask is:");
2840  print_mask_info(fEventMask);
2841  NSLog(@"grab mask is:");
2842  print_mask_info(fPassiveGrabEventMask);
2843  NSLog(@"view's geometry: x == %g, y == %g, w == %g, h == %g", self.frame.origin.x,
2844  self.frame.origin.y, self.frame.size.width, self.frame.size.height);
2845  NSLog(@"----------------End of view info------------------");
2846 }
2847 #endif
2848 
2849 //______________________________________________________________________________
2850 - (void) rightMouseDown : (NSEvent *) theEvent
2851 {
2852  assert(fID != 0 && "-rightMouseDown:, fID is 0");
2853 
2854 #ifdef DEBUG_ROOT_COCOA
2855  [self printViewInformation];
2856 #endif
2857 
2858  assert(dynamic_cast<TGCocoa *>(gVirtualX) != 0 &&
2859  "-rightMouseDown:, gVirtualX is either null or has type different from TGCocoa");
2860  TGCocoa * const vx = static_cast<TGCocoa *>(gVirtualX);
2861  vx->GetEventTranslator()->GenerateButtonPressEvent(self, theEvent, kButton3);
2862 }
2863 
2864 //______________________________________________________________________________
2865 - (void) otherMouseDown : (NSEvent *) theEvent
2866 {
2867  assert(fID != 0 && "-otherMouseDown:, fID is 0");
2868 
2869  //Funny enough, [theEvent buttonNumber] is not the same thing as button masked in [NSEvent pressedMouseButtons],
2870  //button number actually is a kind of right operand for bitshift for pressedMouseButtons.
2871  if ([theEvent buttonNumber] == 2) {//this '2' will correspond to '4' in pressedMouseButtons.
2872  //I do not care about mouse buttons after left/right/wheel - ROOT does not have
2873  //any code for this.
2874  assert(dynamic_cast<TGCocoa *>(gVirtualX) != 0 &&
2875  "-otherMouseDown:, gVirtualX is either null or has type different from TGCocoa");
2876  TGCocoa * const vx = static_cast<TGCocoa *>(gVirtualX);
2877  vx->GetEventTranslator()->GenerateButtonPressEvent(self, theEvent, kButton2);
2878  }
2879 }
2880 
2881 //______________________________________________________________________________
2882 - (void) mouseUp : (NSEvent *) theEvent
2883 {
2884  assert(fID != 0 && "-mouseUp:, fID is 0");
2885 
2886  assert(dynamic_cast<TGCocoa *>(gVirtualX) &&
2887  "-mouseUp:, gVirtualX is either null or has type different from TGCocoa");
2888  TGCocoa * const vx = static_cast<TGCocoa *>(gVirtualX);
2889  vx->GetEventTranslator()->GenerateButtonReleaseEvent(self, theEvent, kButton1);
2890 }
2891 
2892 //______________________________________________________________________________
2893 - (void) rightMouseUp : (NSEvent *) theEvent
2894 {
2895 
2896  assert(fID != 0 && "-rightMouseUp:, fID is 0");
2897 
2898  assert(dynamic_cast<TGCocoa *>(gVirtualX) != 0 &&
2899  "-rightMouseUp:, gVirtualX is either null or has type different from TGCocoa");
2900 
2901  TGCocoa * const vx = static_cast<TGCocoa *>(gVirtualX);
2902  vx->GetEventTranslator()->GenerateButtonReleaseEvent(self, theEvent, kButton3);
2903 }
2904 
2905 //______________________________________________________________________________
2906 - (void) otherMouseUp : (NSEvent *) theEvent
2907 {
2908  assert(fID != 0 && "-otherMouseUp:, fID is 0");
2909 
2910  //Here I assume it's always kButton2.
2911  assert(dynamic_cast<TGCocoa *>(gVirtualX) != 0 &&
2912  "-otherMouseUp:, gVirtualX is either null or has type different from TGCocoa");
2913  TGCocoa * const vx = static_cast<TGCocoa *>(gVirtualX);
2914  vx->GetEventTranslator()->GenerateButtonReleaseEvent(self, theEvent, kButton2);
2915 }
2916 
2917 //______________________________________________________________________________
2918 - (void) mouseEntered : (NSEvent *) theEvent
2919 {
2920  assert(fID != 0 && "-mouseEntered:, fID is 0");
2921  assert(dynamic_cast<TGCocoa *>(gVirtualX) != 0 &&
2922  "-mouseEntered:, gVirtualX is null or not of TGCocoa type");
2923 
2924  TGCocoa * const vx = static_cast<TGCocoa *>(gVirtualX);
2925  vx->GetEventTranslator()->GenerateCrossingEvent(theEvent);
2926 }
2927 
2928 //______________________________________________________________________________
2929 - (void) mouseExited : (NSEvent *) theEvent
2930 {
2931  assert(fID != 0 && "-mouseExited:, fID is 0");
2932 
2933  assert(dynamic_cast<TGCocoa *>(gVirtualX) != 0 &&
2934  "-mouseExited:, gVirtualX is null or not of TGCocoa type");
2935 
2936  TGCocoa * const vx = static_cast<TGCocoa *>(gVirtualX);
2937  vx->GetEventTranslator()->GenerateCrossingEvent(theEvent);
2938 }
2939 
2940 //______________________________________________________________________________
2941 - (void) mouseMoved : (NSEvent *) theEvent
2942 {
2943  assert(fID != 0 && "-mouseMoved:, fID is 0");
2944 
2945  if (fParentView)//Suppress events in all views, except the top-level one.
2946  return; //TODO: check, that it does not create additional problems.
2947 
2948  assert(dynamic_cast<TGCocoa *>(gVirtualX) != 0 &&
2949  "-mouseMoved:, gVirtualX is null or not of TGCocoa type");
2950 
2951  TGCocoa *vx = static_cast<TGCocoa *>(gVirtualX);
2953 }
2954 
2955 //______________________________________________________________________________
2956 - (void) mouseDragged : (NSEvent *) theEvent
2957 {
2958  assert(fID != 0 && "-mouseDragged:, fID is 0");
2959 
2960  TGCocoa * const vx = dynamic_cast<TGCocoa *>(gVirtualX);
2961  assert(vx != 0 && "-mouseDragged:, gVirtualX is null or not of TGCocoa type");
2962 
2964 }
2965 
2966 //______________________________________________________________________________
2967 - (void) rightMouseDragged : (NSEvent *) theEvent
2968 {
2969  assert(fID != 0 && "-rightMouseDragged:, fID is 0");
2970 
2971  assert(dynamic_cast<TGCocoa *>(gVirtualX) != 0 &&
2972  "-rightMouseDragged:, gVirtualX is null or not of TGCocoa type");
2973 
2974  TGCocoa * const vx = static_cast<TGCocoa *>(gVirtualX);
2976 }
2977 
2978 //______________________________________________________________________________
2979 - (void) otherMouseDragged : (NSEvent *) theEvent
2980 {
2981  assert(fID != 0 && "-otherMouseDragged:, fID is 0");
2982 
2983  if ([theEvent buttonNumber] == 2) {
2984  assert(dynamic_cast<TGCocoa *>(gVirtualX) != 0 &&
2985  "-otherMouseDragged:, gVirtualX is null or not of TGCocoa type");
2986  TGCocoa * const vx = static_cast<TGCocoa *>(gVirtualX);
2988  }
2989 }
2990 
2991 //______________________________________________________________________________
2992 - (void) keyDown : (NSEvent *) theEvent
2993 {
2994  assert(fID != 0 && "-keyDown:, fID is 0");
2995 
2996  assert(dynamic_cast<TGCocoa *>(gVirtualX) != 0 &&
2997  "-keyDown:, gVirtualX is null or not of TGCocoa type");
2998 
2999  NSView<X11Window> *eventView = self;
3000  if (NSView<X11Window> *pointerView = X11::FindViewUnderPointer())
3001  eventView = pointerView;
3002 
3003  TGCocoa * const vx = static_cast<TGCocoa *>(gVirtualX);
3004  vx->GetEventTranslator()->GenerateKeyPressEvent(eventView, theEvent);
3005 }
3006 
3007 //______________________________________________________________________________
3008 - (void) keyUp : (NSEvent *) theEvent
3009 {
3010  assert(fID != 0 && "-keyUp:, fID is 0");
3011 
3012  assert(dynamic_cast<TGCocoa *>(gVirtualX) != 0 &&
3013  "-keyUp:, gVirtualX is null or not of TGCocoa type");
3014 
3015  TGCocoa * const vx = static_cast<TGCocoa *>(gVirtualX);
3016  NSView<X11Window> *eventView = self;
3017  if (NSView<X11Window> *pointerView = X11::FindViewUnderPointer())
3018  eventView = pointerView;
3019 
3020  vx->GetEventTranslator()->GenerateKeyReleaseEvent(eventView, theEvent);
3021 }
3022 
3023 #pragma mark - First responder stuff.
3024 
3025 //______________________________________________________________________________
3026 - (BOOL) acceptsFirstMouse : (NSEvent *) theEvent
3027 {
3028 #pragma unused(theEvent)
3029  return YES;
3030 }
3031 
3032 //______________________________________________________________________________
3033 - (BOOL) acceptsFirstResponder
3034 {
3035  return YES;
3036 }
3037 
3038 #pragma mark - Cursors.
3039 
3040 //______________________________________________________________________________
3041 - (void) setFCurrentCursor : (ECursor) cursor
3042 {
3043  if (cursor != fCurrentCursor) {
3044  fCurrentCursor = cursor;
3045  [self.fQuartzWindow invalidateCursorRectsForView : self];
3046  }
3047 }
3048 
3049 //______________________________________________________________________________
3050 - (NSCursor *) createCustomCursor
3051 {
3052  const char *pngFileName = 0;
3053 
3054  switch (fCurrentCursor) {
3055  case kMove:
3056  pngFileName = "move_cursor.png";
3057  break;
3058  case kArrowHor:
3059  pngFileName = "hor_arrow_cursor.png";
3060  break;
3061  case kArrowVer:
3062  pngFileName = "ver_arrow_cursor.png";
3063  break;
3064  case kArrowRight:
3065  pngFileName = "right_arrow_cursor.png";
3066  break;
3067  case kRotate:
3068  pngFileName = "rotate.png";
3069  break;
3070  case kBottomLeft:
3071  case kTopRight:
3072  pngFileName = "top_right_cursor.png";
3073  break;
3074  case kTopLeft:
3075  case kBottomRight:
3076  pngFileName = "top_left_cursor.png";
3077  break;
3078  default:;
3079  }
3080 
3081  if (pngFileName) {
3082  const char * const path = gSystem->Which(TROOT::GetIconPath(), pngFileName, kReadPermission);
3083  const Util::ScopedArray<const char> arrayGuard(path);
3084 
3085  if (!path || path[0] == 0) {
3086  //File was not found.
3087  return nil;
3088  }
3089 
3090  NSString *nsPath = [NSString stringWithFormat : @"%s", path];//in autorelease pool.
3091  NSImage * const cursorImage = [[NSImage alloc] initWithContentsOfFile : nsPath];
3092 
3093  if (!cursorImage)
3094  return nil;
3095 
3096  NSPoint hotSpot = X11::GetCursorHotStop(cursorImage, fCurrentCursor);
3097  NSCursor * const customCursor = [[[NSCursor alloc] initWithImage : cursorImage
3098  hotSpot : hotSpot] autorelease];
3099 
3100  [cursorImage release];
3101 
3102  return customCursor;
3103  }
3104 
3105  return nil;
3106 }
3107 
3108 //______________________________________________________________________________
3109 - (void) resetCursorRects
3110 {
3111  if (NSCursor * const cursor = X11::CreateCursor(fCurrentCursor))
3112  [self addCursorRect : self.visibleRect cursor : cursor];
3113 }
3114 
3115 //______________________________________________________________________________
3116 - (void) cursorUpdate
3117 {
3118  if (NSCursor * const cursor = X11::CreateCursor(fCurrentCursor)) {
3119  // NB: [window invalidateCursorRectsForView] called here has the
3120  // same problem as commented below in -cursorUpdate:.
3121  [cursor set];
3122  }
3123 }
3124 
3125 //______________________________________________________________________________
3126 - (void) cursorUpdate : (NSEvent *) event
3127 {
3128 #pragma unused(event)
3129  // It looks like [NSCursor set] method does not work properly when called from
3130  // cursorUpdate:, having, say, a parent frame with 'arrow' cursor and a child (completely
3131  // filling its parent's area) with 'cross', it happens the 'cross' cursor is not always
3132  // set correctly, for example:
3133  // if we have a TCanvas and resize it, cursor is 'arrow' inside this canvas,
3134  // though it must be 'cross'. This all, as it always happesn with "thinking different"
3135  // Apple is somehow related to run loop or something. As always, it's not documented,
3136  // so Apple can continue to think different. The idea with performSelector comes from:
3137  // http://stackoverflow.com/questions/8430236/nscursor-set-method-has-no-effect
3138  // Or may be it's just a bug:
3139  // http://stackoverflow.com/questions/13901232/nscursor-set-not-working-on-unfocused-window
3140  [self performSelector : @selector(cursorUpdate) withObject : nil afterDelay : 0.05f];
3141 }
3142 
3143 #pragma mark - Emulated X11 properties.
3144 
3145 //______________________________________________________________________________
3146 - (void) setProperty : (const char *) propName data : (unsigned char *) propData
3147  size : (unsigned) dataSize forType : (Atom_t) dataType format : (unsigned) format
3148 {
3149  assert(propName != 0 && "-setProperty:data:size:forType:, parameter 'propName' is null");
3150  assert(propData != 0 && "-setProperty:data:size:forType:, parameter 'propData' is null");
3151  assert(dataSize != 0 && "-setProperty:data:size:forType:, parameter 'dataSize' is 0");
3152 
3153  NSString * const key = [NSString stringWithCString : propName encoding : NSASCIIStringEncoding];
3154  QuartzWindowProperty * property = (QuartzWindowProperty *)[fX11Properties valueForKey : key];
3155 
3156  //At the moment (and I think this will never change) TGX11 always calls XChangeProperty with PropModeReplace.
3157  if (property)
3158  [property resetPropertyData : propData size : dataSize type : dataType format : format];
3159  else {
3160  //No property found, add a new one.
3161  property = [[QuartzWindowProperty alloc] initWithData : propData size : dataSize
3162  type : dataType format : format];
3163  [fX11Properties setObject : property forKey : key];
3164  [property release];
3165  }
3166 }
3167 
3168 //______________________________________________________________________________
3169 - (BOOL) hasProperty : (const char *) propName
3170 {
3171  assert(propName != 0 && "-hasProperty:, propName parameter is null");
3172 
3173  NSString * const key = [NSString stringWithCString : propName encoding : NSASCIIStringEncoding];
3174  QuartzWindowProperty * const property = (QuartzWindowProperty *)[fX11Properties valueForKey : key];
3175 
3176  return property != nil;
3177 }
3178 
3179 //______________________________________________________________________________
3180 - (unsigned char *) getProperty : (const char *) propName returnType : (Atom_t *) type
3181  returnFormat : (unsigned *) format nElements : (unsigned *) nElements
3182 {
3183  assert(propName != 0 &&
3184  "-getProperty:returnType:returnFormat:nElements:, parameter 'propName' is null");
3185  assert(type != 0 &&
3186  "-getProperty:returnType:returnFormat:nElements:, parameter 'type' is null");
3187  assert(format != 0 &&
3188  "-getProperty:returnType:returnFormat:nElements:, parameter 'format' is null");
3189  assert(nElements != 0 &&
3190  "-getProperty:returnType:returnFormat:nElements:, parameter 'nElements' is null");
3191 
3192  NSString * const key = [NSString stringWithCString : propName encoding : NSASCIIStringEncoding];
3193  QuartzWindowProperty * const property = (QuartzWindowProperty *)[fX11Properties valueForKey : key];
3194  assert(property != 0 &&
3195  "-getProperty:returnType:returnFormat:nElements, property not found");
3196 
3197  NSData * const propData = property.fPropertyData;
3198 
3199  const NSUInteger dataSize = [propData length];
3200  unsigned char *buff = 0;
3201  try {
3202  buff = new unsigned char[dataSize]();
3203  } catch (const std::bad_alloc &) {
3204  //Hmm, can I log, if new failed? :)
3205  NSLog(@"QuartzWindow: -getProperty:returnType:returnFormat:nElements:,"
3206  " memory allocation failed");
3207  return 0;
3208  }
3209 
3210  [propData getBytes : buff length : dataSize];
3211  *format = property.fFormat;
3212 
3213  *nElements = dataSize;
3214 
3215  if (*format == 16)
3216  *nElements= dataSize / 2;
3217  else if (*format == 32)
3218  *nElements = dataSize / 4;
3219 
3220  *type = property.fType;
3221 
3222  return buff;
3223 }
3224 
3225 //______________________________________________________________________________
3226 - (void) removeProperty : (const char *) propName
3227 {
3228  assert(propName != 0 && "-removeProperty:, parameter 'propName' is null");
3229 
3230  NSString * const key = [NSString stringWithCString : propName
3231  encoding : NSASCIIStringEncoding];
3232  [fX11Properties removeObjectForKey : key];
3233 }
3234 
3235 //DND
3236 //______________________________________________________________________________
3237 - (NSDragOperation) draggingEntered : (id<NSDraggingInfo>) sender
3238 {
3239  NSPasteboard * const pasteBoard = [sender draggingPasteboard];
3240  const NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
3241 
3242  if ([[pasteBoard types] containsObject : NSFilenamesPboardType] && (sourceDragMask & NSDragOperationCopy))
3243  return NSDragOperationCopy;
3244 
3245  return NSDragOperationNone;
3246 }
3247 
3248 //______________________________________________________________________________
3249 - (BOOL) performDragOperation : (id<NSDraggingInfo>) sender
3250 {
3251  //We can drag some files (images, pdfs, source code files) from
3252  //finder to ROOT's window (mainly TCanvas or text editor).
3253  //The logic is totally screwed here :((( - ROOT will try to
3254  //read a property of some window (not 'self', unfortunately) -
3255  //this works since on Window all data is in a global clipboard
3256  //(on X11 it simply does not work at all).
3257  //I'm attaching the file name as a property for the top level window,
3258  //there is no other way to make this data accessible for ROOT.
3259 
3260  NSPasteboard * const pasteBoard = [sender draggingPasteboard];
3261  const NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
3262 
3263  if ([[pasteBoard types] containsObject : NSFilenamesPboardType] && (sourceDragMask & NSDragOperationCopy)) {
3264 
3265  //Here I try to put string ("file://....") into window's property to make
3266  //it accesible from ROOT's GUI.
3267  const Atom_t textUriAtom = gVirtualX->InternAtom("text/uri-list", kFALSE);
3268 
3269  NSArray * const files = [pasteBoard propertyListForType : NSFilenamesPboardType];
3270  for (NSString *path in files) {
3271  //ROOT can not process several files, use the first one.
3272  NSString * const item = [@"file://" stringByAppendingString : path];
3273  //Yes, only ASCII encoding, but after all, ROOT's not able to work with NON-ASCII strings.
3274  const NSUInteger len = [item lengthOfBytesUsingEncoding : NSASCIIStringEncoding] + 1;
3275  try {
3276  std::vector<unsigned char> propertyData(len);
3277  [item getCString : (char *)&propertyData[0] maxLength : propertyData.size()
3278  encoding : NSASCIIStringEncoding];
3279  //There is no any guarantee, that this will ever work, logic in TGDNDManager is totally crazy.
3280  NSView<X11Window> * const targetView = self.fQuartzWindow.fContentView;
3281  [targetView setProperty : "_XC_DND_DATA" data : &propertyData[0]
3282  size : propertyData.size() forType : textUriAtom format : 8];
3283  } catch (const std::bad_alloc &) {
3284  //Hehe, can I log something in case of bad_alloc??? ;)
3285  NSLog(@"QuartzView: -performDragOperation:, memory allocation failed");
3286  return NO;
3287  }
3288 
3289  break;
3290  }
3291 
3292  //Property is attached now.
3293 
3294  //Gdk on windows creates three events on file drop (WM_DROPFILES): XdndEnter, XdndPosition, XdndDrop.
3295  //1. Dnd enter.
3296  Event_t event1 = {};
3297  event1.fType = kClientMessage;
3298  event1.fWindow = fID;
3299  event1.fHandle = gVirtualX->InternAtom("XdndEnter", kFALSE);
3300  event1.fUser[0] = long(fID);
3301  event1.fUser[2] = textUriAtom;//gVirtualX->InternAtom("text/uri-list", kFALSE);
3302  //
3303  gVirtualX->SendEvent(fID, &event1);
3304 
3305  //2. Dnd position.
3306  Event_t event2 = {};
3307  event2.fType = kClientMessage;
3308  event2.fWindow = fID;
3309  event2.fHandle = gVirtualX->InternAtom("XdndPosition", kFALSE);
3310  event2.fUser[0] = long(fID);
3311  event2.fUser[2] = 0;//Here I have to pack x and y for drop coordinates, shifting by 16 bits.
3312  NSPoint dropPoint = [sender draggingLocation];
3313  //convertPointFromBase is deprecated.
3314  //dropPoint = [self convertPointFromBase : dropPoint];
3315  dropPoint = [self convertPoint : dropPoint fromView : nil];
3316  //
3317  dropPoint = X11::TranslateToScreen(self, dropPoint);
3318  event2.fUser[2] = UShort_t(dropPoint.y) | (UShort_t(dropPoint.x) << 16);
3319 
3320  gVirtualX->SendEvent(fID, &event2);
3321 
3322  Event_t event3 = {};
3323  event3.fType = kClientMessage;
3324  event3.fWindow = fID;
3325  event3.fHandle = gVirtualX->InternAtom("XdndDrop", kFALSE);
3326 
3327  gVirtualX->SendEvent(fID, &event3);
3328  }
3329 
3330  return YES;//Always ok, even if file type is not supported - no need in "animation".
3331 }
3332 
3333 @end
std::vector< unsigned char > DownscaledImageData(unsigned w, unsigned h, CGImageRef image)
int GlobalXCocoaToROOT(CGFloat xCocoa)
BOOL fOverrideRedirect
Definition: QuartzWindow.h:177
void GenerateConfigureNotifyEvent(NSView< X11Window > *view, const NSRect &newFrame)
Definition: X11Events.mm:1153
QuartzWindow * CreateTopLevelWindow(Int_t x, Int_t y, UInt_t w, UInt_t h, UInt_t border, Int_t depth, UInt_t clss, void *visual, SetWindowAttributes_t *attr, UInt_t)
Definition: QuartzWindow.mm:52
NSView< X11Window > * FindViewForPointerEvent(NSEvent *pointerEvent)
virtual const char * GetName() const
Return unique name, used in SavePrimitive methods.
Definition: TGWindow.cxx:221
void GetRootWindowAttributes(WindowAttributes_t *attr)
unsigned long fBackgroundPixel
Definition: QuartzWindow.h:111
void GeneratePointerMotionEvent(NSEvent *theEvent)
Definition: X11Events.mm:1251
void configureNotifyTree()
unsigned fPassiveGrabEventMask
Definition: QuartzWindow.h:183
bool LockFocus(NSView< X11Window > *view)
ROOT::MacOSX::Util::CFScopeGuard< CGImageRef > fImage
Definition: QuartzPixmap.h:105
virtual Bool_t InheritsFrom(const char *classname) const
Returns kTRUE if object inherits from class &quot;classname&quot;.
Definition: TObject.cxx:488
void GetWindowAttributes(NSObject< X11Window > *window, WindowAttributes_t *dst)
TLine * line
QuartzWindow * fQuartzWindow
Definition: QuartzWindow.h:122
UInt_t Mask_t
Definition: GuiTypes.h:42
ECursor fCurrentCursor
Definition: QuartzWindow.h:188
ULong_t fBackingPixel
Definition: GuiTypes.h:127
QuartzWindow * FindWindowInPoint(Int_t x, Int_t y)
void mapSubwindows()
void GenerateKeyReleaseEvent(NSView< X11Window > *eventView, NSEvent *theEvent)
Definition: X11Events.mm:1308
static const TString & GetIconPath()
Get the icon path in the installation. Static utility function.
Definition: TROOT.cxx:2871
const Mask_t kButtonMotionMask
Definition: GuiTypes.h:165
const Mask_t kWACursor
Definition: GuiTypes.h:155
unsigned short UShort_t
Definition: RtypesCore.h:36
NSView< X11Window > * FindDNDAwareViewInPoint(NSView *parentView, Window_t dragWinID, Window_t inputWinID, Int_t x, Int_t y, Int_t maxDepth)
bool AdjustCropArea(const Rectangle &srcRect, Rectangle &cropArea)
TH1 * h
Definition: legend2.C:5
const Mask_t kLeaveWindowMask
Definition: GuiTypes.h:169
const Mask_t kWABackPixmap
Definition: GuiTypes.h:140
BOOL fIsDNDAware
Definition: QuartzWindow.h:189
const Mask_t kWABorderPixel
Definition: GuiTypes.h:143
ROOT::MacOSX::X11::CommandBuffer * GetCommandBuffer() const
Definition: TGCocoa.mm:4406
const Mask_t kWABitGravity
Definition: GuiTypes.h:145
int LocalYCocoaToROOT(NSView< X11Window > *parentView, CGFloat yCocoa)
QuartzView * fContentView
Definition: QuartzWindow.h:46
QuartzImage * fShapeCombineMask
Definition: QuartzWindow.h:48
void unmapWindow()
#define gClient
Definition: TGClient.h:174
int Int_t
Definition: RtypesCore.h:41
const Bool_t kFALSE
Definition: Rtypes.h:92
const Mask_t kWABackingStore
Definition: GuiTypes.h:147
BOOL fIsOpenGLWidget()
virtual char * Which(const char *search, const char *file, EAccessMode mode=kFileExists)
Find location of file in a search path.
Definition: TSystem.cxx:1511
NSView< X11Window > * fContentView
Definition: QuartzWindow.h:255
NSUInteger fModifiers()
unsigned fWidth()
unsigned char * readColorBits:(ROOT::MacOSX::X11::Rectangle area)
QuartzPixmap * fBackBuffer
Definition: QuartzWindow.h:195
static std::string format(double x, double y, int digits, int width)
ECursor
Definition: TVirtualX.h:56
NSCursor * CreateCustomCursor(ECursor currentCursor)
Window_t fWindow
Definition: GuiTypes.h:177
const NSUInteger kTitledWindowMask
BOOL fIsOpenGLWidget()
const NSUInteger kResizableWindowMask
int GlobalYROOTToCocoa(CGFloat yROOT)
void GenerateButtonPressEvent(NSView< X11Window > *eventView, NSEvent *theEvent, EMouseButton btn)
Definition: X11Events.mm:1264
const Mask_t kWABorderPixmap
Definition: GuiTypes.h:142
unsigned fHeight
Definition: QuartzPixmap.h:103
ULong_t fBackgroundPixel
Definition: GuiTypes.h:96
const Mask_t kPointerMotionMask
Definition: GuiTypes.h:164
void addChild:(NSView< X11Window > *child)
Bool_t fMapInstalled
Definition: GuiTypes.h:130
void SetWindowAttributes(const SetWindowAttributes_t *attr, NSObject< X11Window > *window)
QuartzView * fParentView
Definition: QuartzWindow.h:180
NSMutableDictionary * fX11Properties
Definition: QuartzWindow.h:199
Double_t x[n]
Definition: legend1.C:17
NSPoint GetCursorHotStop(NSImage *image, ECursor cursor)
NSPoint TranslateCoordinates(NSView< X11Window > *fromView, NSView< X11Window > *toView, NSPoint sourcePoint)
QuartzImage * fBackgroundPixmap
Definition: QuartzWindow.h:200
NSPoint ConvertPointFromBaseToScreen(NSWindow *window, NSPoint windowPoint)
ULong_t fBackingPlanes
Definition: GuiTypes.h:126
Handle_t fHandle
Definition: GuiTypes.h:186
QuartzWindow * FindWindowForPointerEvent(NSEvent *pointerEvent)
Handle_t Atom_t
Definition: GuiTypes.h:38
Colormap_t fColormap
Definition: GuiTypes.h:129
unsigned fHeight
Definition: QuartzPixmap.h:46
ROOT::MacOSX::X11::PointerGrab fCurrentGrabType
Definition: QuartzWindow.h:202
QuartzWindow * fQuartzWindow
Definition: QuartzWindow.h:256
CGImageRef CreateSubImage(QuartzImage *image, const Rectangle &area)
const Mask_t kWAColormap
Definition: GuiTypes.h:154
void lowerWindow()
XFontStruct * id
Definition: TGX11.cxx:108
NSPoint TranslateFromScreen(NSPoint point, NSView< X11Window > *to)
void CocoaDrawOFF()
Definition: TGCocoa.mm:4418
NSPoint ConvertPointFromScreenToBase(NSPoint screenPoint, NSWindow *window)
const NSUInteger kClosableWindowMask
const Mask_t kWABackingPlanes
Definition: GuiTypes.h:148
const NSUInteger kMiniaturizableWindowMask
int GlobalXROOTToCocoa(CGFloat xROOT)
const Mask_t kButtonPressMask
Definition: GuiTypes.h:162
NSView< X11Window > * FindViewUnderPointer()
BOOL fHasFocus
Definition: QuartzWindow.h:179
NSPoint TranslateToScreen(NSView< X11Window > *from, NSPoint point)
NSView< X11Window > * FrameForTextView(NSView< X11Window > *textView)
const NSEventType kLeftMouseDown
ROOT::MacOSX::X11::Rectangle GetDisplayGeometry() const
Definition: TGCocoa.mm:542
Long_t fAllEventMasks
Definition: GuiTypes.h:132
int GlobalYCocoaToROOT(CGFloat yCocoa)
bool ViewIsHtmlViewFrame(NSView< X11Window > *view, bool checkParent)
void activatePassiveGrab()
void GenerateExposeEvent(NSView< X11Window > *view, const NSRect &exposedRect)
Definition: X11Events.mm:1180
void setOverlapped:(BOOL overlap)
const Mask_t kWAEventMask
Definition: GuiTypes.h:152
R__EXTERN TSystem * gSystem
Definition: TSystem.h:549
const Mask_t kWASaveUnder
Definition: GuiTypes.h:151
SVector< double, 2 > v
Definition: Dict.h:5
static Atom_t fgDeleteWindowAtom
Definition: TGCocoa.h:469
EGEventType fType
Definition: GuiTypes.h:176
QuartzWindow * FindWindowUnderPointer()
unsigned fHeight()
unsigned fWidth
Definition: QuartzPixmap.h:102
const Mask_t kExposureMask
Definition: GuiTypes.h:166
unsigned int UInt_t
Definition: RtypesCore.h:42
QuartzView * fParentView
Definition: QuartzWindow.h:120
QuartzView * CreateChildView(QuartzView *parent, Int_t x, Int_t y, UInt_t w, UInt_t h, UInt_t border, Int_t depth, UInt_t clss, void *visual, SetWindowAttributes_t *attr, UInt_t wtype)
Definition: QuartzWindow.mm:81
BOOL fIsOverlapped()
void UnlockFocus(NSView< X11Window > *view)
void PixelToRGB(Pixel_t pixelColor, CGFloat *rgb)
Definition: X11Colors.mm:920
long fEventMask
Definition: QuartzWindow.h:171
unsigned fID
Definition: QuartzWindow.h:169
#define gVirtualX
Definition: TVirtualX.h:362
int LocalYROOTToCocoa(NSView< X11Window > *parentView, CGFloat yROOT)
bool ViewIsTextView(unsigned viewID)
unsigned fWidth
Definition: QuartzPixmap.h:45
PyObject * fType
const Mask_t kEnterWindowMask
Definition: GuiTypes.h:168
BOOL fPassiveGrabOwnerEvents
Definition: QuartzWindow.h:186
CGContextRef fContext
Definition: QuartzWindow.h:170
unsigned fWidth()
QuartzWindow * fMainWindow
Definition: QuartzWindow.h:42
BOOL fSnapshotDraw
Definition: QuartzWindow.h:187
const Mask_t kStructureNotifyMask
Definition: GuiTypes.h:167
static Int_t init()
bool ViewIsHtmlView(unsigned viewID)
NSView< X11Window > * FrameForHtmlView(NSView< X11Window > *htmlView)
bool ScreenPointIsInView(NSView< X11Window > *view, Int_t x, Int_t y)
const Mask_t kButtonReleaseMask
Definition: GuiTypes.h:163
const NSEventType kRightMouseDown
int type
Definition: TGX11.cxx:120
const Mask_t kWAOverrideRedirect
Definition: GuiTypes.h:150
unsigned long ULong_t
Definition: RtypesCore.h:51
void GenerateCrossingEvent(NSEvent *theEvent)
Definition: X11Events.mm:1198
Window_t fRoot
Definition: GuiTypes.h:121
Double_t y[n]
Definition: legend1.C:17
const Mask_t kWAWinGravity
Definition: GuiTypes.h:146
void WindowLostFocus(Window_t winID)
void ClipToShapeMask(NSView< X11Window > *view, CGContextRef ctx)
QuartzView * fParentView
Definition: X11Drawable.h:105
NSCursor * CreateCursor(ECursor currentCursor)
Long_t fUser[5]
Definition: GuiTypes.h:188
unsigned long fBackgroundPixel
Definition: QuartzWindow.h:176
unsigned fPassiveGrabKeyModifiers
Definition: QuartzWindow.h:184
BOOL fDelayedTransient
Definition: QuartzWindow.h:47
typedef void((*Func_t)())
Bool_t fOverrideRedirect
Definition: GuiTypes.h:135
Handle_t Window_t
Definition: GuiTypes.h:30
Int_t fFormat
Definition: GuiTypes.h:187
This class implements TVirtualX interface for MacOS X, using Cocoa and Quartz 2D. ...
Definition: TGCocoa.h:58
NSComparisonResult CompareViewsToLower(id view1, id view2, void *context)
unsigned fID
Definition: X11Drawable.h:43
const Mask_t kWABorderWidth
Definition: GuiTypes.h:144
#define NULL
Definition: Rtypes.h:82
void GenerateKeyPressEvent(NSView< X11Window > *eventView, NSEvent *theEvent)
Definition: X11Events.mm:1292
NSComparisonResult CompareViewsToRaise(id view1, id view2, void *context)
BOOL fActiveGrabOwnerEvents
Definition: QuartzWindow.h:204
const Mask_t kWABackPixel
Definition: GuiTypes.h:141
double result[121]
const Mask_t kWABackingPixel
Definition: GuiTypes.h:149
const Mask_t kWADontPropagate
Definition: GuiTypes.h:153
ROOT::MacOSX::X11::EventTranslator * GetEventTranslator() const
Definition: TGCocoa.mm:4400
bool ViewIsTextViewFrame(NSView< X11Window > *view, bool checkParent)
void raiseWindow()
const Bool_t kTRUE
Definition: Rtypes.h:91
void CocoaDrawON()
Definition: TGCocoa.mm:4412
Long_t fYourEventMask
Definition: GuiTypes.h:133
unsigned fActiveGrabEventMask
Definition: QuartzWindow.h:185
void GenerateFocusChangeEvent(NSView< X11Window > *eventView)
Definition: X11Events.mm:1328
unsigned fHeight()
int fPassiveGrabButton
Definition: QuartzWindow.h:182
void GetWindowGeometry(NSObject< X11Window > *win, WindowAttributes_t *dst)
NSMutableArray * fPassiveKeyGrabs
Definition: QuartzWindow.h:196
void activateImplicitGrab()
void GenerateButtonReleaseEvent(NSView< X11Window > *eventView, NSEvent *theEvent, EMouseButton btn)
Definition: X11Events.mm:1277