1 /*M///////////////////////////////////////////////////////////////////////////////////////
3 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
5 // By downloading, copying, installing or using the software you agree to this license.
6 // If you do not agree to this license, do not download, install,
7 // copy or use the software.
10 // Intel License Agreement
11 // For Open Source Computer Vision Library
13 // Copyright (C) 2000, Intel Corporation, all rights reserved.
14 // Third party copyrights are property of their respective owners.
16 // Redistribution and use in source and binary forms, with or without modification,
17 // are permitted provided that the following conditions are met:
19 // * Redistribution's of source code must retain the above copyright notice,
20 // this list of conditions and the following disclaimer.
22 // * Redistribution's in binary form must reproduce the above copyright notice,
23 // this list of conditions and the following disclaimer in the documentation
24 // and/or other materials provided with the distribution.
26 // * The name of Intel Corporation may not be used to endorse or promote products
27 // derived from this software without specific prior written permission.
29 // This software is provided by the copyright holders and contributors "as is" and
30 // any express or implied warranties, including, but not limited to, the implied
31 // warranties of merchantability and fitness for a particular purpose are disclaimed.
32 // In no event shall the Intel Corporation or contributors be liable for any direct,
33 // indirect, incidental, special, exemplary, or consequential damages
34 // (including, but not limited to, procurement of substitute goods or services;
35 // loss of use, data, or profits; or business interruption) however caused
36 // and on any theory of liability, whether in contract, strict liability,
37 // or tort (including negligence or otherwise) arising in any way out of
38 // the use of this software, even if advised of the possibility of such damage.
44 #include <Carbon/Carbon.h>
50 //#define MS_TO_TICKS(a) a*3/50
53 #define INTERWIDGETSPACE 16
54 #define WIDGETHEIGHT 32
59 typedef struct CvTrackbar
72 CvTrackbarCallback notify;
77 typedef struct CvWindow
96 CvMouseCallback on_mouse;
109 static CvWindow* hg_windows = 0;
111 #define Assert(exp) \
114 printf("Assertion: %s %s: %d\n", #exp, __FILE__, __LINE__);\
118 static int wasInitialized = 0;
119 static char lastKey = NO_KEY;
120 OSStatus keyHandler(EventHandlerCallRef hcr, EventRef theEvent, void* inUserData);
121 static pascal OSStatus windowEventHandler(EventHandlerCallRef nextHandler, EventRef theEvent, void *inUserData);
123 static const EventTypeSpec applicationKeyboardEvents[] =
125 { kEventClassKeyboard, kEventRawKeyDown },
128 CV_IMPL int cvInitSystem( int argc, char** argv )
131 if( !wasInitialized )
135 err = InstallApplicationEventHandler(NewEventHandlerUPP( keyHandler),GetEventTypeCount(applicationKeyboardEvents),applicationKeyboardEvents,NULL,NULL);
138 fprintf(stderr,"InstallApplicationEventHandler was not ok\n");
146 // TODO: implement missing functionality
147 CV_IMPL int cvStartWindowThread()
152 static int icvCountTrackbarInWindow( const CvWindow* window)
154 CvTrackbar* trackbar = window->toolbar.first;
156 while (trackbar != 0) {
158 trackbar = trackbar->next;
163 static CvTrackbar* icvTrackbarByHandle( void * handle )
165 CvWindow* window = hg_windows;
166 CvTrackbar* trackbar = NULL;
167 while( window != 0 && window->window != handle) {
168 trackbar = window->toolbar.first;
169 while (trackbar != 0 && trackbar->trackbar != handle)
170 trackbar = trackbar->next;
171 if (trackbar != 0 && trackbar->trackbar == handle)
173 window = window->next;
178 static CvWindow* icvWindowByHandle( void * handle )
180 CvWindow* window = hg_windows;
182 while( window != 0 && window->window != handle)
183 window = window->next;
188 CV_IMPL CvWindow * icvFindWindowByName( const char* name)
190 CvWindow* window = hg_windows;
191 while( window != 0 && strcmp(name, window->name) != 0 )
192 window = window->next;
197 static CvTrackbar* icvFindTrackbarByName( const CvWindow* window, const char* name )
199 CvTrackbar* trackbar = window->toolbar.first;
201 while (trackbar != 0 && strcmp( trackbar->name, name ) != 0)
202 trackbar = trackbar->next;
208 /* draw image to frame */
209 static void icvDrawImage( CvWindow* window )
211 Assert( window != 0 );
212 if( window->imageRef == 0 ) return;
214 CGContextRef myContext;
217 int width = window->imageWidth;
218 int height = window->imageHeight;
220 GetWindowPortBounds(window->window, &portrect);
222 if( window->flags & CV_WINDOW_AUTOSIZE )
224 CGPoint origin = {0,0};
225 CGSize size = {portrect.right-portrect.left, portrect.bottom-portrect.top-window->trackbarheight};
226 rect.origin = origin; rect.size = size;
230 CGPoint origin = {0, portrect.bottom - height - window->trackbarheight};
231 CGSize size = {width, height};
232 rect.origin = origin; rect.size = size;
235 /* To be sybnchronous we are using this, better would be to susbcribe to the draw event and process whenever requested, we might save SOME CPU cycles*/
236 SetPortWindowPort (window->window);
237 QDBeginCGContext (GetWindowPort (window->window), &myContext);
238 CGContextSetInterpolationQuality (myContext, kCGInterpolationLow);
239 CGContextDrawImage(myContext,rect,window->imageRef);
240 CGContextFlush(myContext);// 4
241 QDEndCGContext (GetWindowPort(window->window), &myContext);// 5
245 /* update imageRef */
246 static void icvPutImage( CvWindow* window )
248 Assert( window != 0 );
249 if( window->image == 0 ) return;
251 CGColorSpaceRef colorspace = NULL;
252 CGDataProviderRef provider = NULL;
253 int width = window->imageWidth = window->image->cols;
254 int height = window->imageHeight = window->image->rows;
256 colorspace = CGColorSpaceCreateDeviceRGB();
261 provider = CGDataProviderCreateWithData(NULL, window->image->data.ptr, width * height , NULL );
263 if (window->imageRef != NULL){
264 CGImageRelease(window->imageRef);
265 window->image == NULL;
268 window->imageRef = CGImageCreate( width, height, size , size*nbChannels , window->image->step, colorspace, kCGImageAlphaNone , provider, NULL, true, kCGRenderingIntentDefault );
269 icvDrawImage( window );
271 /* release the provider's memory */
272 CGDataProviderRelease( provider );
275 static void icvUpdateWindowSize( const CvWindow* window )
277 int width = 0, height = 240; /* init
\88 al taille de base de l'image*/
280 GetWindowBounds(window->window, kWindowContentRgn, &globalBounds);
284 if( window->image ) {
285 width = MAX(MAX(window->image->width, width), minWidth);
286 height = window->image->height;
290 height += window->trackbarheight;
292 //height +=WIDGETHEIGHT; /* 32 pixels are spearating tracbars from the video display */
294 globalBounds.right = globalBounds.left + width;
295 globalBounds.bottom = globalBounds.top + height;
296 SetWindowBounds(window->window, kWindowContentRgn, &globalBounds);
299 static void icvDeleteWindow( CvWindow* window )
301 CvTrackbar* trackbar;
304 window->prev->next = window->next;
306 hg_windows = window->next;
309 window->next->prev = window->prev;
311 window->prev = window->next = 0;
313 cvReleaseMat( &window->image );
314 cvReleaseMat( &window->dst_image );
316 for( trackbar = window->toolbar.first; trackbar != 0; )
318 CvTrackbar* next = trackbar->next;
319 cvFree( (void**)&trackbar );
323 if (window->imageRef != NULL)
324 CGImageRelease(window->imageRef);
326 cvFree( (void**)&window );
330 CV_IMPL void cvDestroyWindow( const char* name)
332 CV_FUNCNAME( "cvDestroyWindow" );
339 CV_ERROR( CV_StsNullPtr, "NULL name string" );
341 window = icvFindWindowByName( name );
345 icvDeleteWindow( window );
351 CV_IMPL void cvDestroyAllWindows( void )
355 CvWindow* window = hg_windows;
356 icvDeleteWindow( window );
361 CV_IMPL void cvShowImage( const char* name, const CvArr* arr)
363 CV_FUNCNAME( "cvShowImage" );
373 CV_ERROR( CV_StsNullPtr, "NULL name" );
375 window = icvFindWindowByName(name);
376 if( !window || !arr )
377 EXIT; // keep silence here.
379 if( CV_IS_IMAGE_HDR( arr ))
380 origin = ((IplImage*)arr)->origin;
382 CV_CALL( image = cvGetMat( arr, &stub ));
386 cvResizeWindow( name, image->cols, image->rows );
390 !CV_ARE_SIZES_EQ(window->image, image) ) {
391 if ( ! (window->flags & CV_WINDOW_AUTOSIZE) )//FD
393 cvReleaseMat( &window->image );
396 if( !window->image ) {
398 window->image = cvCreateMat( image->rows, image->cols, CV_8UC3 );
401 cvConvertImage( image, window->image, (origin != 0 ? CV_CVTIMG_FLIP : 0) + CV_CVTIMG_SWAP_RB );
402 icvPutImage( window );
404 icvUpdateWindowSize( window );
409 CV_IMPL void cvResizeWindow( const char* name, int width, int height)
411 CV_FUNCNAME( "cvResizeWindow" );
416 //CvTrackbar* trackbar;
419 CV_ERROR( CV_StsNullPtr, "NULL name" );
421 window = icvFindWindowByName(name);
425 SizeWindow(window->window, width, height, true);
430 CV_IMPL void cvMoveWindow( const char* name, int x, int y)
432 CV_FUNCNAME( "cvMoveWindow" );
437 //CvTrackbar* trackbar;
440 CV_ERROR( CV_StsNullPtr, "NULL name" );
442 window = icvFindWindowByName(name);
446 MoveWindow(window->window, x, y, true);
451 void TrackbarActionProcPtr (ControlRef theControl, ControlPartCode partCode)
453 CvTrackbar * trackbar = icvTrackbarByHandle (theControl);
455 if (trackbar == NULL)
457 fprintf(stderr,"Error getting trackbar\n");
462 if ( trackbar->data )
463 *trackbar->data = GetControl32BitValue (theControl);
464 if ( trackbar->notify )
465 trackbar->notify(GetControl32BitValue (theControl));
469 CV_IMPL int cvCreateTrackbar (const char* trackbar_name, const char* window_name,int* val, int count, CvTrackbarCallback on_notify)
473 CV_FUNCNAME( "cvCreateTrackbar" );
476 /*char slider_name[32];*/
477 CvWindow* window = 0;
478 CvTrackbar* trackbar = 0;
480 ControlRef outControl;
481 ControlRef stoutControl;
484 if( !window_name || !trackbar_name )
485 CV_ERROR( CV_StsNullPtr, "NULL window or trackbar name" );
488 CV_ERROR( CV_StsOutOfRange, "Bad trackbar maximal value" );
490 window = icvFindWindowByName(window_name);
494 trackbar = icvFindTrackbarByName(window,trackbar_name);
497 int len = strlen(trackbar_name);
498 trackbar = (CvTrackbar*)cvAlloc(sizeof(CvTrackbar) + len + 1);
499 memset( trackbar, 0, sizeof(*trackbar));
500 trackbar->signature = CV_TRACKBAR_MAGIC_VAL;
501 trackbar->name = (char*)(trackbar+1);
502 memcpy( trackbar->name, trackbar_name, len + 1 );
503 trackbar->parent = window;
504 trackbar->next = window->toolbar.first;
505 window->toolbar.first = trackbar;
514 trackbar->pos = value;
515 trackbar->data = val;
518 trackbar->maxval = count;
519 trackbar->notify = on_notify;
521 int c = icvCountTrackbarInWindow(window);
523 GetWindowBounds(window->window,kWindowContentRgn,&bounds);
525 stboundsRect.top = (INTERWIDGETSPACE +WIDGETHEIGHT)* (c-1)+INTERWIDGETSPACE;
526 stboundsRect.left = INTERWIDGETSPACE;
527 stboundsRect.bottom = stboundsRect.top + WIDGETHEIGHT;
528 stboundsRect.right = stboundsRect.left+LABELWIDTH;
530 fprintf(stdout,"create trackabar bounds (%d %d %d %d)\n",stboundsRect.top,stboundsRect.left,stboundsRect.bottom,stboundsRect.right);
531 CreateStaticTextControl (window->window,&stboundsRect,CFStringCreateWithCString(NULL,trackbar_name,kCFStringEncodingASCII),NULL,&stoutControl);
533 stboundsRect.top = (INTERWIDGETSPACE +WIDGETHEIGHT)* (c-1)+INTERWIDGETSPACE;
534 stboundsRect.left = INTERWIDGETSPACE*2+LABELWIDTH;
535 stboundsRect.bottom = stboundsRect.top + WIDGETHEIGHT;
536 stboundsRect.right = bounds.right-INTERWIDGETSPACE;
538 CreateSliderControl (window->window,&stboundsRect, trackbar->pos,0,trackbar->maxval,kControlSliderLiveFeedback,0,true,NewControlActionUPP(TrackbarActionProcPtr),&outControl);
540 bounds.bottom += INTERWIDGETSPACE + WIDGETHEIGHT;
541 SetControlVisibility (outControl,true,true);
542 SetControlVisibility (stoutControl,true,true);
544 trackbar->trackbar = outControl;
545 trackbar->label = stoutControl;
547 window->trackbarheight = INTERWIDGETSPACE*2 + WIDGETHEIGHT;
549 window->trackbarheight += INTERWIDGETSPACE + WIDGETHEIGHT;
550 icvUpdateWindowSize( window );
557 cvSetMouseCallback( const char* name, CvMouseCallback function, void* info)
559 CvWindow* window = icvFindWindowByName( name );
562 window->on_mouse = function;
563 window->on_mouse_param = info;
567 fprintf(stdout,"Error with cvSetMouseCallback. Window not found : %s\n",name);
571 CV_IMPL int cvGetTrackbarPos( const char* trackbar_name, const char* window_name )
575 CV_FUNCNAME( "cvGetTrackbarPos" );
580 CvTrackbar* trackbar = 0;
582 if( trackbar_name == 0 || window_name == 0 )
583 CV_ERROR( CV_StsNullPtr, "NULL trackbar or window name" );
585 window = icvFindWindowByName( window_name );
587 trackbar = icvFindTrackbarByName( window, trackbar_name );
597 CV_IMPL void cvSetTrackbarPos(const char* trackbar_name, const char* window_name, int pos)
599 CV_FUNCNAME( "cvSetTrackbarPos" );
604 CvTrackbar* trackbar = 0;
606 if( trackbar_name == 0 || window_name == 0 )
607 CV_ERROR( CV_StsNullPtr, "NULL trackbar or window name" );
609 window = icvFindWindowByName( window_name );
611 trackbar = icvFindTrackbarByName( window, trackbar_name );
618 if( pos > trackbar->maxval )
619 pos = trackbar->maxval;
621 // Set new value and redraw the trackbar
622 SetControlValue( trackbar->trackbar, pos );
623 Draw1Control( trackbar->trackbar );
630 CV_IMPL void* cvGetWindowHandle( const char* name )
632 WindowRef result = 0;
637 window = icvFindWindowByName( name );
639 result = window->window;
649 CV_IMPL const char* cvGetWindowName( void* window_handle )
651 const char* window_name = "";
653 CV_FUNCNAME( "cvGetWindowName" );
659 if( window_handle == 0 )
660 CV_ERROR( CV_StsNullPtr, "NULL window" );
661 window = icvWindowByHandle(window_handle );
663 window_name = window->name;
671 CV_IMPL int cvNamedWindow( const char* name, int flags )
674 CV_FUNCNAME( "cvNamedWindow" );
676 cvInitSystem(0, NULL);
678 // to be able to display a window, we need to be a 'faceful' application
679 // http://lists.apple.com/archives/carbon-dev/2005/Jun/msg01414.html
680 static bool switched_to_faceful = false;
681 if (! switched_to_faceful)
683 ProcessSerialNumber psn = { 0, kCurrentProcess };
684 OSStatus ret = TransformProcessType (&psn, kProcessTransformToForegroundApplication );
688 SetFrontProcess( &psn );
689 switched_to_faceful = true;
693 fprintf(stderr, "Failed to tranform process type: %d\n", (int) ret);
700 WindowRef outWindow = NULL;
701 OSStatus err = noErr;
702 Rect contentBounds = {100,100,320,440};
705 UInt wAttributes = 0;
709 const EventTypeSpec genericWindowEventHandler[] = {
710 { kEventClassMouse, kEventMouseMoved},
711 { kEventClassMouse, kEventMouseUp},
712 { kEventClassMouse, kEventMouseDown},
713 { kEventClassWindow, kEventWindowClose },
714 { kEventClassWindow, kEventWindowBoundsChanged }//FD
718 CV_ERROR( CV_StsNullPtr, "NULL name string" );
720 if( icvFindWindowByName( name ) != 0 ){
725 CV_CALL( window = (CvWindow*)cvAlloc(sizeof(CvWindow) + len + 1));
726 memset( window, 0, sizeof(*window));
727 window->name = (char*)(window + 1);
728 memcpy( window->name, name, len + 1 );
729 window->flags = flags;
730 window->signature = CV_WINDOW_MAGIC_VAL;
732 window->last_key = 0;
733 window->on_mouse = 0;
734 window->on_mouse_param = 0;
736 window->next = hg_windows;
739 hg_windows->prev = window;
741 wAttributes = kWindowStandardDocumentAttributes | kWindowStandardHandlerAttribute | kWindowLiveResizeAttribute;
743 err = CreateNewWindow ( kDocumentWindowClass,wAttributes,&contentBounds,&outWindow);
745 fprintf(stderr,"Error while creating the window\n");
747 SetWindowTitleWithCFString(outWindow,CFStringCreateWithCString(NULL,name,kCFStringEncodingASCII));
749 fprintf(stdout,"Error SetWindowTitleWithCFString\n");
751 window->window = outWindow;
753 err = InstallWindowEventHandler(outWindow, NewEventHandlerUPP(windowEventHandler), GetEventTypeCount(genericWindowEventHandler), genericWindowEventHandler, outWindow, NULL);
755 ShowWindow( outWindow );
762 static pascal OSStatus windowEventHandler(EventHandlerCallRef nextHandler, EventRef theEvent, void *inUserData)
764 CvWindow* window = NULL;
765 UInt32 eventKind, eventClass;
769 HIPoint point = {0,0};
770 EventMouseButton eventMouseButton = 0;//FD
771 UInt32 modifiers;//FD
773 WindowRef theWindow = (WindowRef)inUserData;
774 if (theWindow == NULL)
775 return eventNotHandledErr;
776 window = icvWindowByHandle(theWindow);
778 return eventNotHandledErr;
780 eventKind = GetEventKind(theEvent);
781 eventClass = GetEventClass(theEvent);
783 switch (eventClass) {
784 case kEventClassMouse : {
787 case kEventMouseDown :
788 case kEventMouseMoved : {
789 err = CallNextEventHandler(nextHandler, theEvent);
790 if (err != eventNotHandledErr)
792 err = GetEventParameter(theEvent, kEventParamMouseButton, typeMouseButton, NULL, sizeof(eventMouseButton), NULL, &eventMouseButton);
793 err = GetEventParameter(theEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(modifiers), NULL, &modifiers);
794 err = GetEventParameter(theEvent,kEventParamClickCount,typeUInt32,NULL,sizeof(UInt32),NULL,&count);
796 if (count >1) event += 6;
798 event = CV_EVENT_MOUSEMOVE;
801 if (eventKind == kEventMouseUp)
803 if (eventKind == kEventMouseDown)
806 unsigned int flags = 0;
808 err = GetEventParameter(theEvent, kEventParamWindowMouseLocation, typeHIPoint, NULL, sizeof(point), NULL, &point);
809 if (eventKind != kEventMouseMoved){
810 switch(eventMouseButton){
811 case kEventMouseButtonPrimary:
812 if (modifiers & controlKey){
813 flags += CV_EVENT_FLAG_RBUTTON;
816 flags += CV_EVENT_FLAG_LBUTTON;
819 case kEventMouseButtonSecondary:
820 flags += CV_EVENT_FLAG_RBUTTON;
823 case kEventMouseButtonTertiary:
824 flags += CV_EVENT_FLAG_MBUTTON;
830 if (modifiers&controlKey) flags += CV_EVENT_FLAG_CTRLKEY;
831 if (modifiers&shiftKey) flags += CV_EVENT_FLAG_SHIFTKEY;
832 if (modifiers& cmdKey ) flags += CV_EVENT_FLAG_ALTKEY;
834 if (window->on_mouse != NULL){
836 Rect structure, content;
837 GetWindowBounds(theWindow, kWindowStructureRgn, &structure);
838 GetWindowBounds(theWindow, kWindowContentRgn, &content);
839 lx = (int)point.x - content.left + structure.left;
840 ly = (int)point.y - window->trackbarheight - content.top + structure.top; /* minus la taille des trackbars */
841 if (window->flags & CV_WINDOW_AUTOSIZE) {//FD
842 //printf("was %d,%d\n", lx, ly);
843 /* scale the mouse coordinates */
844 lx = lx * window->imageWidth / (content.right - content.left);
845 ly = ly * window->imageHeight / (content.bottom - content.top - window->trackbarheight);
848 if (lx>0 && ly >0){ /* a remettre dans les coordonn
\8ees locale */
849 window->on_mouse (event, lx, ly, flags, window->on_mouse_param);
854 default : return eventNotHandledErr;
857 case kEventClassWindow : {//FD
859 case kEventWindowBoundsChanged :
861 /* resize the trackbars */
864 GetWindowBounds(window->window,kWindowContentRgn,&bounds);
865 for ( t = window->toolbar.first; t != 0; t = t->next )
866 SizeControl(t->trackbar,bounds.right - bounds.left - INTERWIDGETSPACE*3 - LABELWIDTH , WIDGETHEIGHT);
868 /* redraw the image */
869 icvDrawImage(window);
872 return eventNotHandledErr;
876 return eventNotHandledErr;
879 return eventNotHandledErr;
882 OSStatus keyHandler(EventHandlerCallRef hcr, EventRef theEvent, void* inUserData)
888 eventKind = GetEventKind (theEvent);
889 eventClass = GetEventClass (theEvent);
890 err = GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(lastKey), NULL, &lastKey);
897 CV_IMPL int cvWaitKey (int maxWait)
899 EventRecord theEvent;
901 // wait at least for one event (to allow mouse, etc. processing), exit if maxWait milliseconds passed (nullEvent)
902 UInt32 start = TickCount();
905 // remaining time until maxWait is over
906 UInt32 wait = EventTimeToTicks (maxWait / 1000.0) - (TickCount() - start);
910 WaitNextEvent (everyEvent, &theEvent, maxWait > 0 ? wait : kDurationForever, NULL);
912 while (lastKey == NO_KEY && theEvent.what != nullEvent);