File: gimppickbutton-quartz.c

package info (click to toggle)
gimp 2.10.8-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 218,716 kB
  • sloc: ansic: 787,125; makefile: 11,685; python: 6,198; lisp: 5,456; sh: 4,486; cpp: 4,114; perl: 3,807; xml: 1,481; yacc: 588; lex: 342
file content (480 lines) | stat: -rw-r--r-- 13,209 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
/* LIBGIMP - The GIMP Library
 * Copyright (C) 1995-1997 Peter Mattis and Spencer Kimball
 *
 * gimppickbutton-quartz.c
 * Copyright (C) 2015 Kristian Rietveld <kris@loopnest.org>
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see
 * <https://www.gnu.org/licenses/>.
 */

#include "config.h"

#include <gegl.h>
#include <gtk/gtk.h>
#include <gdk/gdkkeysyms.h>

#include "libgimpcolor/gimpcolor.h"

#include "gimpwidgetstypes.h"
#include "gimppickbutton.h"
#include "gimppickbutton-quartz.h"

#include "cursors/gimp-color-picker-cursors.c"

#ifdef GDK_WINDOWING_QUARTZ
#import <AppKit/AppKit.h>
#include <Carbon/Carbon.h>  /* For virtual key codes ... */
#include <ApplicationServices/ApplicationServices.h>
#endif

#if MAC_OS_X_VERSION_MAX_ALLOWED < 1070
@interface NSWindow (GIMPExt)
- (NSRect) convertRectToScreen: (NSRect)aRect;
@end
@implementation NSWindow (GIMPExt)
- (NSRect) convertRectToScreen: (NSRect)aRect
{
  NSRect result = aRect;
  NSPoint origin = result.origin;
  result.origin = [self convertBaseToScreen:origin];
  return result;
}
@end
#endif


@interface GimpPickWindowController : NSObject
{
  GimpPickButton *button;
  NSMutableArray *windows;
}

@property (nonatomic, assign) BOOL firstBecameKey;
@property (readonly, retain) NSCursor *cursor;

- (id)initWithButton:(GimpPickButton *)_button;
- (void)updateKeyWindow;
- (void)shutdown;
@end

@interface GimpPickView : NSView
{
  GimpPickButton *button;
  GimpPickWindowController *controller;
}

@property (readonly,assign) NSTrackingArea *area;

- (id)initWithButton:(GimpPickButton *)_button controller:(GimpPickWindowController *)controller;
@end

@implementation GimpPickView

@synthesize area;

- (id)initWithButton:(GimpPickButton *)_button controller:(GimpPickWindowController *)_controller
{
  self = [super init];

  if (self)
    {
      button = _button;
      controller = _controller;
    }

  return self;
}

- (void)dealloc
{
  [self removeTrackingArea:self.area];

  [super dealloc];
}

- (void)viewDidMoveToWindow
{
  NSTrackingAreaOptions options;

  [super viewDidMoveToWindow];

  if ([self window] == nil)
    return;

  options = NSTrackingMouseEnteredAndExited |
            NSTrackingMouseMoved |
            NSTrackingActiveAlways;

  /* Add assume inside if mouse pointer is above this window */
  if (NSPointInRect ([NSEvent mouseLocation], self.window.frame))
    options |= NSTrackingAssumeInside;

  area = [[NSTrackingArea alloc] initWithRect:self.bounds
                                 options:options
                                 owner:self
                                 userInfo:nil];
  [self addTrackingArea:self.area];
}

- (void)mouseEntered:(NSEvent *)event
{
  /* We handle the mouse cursor manually, see also the comment in
   * [GimpPickWindow windowDidBecomeMain below].
   */
  if (controller.cursor)
    [controller.cursor push];
}

- (void)mouseExited:(NSEvent *)event
{
  if (controller.cursor)
    [controller.cursor pop];

  [controller updateKeyWindow];
}

- (void)mouseMoved:(NSEvent *)event
{
  [self pickColor:event];
}

- (void)mouseUp:(NSEvent *)event
{
  [self pickColor:event];

  [controller shutdown];
}

- (void)rightMouseUp:(NSEvent *)event
{
  [self mouseUp:event];
}

- (void)otherMouseUp:(NSEvent *)event
{
  [self mouseUp:event];
}

- (void)keyDown:(NSEvent *)event
{
  if (event.keyCode == kVK_Escape)
    [controller shutdown];
}

- (void)pickColor:(NSEvent *)event
{
  CGImageRef        root_image_ref;
  CFDataRef         pixel_data;
  const guchar     *data;
  GimpRGB           rgb;
  NSPoint           point;
  GimpColorProfile *profile     = NULL;
  CGColorSpaceRef   color_space = NULL;

  /* The event gives us a point in Cocoa window coordinates. The function
   * CGWindowListCreateImage expects a rectangle in screen coordinates
   * with the origin in the upper left (contrary to Cocoa). The origin is
   * on the screen showing the menu bar (this is the screen at index 0 in the
   * screens array). So, after converting the rectangle to Cocoa screen
   * coordinates, we use the height of this particular screen to translate
   * to the coordinate space expected by CGWindowListCreateImage.
   */
  point = event.locationInWindow;
  NSRect rect = NSMakeRect (point.x, point.y,
                            1, 1);
  rect = [self.window convertRectToScreen:rect];
  rect.origin.y = [[[NSScreen screens] objectAtIndex:0] frame].size.height - rect.origin.y;

  root_image_ref = CGWindowListCreateImage (rect,
                                            kCGWindowListOptionOnScreenOnly,
                                            kCGNullWindowID,
                                            kCGWindowImageDefault);
  pixel_data = CGDataProviderCopyData (CGImageGetDataProvider (root_image_ref));
  data = CFDataGetBytePtr (pixel_data);

  color_space = CGImageGetColorSpace (root_image_ref);
  if (color_space)
    {
      CFDataRef icc_data = NULL;

      icc_data = CGColorSpaceCopyICCProfile (color_space);
      if (icc_data)
        {
          UInt8 *buffer = g_malloc (CFDataGetLength (icc_data));

          CFDataGetBytes (icc_data, CFRangeMake (0, CFDataGetLength (icc_data)),
                          buffer);

          profile = gimp_color_profile_new_from_icc_profile (buffer,
                                                             CFDataGetLength (icc_data),
                                                             NULL);
          g_free (buffer);
          CFRelease (icc_data);
        }
    }

  gimp_rgba_set_uchar (&rgb, data[2], data[1], data[0], 255);
  if (profile)
    {
      GimpColorProfile        *srgb_profile;
      GimpColorTransform      *transform;
      const Babl              *format;
      GimpColorTransformFlags  flags = 0;

      format = babl_format ("R'G'B'A double");

      flags |= GIMP_COLOR_TRANSFORM_FLAGS_NOOPTIMIZE;
      flags |= GIMP_COLOR_TRANSFORM_FLAGS_BLACK_POINT_COMPENSATION;

      srgb_profile = gimp_color_profile_new_rgb_srgb ();
      transform = gimp_color_transform_new (profile,      format,
                                            srgb_profile, format,
                                            GIMP_COLOR_RENDERING_INTENT_PERCEPTUAL,
                                            flags);

      if (transform)
        {
          gimp_color_transform_process_pixels (transform,
                                               format, &rgb,
                                               format, &rgb,
                                               1);
          gimp_rgb_clamp (&rgb);

          g_object_unref (transform);
        }
      g_object_unref (srgb_profile);
      g_object_unref (profile);
    }

  CGImageRelease (root_image_ref);
  CFRelease (pixel_data);

  g_signal_emit_by_name (button, "color-picked", &rgb);
}
@end


@interface GimpPickWindow : NSWindow <NSWindowDelegate>
{
  GimpPickWindowController *controller;
}

- (id)initWithButton:(GimpPickButton *)button forScreen:(NSScreen *)screen withController:(GimpPickWindowController *)_controller;
@end

@implementation GimpPickWindow
- (id)initWithButton:(GimpPickButton *)button forScreen:(NSScreen *)screen withController:(GimpPickWindowController *)_controller
{
  self = [super initWithContentRect:screen.frame
                styleMask:NSBorderlessWindowMask
                backing:NSBackingStoreBuffered
                defer:NO];

  if (self)
    {
      GimpPickView *view;

      controller = _controller;

      [self setDelegate:self];

      [self setAlphaValue:0.0];
#if 0
      /* Useful for debugging purposes */
      [self setBackgroundColor:[NSColor redColor]];
      [self setAlphaValue:0.2];
#endif
      [self setIgnoresMouseEvents:NO];
      [self setAcceptsMouseMovedEvents:YES];
      [self setHasShadow:NO];
      [self setOpaque:NO];

      /* Set the highest level, so on top of everything */
      [self setLevel:NSScreenSaverWindowLevel];

      view = [[GimpPickView alloc] initWithButton:button controller:controller];
      [self setContentView:view];
      [self makeFirstResponder:view];
      [view release];

      [self disableCursorRects];
    }

  return self;
}

/* Borderless windows cannot become key/main by default, so we force it
 * to make it so. We need this to receive events.
 */
- (BOOL)canBecomeKeyWindow
{
  return YES;
}

- (BOOL)canBecomeMainWindow
{
  return YES;
}

- (void)windowDidBecomeKey:(NSNotification *)aNotification
{
  /* We cannot use the usual Cocoa method for handling cursor updates,
   * since the GDK Quartz backend is interfering. Additionally, because
   * one of the screen-spanning windows pops up under the mouse pointer this
   * view will not receive a MouseEntered event. So, we synthesize such
   * an event here and the view can set the mouse pointer in response to
   * this. So, this event only has to be synthesized once and only for
   * the window that pops up under the mouse cursor. Synthesizing multiple
   * times messes up the mouse cursor stack.
   *
   * We cannot set the mouse pointer at this moment, because the GDK window
   * will still receive an MouseExited event in which turn it will modify
   * the cursor. So, with this synthesized event we also ensure we set
   * the mouse cursor *after* the GDK window has manipulated the cursor.
   */
  NSEvent *event;

  if (!controller.firstBecameKey ||
      !NSPointInRect ([NSEvent mouseLocation], self.frame))
    return;

  controller.firstBecameKey = NO;

  event = [NSEvent enterExitEventWithType:NSMouseEntered
                   location:[self mouseLocationOutsideOfEventStream]
                   modifierFlags:0
                   timestamp:[[NSApp currentEvent] timestamp]
                   windowNumber:self.windowNumber
                   context:nil
                   eventNumber:0
                   trackingNumber:(NSInteger)[[self contentView] area]
                   userData:nil];

  [NSApp postEvent:event atStart:NO];
}
@end


/* To properly handle multi-monitor setups we need to create a
 * GimpPickWindow for each monitor (NSScreen). This is necessary because
 * a window on Mac OS X (tested on 10.9) cannot span more than one
 * monitor, so any approach that attempts to create one large window
 * spanning all monitors cannot work. So, we have to create multiple
 * windows in case of multi-monitor setups and these different windows
 * are managed by GimpPickWindowController.
 */
@implementation GimpPickWindowController

@synthesize firstBecameKey;
@synthesize cursor;

- (id)initWithButton:(GimpPickButton *)_button;
{
  self = [super init];

  if (self)
    {
      firstBecameKey = YES;
      button = _button;
      cursor = [GimpPickWindowController makePickCursor];

      windows = [[NSMutableArray alloc] init];

      for (NSScreen *screen in [NSScreen screens])
        {
          GimpPickWindow *window;

          window = [[GimpPickWindow alloc] initWithButton:button
                                           forScreen:screen
                                           withController:self];

          [window orderFrontRegardless];
          [window makeMainWindow];

          [windows addObject:window];
        }

      [self updateKeyWindow];
    }

  return self;
}

- (void)updateKeyWindow
{
  for (GimpPickWindow *window in windows)
    {
      if (NSPointInRect ([NSEvent mouseLocation], window.frame))
        [window makeKeyWindow];
    }
}

- (void)shutdown
{
  GtkWidget *window;

  for (GimpPickWindow *window in windows)
    [window close];

  [windows release];

  if (cursor)
    [cursor release];

  /* Give focus back to the window containing the pick button */
  window = gtk_widget_get_toplevel (GTK_WIDGET (button));
  gtk_window_present_with_time (GTK_WINDOW (window), GDK_CURRENT_TIME);

  [self release];
}

+ (NSCursor *)makePickCursor
{
  GBytes    *bytes = NULL;
  GError    *error = NULL;

  bytes = g_resources_lookup_data ("/org/gimp/color-picker-cursors-raw/cursor-color-picker.png",
                                   G_RESOURCE_LOOKUP_FLAGS_NONE, &error);

  if (bytes)
    {
      NSData   *data = [NSData dataWithBytes:g_bytes_get_data (bytes, NULL)
                               length:g_bytes_get_size (bytes)];
      NSImage  *image = [[NSImage alloc] initWithData:data];
      NSCursor *cursor = [[NSCursor alloc] initWithImage:image hotSpot:NSMakePoint(1, 30)];

      [image release];
      g_bytes_unref (bytes);

      return [cursor retain];
    }
  else
    {
      g_critical ("Failed to create cursor image: %s", error->message);
      g_clear_error (&error);
    }

  return NULL;
}
@end

/* entry point to this file, called from gimppickbutton.c */
void
_gimp_pick_button_quartz_pick (GimpPickButton *button)
{
  GimpPickWindowController *controller;
  NSAutoreleasePool        *pool;

  pool = [[NSAutoreleasePool alloc] init];

  controller = [[GimpPickWindowController alloc] initWithButton:button];

  [pool release];
}