Update the changelog
[opencv] / otherlibs / highgui / window_gtk.cpp
1 /*M///////////////////////////////////////////////////////////////////////////////////////
2 //
3 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4 //
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.
8 //
9 //
10 //                        Intel License Agreement
11 //                For Open Source Computer Vision Library
12 //
13 // Copyright (C) 2000, Intel Corporation, all rights reserved.
14 // Third party copyrights are property of their respective owners.
15 //
16 // Redistribution and use in source and binary forms, with or without modification,
17 // are permitted provided that the following conditions are met:
18 //
19 //   * Redistribution's of source code must retain the above copyright notice,
20 //     this list of conditions and the following disclaimer.
21 //
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.
25 //
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.
28 //
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.
39 //
40 //M*/
41
42 #include "_highgui.h"
43
44 #ifndef WIN32
45
46 #ifdef HAVE_GTK
47
48 #include "gtk/gtk.h"
49 #include "gdk/gdkkeysyms.h"
50 #include <stdio.h>
51
52 #include "cv.h"
53 /*#if _MSC_VER >= 1200
54 #pragma warning( disable: 4505 )
55 #pragma comment(lib,"gtk-win32-2.0.lib")
56 #pragma comment(lib,"glib-2.0.lib")
57 #pragma comment(lib,"gobject-2.0.lib")
58 #pragma comment(lib,"gdk-win32-2.0.lib")
59 #pragma comment(lib,"gdk_pixbuf-2.0.lib")
60 #endif*/
61
62
63 // TODO Fix the initial window size when flags=0.  Right now the initial window is by default
64 // 320x240 size.  A better default would be actual size of the image.  Problem
65 // is determining desired window size with trackbars while still allowing resizing.
66 //
67 // Gnome Totem source may be of use here, see bacon_video_widget_set_scale_ratio
68 // in totem/src/backend/bacon-video-widget-xine.c
69
70 ////////////////////////////////////////////////////////////
71 // CvImageWidget GTK Widget Public API
72 ////////////////////////////////////////////////////////////
73 typedef struct _CvImageWidget        CvImageWidget;
74 typedef struct _CvImageWidgetClass   CvImageWidgetClass;
75
76 struct _CvImageWidget {
77         GtkWidget widget;
78         CvMat * original_image;
79         CvMat * scaled_image;
80         int flags;
81 };
82
83 struct _CvImageWidgetClass
84 {
85   GtkWidgetClass parent_class;
86 };
87
88
89 /** Allocate new image viewer widget */
90 GtkWidget*     cvImageWidgetNew      (int flags);
91
92 /** Set the image to display in the widget */
93 void           cvImageWidgetSetImage(CvImageWidget * widget, const CvArr *arr);
94
95 // standard GTK object macros
96 #define CV_IMAGE_WIDGET(obj)          GTK_CHECK_CAST (obj, cvImageWidget_get_type (), CvImageWidget)
97 #define CV_IMAGE_WIDGET_CLASS(klass)  GTK_CHECK_CLASS_CAST (klass, cvImageWidget_get_type (), CvImageWidgetClass)
98 #define CV_IS_IMAGE_WIDGET(obj)       GTK_CHECK_TYPE (obj, cvImageWidget_get_type ())
99
100 /////////////////////////////////////////////////////////////////////////////
101 // Private API ////////////////////////////////////////////////////////
102 /////////////////////////////////////////////////////////////////////////////
103 GtkType        cvImageWidget_get_type (void);
104
105 static GtkWidgetClass * parent_class = NULL;
106
107 // flag to help size initial window
108 #define CV_WINDOW_NO_IMAGE 2
109
110 void cvImageWidgetSetImage(CvImageWidget * widget, const CvArr *arr){
111         CvMat * mat, stub;
112         int origin=0;
113
114         //printf("cvImageWidgetSetImage\n");
115
116         if( CV_IS_IMAGE_HDR( arr ))
117                 origin = ((IplImage*)arr)->origin;
118
119         mat = cvGetMat(arr, &stub);
120
121         if(widget->original_image && !CV_ARE_SIZES_EQ(mat, widget->original_image)){
122                 cvReleaseMat( &widget->original_image );
123         }
124         if(!widget->original_image){
125                 widget->original_image = cvCreateMat( mat->rows, mat->cols, CV_8UC3 );
126                 gtk_widget_queue_resize( GTK_WIDGET( widget ) );
127         }
128         cvConvertImage( mat, widget->original_image,
129                                         (origin != 0 ? CV_CVTIMG_FLIP : 0) + CV_CVTIMG_SWAP_RB );
130         if(widget->scaled_image){
131                 cvResize( widget->original_image, widget->scaled_image, CV_INTER_AREA );
132         }
133
134         // window does not refresh without this
135         gtk_widget_queue_draw( GTK_WIDGET(widget) );
136 }
137
138 GtkWidget*
139 cvImageWidgetNew (int flags)
140 {
141   CvImageWidget *image_widget;
142
143   image_widget = CV_IMAGE_WIDGET( gtk_type_new (cvImageWidget_get_type ()) );
144   image_widget->original_image = 0;
145   image_widget->scaled_image = 0;
146   image_widget->flags = flags | CV_WINDOW_NO_IMAGE;
147
148   return GTK_WIDGET (image_widget);
149 }
150
151 static void
152 cvImageWidget_realize (GtkWidget *widget)
153 {
154   CvImageWidget *image_widget;
155   GdkWindowAttr attributes;
156   gint attributes_mask;
157
158   //printf("cvImageWidget_realize\n");
159   g_return_if_fail (widget != NULL);
160   g_return_if_fail (CV_IS_IMAGE_WIDGET (widget));
161
162   GTK_WIDGET_SET_FLAGS (widget, GTK_REALIZED);
163   image_widget = CV_IMAGE_WIDGET (widget);
164
165   attributes.x = widget->allocation.x;
166   attributes.y = widget->allocation.y;
167   attributes.width = widget->allocation.width;
168   attributes.height = widget->allocation.height;
169   attributes.wclass = GDK_INPUT_OUTPUT;
170   attributes.window_type = GDK_WINDOW_CHILD;
171   attributes.event_mask = gtk_widget_get_events (widget) | 
172     GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK | 
173     GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK;
174   attributes.visual = gtk_widget_get_visual (widget);
175   attributes.colormap = gtk_widget_get_colormap (widget);
176
177   attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;
178   widget->window = gdk_window_new (widget->parent->window, &attributes, attributes_mask);
179
180   widget->style = gtk_style_attach (widget->style, widget->window);
181
182   gdk_window_set_user_data (widget->window, widget);
183
184   gtk_style_set_background (widget->style, widget->window, GTK_STATE_ACTIVE);
185 }
186
187 static CvSize cvImageWidget_calc_size( int im_width, int im_height, int max_width, int max_height ){
188     float aspect = (float)im_width/(float)im_height;
189     float max_aspect = (float)max_width/(float)max_height;
190     if(aspect > max_aspect){
191         return cvSize( max_width, cvRound(max_width/aspect) );
192     }
193     return cvSize( cvRound(max_height*aspect), max_height );
194 }
195
196 static void 
197 cvImageWidget_size_request (GtkWidget      *widget,
198                        GtkRequisition *requisition)
199 {
200         CvImageWidget * image_widget = CV_IMAGE_WIDGET( widget );
201         
202         //printf("cvImageWidget_size_request ");
203         // the case the first time cvShowImage called or when AUTOSIZE
204         if( image_widget->original_image && 
205                 ((image_widget->flags & CV_WINDOW_AUTOSIZE) ||
206                  (image_widget->flags & CV_WINDOW_NO_IMAGE))) 
207         {
208                 //printf("original ");
209                 requisition->width = image_widget->original_image->cols;
210                 requisition->height = image_widget->original_image->rows;
211         }
212         // default case
213         else if(image_widget->scaled_image){
214                 //printf("scaled ");
215                 requisition->width = image_widget->scaled_image->cols;
216                 requisition->height = image_widget->scaled_image->rows;
217         }
218         // the case before cvShowImage called
219         else{
220                 //printf("default ");
221                 requisition->width = 320;
222                 requisition->height = 240;
223         }
224         //printf("%d %d\n",requisition->width, requisition->height);
225 }
226
227 static void cvImageWidget_set_size(GtkWidget * widget, int max_width, int max_height){
228         CvImageWidget * image_widget = CV_IMAGE_WIDGET( widget );
229
230         //printf("cvImageWidget_set_size %d %d\n", max_width, max_height);
231
232         // don't allow to set the size
233         if(image_widget->flags & CV_WINDOW_AUTOSIZE) return;
234         if(!image_widget->original_image) return;
235
236         CvSize scaled_image_size = cvImageWidget_calc_size( image_widget->original_image->cols,
237                         image_widget->original_image->rows, max_width, max_height );
238
239         if( image_widget->scaled_image &&
240                         ( image_widget->scaled_image->cols != scaled_image_size.width ||
241                           image_widget->scaled_image->rows != scaled_image_size.height ))
242         {
243                 cvReleaseMat( &image_widget->scaled_image );
244         }
245         if( !image_widget->scaled_image ){
246                 image_widget->scaled_image = cvCreateMat( scaled_image_size.height, scaled_image_size.width,        CV_8UC3 );
247                 
248
249         }
250         assert( image_widget->scaled_image );
251 }
252
253 static void
254 cvImageWidget_size_allocate (GtkWidget     *widget,
255                         GtkAllocation *allocation)
256 {
257   CvImageWidget *image_widget;
258
259   //printf("cvImageWidget_size_allocate\n");
260   g_return_if_fail (widget != NULL);
261   g_return_if_fail (CV_IS_IMAGE_WIDGET (widget));
262   g_return_if_fail (allocation != NULL);
263
264   widget->allocation = *allocation;
265   image_widget = CV_IMAGE_WIDGET (widget);
266   
267
268   if( (image_widget->flags & CV_WINDOW_AUTOSIZE)==0 && image_widget->original_image ){
269           // (re) allocated scaled image
270           if( image_widget->flags & CV_WINDOW_NO_IMAGE ){
271                   cvImageWidget_set_size( widget, image_widget->original_image->cols, 
272                                                           image_widget->original_image->rows);
273           }
274           else{
275                   cvImageWidget_set_size( widget, allocation->width, allocation->height );
276           }
277           cvResize( image_widget->original_image, image_widget->scaled_image, CV_INTER_AREA );
278   }
279
280   if (GTK_WIDGET_REALIZED (widget))
281     {
282       image_widget = CV_IMAGE_WIDGET (widget);
283
284           if( image_widget->original_image && 
285                           ((image_widget->flags & CV_WINDOW_AUTOSIZE) || 
286                            (image_widget->flags & CV_WINDOW_NO_IMAGE)) )
287           {
288                   widget->allocation.width = image_widget->original_image->cols;
289                   widget->allocation.height = image_widget->original_image->rows;
290                   gdk_window_move_resize( widget->window, allocation->x, allocation->y, 
291                                   image_widget->original_image->cols, image_widget->original_image->rows );
292                   if(image_widget->flags & CV_WINDOW_NO_IMAGE){
293                           image_widget->flags &= ~CV_WINDOW_NO_IMAGE;
294                           gtk_widget_queue_resize( GTK_WIDGET(widget) );
295                   }
296           }
297           else{
298                   gdk_window_move_resize (widget->window,
299                                   allocation->x, allocation->y,
300                                   allocation->width, allocation->height );
301
302           }
303     }
304 }
305
306 static gboolean
307 cvImageWidget_expose( GtkWidget      *widget,
308                  GdkEventExpose *event )
309 {
310   CvImageWidget *image_widget;
311
312   g_return_val_if_fail (widget != NULL, FALSE);
313   g_return_val_if_fail (CV_IS_IMAGE_WIDGET (widget), FALSE);
314   g_return_val_if_fail (event != NULL, FALSE);
315
316   if (event->count > 0)
317     return FALSE;
318   
319   image_widget = CV_IMAGE_WIDGET (widget);
320
321   gdk_window_clear_area (widget->window,
322                          0, 0,
323                          widget->allocation.width,
324                          widget->allocation.height);
325   if( image_widget->scaled_image ){
326           // center image in available region
327           int x0 = (widget->allocation.width - image_widget->scaled_image->cols)/2;
328           int y0 = (widget->allocation.height - image_widget->scaled_image->rows)/2;
329           
330           gdk_draw_rgb_image( widget->window, widget->style->fg_gc[GTK_STATE_NORMAL],
331                   x0, y0, MIN(image_widget->scaled_image->cols, widget->allocation.width), 
332                   MIN(image_widget->scaled_image->rows, widget->allocation.height),
333                   GDK_RGB_DITHER_MAX, image_widget->scaled_image->data.ptr, image_widget->scaled_image->step );
334   }
335   else if( image_widget->original_image ){
336           gdk_draw_rgb_image( widget->window, widget->style->fg_gc[GTK_STATE_NORMAL],
337                   0, 0, 
338                   MIN(image_widget->original_image->cols, widget->allocation.width), 
339                    MIN(image_widget->original_image->rows, widget->allocation.height), 
340                   GDK_RGB_DITHER_MAX, image_widget->original_image->data.ptr, image_widget->original_image->step );
341   }
342   return TRUE;
343 }
344
345 static void
346 cvImageWidget_destroy (GtkObject *object)
347 {
348   CvImageWidget *image_widget;
349
350   g_return_if_fail (object != NULL);
351   g_return_if_fail (CV_IS_IMAGE_WIDGET (object));
352
353   image_widget = CV_IMAGE_WIDGET (object);
354
355   cvReleaseMat( &image_widget->scaled_image );
356   cvReleaseMat( &image_widget->original_image );
357
358   if (GTK_OBJECT_CLASS (parent_class)->destroy)
359     (* GTK_OBJECT_CLASS (parent_class)->destroy) (object);
360 }
361
362 static void cvImageWidget_class_init (CvImageWidgetClass * klass)
363 {
364   GtkObjectClass *object_class;
365   GtkWidgetClass *widget_class;
366
367   object_class = (GtkObjectClass*) klass;
368   widget_class = (GtkWidgetClass*) klass;
369   
370   parent_class = GTK_WIDGET_CLASS( gtk_type_class (gtk_widget_get_type ()) );
371
372   object_class->destroy = cvImageWidget_destroy;
373
374   widget_class->realize = cvImageWidget_realize;
375   widget_class->expose_event = cvImageWidget_expose;
376   widget_class->size_request = cvImageWidget_size_request;
377   widget_class->size_allocate = cvImageWidget_size_allocate;
378   widget_class->button_press_event = NULL;
379   widget_class->button_release_event = NULL;
380   widget_class->motion_notify_event = NULL;
381 }
382
383 static void
384 cvImageWidget_init (CvImageWidget *image_widget)
385 {
386         image_widget->original_image=0;
387         image_widget->scaled_image=0;
388         image_widget->flags=0;
389 }
390
391 GtkType cvImageWidget_get_type (void){
392   static GtkType image_type = 0;
393
394   if (!image_type)
395     {
396       static const GtkTypeInfo image_info =
397       {
398         "CvImageWidget",
399         sizeof (CvImageWidget),
400         sizeof (CvImageWidgetClass),
401         (GtkClassInitFunc) cvImageWidget_class_init,
402         (GtkObjectInitFunc) cvImageWidget_init,
403         /* reserved_1 */ NULL,
404         /* reserved_1 */ NULL,
405         (GtkClassInitFunc) NULL
406       };
407
408       image_type = gtk_type_unique (GTK_TYPE_WIDGET, &image_info);
409     }
410
411   return image_type;
412 }
413 /////////////////////////////////////////////////////////////////////////////
414 // End CvImageWidget
415 /////////////////////////////////////////////////////////////////////////////
416
417
418 struct CvWindow;
419
420 typedef struct CvTrackbar
421 {
422     int signature;
423     GtkWidget* widget;
424     char* name;
425     CvTrackbar* next;
426     CvWindow* parent;
427     int* data;
428     int pos;
429     int maxval;
430     CvTrackbarCallback notify;
431 }
432 CvTrackbar;
433
434 typedef struct CvWindow
435 {
436     int signature;
437     GtkWidget* widget;
438     GtkWidget* frame;
439     GtkWidget* paned;
440     char* name;
441     CvWindow* prev;
442     CvWindow* next;
443     
444     int last_key;
445     int flags;
446
447     CvMouseCallback on_mouse;
448     void* on_mouse_param;
449
450     struct
451     {
452         int pos;
453         int rows;
454         CvTrackbar* first;
455     }
456     toolbar;
457 }
458 CvWindow;
459
460
461 static gboolean icvOnClose( GtkWidget* widget, GdkEvent* event, gpointer user_data );
462 static gboolean icvOnKeyPress( GtkWidget* widget, GdkEventKey* event, gpointer user_data );
463 static void icvOnTrackbar( GtkWidget* widget, gpointer user_data );
464 static gboolean icvOnMouse( GtkWidget *widget, GdkEvent *event, gpointer user_data );
465
466 #ifdef HAVE_GTHREAD
467 int thread_started=0;
468 static gpointer icvWindowThreadLoop();
469 GMutex*                            last_key_mutex;
470 GCond*                             cond_have_key;
471 GMutex*                            window_mutex;
472 GThread*                           window_thread;
473 GtkWidget*             cvTopLevelWidget = 0;
474 #endif
475
476 static int             last_key = -1;
477 static CvWindow* hg_windows = 0;
478
479 CV_IMPL int cvInitSystem( int argc, char** argv )
480 {
481     static int wasInitialized = 0;    
482
483     // check initialization status
484     if( !wasInitialized )
485     {
486         hg_windows = 0;
487
488         gtk_init( &argc, &argv );
489         wasInitialized = 1;
490     }
491
492     return 0;
493 }
494
495 CV_IMPL int cvStartWindowThread(){
496 #ifdef HAVE_GTHREAD
497         cvInitSystem(0,NULL);
498     if (!thread_started) {
499         if (!g_thread_supported ()) {
500             /* the GThread system wasn't inited, so init it */
501             g_thread_init(NULL);
502         }
503         
504         // this mutex protects the window resources 
505         window_mutex = g_mutex_new();
506         
507         // protects the 'last key pressed' variable
508         last_key_mutex = g_mutex_new();
509         
510         // conditional that indicates a key has been pressed
511         cond_have_key = g_cond_new();
512
513         // this is the window update thread
514         window_thread = g_thread_create((GThreadFunc) icvWindowThreadLoop,
515                                         NULL, TRUE, NULL);
516     }
517     thread_started = window_thread!=NULL;
518     return thread_started;
519 #else
520     return 0;
521 #endif
522 }
523
524 #ifdef HAVE_GTHREAD
525 gpointer icvWindowThreadLoop(){
526         while(1){
527                 g_mutex_lock(window_mutex);
528                 gtk_main_iteration_do(FALSE);
529                 g_mutex_unlock(window_mutex);
530
531                 // little sleep 
532                 g_usleep(500);
533
534                 g_thread_yield();
535         }
536         return NULL;
537 }
538
539 #define CV_LOCK_MUTEX() \
540 if(thread_started && g_thread_self()!=window_thread){ g_mutex_lock( window_mutex ); } else { }
541
542 #define CV_UNLOCK_MUTEX() \
543 if(thread_started && g_thread_self()!=window_thread){ g_mutex_unlock( window_mutex); } else { }
544
545 #else
546 #define CV_LOCK_MUTEX()
547 #define CV_UNLOCK_MUTEX()
548 #endif
549
550 static CvWindow* icvFindWindowByName( const char* name )
551 {
552     CvWindow* window = hg_windows;
553     while( window != 0 && strcmp(name, window->name) != 0 )
554         window = window->next;
555
556     return window;
557 }
558
559 static CvWindow* icvWindowByWidget( GtkWidget* widget )
560 {
561     CvWindow* window = hg_windows;
562
563     while( window != 0 && window->widget != widget &&
564            window->frame != widget && window->paned != widget )
565         window = window->next;
566
567     return window;
568 }
569
570 CV_IMPL int cvNamedWindow( const char* name, int flags )
571 {
572     int result = 0;
573     CV_FUNCNAME( "cvNamedWindow" );
574
575     __BEGIN__;
576
577     CvWindow* window;
578     int len;
579
580     cvInitSystem(1,(char**)&name);
581     if( !name )
582         CV_ERROR( CV_StsNullPtr, "NULL name string" );
583
584     // Check the name in the storage
585     if( icvFindWindowByName( name ) != 0 )
586     {
587         result = 1;
588         EXIT;
589     }
590
591     len = strlen(name);
592     CV_CALL( window = (CvWindow*)cvAlloc(sizeof(CvWindow) + len + 1));
593     memset( window, 0, sizeof(*window));
594     window->name = (char*)(window + 1);
595     memcpy( window->name, name, len + 1 );
596     window->flags = flags;
597     window->signature = CV_WINDOW_MAGIC_VAL;
598     window->last_key = 0;
599     window->on_mouse = 0;
600     window->on_mouse_param = 0;
601     memset( &window->toolbar, 0, sizeof(window->toolbar));
602     window->next = hg_windows;
603     window->prev = 0;
604
605         CV_LOCK_MUTEX();
606         
607     window->frame = gtk_window_new( GTK_WINDOW_TOPLEVEL );
608
609     window->paned = gtk_vbox_new( FALSE, 0 );
610     window->widget = cvImageWidgetNew( flags );
611     gtk_box_pack_end( GTK_BOX(window->paned), window->widget, TRUE, TRUE, 0 );
612     gtk_widget_show( window->widget );
613     gtk_container_add( GTK_CONTAINER(window->frame), window->paned );
614     gtk_widget_show( window->paned );
615         //
616         // configure event handlers
617         // TODO -- move this to CvImageWidget ?
618     gtk_signal_connect( GTK_OBJECT(window->frame), "key-press-event",
619                         GTK_SIGNAL_FUNC(icvOnKeyPress), window );
620     gtk_signal_connect( GTK_OBJECT(window->widget), "button-press-event",
621                         GTK_SIGNAL_FUNC(icvOnMouse), window );
622     gtk_signal_connect( GTK_OBJECT(window->widget), "button-release-event",
623                         GTK_SIGNAL_FUNC(icvOnMouse), window );
624     gtk_signal_connect( GTK_OBJECT(window->widget), "motion-notify-event",
625                         GTK_SIGNAL_FUNC(icvOnMouse), window );
626     gtk_signal_connect( GTK_OBJECT(window->frame), "delete-event",
627                         GTK_SIGNAL_FUNC(icvOnClose), window );
628
629         gtk_widget_add_events (window->widget, GDK_EXPOSURE_MASK | GDK_BUTTON_RELEASE_MASK |
630                                           GDK_BUTTON_PRESS_MASK | GDK_POINTER_MOTION_MASK) ;
631
632     gtk_widget_show( window->frame );
633     gtk_window_set_title( GTK_WINDOW(window->frame), name );
634
635     if( hg_windows )
636         hg_windows->prev = window;
637     hg_windows = window;
638
639     gtk_window_set_resizable( GTK_WINDOW(window->frame), (flags & CV_WINDOW_AUTOSIZE) == 0 );
640
641
642         // allow window to be resized
643         if( (flags & CV_WINDOW_AUTOSIZE)==0 ){
644                 GdkGeometry geometry;
645                 geometry.min_width = 50;
646                 geometry.min_height = 50;
647                 gtk_window_set_geometry_hints( GTK_WINDOW( window->frame ), GTK_WIDGET( window->widget ), 
648                         &geometry, (GdkWindowHints) (GDK_HINT_MIN_SIZE));
649         }
650
651         CV_UNLOCK_MUTEX();
652
653     result = 1;
654     __END__;
655
656     return result;
657 }
658
659
660 static void icvDeleteWindow( CvWindow* window )
661 {
662     CvTrackbar* trackbar;
663     
664     if( window->prev )
665         window->prev->next = window->next;
666     else
667         hg_windows = window->next;
668
669     if( window->next )
670         window->next->prev = window->prev;
671
672     window->prev = window->next = 0;
673         
674         gtk_widget_destroy( window->frame );
675         
676     for( trackbar = window->toolbar.first; trackbar != 0; )
677     {
678         CvTrackbar* next = trackbar->next;
679         cvFree( &trackbar );
680         trackbar = next;
681     }
682
683     cvFree( &window );
684 #ifdef HAVE_GTHREAD
685         // if last window, send key press signal 
686         // to jump out of any waiting cvWaitKey's
687         if(hg_windows==0 && thread_started){
688                 g_cond_broadcast(cond_have_key);
689         }
690 #endif
691 }
692
693
694 CV_IMPL void cvDestroyWindow( const char* name )
695 {
696     CV_FUNCNAME( "cvDestroyWindow" );
697     
698     __BEGIN__;
699
700     CvWindow* window;
701
702     if(!name)
703         CV_ERROR( CV_StsNullPtr, "NULL name string" );
704
705     window = icvFindWindowByName( name );
706     if( !window )
707         EXIT;
708
709         // note that it is possible for the update thread to run this function
710         // if there is a call to cvShowImage in a mouse callback
711         // (this would produce a deadlock on window_mutex)
712         CV_LOCK_MUTEX();
713         
714         icvDeleteWindow( window );
715         
716         CV_UNLOCK_MUTEX();
717
718     __END__;
719 }
720
721
722 CV_IMPL void
723 cvDestroyAllWindows( void )
724 {
725         CV_LOCK_MUTEX();
726
727     while( hg_windows )
728     {
729         CvWindow* window = hg_windows;
730         icvDeleteWindow( window );
731     }
732         CV_UNLOCK_MUTEX();
733 }
734
735 CvSize icvCalcOptimalWindowSize( CvWindow * window, CvSize new_image_size){
736         CvSize window_size;
737         GtkWidget * toplevel = gtk_widget_get_toplevel( window->frame );
738         gdk_drawable_get_size( GDK_DRAWABLE(toplevel->window), 
739                         &window_size.width, &window_size.height );
740
741         window_size.width = window_size.width + new_image_size.width - window->widget->allocation.width;
742         window_size.height = window_size.height + new_image_size.height - window->widget->allocation.height;
743
744         return window_size; 
745 }
746
747 CV_IMPL void
748 cvShowImage( const char* name, const CvArr* arr )
749 {
750     CV_FUNCNAME( "cvShowImage" );
751
752     __BEGIN__;
753         
754     CvWindow* window;
755
756     if( !name )
757         CV_ERROR( CV_StsNullPtr, "NULL name" );
758
759         CV_LOCK_MUTEX();
760
761     window = icvFindWindowByName(name);
762     if( window && arr ){
763                 CvImageWidget * image_widget = CV_IMAGE_WIDGET( window->widget );
764                 cvImageWidgetSetImage( image_widget, arr );
765         }
766
767         CV_UNLOCK_MUTEX();
768
769     __END__;
770 }
771
772 CV_IMPL void cvResizeWindow(const char* name, int width, int height )
773 {
774     CV_FUNCNAME( "cvResizeWindow" );
775
776     __BEGIN__;
777     
778     CvWindow* window;
779         CvImageWidget * image_widget;
780
781     if( !name )
782         CV_ERROR( CV_StsNullPtr, "NULL name" );
783
784     window = icvFindWindowByName(name);
785     if(!window)
786         EXIT;
787
788         image_widget = CV_IMAGE_WIDGET( window->widget );
789         if(image_widget->flags & CV_WINDOW_AUTOSIZE) 
790                 EXIT;
791
792         CV_LOCK_MUTEX();
793
794         gtk_window_set_resizable( GTK_WINDOW(window->frame), 1 );
795     gtk_window_resize( GTK_WINDOW(window->frame), width, height );
796
797         // disable initial resize since presumably user wants to keep
798         // this window size
799         image_widget->flags &= ~CV_WINDOW_NO_IMAGE;
800
801         CV_UNLOCK_MUTEX();
802
803     __END__;
804 }
805
806
807 CV_IMPL void cvMoveWindow( const char* name, int x, int y )
808 {
809     CV_FUNCNAME( "cvMoveWindow" );
810
811     __BEGIN__;
812
813     CvWindow* window;
814
815     if( !name )
816         CV_ERROR( CV_StsNullPtr, "NULL name" );
817
818     window = icvFindWindowByName(name);
819     if(!window)
820         EXIT;
821
822         CV_LOCK_MUTEX();
823
824     gtk_window_move( GTK_WINDOW(window->frame), x, y );
825
826         CV_UNLOCK_MUTEX();
827
828     __END__;
829 }
830
831
832 static CvTrackbar*
833 icvFindTrackbarByName( const CvWindow* window, const char* name )
834 {
835     CvTrackbar* trackbar = window->toolbar.first;
836
837     for( ; trackbar != 0 && strcmp( trackbar->name, name ) != 0; trackbar = trackbar->next )
838         ;
839
840     return trackbar;
841 }
842
843 CV_IMPL int
844 cvCreateTrackbar( const char* trackbar_name, const char* window_name,
845                   int* val, int count, CvTrackbarCallback on_notify )
846 {
847     int result = 0;
848
849     CV_FUNCNAME( "cvCreateTrackbar" );
850
851     __BEGIN__;
852     
853     /*char slider_name[32];*/
854     CvWindow* window = 0;
855     CvTrackbar* trackbar = 0;
856
857     if( !window_name || !trackbar_name )
858         CV_ERROR( CV_StsNullPtr, "NULL window or trackbar name" );
859
860     if( count <= 0 )
861         CV_ERROR( CV_StsOutOfRange, "Bad trackbar maximal value" );
862
863     window = icvFindWindowByName(window_name);
864     if( !window )
865         EXIT;
866
867     trackbar = icvFindTrackbarByName(window,trackbar_name);
868
869         CV_LOCK_MUTEX();
870
871     if( !trackbar )
872     {
873         int len = strlen(trackbar_name);
874         trackbar = (CvTrackbar*)cvAlloc(sizeof(CvTrackbar) + len + 1);
875         memset( trackbar, 0, sizeof(*trackbar));
876         trackbar->signature = CV_TRACKBAR_MAGIC_VAL;
877         trackbar->name = (char*)(trackbar+1);
878         memcpy( trackbar->name, trackbar_name, len + 1 );
879         trackbar->parent = window;
880         trackbar->next = window->toolbar.first;
881         window->toolbar.first = trackbar;
882         
883         GtkWidget* hscale_box = gtk_hbox_new( FALSE, 10 );
884         GtkWidget* hscale_label = gtk_label_new( trackbar_name );
885         GtkWidget* hscale = gtk_hscale_new_with_range( 0, count, 1 );
886         gtk_range_set_update_policy( GTK_RANGE(hscale), GTK_UPDATE_CONTINUOUS );
887         gtk_scale_set_digits( GTK_SCALE(hscale), 0 );
888         //gtk_scale_set_value_pos( hscale, GTK_POS_TOP );
889         gtk_scale_set_draw_value( GTK_SCALE(hscale), TRUE );
890
891         trackbar->widget = hscale;
892         gtk_box_pack_start( GTK_BOX(hscale_box), hscale_label, FALSE, FALSE, 5 );
893         gtk_widget_show( hscale_label );
894         gtk_box_pack_start( GTK_BOX(hscale_box), hscale, TRUE, TRUE, 5 );
895         gtk_widget_show( hscale );
896         gtk_box_pack_start( GTK_BOX(window->paned), hscale_box, FALSE, FALSE, 5 );
897         gtk_widget_show( hscale_box );
898
899         }
900         
901     if( val )
902     {
903         int value = *val;
904         if( value < 0 )
905             value = 0;
906         if( value > count )
907             value = count;
908         gtk_range_set_value( GTK_RANGE(trackbar->widget), value );
909         trackbar->pos = value;
910         trackbar->data = val;
911     }
912         
913     trackbar->maxval = count;
914     trackbar->notify = on_notify;
915     gtk_signal_connect( GTK_OBJECT(trackbar->widget), "value-changed",
916                         GTK_SIGNAL_FUNC(icvOnTrackbar), trackbar );
917
918         // queue a widget resize to trigger a window resize to 
919         // compensate for the addition of trackbars
920         gtk_widget_queue_resize( GTK_WIDGET(window->widget) );
921
922
923         CV_UNLOCK_MUTEX();
924
925     result = 1;
926
927     __END__;
928
929     return result;
930 }
931
932
933 CV_IMPL void
934 cvSetMouseCallback( const char* window_name, CvMouseCallback on_mouse, void* param )
935 {
936     CV_FUNCNAME( "cvSetMouseCallback" );
937
938     __BEGIN__;
939     
940     CvWindow* window = 0;
941
942     if( !window_name )
943         CV_ERROR( CV_StsNullPtr, "NULL window name" );
944
945     window = icvFindWindowByName(window_name);
946     if( !window )
947         EXIT;
948
949     window->on_mouse = on_mouse;
950     window->on_mouse_param = param;
951
952     __END__;
953 }
954
955
956 CV_IMPL int cvGetTrackbarPos( const char* trackbar_name, const char* window_name )
957 {
958     int pos = -1;
959     
960     CV_FUNCNAME( "cvGetTrackbarPos" );
961
962     __BEGIN__;
963
964     CvWindow* window;
965     CvTrackbar* trackbar = 0;
966
967     if( trackbar_name == 0 || window_name == 0 )
968         CV_ERROR( CV_StsNullPtr, "NULL trackbar or window name" );
969
970     window = icvFindWindowByName( window_name );
971     if( window )
972         trackbar = icvFindTrackbarByName( window, trackbar_name );
973
974     if( trackbar )
975         pos = trackbar->pos;
976
977     __END__;
978
979     return pos;
980 }
981
982
983 CV_IMPL void cvSetTrackbarPos( const char* trackbar_name, const char* window_name, int pos )
984 {
985     CV_FUNCNAME( "cvSetTrackbarPos" );
986
987     __BEGIN__;
988
989     CvWindow* window;
990     CvTrackbar* trackbar = 0;
991
992     if( trackbar_name == 0 || window_name == 0 )
993         CV_ERROR( CV_StsNullPtr, "NULL trackbar or window name" );
994
995     window = icvFindWindowByName( window_name );
996     if( window )
997         trackbar = icvFindTrackbarByName( window, trackbar_name );
998
999     if( trackbar )
1000     {
1001         if( pos < 0 )
1002             pos = 0;
1003
1004         if( pos > trackbar->maxval )
1005             pos = trackbar->maxval;
1006     }
1007
1008         CV_LOCK_MUTEX();
1009
1010     gtk_range_set_value( GTK_RANGE(trackbar->widget), pos );
1011
1012         CV_UNLOCK_MUTEX();
1013
1014     __END__;
1015 }
1016
1017
1018 CV_IMPL void* cvGetWindowHandle( const char* window_name )
1019 {
1020     void* widget = 0;
1021     
1022     CV_FUNCNAME( "cvGetWindowHandle" );
1023
1024     __BEGIN__;
1025
1026     CvWindow* window;
1027
1028     if( window_name == 0 )
1029         CV_ERROR( CV_StsNullPtr, "NULL window name" );
1030
1031     window = icvFindWindowByName( window_name );
1032     if( window )
1033         widget = (void*)window->widget;
1034
1035     __END__;
1036
1037     return widget;
1038 }
1039     
1040
1041 CV_IMPL const char* cvGetWindowName( void* window_handle )
1042 {
1043     const char* window_name = "";
1044     
1045     CV_FUNCNAME( "cvGetWindowName" );
1046
1047     __BEGIN__;
1048
1049     CvWindow* window;
1050
1051     if( window_handle == 0 )
1052         CV_ERROR( CV_StsNullPtr, "NULL window" );
1053
1054     window = icvWindowByWidget( (GtkWidget*)window_handle );
1055     if( window )
1056         window_name = window->name;
1057
1058     __END__;
1059
1060     return window_name;
1061 }
1062
1063 static gboolean icvOnKeyPress( GtkWidget * /*widget*/,
1064                 GdkEventKey* event, gpointer /*user_data*/ )
1065 {
1066     int code = 0;
1067     
1068     switch( event->keyval )
1069     {
1070     case GDK_Escape:
1071         code = 27;
1072         break;
1073     case GDK_Return:
1074     case GDK_Linefeed:
1075         code = '\n';
1076         break;
1077     case GDK_Tab:
1078         code = '\t';
1079         break;
1080     default:
1081         code = event->keyval;
1082     }
1083
1084     code |= event->state << 16;
1085
1086 #ifdef HAVE_GTHREAD
1087         if(thread_started) g_mutex_lock(last_key_mutex);
1088 #endif
1089         
1090         last_key = code;
1091         
1092 #ifdef HAVE_GTHREAD
1093         if(thread_started){
1094                 // signal any waiting threads
1095                 g_cond_broadcast(cond_have_key);
1096                 g_mutex_unlock(last_key_mutex);
1097         }
1098 #endif
1099
1100     return FALSE;
1101 }
1102
1103
1104 static void icvOnTrackbar( GtkWidget* widget, gpointer user_data )
1105 {
1106     int pos = cvRound( gtk_range_get_value(GTK_RANGE(widget)));
1107     CvTrackbar* trackbar = (CvTrackbar*)user_data;
1108
1109     if( trackbar && trackbar->signature == CV_TRACKBAR_MAGIC_VAL &&
1110         trackbar->widget == widget )
1111     {
1112         trackbar->pos = pos;
1113         if( trackbar->data )
1114             *trackbar->data = pos;
1115         if( trackbar->notify )
1116             trackbar->notify(pos);
1117     }
1118 }
1119
1120 static gboolean icvOnClose( GtkWidget* widget, GdkEvent* /*event*/, gpointer user_data )
1121 {
1122     CvWindow* window = (CvWindow*)user_data;
1123     if( window->signature == CV_WINDOW_MAGIC_VAL &&
1124         window->frame == widget )
1125         {
1126         icvDeleteWindow(window);
1127         }
1128     return TRUE;
1129 }
1130
1131
1132 static gboolean icvOnMouse( GtkWidget *widget, GdkEvent *event, gpointer user_data )
1133 {
1134         // TODO move this logic to CvImageWidget
1135     CvWindow* window = (CvWindow*)user_data;
1136         CvPoint2D32f pt32f = {-1., -1.};
1137     CvPoint pt = {-1,-1};
1138     int cv_event = -1, state = 0;
1139         CvImageWidget * image_widget = CV_IMAGE_WIDGET( widget );
1140
1141     if( window->signature != CV_WINDOW_MAGIC_VAL ||
1142         window->widget != widget || !window->widget || 
1143                 !window->on_mouse || !image_widget->original_image)
1144         return FALSE;
1145
1146     if( event->type == GDK_MOTION_NOTIFY )
1147     {
1148         GdkEventMotion* event_motion = (GdkEventMotion*)event;
1149         
1150         cv_event = CV_EVENT_MOUSEMOVE;
1151         pt32f.x = cvRound(event_motion->x);
1152         pt32f.y = cvRound(event_motion->y);
1153         state = event_motion->state;
1154     }
1155     else if( event->type == GDK_BUTTON_PRESS ||
1156              event->type == GDK_BUTTON_RELEASE ||
1157              event->type == GDK_2BUTTON_PRESS )
1158     {
1159         GdkEventButton* event_button = (GdkEventButton*)event;
1160         pt32f.x = cvRound(event_button->x);
1161         pt32f.y = cvRound(event_button->y);
1162                 
1163                 
1164         if( event_button->type == GDK_BUTTON_PRESS )
1165         {
1166             cv_event = event_button->button == 1 ? CV_EVENT_LBUTTONDOWN :
1167                        event_button->button == 2 ? CV_EVENT_MBUTTONDOWN :
1168                        event_button->button == 3 ? CV_EVENT_RBUTTONDOWN : 0;
1169         }
1170         else if( event_button->type == GDK_BUTTON_RELEASE )
1171         {
1172             cv_event = event_button->button == 1 ? CV_EVENT_LBUTTONUP :
1173                        event_button->button == 2 ? CV_EVENT_MBUTTONUP :
1174                        event_button->button == 3 ? CV_EVENT_RBUTTONUP : 0;
1175         }
1176         else if( event_button->type == GDK_2BUTTON_PRESS )
1177         {
1178             cv_event = event_button->button == 1 ? CV_EVENT_LBUTTONDBLCLK :
1179                        event_button->button == 2 ? CV_EVENT_MBUTTONDBLCLK :
1180                        event_button->button == 3 ? CV_EVENT_RBUTTONDBLCLK : 0;
1181         }
1182         state = event_button->state;
1183     }
1184
1185     if( cv_event >= 0 ){
1186                 // scale point if image is scaled 
1187                 if( (image_widget->flags & CV_WINDOW_AUTOSIZE)==0 &&
1188                      image_widget->original_image &&
1189                          image_widget->scaled_image ){
1190                         // image origin is not necessarily at (0,0)
1191                         int x0 = (widget->allocation.width - image_widget->scaled_image->cols)/2;
1192                         int y0 = (widget->allocation.height - image_widget->scaled_image->rows)/2;
1193                         pt.x = cvRound( ((pt32f.x-x0)*image_widget->original_image->cols)/
1194                                                                 image_widget->scaled_image->cols );
1195                         pt.y = cvRound( ((pt32f.y-y0)*image_widget->original_image->rows)/
1196                                                                 image_widget->scaled_image->rows );
1197                 }
1198                 else{
1199                         pt = cvPointFrom32f( pt32f );
1200                 }
1201                 
1202                 if((unsigned)pt.x < (unsigned)(image_widget->original_image->width) &&
1203                    (unsigned)pt.y < (unsigned)(image_widget->original_image->height) )
1204                 {
1205                         int flags = (state & GDK_SHIFT_MASK ? CV_EVENT_FLAG_SHIFTKEY : 0) |
1206                                 (state & GDK_CONTROL_MASK ? CV_EVENT_FLAG_CTRLKEY : 0) |
1207                                 (state & (GDK_MOD1_MASK|GDK_MOD2_MASK) ? CV_EVENT_FLAG_ALTKEY : 0) |
1208                                 (state & GDK_BUTTON1_MASK ? CV_EVENT_FLAG_LBUTTON : 0) |
1209                                 (state & GDK_BUTTON2_MASK ? CV_EVENT_FLAG_MBUTTON : 0) |
1210                                 (state & GDK_BUTTON3_MASK ? CV_EVENT_FLAG_RBUTTON : 0);
1211                         window->on_mouse( cv_event, pt.x, pt.y, flags, window->on_mouse_param );
1212                 }
1213         }
1214
1215                 return FALSE;    
1216         }
1217
1218
1219 static gboolean icvAlarm( gpointer user_data )
1220 {
1221     *(int*)user_data = 1;
1222     return FALSE;
1223 }
1224
1225
1226 CV_IMPL int cvWaitKey( int delay )
1227 {
1228 #ifdef HAVE_GTHREAD
1229         if(thread_started && g_thread_self()!=window_thread){
1230                 gboolean expired;
1231                 int my_last_key;
1232
1233                 // wait for signal or timeout if delay > 0
1234                 if(delay>0){    
1235                         GTimeVal timer;
1236                         g_get_current_time(&timer);
1237                         g_time_val_add(&timer, delay*1000);
1238                         expired = !g_cond_timed_wait(cond_have_key, last_key_mutex, &timer);
1239                 }
1240                 else{
1241                         g_cond_wait(cond_have_key, last_key_mutex);
1242                         expired=false;
1243                 }
1244                 my_last_key = last_key;
1245                 g_mutex_unlock(last_key_mutex);
1246                 if(expired || hg_windows==0){
1247                         return -1;
1248                 }
1249                 return my_last_key;
1250         }
1251         else{
1252 #endif
1253                 int expired = 0;
1254                 guint timer = 0;
1255                 if( delay > 0 )
1256                         timer = g_timeout_add( delay, icvAlarm, &expired );
1257                 last_key = -1;
1258                 while( gtk_main_iteration_do(TRUE) && last_key < 0 && !expired && hg_windows != 0 )
1259                         ;
1260
1261                 if( delay > 0 && !expired )
1262                         g_source_remove(timer);
1263 #ifdef HAVE_GTHREAD
1264         }
1265 #endif
1266         return last_key;
1267 }
1268
1269
1270 #endif  // HAVE_GTK
1271 #endif  // WIN32
1272
1273 /* End of file. */