summaryrefslogtreecommitdiff
path: root/dggui/nativewindow_cocoa.mm
blob: 9484af79a6fa9e8779ef5ef997b8d6a3e6439242 (plain)
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
/* -*- Mode: ObjC; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/***************************************************************************
 *            nativewindow_cocoa.mm
 *
 *  Fri Dec  2 20:31:03 CET 2016
 *  Copyright 2016 Bent Bisballe Nyeng
 *  deva@aasimon.org
 ****************************************************************************/

/*
 *  This file is part of DrumGizmo.
 *
 *  DrumGizmo is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  DrumGizmo 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 Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with DrumGizmo; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
 */
#include "nativewindow_cocoa.h"

#include "guievent.h"

#include <stdio.h>
#include <unistd.h>

#import <Cocoa/Cocoa.h>

#include "window.h"

#include <Availability.h>

#ifdef __MAC_OS_X_VERSION_MAX_ALLOWED
#if __MAC_OS_X_VERSION_MAX_ALLOWED < 101300 // Before MacOSX 10.13 (High-Sierra)
#define STYLE_MASK                              \
	(NSClosableWindowMask |                       \
	 NSTitledWindowMask |                         \
	 NSResizableWindowMask)
#define IMAGE_FLAGS                             \
	(kCGBitmapByteOrder32Big |                    \
	 kCGImageAlphaPremultipliedLast)
#define EVENT_MASK                              \
	NSAnyEventMask
#else
#define STYLE_MASK                              \
	(NSWindowStyleMaskClosable |                  \
	 NSWindowStyleMaskTitled |                    \
	 NSWindowStyleMaskResizable)
#define IMAGE_FLAGS                             \
	(kCGImageByteOrder32Big |                     \
	 kCGImageAlphaPremultipliedLast)
#define EVENT_MASK                              \
	NSEventMaskAny
#endif

#if __MAC_OS_X_VERSION_MAX_ALLOWED < 101400 // Before MacOSX 10.14 (Mojave)
// Nothing here yet...
#endif
#endif

@interface DGListener : NSWindow
{
@public
	NSWindow* window;
	dggui::NativeWindowCocoa* native;
}

- (id) initWithWindow:(NSWindow*)ref
               native:(dggui::NativeWindowCocoa*)_native;
- (void) dealloc;
- (void) windowDidResize;
- (void) windowWillResize;
- (void) windowWillClose;
- (void) unbindNative;
@end

@implementation DGListener
- (id) initWithWindow:(NSWindow*)ref
               native:(dggui::NativeWindowCocoa*)_native
{
	[super init];

	native = _native;
	window = ref;

	[[NSNotificationCenter defaultCenter]
	  addObserver:self
	     selector:@selector(windowDidResize)
	         name:NSWindowDidResizeNotification
	       object:ref];

	[[NSNotificationCenter defaultCenter]
	  addObserver:self
	     selector:@selector(windowWillResize)
	         name:NSWindowWillStartLiveResizeNotification
	       object:ref];

	[[NSNotificationCenter defaultCenter]
	  addObserver:self
	     selector:@selector(windowWillClose)
	         name:NSWindowWillCloseNotification
	       object:ref];

	[self windowWillResize]; // trigger to get the initial size as a size change

	return self;
}

- (void) dealloc
{
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	[super dealloc];
}

- (void)windowDidResize
{
	if(!native)
	{
		return;
	}

	native->resized();
}

- (void)windowWillResize
{
	if(!native)
	{
		return;
	}

	native->resized();
}

- (void) windowWillClose
{
	if(!native)
	{
		return;
	}

	auto closeEvent = std::make_shared<dggui::CloseEvent>();
	native->pushBackEvent(closeEvent);
}

- (void) unbindNative
{
	native = nullptr;
}
@end

@interface DGView : NSView
{
	int colorBits;
	int depthBits;

@private
	dggui::NativeWindowCocoa* native;
	NSTrackingArea* trackingArea;
}

//- (id) initWithFrame:(NSRect)frame
//           colorBits:(int)numColorBits
//           depthBits:(int)numDepthBits;
- (void) updateTrackingAreas;

- (void) mouseEntered:(NSEvent *)event;
- (void) mouseExited:(NSEvent *)event;
- (void) mouseMoved:(NSEvent*)event;
- (void) mouseDown:(NSEvent*)event;
- (void) mouseUp:(NSEvent*)event;
- (void) rightMouseDown:(NSEvent*)event;
- (void) rightMouseUp:(NSEvent*)event;
- (void) otherMouseDown:(NSEvent*)event;
- (void) otherMouseUp:(NSEvent*)event;
- (void) mouseDragged:(NSEvent*)event;
- (void) rightMouseDragged:(NSEvent*)event;
- (void) otherMouseDragged:(NSEvent*)event;
- (void) scrollWheel:(NSEvent*)event;
- (void) keyDown:(NSEvent*)event;
- (void) keyUp:(NSEvent*)event;

- (void) dealloc;
- (void) bindNative:(dggui::NativeWindowCocoa*)native;
- (void) unbindNative;
@end

@implementation DGView
//- (id) initWithFrame:(NSRect)frame
//           colorBits:(int)numColorBits
//           depthBits:(int)numDepthBits
//{
//	[super init];
//	[self updateTrackingAreas];
//	return self;
//}

- (void) updateTrackingAreas
{
	if(trackingArea != nil)
	{
		[self removeTrackingArea:trackingArea];
		[trackingArea release];
	}

	int opts =
		NSTrackingMouseEnteredAndExited |
		NSTrackingMouseMoved |
		NSTrackingActiveAlways;

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

- (void) mouseEntered:(NSEvent *)event
{
	[super mouseEntered:event];
	auto frame = [self frame];
	NSPoint loc = [event locationInWindow];
	auto mouseEnterEvent = std::make_shared<dggui::MouseEnterEvent>();
	mouseEnterEvent->x = loc.x - frame.origin.x;
	mouseEnterEvent->y = frame.size.height - loc.y - frame.origin.y;
	native->pushBackEvent(mouseEnterEvent);
	//[[NSCursor pointingHandCursor] set];
}

- (void) mouseExited:(NSEvent *)event
{
	[super mouseExited:event];
	auto frame = [self frame];
	NSPoint loc = [event locationInWindow];
	auto mouseLeaveEvent = std::make_shared<dggui::MouseLeaveEvent>();
	mouseLeaveEvent->x = loc.x - frame.origin.x;
	mouseLeaveEvent->y = frame.size.height - loc.y - frame.origin.y;
	native->pushBackEvent(mouseLeaveEvent);
	//[[NSCursor arrowCursor] set];
}

- (void) mouseMoved:(NSEvent*)event
{
	auto frame = [self frame];
	NSPoint loc = [event locationInWindow];
	auto mouseMoveEvent = std::make_shared<dggui::MouseMoveEvent>();
	mouseMoveEvent->x = loc.x - frame.origin.x;
	mouseMoveEvent->y = frame.size.height - loc.y - frame.origin.y;
	native->pushBackEvent(mouseMoveEvent);
}

- (void) mouseDown:(NSEvent*)event
{
	auto frame = [self frame];
	NSPoint loc = [event locationInWindow];

	auto buttonEvent = std::make_shared<dggui::ButtonEvent>();
	buttonEvent->x = loc.x - frame.origin.x;
	buttonEvent->y = frame.size.height - loc.y - frame.origin.y;
	switch((int)[event buttonNumber])
	{
	case 0:
		buttonEvent->button = dggui::MouseButton::left;
		break;
	case 1:
		buttonEvent->button = dggui::MouseButton::right;
		break;
	case 2:
		buttonEvent->button = dggui::MouseButton::middle;
		break;
	default:
		return;
	}
	buttonEvent->direction = dggui::Direction::down;
	buttonEvent->doubleClick = [event clickCount] == 2;
	native->pushBackEvent(buttonEvent);

	[super mouseDown: event];
}

- (void) mouseUp:(NSEvent*)event
{
	auto frame = [self frame];
	NSPoint loc = [event locationInWindow];

	auto buttonEvent = std::make_shared<dggui::ButtonEvent>();
	buttonEvent->x = loc.x - frame.origin.x;
	buttonEvent->y = frame.size.height - loc.y - frame.origin.y;
	switch((int)[event buttonNumber])
	{
	case 0:
		buttonEvent->button = dggui::MouseButton::left;
		break;
	case 1:
		buttonEvent->button = dggui::MouseButton::right;
		break;
	case 2:
		buttonEvent->button = dggui::MouseButton::middle;
		break;
	default:
		return;
	}
	buttonEvent->direction = dggui::Direction::up;
	buttonEvent->doubleClick = false;
	native->pushBackEvent(buttonEvent);

	[super mouseUp: event];
}

- (void) rightMouseDown:(NSEvent*)event
{
	[self mouseDown: event];
	[super rightMouseDown: event];
}

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

- (void) otherMouseDown:(NSEvent*)event
{
	[self mouseDown: event];
	[super otherMouseDown: event];
}

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

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

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

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

- (void) scrollWheel:(NSEvent*)event
{
	auto frame = [self frame];
	NSPoint loc = [event locationInWindow];

	auto scrollEvent = std::make_shared<dggui::ScrollEvent>();
	scrollEvent->x = loc.x - frame.origin.x;
	scrollEvent->y = frame.size.height - loc.y - frame.origin.y;
	scrollEvent->delta = [event deltaY] * -1.0f;
	native->pushBackEvent(scrollEvent);

	[super scrollWheel: event];
}

- (void) keyDown:(NSEvent*)event
{
	const NSString* chars = [event characters];
	const char* str = [chars UTF8String];

	auto keyEvent = std::make_shared<dggui::KeyEvent>();

	switch([event keyCode])
	{
	case 123: keyEvent->keycode = dggui::Key::left; break;
	case 124: keyEvent->keycode = dggui::Key::right; break;
	case 126: keyEvent->keycode = dggui::Key::up; break;
	case 125: keyEvent->keycode = dggui::Key::down; break;
	case 117: keyEvent->keycode = dggui::Key::deleteKey; break;
	case 51:  keyEvent->keycode = dggui::Key::backspace; break;
	case 115: keyEvent->keycode = dggui::Key::home; break;
	case 119: keyEvent->keycode = dggui::Key::end; break;
	case 121: keyEvent->keycode = dggui::Key::pageDown; break;
	case 116: keyEvent->keycode = dggui::Key::pageUp; break;
	case 36:  keyEvent->keycode = dggui::Key::enter; break;
	default:  keyEvent->keycode = dggui::Key::unknown; break;
	}

	if(strlen(str) && keyEvent->keycode == dggui::Key::unknown)
	{
		keyEvent->keycode = dggui::Key::character;
	}

	keyEvent->text = str; // TODO: UTF8 decode
	keyEvent->direction = dggui::Direction::down;

	native->pushBackEvent(keyEvent);
	[super keyDown: event];
}

- (void) keyUp:(NSEvent*)event
{
	const NSString* chars = [event characters];
	const char* str = [chars UTF8String];
	auto keyEvent = std::make_shared<dggui::KeyEvent>();

	switch([event keyCode])
	{
	case 123: keyEvent->keycode = dggui::Key::left; break;
	case 124: keyEvent->keycode = dggui::Key::right; break;
	case 126: keyEvent->keycode = dggui::Key::up; break;
	case 125: keyEvent->keycode = dggui::Key::down; break;
	case 117: keyEvent->keycode = dggui::Key::deleteKey; break;
	case 51:  keyEvent->keycode = dggui::Key::backspace; break;
	case 115: keyEvent->keycode = dggui::Key::home; break;
	case 119: keyEvent->keycode = dggui::Key::end; break;
	case 121: keyEvent->keycode = dggui::Key::pageDown; break;
	case 116: keyEvent->keycode = dggui::Key::pageUp; break;
	case 36:  keyEvent->keycode = dggui::Key::enter; break;
	default:  keyEvent->keycode = dggui::Key::unknown; break;
	}

	if(strlen(str) && keyEvent->keycode == dggui::Key::unknown)
	{
		keyEvent->keycode = dggui::Key::character;
	}

	keyEvent->text = str; // TODO: UTF8 decode
	keyEvent->direction = dggui::Direction::up;

	native->pushBackEvent(keyEvent);
	[super keyUp: event];
}

- (void) dealloc
{
	[super dealloc];
}

- (void)bindNative:(dggui::NativeWindowCocoa*)_native
{
	native = _native;
}

- (void) unbindNative
{
	native = nullptr;
}
@end


namespace dggui
{

struct priv
{
	NSWindow* window;
	DGView* view;
	id listener;
	id parent_view;
	std::uint8_t* pixel_buffer{nullptr};
	std::size_t pixel_buffer_width{0};
	std::size_t pixel_buffer_height{0};
};

NativeWindowCocoa::NativeWindowCocoa(void* native_window, Window& window)
	: window(window)
	, priv(new struct priv())
	, native_window(native_window)
{
	[NSAutoreleasePool new];
	[NSApplication sharedApplication];
	[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];

	priv->view = [DGView new];

	[priv->view bindNative:this];

	if(native_window)
	{
		if(sizeof(std::size_t) == sizeof(unsigned int)) // 32 bit machine
		{
			WindowRef ptr = (WindowRef)native_window;
			priv->window = [[[NSWindow alloc] initWithWindowRef:ptr] retain];
			priv->parent_view = [priv->window contentView];
		}
		else  // 64 bit machine
		{
			priv->parent_view = (NSView*)native_window;
			priv->window = [priv->parent_view window];
		}

		[priv->parent_view addSubview:priv->view];
		[priv->view display];
		[priv->parent_view setNeedsDisplay:YES];
	}
	else
	{
		priv->window =
			[[[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 10, 10)
			                             styleMask:STYLE_MASK
			                               backing:NSBackingStoreBuffered
			                                 defer:NO]
			  retain];
		[priv->window setLevel:NSStatusWindowLevel];
	}

	priv->listener =
		[[[DGListener alloc] initWithWindow:priv->window
		                             native:this]
		  retain];

	if(native_window)
	{
		[[priv->window contentView] addSubview:priv->view];
	}
	else
	{
		[priv->window setReleasedWhenClosed:NO];
		[priv->window setContentView:priv->view];
	}

	scale = [[NSScreen mainScreen] backingScaleFactor];

	[priv->view setWantsLayer:YES];
	[priv->view setLayerContentsPlacement:NSViewLayerContentsPlacementTopLeft];
	[priv->view updateTrackingAreas];

	if(!native_window)
	{
	  hide();
	}
}

NativeWindowCocoa::~NativeWindowCocoa()
{
	// Make the garbage collector able to collect the ObjC objects:
	if(visible())
	{
		hide();
	}

	[priv->listener unbindNative];
	[priv->listener release];

	[priv->view unbindNative];
	[priv->view release];

	if(native_window)
	{
		if(sizeof(std::size_t) == sizeof(unsigned int)) // 32 bit machine
		{
			[priv->window release];
		}
		else
		{
			// in 64-bit the window was not created by us
		}
	}
	else
	{
		[priv->window release];
	}
}

void NativeWindowCocoa::setFixedSize(std::size_t width, std::size_t height)
{
	resize(width, height);
	[priv->window setMinSize:NSMakeSize(width, height + 22)];
	[priv->window setMaxSize:NSMakeSize(width, height + 22)];
}

void NativeWindowCocoa::setAlwaysOnTop(bool always_on_top)
{
	if(always_on_top)
	{
		[priv->window setLevel: NSStatusWindowLevel];
	}
	else
	{
		[priv->window setLevel: NSNormalWindowLevel];
	}
}

void NativeWindowCocoa::resize(std::size_t width, std::size_t height)
{
	[priv->window setContentSize:NSMakeSize(width, height)];
}

std::pair<std::size_t, std::size_t> NativeWindowCocoa::getSize() const
{
	if(native_window)
	{
		auto frame = [priv->parent_view frame];
		return {frame.size.width, frame.size.height - frame.origin.y};
	}
	else
	{
		NSSize size = [priv->view frame].size;
		return {size.width, size.height};
	}
}

bool NativeWindowCocoa::isHiDPI()
{
  float dpi = [priv->window backingScaleFactor];
  return dpi > 1.0f;
}

void NativeWindowCocoa::move(int x, int y)
{
	NSRect screen = [[NSScreen mainScreen] frame];
	[priv->window setFrameTopLeftPoint:NSMakePoint(x, screen.size.height - y)];
}

std::pair<int, int> NativeWindowCocoa::getPosition() const
{
	NSRect screen = [[NSScreen mainScreen] frame];
	NSPoint pos = [[priv->window contentView] frame].origin;
	return {pos.x, screen.size.height - pos.y};
}

void NativeWindowCocoa::show()
{
	if(!native_window)
	{
		[priv->window makeKeyAndOrderFront:priv->window];
		[NSApp activateIgnoringOtherApps:YES];
	}
}

void NativeWindowCocoa::hide()
{
	if(!native_window)
	{
		[priv->window orderOut:priv->window];
	}
}

bool NativeWindowCocoa::visible() const
{
	return [priv->window isVisible];
}

void NativeWindowCocoa::redraw(const Rect& dirty_rect)
{
	NSSize size;
	if(native_window)
	{
		size = [priv->parent_view frame].size;
	}
	else
	{
		size = [priv->view frame].size;
	}

	std::size_t width = size.width;
	std::size_t height = size.height;

	if(priv->pixel_buffer == nullptr ||
	   priv->pixel_buffer_width != width ||
	   priv->pixel_buffer_height != height)
	{
		if(priv->pixel_buffer) delete[] priv->pixel_buffer;
		priv->pixel_buffer = new std::uint8_t[width * height * 4];
		priv->pixel_buffer_width = width;
		priv->pixel_buffer_height = height;
	}

	CGColorSpaceRef rgb = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
	CGContextRef gc =
		CGBitmapContextCreate(priv->pixel_buffer, width, height,
		                      8, width * 4, rgb,
		                      IMAGE_FLAGS);
	CGColorSpaceRelease(rgb);

	size_t pitch = CGBitmapContextGetBytesPerRow(gc);
	uint8_t *buffer = (uint8_t *)CGBitmapContextGetData(gc);

	struct Pixel
	{
		std::uint8_t red;
		std::uint8_t green;
		std::uint8_t blue;
		std::uint8_t alpha;
	};
	std::uint8_t* pixels = window.wpixbuf.buf;
	for(std::size_t y = dirty_rect.y1; y < std::min(dirty_rect.y2, height); ++y)
	{
		Pixel *row = (Pixel *)(buffer + y * pitch);
		for(std::size_t x = dirty_rect.x1; x < std::min(dirty_rect.x2, width); ++x)
		{
			row[x] = *(Pixel*)&pixels[(y * width + x) * 3];
			row[x].alpha = 0xff;
		}
	}
	CGImageRef image = CGBitmapContextCreateImage(gc);
	CGContextRelease(gc);

	auto nsImage = [[NSImage alloc] initWithCGImage:image size:NSZeroSize];

	id layerContents = [nsImage layerContentsForContentsScale:scale];
	[[priv->view layer] setContents:layerContents];
	updateLayerOffset();
	[[priv->view layer] setContentsScale:scale];
}

void NativeWindowCocoa::setCaption(const std::string &caption)
{
	NSString* title =
		[NSString stringWithCString:caption.data()
		                   encoding:[NSString defaultCStringEncoding]];
	[priv->window setTitle:title];
}

void NativeWindowCocoa::grabMouse(bool grab)
{
}

void NativeWindowCocoa::updateLayerOffset()
{
	if(native_window)
	{
		//auto r1 = [priv->parent_view frame];
		auto r2 = [priv->view frame];

		CATransform3D t = [[priv->view layer] transform];
		if(t.m42 != -r2.origin.y)
		{
			t.m42 = -r2.origin.y; // y
			[[priv->view layer] setTransform:t];
		}
	}
}

EventQueue NativeWindowCocoa::getEvents()
{
	if(first)
	{
		resized();
		first = false;
	}

	// If this is the root window, process the events - event processing will
	// be handled by the hosting window if the window is embedded.
	if(!native_window)
	{
		NSEvent* event = nil;
		do
		{
			event = [NSApp nextEventMatchingMask:EVENT_MASK
			                           untilDate:[NSDate distantPast]
			                              inMode:NSDefaultRunLoopMode
			                             dequeue:YES];
			[NSApp sendEvent:event];
		}
		while(event != nil);
	}

	EventQueue events;
	std::swap(events, event_queue);
	return events;
}

void* NativeWindowCocoa::getNativeWindowHandle() const
{
	if(sizeof(std::size_t) == sizeof(unsigned int)) // 32 bit machine
	{
		return [priv->window windowRef];
	}
	else // 64 bit machine
	{
		return [priv->window contentView];
	}
}

Point NativeWindowCocoa::translateToScreen(const Point& point)
{
	NSRect e = [[NSScreen mainScreen] frame];
	NSRect frame;
	if(native_window)
	{
		frame = [priv->parent_view frame];
	}
	else
	{
		frame = [priv->view frame];
	}

	NSRect rect { { point.x + frame.origin.x,
	                frame.size.height - point.y + frame.origin.y},
	              {0.0, 0.0} };
	rect = [priv->window convertRectToScreen:rect];

	return { (int)rect.origin.x, (int)(e.size.height - rect.origin.y) };
}

Window& NativeWindowCocoa::getWindow()
{
	return window;
}

PixelBuffer& NativeWindowCocoa::getWindowPixbuf()
{
	window.updateBuffer();
	return window.wpixbuf;
}

void NativeWindowCocoa::resized()
{
	if(native_window)
	{
		NSRect frame = [priv->parent_view frame];
		[priv->view setFrame:frame];
		[priv->view updateTrackingAreas];
		updateLayerOffset();
	}

	auto resizeEvent = std::make_shared<dggui::ResizeEvent>();
	resizeEvent->width = 42; // size is not actually used
	resizeEvent->height = 42; // size is not actually used
	pushBackEvent(resizeEvent);
}

void NativeWindowCocoa::pushBackEvent(std::shared_ptr<Event> event)
{
	event_queue.push_back(event);
}

} // dggui::