window_cocoa.mm 29 KB
Newer Older
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
/* The file is the modified version of window_cocoa.mm from opencv-cocoa project by Andre Cohen */

/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                         License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2010, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of Intel Corporation may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
43
#include "precomp.hpp"
44

45 46 47 48
#import <TargetConditionals.h>

#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
/*** begin IPhone OS Stubs ***/
49 50
// When highgui functions are referred to on iPhone OS, they will fail silently.
CV_IMPL int cvInitSystem( int argc, char** argv) { return 0;}
51 52 53 54 55 56 57 58 59 60 61 62 63
CV_IMPL int cvStartWindowThread(){ return 0; }
CV_IMPL void cvDestroyWindow( const char* name) {}
CV_IMPL void cvDestroyAllWindows( void ) {}
CV_IMPL void cvShowImage( const char* name, const CvArr* arr) {}
CV_IMPL void cvResizeWindow( const char* name, int width, int height) {}
CV_IMPL void cvMoveWindow( const char* name, int x, int y){}
CV_IMPL int cvCreateTrackbar (const char* trackbar_name,const char* window_name,
                              int* val, int count, CvTrackbarCallback on_notify) {return  0;}
CV_IMPL int cvCreateTrackbar2(const char* trackbar_name,const char* window_name,
                              int* val, int count, CvTrackbarCallback2 on_notify2, void* userdata) {return 0;}
CV_IMPL void cvSetMouseCallback( const char* name, CvMouseCallback function, void* info) {}
CV_IMPL int cvGetTrackbarPos( const char* trackbar_name, const char* window_name ) {return 0;}
CV_IMPL void cvSetTrackbarPos(const char* trackbar_name, const char* window_name, int pos) {}
64
CV_IMPL void* cvGetWindowHandle( const char* name ) {return NULL;}
65 66 67 68 69 70
CV_IMPL const char* cvGetWindowName( void* window_handle ) {return NULL;}
CV_IMPL int cvNamedWindow( const char* name, int flags ) {return 0; }
CV_IMPL int cvWaitKey (int maxWait) {return 0;}
//*** end IphoneOS Stubs ***/
#else

71
#import <Cocoa/Cocoa.h>
72

73 74
#include <iostream>

75
const int TOP_BORDER  = 7;
76
const int MIN_SLIDER_WIDTH=200;
77 78 79 80 81 82 83

static NSApplication *application = nil;
static NSAutoreleasePool *pool = nil;
static NSMutableDictionary *windows = nil;
static bool wasInitialized = false;

@interface CVView : NSView {
84
    NSImage *image;
85
}
86
@property(retain) NSImage *image;
87 88 89 90
- (void)setImageData:(CvArr *)arr;
@end

@interface CVSlider : NSView {
91 92 93 94 95 96
    NSSlider *slider;
    NSTextField *name;
    int *value;
    void *userData;
    CvTrackbarCallback callback;
    CvTrackbarCallback2 callback2;
97
}
98 99
@property(retain) NSSlider *slider;
@property(retain) NSTextField *name;
100 101 102 103 104 105 106
@property(assign) int *value;
@property(assign) void *userData;
@property(assign) CvTrackbarCallback callback;
@property(assign) CvTrackbarCallback2 callback2;
@end

@interface CVWindow : NSWindow {
107 108 109 110 111
    NSMutableDictionary *sliders;
    CvMouseCallback mouseCallback;
    void *mouseParam;
    BOOL autosize;
    BOOL firstContent;
112
    int status;
113 114 115 116
}
@property(assign) CvMouseCallback mouseCallback;
@property(assign) void *mouseParam;
@property(assign) BOOL autosize;
117
@property(assign) BOOL firstContent;
118
@property(retain) NSMutableDictionary *sliders;
119
@property(readwrite) int status;
120 121 122 123 124 125
- (CVView *)contentView;
- (void)cvSendMouseEvent:(NSEvent *)event type:(int)type flags:(int)flags;
- (void)cvMouseEvent:(NSEvent *)event;
- (void)createSliderWithName:(const char *)name maxValue:(int)max value:(int *)value callback:(CvTrackbarCallback)callback;
@end

126
/*static void icvCocoaCleanup(void)
127
{
128
    //cout << "icvCocoaCleanup" << endl;
129 130
    if( application )
    {
131
        cvDestroyAllWindows();
132
        //[application terminate:nil];
133 134 135
        application = 0;
        [pool release];
    }
136
}*/
137

Andrey Kamaev's avatar
Andrey Kamaev committed
138
CV_IMPL int cvInitSystem( int , char** )
139
{
140 141 142 143 144 145
    //cout << "cvInitSystem" << endl;
    wasInitialized = true;

    pool = [[NSAutoreleasePool alloc] init];
    application = [NSApplication sharedApplication];
    windows = [[NSMutableDictionary alloc] init];
146 147

#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
148

149 150 151 152 153 154
#ifndef NSAppKitVersionNumber10_5
#define NSAppKitVersionNumber10_5 949
#endif
    if( floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_5 )
        [application setActivationPolicy:0/*NSApplicationActivationPolicyRegular*/];
#endif
155 156
    //[application finishLaunching];
    //atexit(icvCocoaCleanup);
157

158 159 160
    return 0;
}

Andrey Kamaev's avatar
Andrey Kamaev committed
161
static CVWindow *cvGetWindow(const char *name) {
162 163 164 165 166 167 168 169 170 171
    //cout << "cvGetWindow" << endl;
    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];
    NSString *cvname = [NSString stringWithFormat:@"%s", name];
    CVWindow* retval = (CVWindow*) [windows valueForKey:cvname] ;
    //cout << "retain count: " << [retval retainCount] << endl;
    //retval = [retval retain];
    //cout << "retain count: " << [retval retainCount] << endl;
    [localpool drain];
    //cout << "retain count: " << [retval retainCount] << endl;
    return retval;
172 173 174 175
}

CV_IMPL int cvStartWindowThread()
{
176
    //cout << "cvStartWindowThread" << endl;
177 178 179 180 181
    return 0;
}

CV_IMPL void cvDestroyWindow( const char* name)
{
182 183 184 185 186 187 188 189 190

    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];
    //cout << "cvDestroyWindow" << endl;
    CVWindow *window = cvGetWindow(name);
    if(window) {
        [window close];
        [windows removeObjectForKey:[NSString stringWithFormat:@"%s", name]];
    }
    [localpool drain];
191 192 193 194 195
}


CV_IMPL void cvDestroyAllWindows( void )
{
196 197 198 199 200
    //cout << "cvDestroyAllWindows" << endl;
    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];
    NSDictionary* list = [NSDictionary dictionaryWithDictionary:windows];
    for(NSString *key in list) {
        cvDestroyWindow([key cStringUsingEncoding:NSASCIIStringEncoding]);
201
    }
202
    [localpool drain];
203 204 205 206 207
}


CV_IMPL void cvShowImage( const char* name, const CvArr* arr)
{
208 209 210
    //cout << "cvShowImage" << endl;
    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];
    CVWindow *window = cvGetWindow(name);
211 212 213 214 215
    if(!window)
    {
        cvNamedWindow(name, CV_WINDOW_AUTOSIZE);
        window = cvGetWindow(name);
    }
216 217

    if(window)
218 219 220 221
    {
        bool empty = [[window contentView] image] == nil;
        NSRect rect = [window frame];
        NSRect vrectOld = [[window contentView] frame];
222 223 224

        [[window contentView] setImageData:(CvArr *)arr];
        if([window autosize] || [window firstContent] || empty)
225
        {
226 227 228 229 230 231
            //Set new view size considering sliders (reserve height and min width)
            NSRect vrectNew = vrectOld;
            int slider_height = 0;
            for(NSString *key in [window sliders]) {
                slider_height += [[[window sliders] valueForKey:key] frame].size.height;
            }
232 233 234 235
            vrectNew.size.height = [[[window contentView] image] size].height + slider_height;
            vrectNew.size.width = std::max<int>([[[window contentView] image] size].width, MIN_SLIDER_WIDTH);
            [[window contentView]  setFrameSize:vrectNew.size]; //adjust sliders to fit new window size

236 237
            rect.size.width += vrectNew.size.width - vrectOld.size.width;
            rect.size.height += vrectNew.size.height - vrectOld.size.height;
238 239
            rect.origin.y -= vrectNew.size.height - vrectOld.size.height;

240
            [window setFrame:rect display:YES];
241
        }
242
        else
243 244 245 246
            [window display];
        [window setFirstContent:NO];
    }
    [localpool drain];
247 248 249 250
}

CV_IMPL void cvResizeWindow( const char* name, int width, int height)
{
251

252 253 254 255 256 257 258 259 260 261
    //cout << "cvResizeWindow" << endl;
    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];
    CVWindow *window = cvGetWindow(name);
    if(window) {
        NSRect frame = [window frame];
        frame.size.width = width;
        frame.size.height = height;
        [window setFrame:frame display:YES];
    }
    [localpool drain];
262 263 264 265
}

CV_IMPL void cvMoveWindow( const char* name, int x, int y)
{
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283

    CV_FUNCNAME("cvMoveWindow");
    __BEGIN__;

    NSAutoreleasePool* localpool1 = [[NSAutoreleasePool alloc] init];
    CVWindow *window = nil;

    if(name == NULL)
        CV_ERROR( CV_StsNullPtr, "NULL window name" );
    //cout << "cvMoveWindow"<< endl;
    window = cvGetWindow(name);
    if(window) {
        y = [[window screen] frame].size.height - y;
        [window setFrameTopLeftPoint:NSMakePoint(x, y)];
    }
    [localpool1 drain];

    __END__;
284 285 286 287 288 289 290
}

CV_IMPL int cvCreateTrackbar (const char* trackbar_name,
                              const char* window_name,
                              int* val, int count,
                              CvTrackbarCallback on_notify)
{
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
    CV_FUNCNAME("cvCreateTrackbar");


    int result = 0;
    CVWindow *window = nil;
    NSAutoreleasePool* localpool2 = nil;

    __BEGIN__;
    if (localpool2 != nil) [localpool2 drain];
    localpool2 = [[NSAutoreleasePool alloc] init];

    if(window_name == NULL)
        CV_ERROR( CV_StsNullPtr, "NULL window name" );

    //cout << "cvCreateTrackbar" << endl ;
    window = cvGetWindow(window_name);
    if(window) {
        [window createSliderWithName:trackbar_name
                            maxValue:count
                               value:val
                            callback:on_notify];
        result = 1;
    }
    [localpool2 drain];
    __END__;
    return result;
317 318 319 320 321 322 323 324 325
}


CV_IMPL int cvCreateTrackbar2(const char* trackbar_name,
                              const char* window_name,
                              int* val, int count,
                              CvTrackbarCallback2 on_notify2,
                              void* userdata)
{
326 327 328 329 330 331 332 333 334 335
    //cout <<"cvCreateTrackbar2" << endl;
    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];
    int res = cvCreateTrackbar(trackbar_name, window_name, val, count, NULL);
    if(res) {
        CVSlider *slider = [[cvGetWindow(window_name) sliders] valueForKey:[NSString stringWithFormat:@"%s", trackbar_name]];
        [slider setCallback2:on_notify2];
        [slider setUserData:userdata];
    }
    [localpool drain];
    return res;
336 337 338 339 340 341
}


CV_IMPL void
cvSetMouseCallback( const char* name, CvMouseCallback function, void* info)
{
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
    CV_FUNCNAME("cvSetMouseCallback");

    CVWindow *window = nil;
    NSAutoreleasePool* localpool3 = nil;
    __BEGIN__;
    //cout << "cvSetMouseCallback" << endl;

    if (localpool3 != nil) [localpool3 drain];
    localpool3 = [[NSAutoreleasePool alloc] init];

    if(name == NULL)
        CV_ERROR( CV_StsNullPtr, "NULL window name" );

    window = cvGetWindow(name);
    if(window) {
        [window setMouseCallback:function];
        [window setMouseParam:info];
    }
    [localpool3 drain];

    __END__;
363 364 365 366
}

 CV_IMPL int cvGetTrackbarPos( const char* trackbar_name, const char* window_name )
{
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
    CV_FUNCNAME("cvGetTrackbarPos");

    CVWindow *window = nil;
    int pos = -1;
    NSAutoreleasePool* localpool4 = nil;
    __BEGIN__;

    //cout << "cvGetTrackbarPos" << endl;
    if(trackbar_name == NULL || window_name == NULL)
        CV_ERROR( CV_StsNullPtr, "NULL trackbar or window name" );

    if (localpool4 != nil) [localpool4 drain];
    localpool4 = [[NSAutoreleasePool alloc] init];

    window = cvGetWindow(window_name);
    if(window) {
        CVSlider *slider = [[window sliders] valueForKey:[NSString stringWithFormat:@"%s", trackbar_name]];
        if(slider) {
            pos = [[slider slider] intValue];
        }
    }
    [localpool4 drain];
    __END__;
    return pos;
391 392 393 394
}

CV_IMPL void cvSetTrackbarPos(const char* trackbar_name, const char* window_name, int pos)
{
395 396 397 398 399 400 401 402 403 404 405 406
    CV_FUNCNAME("cvSetTrackbarPos");

    CVWindow *window = nil;
    CVSlider *slider = nil;
    NSAutoreleasePool* localpool5 = nil;

    __BEGIN__;
    //cout << "cvSetTrackbarPos" << endl;
    if(trackbar_name == NULL || window_name == NULL)
        CV_ERROR( CV_StsNullPtr, "NULL trackbar or window name" );

    if(pos < 0)
407
        CV_ERROR( CV_StsOutOfRange, "Bad trackbar maximal value" );
408 409 410 411 412 413 414 415 416 417 418 419 420 421

    if (localpool5 != nil) [localpool5 drain];
    localpool5 = [[NSAutoreleasePool alloc] init];

    window = cvGetWindow(window_name);
    if(window) {
        slider = [[window sliders] valueForKey:[NSString stringWithFormat:@"%s", trackbar_name]];
        if(slider) {
            [[slider slider] setIntValue:pos];
        }
    }
    [localpool5 drain];

    __END__;
422 423 424 425
}

CV_IMPL void* cvGetWindowHandle( const char* name )
{
426 427
    //cout << "cvGetWindowHandle" << endl;
    return cvGetWindow(name);
428 429 430 431
}


CV_IMPL const char* cvGetWindowName( void* window_handle )
432 433 434 435 436 437 438 439 440 441 442
{
    //cout << "cvGetWindowName" << endl;
    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];
    for(NSString *key in windows) {
        if([windows valueForKey:key] == window_handle) {
            [localpool drain];
            return [key UTF8String];
        }
    }
    [localpool drain];
    return 0;
443 444 445 446 447 448
}

CV_IMPL int cvNamedWindow( const char* name, int flags )
{
    if( !wasInitialized )
        cvInitSystem(0, 0);
449 450 451 452

    //cout << "cvNamedWindow" << endl;
    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];
    CVWindow *window = cvGetWindow(name);
453 454 455
    if( window )
    {
        [window setAutosize:(flags == CV_WINDOW_AUTOSIZE)];
456
        [localpool drain];
457 458
        return 0;
    }
459 460 461 462 463 464 465 466 467 468 469 470 471 472

    NSScreen* mainDisplay = [NSScreen mainScreen];

    NSString *windowName = [NSString stringWithFormat:@"%s", name];
    NSUInteger showResize = (flags == CV_WINDOW_AUTOSIZE) ? 0: NSResizableWindowMask ;
    NSUInteger styleMask = NSTitledWindowMask|NSMiniaturizableWindowMask|showResize;
    CGFloat windowWidth = [NSWindow minFrameWidthWithTitle:windowName styleMask:styleMask];
    NSRect initContentRect = NSMakeRect(0, 0, windowWidth, 0);
    if (mainDisplay) {
        NSRect dispFrame = [mainDisplay visibleFrame];
        initContentRect.origin.y = dispFrame.size.height-20;
    }


473
    window = [[CVWindow alloc] initWithContentRect:initContentRect
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
                                         styleMask:NSTitledWindowMask|NSMiniaturizableWindowMask|showResize
                                           backing:NSBackingStoreBuffered
                                             defer:YES
                                            screen:mainDisplay];

    [window setFrameTopLeftPoint:initContentRect.origin];

    [window setFirstContent:YES];

    [window setContentView:[[CVView alloc] init]];

    [window setHasShadow:YES];
    [window setAcceptsMouseMovedEvents:YES];
    [window useOptimizedDrawing:YES];
    [window setTitle:windowName];
    [window makeKeyAndOrderFront:nil];

    [window setAutosize:(flags == CV_WINDOW_AUTOSIZE)];

    [windows setValue:window forKey:windowName];

    [localpool drain];
    return [windows count]-1;
497 498 499 500
}

CV_IMPL int cvWaitKey (int maxWait)
{
501
    //cout << "cvWaitKey" << endl;
502
    int returnCode = -1;
503
    NSAutoreleasePool *localpool = [[NSAutoreleasePool alloc] init];
504 505 506 507 508
    double start = [[NSDate date] timeIntervalSince1970];

    while(true) {
        if(([[NSDate date] timeIntervalSince1970] - start) * 1000 >= maxWait && maxWait>0)
            break;
509

510
        //event = [application currentEvent];
511 512
        [localpool drain];
        localpool = [[NSAutoreleasePool alloc] init];
513

514 515 516 517 518 519 520
        NSEvent *event =
        [application
         nextEventMatchingMask:NSAnyEventMask
         untilDate://[NSDate dateWithTimeIntervalSinceNow: 1./100]
         [NSDate distantPast]
         inMode:NSDefaultRunLoopMode
         dequeue:YES];
521 522 523

        if([event type] == NSKeyDown) {
            returnCode = [[event characters] characterAtIndex:0];
524
            break;
525 526
        }

527 528
        [application sendEvent:event];
        [application updateWindows];
529 530 531

        [NSThread sleepForTimeInterval:1/100.];
    }
532
    [localpool drain];
533

534
    return returnCode;
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
double cvGetModeWindow_COCOA( const char* name )
{
    double result = -1;
    CVWindow *window = nil;

    CV_FUNCNAME( "cvGetModeWindow_COCOA" );

    __BEGIN__;
    if( name == NULL )
    {
        CV_ERROR( CV_StsNullPtr, "NULL name string" );
    }

    window = cvGetWindow( name );
    if ( window == NULL )
    {
        CV_ERROR( CV_StsNullPtr, "NULL window" );
    }

    result = window.status;

    __END__;
    return result;
}

void cvSetModeWindow_COCOA( const char* name, double prop_value )
{
    CVWindow *window = nil;
    NSDictionary *fullscreenOptions = nil;
    NSAutoreleasePool* localpool = nil;

    CV_FUNCNAME( "cvSetModeWindow_COCOA" );

    __BEGIN__;
    if( name == NULL )
    {
        CV_ERROR( CV_StsNullPtr, "NULL name string" );
    }

    window = cvGetWindow(name);
    if ( window == NULL )
    {
        CV_ERROR( CV_StsNullPtr, "NULL window" );
    }

    if ( [window autosize] )
    {
        return;
    }

    localpool = [[NSAutoreleasePool alloc] init];

    fullscreenOptions = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:NSFullScreenModeSetting];
    if ( [[window contentView] isInFullScreenMode] && prop_value==CV_WINDOW_NORMAL )
    {
        [[window contentView] exitFullScreenModeWithOptions:fullscreenOptions];
        window.status=CV_WINDOW_NORMAL;
    }
    else if( ![[window contentView] isInFullScreenMode] && prop_value==CV_WINDOW_FULLSCREEN )
    {
        [[window contentView] enterFullScreenMode:[NSScreen mainScreen] withOptions:fullscreenOptions];
        window.status=CV_WINDOW_FULLSCREEN;
    }

    [localpool drain];

    __END__;
}

606
@implementation CVWindow
607 608 609 610

@synthesize mouseCallback;
@synthesize mouseParam;
@synthesize autosize;
611
@synthesize firstContent;
612
@synthesize sliders;
613
@synthesize status;
614 615

- (void)cvSendMouseEvent:(NSEvent *)event type:(int)type flags:(int)flags {
Andrey Kamaev's avatar
Andrey Kamaev committed
616
    (void)event;
617 618 619
    //cout << "cvSendMouseEvent" << endl;
    NSPoint mp = [NSEvent mouseLocation];
    //NSRect visible = [[self contentView] frame];
620 621 622 623 624 625 626 627 628 629
    mp = [self convertScreenToBase: mp];
    double viewHeight = [self contentView].frame.size.height;
    double viewWidth = [self contentView].frame.size.width;
    CVWindow *window = (CVWindow *)[[self contentView] window];
    for(NSString *key in [window sliders]) {
        NSSlider *slider = [[window sliders] valueForKey:key];
        viewHeight = std::min(viewHeight, (double)([slider frame].origin.y));
    }
    viewHeight -= TOP_BORDER;
    mp.y = viewHeight - mp.y;
630

631 632 633 634
    NSImage* image = ((CVView*)[self contentView]).image;
    NSSize imageSize = [image size];
    mp.x = mp.x * imageSize.width / std::max(viewWidth, 1.);
    mp.y = mp.y * imageSize.height / std::max(viewHeight, 1.);
635

636 637 638 639 640
    if( mp.x >= 0 && mp.y >= 0 && mp.x < imageSize.width && mp.y < imageSize.height )
        mouseCallback(type, mp.x, mp.y, flags, mouseParam);
}

- (void)cvMouseEvent:(NSEvent *)event {
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
    //cout << "cvMouseEvent" << endl;
    if(!mouseCallback)
        return;

    int flags = 0;
    if([event modifierFlags] & NSShiftKeyMask)		flags |= CV_EVENT_FLAG_SHIFTKEY;
    if([event modifierFlags] & NSControlKeyMask)	flags |= CV_EVENT_FLAG_CTRLKEY;
    if([event modifierFlags] & NSAlternateKeyMask)	flags |= CV_EVENT_FLAG_ALTKEY;

    if([event type] == NSLeftMouseDown)	{[self cvSendMouseEvent:event type:CV_EVENT_LBUTTONDOWN flags:flags | CV_EVENT_FLAG_LBUTTON];}
    if([event type] == NSLeftMouseUp)	{[self cvSendMouseEvent:event type:CV_EVENT_LBUTTONUP   flags:flags | CV_EVENT_FLAG_LBUTTON];}
    if([event type] == NSRightMouseDown){[self cvSendMouseEvent:event type:CV_EVENT_RBUTTONDOWN flags:flags | CV_EVENT_FLAG_RBUTTON];}
    if([event type] == NSRightMouseUp)	{[self cvSendMouseEvent:event type:CV_EVENT_RBUTTONUP   flags:flags | CV_EVENT_FLAG_RBUTTON];}
    if([event type] == NSOtherMouseDown){[self cvSendMouseEvent:event type:CV_EVENT_MBUTTONDOWN flags:flags];}
    if([event type] == NSOtherMouseUp)	{[self cvSendMouseEvent:event type:CV_EVENT_MBUTTONUP   flags:flags];}
    if([event type] == NSMouseMoved)	{[self cvSendMouseEvent:event type:CV_EVENT_MOUSEMOVE   flags:flags];}
    if([event type] == NSLeftMouseDragged) {[self cvSendMouseEvent:event type:CV_EVENT_MOUSEMOVE   flags:flags | CV_EVENT_FLAG_LBUTTON];}
    if([event type] == NSRightMouseDragged)	{[self cvSendMouseEvent:event type:CV_EVENT_MOUSEMOVE   flags:flags | CV_EVENT_FLAG_RBUTTON];}
    if([event type] == NSOtherMouseDragged)	{[self cvSendMouseEvent:event type:CV_EVENT_MOUSEMOVE   flags:flags | CV_EVENT_FLAG_MBUTTON];}
660 661
}
- (void)keyDown:(NSEvent *)theEvent {
662 663
    //cout << "keyDown" << endl;
    [super keyDown:theEvent];
664 665
}
- (void)rightMouseDragged:(NSEvent *)theEvent {
666 667
    //cout << "rightMouseDragged" << endl ;
    [self cvMouseEvent:theEvent];
668 669
}
- (void)rightMouseUp:(NSEvent *)theEvent {
670 671
    //cout << "rightMouseUp" << endl;
    [self cvMouseEvent:theEvent];
672 673
}
- (void)rightMouseDown:(NSEvent *)theEvent {
674 675 676
    // Does not seem to work?
    //cout << "rightMouseDown" << endl;
    [self cvMouseEvent:theEvent];
677 678
}
- (void)mouseMoved:(NSEvent *)theEvent {
679
    [self cvMouseEvent:theEvent];
680 681
}
- (void)otherMouseDragged:(NSEvent *)theEvent {
682
    [self cvMouseEvent:theEvent];
683 684
}
- (void)otherMouseUp:(NSEvent *)theEvent {
685
    [self cvMouseEvent:theEvent];
686 687
}
- (void)otherMouseDown:(NSEvent *)theEvent {
688
    [self cvMouseEvent:theEvent];
689 690
}
- (void)mouseDragged:(NSEvent *)theEvent {
691
    [self cvMouseEvent:theEvent];
692 693
}
- (void)mouseUp:(NSEvent *)theEvent {
694
    [self cvMouseEvent:theEvent];
695 696
}
- (void)mouseDown:(NSEvent *)theEvent {
697
    [self cvMouseEvent:theEvent];
698 699 700
}

- (void)createSliderWithName:(const char *)name maxValue:(int)max value:(int *)value callback:(CvTrackbarCallback)callback {
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
    //cout << "createSliderWithName" << endl;
    if(sliders == nil)
        sliders = [[NSMutableDictionary alloc] init];

    NSString *cvname = [NSString stringWithFormat:@"%s", name];

    // Avoid overwriting slider
    if([sliders valueForKey:cvname]!=nil)
        return;

    // Create slider
    CVSlider *slider = [[CVSlider alloc] init];
    [[slider name] setStringValue:cvname];
    [[slider slider] setMaxValue:max];
    [[slider slider] setMinValue:0];
    [[slider slider] setNumberOfTickMarks:(max+1)];
    [[slider slider] setAllowsTickMarkValuesOnly:YES];
    if(value)
719
    {
720
        [[slider slider] setIntValue:*value];
721 722
        [slider setValue:value];
    }
723 724 725 726 727 728 729
    if(callback)
        [slider setCallback:callback];

    // Save slider
    [sliders setValue:slider forKey:cvname];
    [[self contentView] addSubview:slider];

730

731 732 733 734 735
    //update contentView size to contain sliders
    NSSize viewSize=[[self contentView] frame].size,
           sliderSize=[slider frame].size;
    viewSize.height += sliderSize.height;
    viewSize.width = std::max<int>(viewSize.width, MIN_SLIDER_WIDTH);
736

737 738 739 740 741 742 743 744 745
    // Update slider sizes
    [[self contentView] setFrameSize:viewSize];
    [[self contentView] setNeedsDisplay:YES];

    //update window size to contain sliders
    NSRect rect = [self frame];
    rect.size.height += [slider frame].size.height;
    rect.size.width = std::max<int>(rect.size.width, MIN_SLIDER_WIDTH);
    [self setFrame:rect display:YES];
746 747 748



749 750 751
}

- (CVView *)contentView {
752
    return (CVView*)[super contentView];
753 754 755 756
}

@end

757
@implementation CVView
758 759 760 761

@synthesize image;

- (id)init {
762 763 764 765
    //cout << "CVView init" << endl;
    [super init];
    image = [[NSImage alloc] init];
    return self;
766 767 768
}

- (void)setImageData:(CvArr *)arr {
769 770 771 772 773 774 775 776 777 778
    //cout << "setImageData" << endl;
    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];
    CvMat *arrMat, *cvimage, stub;

    arrMat = cvGetMat(arr, &stub);

    cvimage = cvCreateMat(arrMat->rows, arrMat->cols, CV_8UC3);
    cvConvertImage(arrMat, cvimage, CV_CVTIMG_SWAP_RB);

    /*CGColorSpaceRef colorspace = NULL;
779
    CGDataProviderRef provider = NULL;
780
    int width = cvimage->width;
781 782 783 784 785 786
    int height = cvimage->height;

    colorspace = CGColorSpaceCreateDeviceRGB();

    int size = 8;
    int nbChannels = 3;
787

788
    provider = CGDataProviderCreateWithData(NULL, cvimage->data.ptr, width * height , NULL );
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

    CGImageRef imageRef = CGImageCreate(width, height, size , size*nbChannels , cvimage->step, colorspace,  kCGImageAlphaNone , provider, NULL, true, kCGRenderingIntentDefault);

    NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithCGImage:imageRef];
    if(image) {
        [image release];
    }*/

    NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
                pixelsWide:cvimage->width
                pixelsHigh:cvimage->height
                bitsPerSample:8
                samplesPerPixel:3
                hasAlpha:NO
                isPlanar:NO
                colorSpaceName:NSDeviceRGBColorSpace
                bytesPerRow:(cvimage->width * 4)
                bitsPerPixel:32];

    int	pixelCount = cvimage->width * cvimage->height;
    unsigned char *src = cvimage->data.ptr;
    unsigned char *dst = [bitmap bitmapData];

    for( int i = 0; i < pixelCount; i++ )
    {
        dst[i * 4 + 0] = src[i * 3 + 0];
        dst[i * 4 + 1] = src[i * 3 + 1];
        dst[i * 4 + 2] = src[i * 3 + 2];
    }

819
    if( image )
820 821 822 823 824 825 826
        [image release];

    image = [[NSImage alloc] init];
    [image addRepresentation:bitmap];
    [bitmap release];

    /*CGColorSpaceRelease(colorspace);
827
    CGDataProviderRelease(provider);
828 829 830 831 832 833
    CGImageRelease(imageRef);*/
    cvReleaseMat(&cvimage);
    [localpool drain];

    [self setNeedsDisplay:YES];

834 835 836
}

- (void)setFrameSize:(NSSize)size {
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
    //cout << "setFrameSize" << endl;
    [super setFrameSize:size];

    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];
    int height = size.height;

    CVWindow *cvwindow = (CVWindow *)[self window];
    for(NSString *key in [cvwindow sliders]) {
        NSSlider *slider = [[cvwindow sliders] valueForKey:key];
        NSRect r = [slider frame];
        r.origin.y = height - r.size.height;
        r.size.width = [[cvwindow contentView] frame].size.width;
        [slider setFrame:r];
        height -= r.size.height;
    }
    [localpool drain];
853 854 855
}

- (void)drawRect:(NSRect)rect {
856 857 858 859 860 861
    //cout << "drawRect" << endl;
    [super drawRect:rect];

    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];
    CVWindow *cvwindow = (CVWindow *)[self window];
    int height = 0;
862 863 864 865 866
    if ([cvwindow respondsToSelector:@selector(sliders)]) {
        for(NSString *key in [cvwindow sliders]) {
            height += [[[cvwindow sliders] valueForKey:key] frame].size.height;
        }
    }
867

868 869 870 871 872 873 874 875 876 877

    NSRect imageRect = {{0,0}, {[image size].width, [image size].height}};

    if(image != nil) {
        [image drawInRect: imageRect
                              fromRect: NSZeroRect
                             operation: NSCompositeSourceOver
                              fraction: 1.0];
    }
    [localpool release];
878 879 880 881 882

}

@end

883
@implementation CVSlider
884 885 886 887 888 889 890 891 892

@synthesize slider;
@synthesize name;
@synthesize value;
@synthesize userData;
@synthesize callback;
@synthesize callback2;

- (id)init {
893
    [super init];
894

895 896 897
    callback = NULL;
    value = NULL;
    userData = NULL;
898

899
    [self setFrame:NSMakeRect(0,0,200,30)];
900

901 902
    name = [[NSTextField alloc] initWithFrame:NSMakeRect(10, 0,110, 25)];
    [name setEditable:NO];
903 904 905
    [name setSelectable:NO];
    [name setBezeled:NO];
    [name setBordered:NO];
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
    [name setDrawsBackground:NO];
    [[name cell] setLineBreakMode:NSLineBreakByTruncatingTail];
    [self addSubview:name];

    slider = [[NSSlider alloc] initWithFrame:NSMakeRect(120, 0, 70, 25)];
    [slider setAutoresizingMask:NSViewWidthSizable];
    [slider setMinValue:0];
    [slider setMaxValue:100];
    [slider setContinuous:YES];
    [slider setTarget:self];
    [slider setAction:@selector(sliderChanged:)];
    [self addSubview:slider];

    [self setAutoresizingMask:NSViewWidthSizable];

    //[self setFrame:NSMakeRect(12, 0, 100, 30)];

    return self;
924 925 926
}

- (void)sliderChanged:(NSNotification *)notification {
Andrey Kamaev's avatar
Andrey Kamaev committed
927
    (void)notification;
928 929 930
    int pos = [slider intValue];
    if(value)
        *value = pos;
931 932 933 934
    if(callback)
        callback(pos);
    if(callback2)
        callback2(pos, userData);
935 936 937 938
}

@end

939 940
#endif

941
/* End of file. */