fixing locale settings - making it universal
[platform/upstream/opencv.git] / modules / highgui / src / window_QT.cpp
1 //IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
2
3 // By downloading, copying, installing or using the software you agree to this license.
4 // If you do not agree to this license, do not download, install,
5 // copy or use the software.
6
7
8 //                          License Agreement
9 //               For Open Source Computer Vision Library
10
11 //Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
12 //Copyright (C) 2008-2010, Willow Garage Inc., all rights reserved.
13 //Third party copyrights are property of their respective owners.
14
15 //Redistribution and use in source and binary forms, with or without modification,
16 //are permitted provided that the following conditions are met:
17
18 //  * Redistribution's of source code must retain the above copyright notice,
19 //  this list of conditions and the following disclaimer.
20
21 //  * Redistribution's in binary form must reproduce the above copyright notice,
22 //  this list of conditions and the following disclaimer in the documentation
23 //  and/or other materials provided with the distribution.
24
25 //  * The name of the copyright holders may not be used to endorse or promote products
26 //  derived from this software without specific prior written permission.
27
28 //This software is provided by the copyright holders and contributors "as is" and
29 //any express or implied warranties, including, but not limited to, the implied
30 //warranties of merchantability and fitness for a particular purpose are disclaimed.
31 //In no event shall the Intel Corporation or contributors be liable for any direct,
32 //indirect, incidental, special, exemplary, or consequential damages
33 //(including, but not limited to, procurement of substitute goods or services;
34 //loss of use, data, or profits; or business interruption) however caused
35 //and on any theory of liability, whether in contract, strict liability,
36 //or tort (including negligence or otherwise) arising in any way out of
37 //the use of this software, even if advised of the possibility of such damage.
38
39 //--------------------Google Code 2010 -- Yannick Verdie--------------------//
40
41 #include "precomp.hpp"
42
43 #if defined(HAVE_QT)
44
45 #include <memory>
46
47 #include <window_QT.h>
48
49 #include <math.h>
50
51 #ifdef _WIN32
52 #include <windows.h>
53 #else
54 #include <unistd.h>
55 #endif
56
57 #ifdef HAVE_QT_OPENGL
58     #ifdef Q_WS_X11
59         #include <GL/glx.h>
60     #endif
61 #endif
62
63
64 //Static and global first
65 static GuiReceiver *guiMainThread = NULL;
66 static int parameterSystemC = 1;
67 static char* parameterSystemV[] = {(char*)""};
68 static bool multiThreads = false;
69 static int last_key = -1;
70 QWaitCondition key_pressed;
71 QMutex mutexKey;
72 static const unsigned int threshold_zoom_img_region = 30;
73 //the minimum zoom value to start displaying the values in the grid
74 //that is also the number of pixel per grid
75
76 static CvWinProperties* global_control_panel = NULL;
77 //end static and global
78
79 // Declaration
80 Qt::ConnectionType autoBlockingConnection();
81
82 // Implementation - this allows us to do blocking whilst automatically selecting the right
83 // behaviour for in-thread and out-of-thread launches of cv windows. Qt strangely doesn't
84 // cater for this, but does for strictly queued connections.
85 Qt::ConnectionType autoBlockingConnection() {
86   return (QThread::currentThread() != QApplication::instance()->thread())
87       ? Qt::BlockingQueuedConnection
88       : Qt::DirectConnection;
89 }
90
91 CV_IMPL CvFont cvFontQt(const char* nameFont, int pointSize,CvScalar color,int weight,int style, int spacing)
92 {
93     /*
94     //nameFont   <- only Qt
95     //CvScalar color   <- only Qt (blue_component, green_component, red\_component[, alpha_component])
96     int         font_face;//<- style in Qt
97     const int*  ascii;
98     const int*  greek;
99     const int*  cyrillic;
100     float       hscale, vscale;
101     float       shear;
102     int         thickness;//<- weight in Qt
103     float       dx;//spacing letter in Qt (0 default) in pixel
104     int         line_type;//<- pointSize in Qt
105     */
106     CvFont f = {nameFont,color,style,NULL,NULL,NULL,0,0,0,weight,spacing,pointSize};
107     return f;
108 }
109
110
111 CV_IMPL void cvAddText(const CvArr* img, const char* text, CvPoint org, CvFont* font)
112 {
113     if (!guiMainThread)
114         CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
115
116     QMetaObject::invokeMethod(guiMainThread,
117         "putText",
118         autoBlockingConnection(),
119         Q_ARG(void*, (void*) img),
120         Q_ARG(QString,QString(text)),
121         Q_ARG(QPoint, QPoint(org.x,org.y)),
122         Q_ARG(void*,(void*) font));
123 }
124
125
126 double cvGetRatioWindow_QT(const char* name)
127 {
128     if (!guiMainThread)
129         CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
130
131     double result = -1;
132     QMetaObject::invokeMethod(guiMainThread,
133         "getRatioWindow",
134         autoBlockingConnection(),
135         Q_RETURN_ARG(double, result),
136         Q_ARG(QString, QString(name)));
137
138     return result;
139 }
140
141
142 void cvSetRatioWindow_QT(const char* name,double prop_value)
143 {
144
145     if (!guiMainThread)
146         CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
147
148     QMetaObject::invokeMethod(guiMainThread,
149         "setRatioWindow",
150         autoBlockingConnection(),
151         Q_ARG(QString, QString(name)),
152         Q_ARG(double, prop_value));
153 }
154
155
156 double cvGetPropWindow_QT(const char* name)
157 {
158     if (!guiMainThread)
159         CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
160
161     double result = -1;
162     QMetaObject::invokeMethod(guiMainThread,
163         "getPropWindow",
164         autoBlockingConnection(),
165         Q_RETURN_ARG(double, result),
166         Q_ARG(QString, QString(name)));
167
168     return result;
169 }
170
171
172 void cvSetPropWindow_QT(const char* name,double prop_value)
173 {
174     if (!guiMainThread)
175         CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
176
177     QMetaObject::invokeMethod(guiMainThread,
178         "setPropWindow",
179         autoBlockingConnection(),
180         Q_ARG(QString, QString(name)),
181         Q_ARG(double, prop_value));
182 }
183
184 void cv::setWindowTitle(const String& winname, const String& title)
185 {
186     if (!guiMainThread)
187         CV_Error(Error::StsNullPtr, "NULL guiReceiver (please create a window)");
188
189     QMetaObject::invokeMethod(guiMainThread,
190         "setWindowTitle",
191         autoBlockingConnection(),
192         Q_ARG(QString, QString(winname.c_str())),
193         Q_ARG(QString, QString(title.c_str())));
194 }
195
196
197 void cvSetModeWindow_QT(const char* name, double prop_value)
198 {
199     if (!guiMainThread)
200         CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
201
202     QMetaObject::invokeMethod(guiMainThread,
203         "toggleFullScreen",
204         autoBlockingConnection(),
205         Q_ARG(QString, QString(name)),
206         Q_ARG(double, prop_value));
207 }
208
209
210 double cvGetModeWindow_QT(const char* name)
211 {
212     if (!guiMainThread)
213         CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
214
215     double result = -1;
216
217     QMetaObject::invokeMethod(guiMainThread,
218         "isFullScreen",
219         autoBlockingConnection(),
220         Q_RETURN_ARG(double, result),
221         Q_ARG(QString, QString(name)));
222
223     return result;
224 }
225
226
227 CV_IMPL void cvDisplayOverlay(const char* name, const char* text, int delayms)
228 {
229     if (!guiMainThread)
230         CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
231
232     QMetaObject::invokeMethod(guiMainThread,
233         "displayInfo",
234         autoBlockingConnection(),
235         Q_ARG(QString, QString(name)),
236         Q_ARG(QString, QString(text)),
237         Q_ARG(int, delayms));
238 }
239
240
241 CV_IMPL void cvSaveWindowParameters(const char* name)
242 {
243     if (!guiMainThread)
244         CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
245
246     QMetaObject::invokeMethod(guiMainThread,
247         "saveWindowParameters",
248         autoBlockingConnection(),
249         Q_ARG(QString, QString(name)));
250 }
251
252
253 CV_IMPL void cvLoadWindowParameters(const char* name)
254 {
255     if (!guiMainThread)
256         CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
257
258     QMetaObject::invokeMethod(guiMainThread,
259         "loadWindowParameters",
260         autoBlockingConnection(),
261         Q_ARG(QString, QString(name)));
262 }
263
264
265 CV_IMPL void cvDisplayStatusBar(const char* name, const char* text, int delayms)
266 {
267     if (!guiMainThread)
268         CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
269
270     QMetaObject::invokeMethod(guiMainThread,
271         "displayStatusBar",
272         autoBlockingConnection(),
273         Q_ARG(QString, QString(name)),
274         Q_ARG(QString, QString(text)),
275         Q_ARG(int, delayms));
276 }
277
278
279 CV_IMPL int cvWaitKey(int delay)
280 {
281     int result = -1;
282
283     if (!guiMainThread)
284         return result;
285
286     unsigned long delayms = delay <= 0 ? ULONG_MAX : delay; //in milliseconds
287
288     if (multiThreads)
289     {
290         mutexKey.lock();
291         if (key_pressed.wait(&mutexKey, delayms)) //false if timeout
292         {
293             result = last_key;
294         }
295         last_key = -1;
296         mutexKey.unlock();
297     }
298     else
299     {
300         //cannot use wait here because events will not be distributed before processEvents (the main eventLoop is broken)
301         //so I create a Thread for the QTimer
302
303         if (delay > 0)
304             guiMainThread->timer->start(delay);
305
306         //QMutex dummy;
307
308         while (!guiMainThread->bTimeOut)
309         {
310             qApp->processEvents(QEventLoop::AllEvents);
311
312             if (!guiMainThread)//when all the windows are deleted
313                 return result;
314
315             mutexKey.lock();
316             if (last_key != -1)
317             {
318                 result = last_key;
319                 last_key = -1;
320                 guiMainThread->timer->stop();
321                 //printf("keypressed\n");
322             }
323             mutexKey.unlock();
324
325             if (result!=-1)
326             {
327                 break;
328             }
329             else
330             {
331                 /*
332     * //will not work, I broke the event loop !!!!
333     dummy.lock();
334     QWaitCondition waitCondition;
335     waitCondition.wait(&dummy, 2);
336     */
337
338                 //to decrease CPU usage
339                 //sleep 1 millisecond
340 #if defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64
341                 Sleep(1);
342 #else
343                 usleep(1000);
344 #endif
345             }
346         }
347
348         guiMainThread->bTimeOut = false;
349     }
350     return result;
351 }
352
353
354 //Yannick Verdie
355 //This function is experimental and some functions (such as cvSet/getWindowProperty will not work)
356 //We recommend not using this function for now
357 CV_IMPL int cvStartLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char* argv[])
358 {
359     multiThreads = true;
360     QFuture<int> future = QtConcurrent::run(pt2Func, argc, argv);
361     return guiMainThread->start();
362 }
363
364
365 CV_IMPL void cvStopLoop()
366 {
367     qApp->exit();
368 }
369
370
371 static CvWindow* icvFindWindowByName(QString name)
372 {
373     CvWindow* window = 0;
374
375     //This is not a very clean way to do the stuff. Indeed, QAction automatically generate toolTil (QLabel)
376     //that can be grabbed here and crash the code at 'w->param_name==name'.
377     foreach (QWidget* widget, QApplication::topLevelWidgets())
378     {
379         if (widget->isWindow() && !widget->parentWidget())//is a window without parent
380         {
381             CvWinModel* temp = (CvWinModel*) widget;
382
383             if (temp->type == type_CvWindow)
384             {
385                 CvWindow* w = (CvWindow*) temp;
386                 if (w->objectName() == name)
387                 {
388                     window = w;
389                     break;
390                 }
391             }
392         }
393     }
394
395     return window;
396 }
397
398
399 static CvBar* icvFindBarByName(QBoxLayout* layout, QString name_bar, typeBar type)
400 {
401     if (!layout)
402         return NULL;
403
404     int stop_index = layout->layout()->count();
405
406     for (int i = 0; i < stop_index; ++i)
407     {
408         CvBar* t = (CvBar*) layout->layout()->itemAt(i);
409
410         if (t->type == type && t->name_bar == name_bar)
411             return t;
412     }
413
414     return NULL;
415 }
416
417
418 static CvTrackbar* icvFindTrackBarByName(const char* name_trackbar, const char* name_window, QBoxLayout* layout = NULL)
419 {
420     QString nameQt(name_trackbar);
421     if ((!name_window || !name_window[0]) && global_control_panel) //window name is null and we have a control panel
422         layout = global_control_panel->myLayout;
423
424     if (!layout)
425     {
426         QPointer<CvWindow> w = icvFindWindowByName(QLatin1String(name_window));
427
428         if (!w)
429             CV_Error(CV_StsNullPtr, "NULL window handler");
430
431         if (w->param_gui_mode == CV_GUI_NORMAL)
432             return (CvTrackbar*) icvFindBarByName(w->myBarLayout, nameQt, type_CvTrackbar);
433
434         if (w->param_gui_mode == CV_GUI_EXPANDED)
435         {
436             CvBar* result = icvFindBarByName(w->myBarLayout, nameQt, type_CvTrackbar);
437
438             if (result)
439                 return (CvTrackbar*) result;
440
441             return (CvTrackbar*) icvFindBarByName(global_control_panel->myLayout, nameQt, type_CvTrackbar);
442         }
443
444         return NULL;
445     }
446     else
447     {
448         //layout was specified
449         return (CvTrackbar*) icvFindBarByName(layout, nameQt, type_CvTrackbar);
450     }
451 }
452
453 /*
454 static CvButtonbar* icvFindButtonBarByName(const char* button_name, QBoxLayout* layout)
455 {
456     QString nameQt(button_name);
457     return (CvButtonbar*) icvFindBarByName(layout, nameQt, type_CvButtonbar);
458 }
459 */
460
461 static int icvInitSystem(int* c, char** v)
462 {
463     //"For any GUI application using Qt, there is precisely one QApplication object"
464     if (!QApplication::instance())
465     {
466         new QApplication(*c, v);
467         setlocale(LC_NUMERIC,"C");
468
469         qDebug() << "init done";
470
471 #ifdef HAVE_QT_OPENGL
472         qDebug() << "opengl support available";
473 #endif
474     }
475
476     return 0;
477 }
478
479
480 CV_IMPL int cvInitSystem(int, char**)
481 {
482     icvInitSystem(&parameterSystemC, parameterSystemV);
483     return 0;
484 }
485
486
487 CV_IMPL int cvNamedWindow(const char* name, int flags)
488 {
489     if (!guiMainThread)
490         guiMainThread = new GuiReceiver;
491     if (QThread::currentThread() != QApplication::instance()->thread()) {
492         multiThreads = true;
493         QMetaObject::invokeMethod(guiMainThread,
494         "createWindow",
495         Qt::BlockingQueuedConnection,  // block so that we can do useful stuff once we confirm it is created
496         Q_ARG(QString, QString(name)),
497         Q_ARG(int, flags));
498      } else {
499         guiMainThread->createWindow(QString(name), flags);
500      }
501
502     return 1; //Dummy value - probably should return the result of the invocation.
503 }
504
505
506 CV_IMPL void cvDestroyWindow(const char* name)
507 {
508     if (!guiMainThread)
509         CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
510
511     QMetaObject::invokeMethod(guiMainThread,
512         "destroyWindow",
513         Qt::AutoConnection,  // if another thread is controlling, let it handle it without blocking ourselves here
514         Q_ARG(QString, QString(name)));
515 }
516
517
518 CV_IMPL void cvDestroyAllWindows()
519 {
520     if (!guiMainThread)
521         return;
522     QMetaObject::invokeMethod(guiMainThread,
523         "destroyAllWindow",
524         Qt::AutoConnection  // if another thread is controlling, let it handle it without blocking ourselves here
525         );
526 }
527
528
529 CV_IMPL void* cvGetWindowHandle(const char* name)
530 {
531     if (!name)
532         CV_Error( CV_StsNullPtr, "NULL name string" );
533
534     return (void*) icvFindWindowByName(QLatin1String(name));
535 }
536
537
538 CV_IMPL const char* cvGetWindowName(void* window_handle)
539 {
540     if( !window_handle )
541         CV_Error( CV_StsNullPtr, "NULL window handler" );
542
543     return ((CvWindow*)window_handle)->objectName().toLatin1().data();
544 }
545
546
547 CV_IMPL void cvMoveWindow(const char* name, int x, int y)
548 {
549     if (!guiMainThread)
550         CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
551     QMetaObject::invokeMethod(guiMainThread,
552         "moveWindow",
553         autoBlockingConnection(),
554         Q_ARG(QString, QString(name)),
555         Q_ARG(int, x),
556         Q_ARG(int, y));
557 }
558
559 CV_IMPL void cvResizeWindow(const char* name, int width, int height)
560 {
561     if (!guiMainThread)
562         CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
563     QMetaObject::invokeMethod(guiMainThread,
564         "resizeWindow",
565         autoBlockingConnection(),
566         Q_ARG(QString, QString(name)),
567         Q_ARG(int, width),
568         Q_ARG(int, height));
569 }
570
571
572 CV_IMPL int cvCreateTrackbar2(const char* name_bar, const char* window_name, int* val, int count, CvTrackbarCallback2 on_notify, void* userdata)
573 {
574     if (!guiMainThread)
575         CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
576
577     QMetaObject::invokeMethod(guiMainThread,
578         "addSlider2",
579         autoBlockingConnection(),
580         Q_ARG(QString, QString(name_bar)),
581         Q_ARG(QString, QString(window_name)),
582         Q_ARG(void*, (void*)val),
583         Q_ARG(int, count),
584         Q_ARG(void*, (void*)on_notify),
585         Q_ARG(void*, (void*)userdata));
586
587     return 1; //dummy value
588 }
589
590
591 CV_IMPL int cvStartWindowThread()
592 {
593     return 0;
594 }
595
596
597 CV_IMPL int cvCreateTrackbar(const char* name_bar, const char* window_name, int* value, int count, CvTrackbarCallback on_change)
598 {
599     if (!guiMainThread)
600         CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
601
602     QMetaObject::invokeMethod(guiMainThread,
603         "addSlider",
604         autoBlockingConnection(),
605         Q_ARG(QString, QString(name_bar)),
606         Q_ARG(QString, QString(window_name)),
607         Q_ARG(void*, (void*)value),
608         Q_ARG(int, count),
609         Q_ARG(void*, (void*)on_change));
610
611     return 1; //dummy value
612 }
613
614
615 CV_IMPL int cvCreateButton(const char* button_name, CvButtonCallback on_change, void* userdata, int button_type, int initial_button_state)
616 {
617     if (!guiMainThread)
618         CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
619
620     if (initial_button_state < 0 || initial_button_state > 1)
621         return 0;
622
623     QMetaObject::invokeMethod(guiMainThread,
624         "addButton",
625         autoBlockingConnection(),
626         Q_ARG(QString, QString(button_name)),
627         Q_ARG(int,  button_type),
628         Q_ARG(int, initial_button_state),
629         Q_ARG(void*, (void*)on_change),
630         Q_ARG(void*, userdata));
631
632     return 1;//dummy value
633 }
634
635
636 CV_IMPL int cvGetTrackbarPos(const char* name_bar, const char* window_name)
637 {
638     int result = -1;
639
640     QPointer<CvTrackbar> t = icvFindTrackBarByName(name_bar, window_name);
641
642     if (t)
643         result = t->slider->value();
644
645     return result;
646 }
647
648
649 CV_IMPL void cvSetTrackbarPos(const char* name_bar, const char* window_name, int pos)
650 {
651     QPointer<CvTrackbar> t = icvFindTrackBarByName(name_bar, window_name);
652
653     if (t)
654         t->slider->setValue(pos);
655 }
656
657
658 CV_IMPL void cvSetTrackbarMax(const char* name_bar, const char* window_name, int maxval)
659 {
660     if (maxval >= 0)
661     {
662         QPointer<CvTrackbar> t = icvFindTrackBarByName(name_bar, window_name);
663         if (t)
664         {
665             t->slider->setMaximum(maxval);
666         }
667     }
668 }
669
670
671 /* assign callback for mouse events */
672 CV_IMPL void cvSetMouseCallback(const char* window_name, CvMouseCallback on_mouse, void* param)
673 {
674     QPointer<CvWindow> w = icvFindWindowByName(QLatin1String(window_name));
675
676     if (!w)
677         CV_Error(CV_StsNullPtr, "NULL window handler");
678
679     w->setMouseCallBack(on_mouse, param);
680
681 }
682
683
684 CV_IMPL void cvShowImage(const char* name, const CvArr* arr)
685 {
686     if (!guiMainThread)
687         guiMainThread = new GuiReceiver;
688     if (QThread::currentThread() != QApplication::instance()->thread()) {
689         multiThreads = true;
690         QMetaObject::invokeMethod(guiMainThread,
691             "showImage",
692              autoBlockingConnection(),
693              Q_ARG(QString, QString(name)),
694              Q_ARG(void*, (void*)arr)
695         );
696      } else {
697         guiMainThread->showImage(QString(name), (void*)arr);
698      }
699 }
700
701
702 #ifdef HAVE_QT_OPENGL
703
704 CV_IMPL void cvSetOpenGlDrawCallback(const char* window_name, CvOpenGlDrawCallback callback, void* userdata)
705 {
706     if (!guiMainThread)
707         CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
708
709     QMetaObject::invokeMethod(guiMainThread,
710         "setOpenGlDrawCallback",
711         autoBlockingConnection(),
712         Q_ARG(QString, QString(window_name)),
713         Q_ARG(void*, (void*)callback),
714         Q_ARG(void*, userdata));
715 }
716
717
718 CV_IMPL void cvSetOpenGlContext(const char* window_name)
719 {
720     if (!guiMainThread)
721         CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
722
723     QMetaObject::invokeMethod(guiMainThread,
724         "setOpenGlContext",
725         autoBlockingConnection(),
726         Q_ARG(QString, QString(window_name)));
727 }
728
729
730 CV_IMPL void cvUpdateWindow(const char* window_name)
731 {
732     if (!guiMainThread)
733         CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
734
735     QMetaObject::invokeMethod(guiMainThread,
736         "updateWindow",
737         autoBlockingConnection(),
738         Q_ARG(QString, QString(window_name)));
739 }
740
741 #endif
742
743
744 double cvGetOpenGlProp_QT(const char* name)
745 {
746     double result = -1;
747
748     if (guiMainThread)
749     {
750         QMetaObject::invokeMethod(guiMainThread,
751             "isOpenGl",
752             autoBlockingConnection(),
753             Q_RETURN_ARG(double, result),
754             Q_ARG(QString, QString(name)));
755     }
756
757     return result;
758 }
759
760
761 //////////////////////////////////////////////////////
762 // GuiReceiver
763
764
765 GuiReceiver::GuiReceiver() : bTimeOut(false), nb_windows(0)
766 {
767     doesExternalQAppExist = (QApplication::instance() != 0);
768     icvInitSystem(&parameterSystemC, parameterSystemV);
769
770     timer = new QTimer(this);
771     QObject::connect(timer, SIGNAL(timeout()), this, SLOT(timeOut()));
772     timer->setSingleShot(true);
773     if ( doesExternalQAppExist ) {
774         moveToThread(QApplication::instance()->thread());
775     }
776 }
777
778
779 void GuiReceiver::isLastWindow()
780 {
781     if (--nb_windows <= 0)
782     {
783         delete guiMainThread;//delete global_control_panel too
784         guiMainThread = NULL;
785
786         if (!doesExternalQAppExist)
787         {
788             qApp->quit();
789         }
790     }
791 }
792
793
794 GuiReceiver::~GuiReceiver()
795 {
796     if (global_control_panel)
797     {
798         delete global_control_panel;
799         global_control_panel = NULL;
800     }
801 }
802
803
804 void GuiReceiver::putText(void* arr, QString text, QPoint org, void* arg2)
805 {
806     CV_Assert(arr);
807
808     CvMat* mat, stub;
809     mat = cvGetMat(arr, &stub);
810
811     int nbChannelOriginImage = cvGetElemType(mat);
812     if (nbChannelOriginImage != CV_8UC3) return; //for now, font works only with 8UC3
813
814     QImage qimg(mat->data.ptr, mat->cols, mat->rows, mat->step, QImage::Format_RGB888);
815
816     CvFont* font = (CvFont*)arg2;
817
818     QPainter qp(&qimg);
819     if (font)
820     {
821         QFont f(font->nameFont, font->line_type/*PointSize*/, font->thickness/*weight*/);
822         f.setStyle((QFont::Style) font->font_face/*style*/);
823         f.setLetterSpacing(QFont::AbsoluteSpacing, font->dx/*spacing*/);
824         //cvScalar(blue_component, green_component, red_component[, alpha_component])
825         //Qt map non-transparent to 0xFF and transparent to 0
826         //OpenCV scalar is the reverse, so 255-font->color.val[3]
827         qp.setPen(QColor(font->color.val[2], font->color.val[1], font->color.val[0], 255 - font->color.val[3]));
828         qp.setFont(f);
829     }
830     qp.drawText(org, text);
831     qp.end();
832 }
833
834
835 void GuiReceiver::saveWindowParameters(QString name)
836 {
837     QPointer<CvWindow> w = icvFindWindowByName(name);
838
839     if (w)
840         w->writeSettings();
841 }
842
843
844 void GuiReceiver::loadWindowParameters(QString name)
845 {
846     QPointer<CvWindow> w = icvFindWindowByName(name);
847
848     if (w)
849         w->readSettings();
850 }
851
852
853 double GuiReceiver::getRatioWindow(QString name)
854 {
855     QPointer<CvWindow> w = icvFindWindowByName(name);
856
857     if (!w)
858         return -1;
859
860     return w->getRatio();
861 }
862
863
864 void GuiReceiver::setRatioWindow(QString name, double arg2)
865 {
866     QPointer<CvWindow> w = icvFindWindowByName( name.toLatin1().data() );
867
868     if (!w)
869         return;
870
871     int flags = (int) arg2;
872
873     w->setRatio(flags);
874 }
875
876
877 double GuiReceiver::getPropWindow(QString name)
878 {
879     QPointer<CvWindow> w = icvFindWindowByName(name);
880
881     if (!w)
882         return -1;
883
884     return (double) w->getPropWindow();
885 }
886
887
888 void GuiReceiver::setPropWindow(QString name, double arg2)
889 {
890     QPointer<CvWindow> w = icvFindWindowByName(name);
891
892     if (!w)
893         return;
894
895     int flags = (int) arg2;
896
897     w->setPropWindow(flags);
898 }
899
900 void GuiReceiver::setWindowTitle(QString name, QString title)
901 {
902     QPointer<CvWindow> w = icvFindWindowByName(name);
903
904     if (!w)
905     {
906         cvNamedWindow(name.toLatin1().data());
907         w = icvFindWindowByName(name);
908     }
909
910     if (!w)
911         return;
912
913     w->setWindowTitle(title);
914 }
915
916
917 double GuiReceiver::isFullScreen(QString name)
918 {
919     QPointer<CvWindow> w = icvFindWindowByName(name);
920
921     if (!w)
922         return -1;
923
924     return w->isFullScreen() ? CV_WINDOW_FULLSCREEN : CV_WINDOW_NORMAL;
925 }
926
927
928 void GuiReceiver::toggleFullScreen(QString name, double arg2)
929 {
930     QPointer<CvWindow> w = icvFindWindowByName(name);
931
932     if (!w)
933         return;
934
935     int flags = (int) arg2;
936
937     w->toggleFullScreen(flags);
938 }
939
940
941 void GuiReceiver::createWindow(QString name, int flags)
942 {
943     if (!qApp)
944         CV_Error(CV_StsNullPtr, "NULL session handler" );
945
946     // Check the name in the storage
947     if (icvFindWindowByName(name.toLatin1().data()))
948     {
949         return;
950     }
951
952     nb_windows++;
953     new CvWindow(name, flags);
954 }
955
956
957 void GuiReceiver::timeOut()
958 {
959     bTimeOut = true;
960 }
961
962
963 void GuiReceiver::displayInfo(QString name, QString text, int delayms)
964 {
965     QPointer<CvWindow> w = icvFindWindowByName(name);
966
967     if (w)
968         w->displayInfo(text, delayms);
969 }
970
971
972 void GuiReceiver::displayStatusBar(QString name, QString text, int delayms)
973 {
974     QPointer<CvWindow> w = icvFindWindowByName(name);
975
976     if (w)
977         w->displayStatusBar(text, delayms);
978 }
979
980
981 void GuiReceiver::showImage(QString name, void* arr)
982 {
983     QPointer<CvWindow> w = icvFindWindowByName(name);
984
985     if (!w) //as observed in the previous implementation (W32, GTK or Carbon), create a new window is the pointer returned is null
986     {
987         cvNamedWindow(name.toLatin1().data());
988         w = icvFindWindowByName(name);
989     }
990
991     if (!w || !arr)
992         return; // keep silence here.
993
994     if (w->isOpenGl())
995     {
996         CvMat* mat, stub;
997
998         mat = cvGetMat(arr, &stub);
999
1000         cv::Mat im = cv::cvarrToMat(mat);
1001         cv::imshow(name.toUtf8().data(), im);
1002     }
1003     else
1004     {
1005         w->updateImage(arr);
1006     }
1007
1008     if (w->isHidden())
1009         w->show();
1010 }
1011
1012
1013 void GuiReceiver::destroyWindow(QString name)
1014 {
1015
1016     QPointer<CvWindow> w = icvFindWindowByName(name);
1017
1018     if (w)
1019     {
1020         w->close();
1021
1022         //in not-multiThreads mode, looks like the window is hidden but not deleted
1023         //so I do it manually
1024         //otherwise QApplication do it for me if the exec command was executed (in multiThread mode)
1025         if (!multiThreads)
1026             delete w;
1027     }
1028 }
1029
1030
1031 void GuiReceiver::destroyAllWindow()
1032 {
1033     if (!qApp)
1034         CV_Error(CV_StsNullPtr, "NULL session handler" );
1035
1036     if (multiThreads)
1037     {
1038         // WARNING: this could even close windows from an external parent app
1039         //#TODO check externalQAppExists and in case it does, close windows carefully,
1040         //      i.e. apply the className-check from below...
1041         qApp->closeAllWindows();
1042     }
1043     else
1044     {
1045         bool isWidgetDeleted = true;
1046         while(isWidgetDeleted)
1047         {
1048             isWidgetDeleted = false;
1049             QWidgetList list = QApplication::topLevelWidgets();
1050             for (int i = 0; i < list.count(); i++)
1051             {
1052                 QObject *obj = list.at(i);
1053                 if (obj->metaObject()->className() == QString("CvWindow"))
1054                 {
1055                     delete obj;
1056                     isWidgetDeleted = true;
1057                     break;
1058                 }
1059             }
1060         }
1061     }
1062 }
1063
1064
1065 void GuiReceiver::moveWindow(QString name, int x, int y)
1066 {
1067     QPointer<CvWindow> w = icvFindWindowByName(name);
1068
1069     if (w)
1070         w->move(x, y);
1071 }
1072
1073
1074 void GuiReceiver::resizeWindow(QString name, int width, int height)
1075 {
1076     QPointer<CvWindow> w = icvFindWindowByName(name);
1077
1078     if (w)
1079     {
1080         w->showNormal();
1081         w->setViewportSize(QSize(width, height));
1082     }
1083 }
1084
1085
1086 void GuiReceiver::enablePropertiesButtonEachWindow()
1087 {
1088     //For each window, enable window property button
1089     foreach (QWidget* widget, QApplication::topLevelWidgets())
1090     {
1091         if (widget->isWindow() && !widget->parentWidget()) //is a window without parent
1092         {
1093             CvWinModel* temp = (CvWinModel*) widget;
1094             if (temp->type == type_CvWindow)
1095             {
1096                 CvWindow* w = (CvWindow*) widget;
1097
1098                 //active window properties button
1099                 w->enablePropertiesButton();
1100             }
1101         }
1102     }
1103 }
1104
1105
1106 void GuiReceiver::addButton(QString button_name, int button_type, int initial_button_state, void* on_change, void* userdata)
1107 {
1108     if (!global_control_panel)
1109         return;
1110
1111     QPointer<CvButtonbar> b;
1112
1113     if (global_control_panel->myLayout->count() == 0) //if that is the first button attach to the control panel, create a new button bar
1114     {
1115         b = CvWindow::createButtonBar(button_name); //the bar has the name of the first button attached to it
1116         enablePropertiesButtonEachWindow();
1117
1118     }
1119     else
1120     {
1121         CvBar* lastbar = (CvBar*) global_control_panel->myLayout->itemAt(global_control_panel->myLayout->count() - 1);
1122
1123         if (lastbar->type == type_CvTrackbar) //if last bar is a trackbar, create a new buttonbar, else, attach to the current bar
1124             b = CvWindow::createButtonBar(button_name); //the bar has the name of the first button attached to it
1125         else
1126             b = (CvButtonbar*) lastbar;
1127
1128     }
1129
1130     b->addButton(button_name, (CvButtonCallback) on_change, userdata, button_type, initial_button_state);
1131 }
1132
1133
1134 void GuiReceiver::addSlider2(QString bar_name, QString window_name, void* value, int count, void* on_change, void *userdata)
1135 {
1136     QBoxLayout *layout = NULL;
1137     QPointer<CvWindow> w;
1138
1139     if (!window_name.isEmpty())
1140     {
1141         w = icvFindWindowByName(window_name);
1142
1143         if (!w)
1144             return;
1145     }
1146     else
1147     {
1148         if (global_control_panel)
1149             layout = global_control_panel->myLayout;
1150     }
1151
1152     QPointer<CvTrackbar> t = icvFindTrackBarByName(bar_name.toLatin1().data(), window_name.toLatin1().data(), layout);
1153
1154     if (t) //trackbar exists
1155         return;
1156
1157     if (!value)
1158         CV_Error(CV_StsNullPtr, "NULL value pointer" );
1159
1160     if (count <= 0) //count is the max value of the slider, so must be bigger than 0
1161         CV_Error(CV_StsNullPtr, "Max value of the slider must be bigger than 0" );
1162
1163     CvWindow::addSlider2(w, bar_name, (int*)value, count, (CvTrackbarCallback2) on_change, userdata);
1164 }
1165
1166
1167 void GuiReceiver::addSlider(QString bar_name, QString window_name, void* value, int count, void* on_change)
1168 {
1169     QBoxLayout *layout = NULL;
1170     QPointer<CvWindow> w;
1171
1172     if (!window_name.isEmpty())
1173     {
1174         w = icvFindWindowByName(window_name);
1175
1176         if (!w)
1177             return;
1178     }
1179     else
1180     {
1181         if (global_control_panel)
1182             layout = global_control_panel->myLayout;
1183     }
1184
1185     QPointer<CvTrackbar> t = icvFindTrackBarByName(bar_name.toLatin1().data(), window_name.toLatin1().data(), layout);
1186
1187     if (t) //trackbar exists
1188         return;
1189
1190     if (!value)
1191         CV_Error(CV_StsNullPtr, "NULL value pointer" );
1192
1193     if (count <= 0) //count is the max value of the slider, so must be bigger than 0
1194         CV_Error(CV_StsNullPtr, "Max value of the slider must be bigger than 0" );
1195
1196     CvWindow::addSlider(w, bar_name, (int*)value, count, (CvTrackbarCallback) on_change);
1197 }
1198
1199
1200 int GuiReceiver::start()
1201 {
1202     return qApp->exec();
1203 }
1204
1205
1206 void GuiReceiver::setOpenGlDrawCallback(QString name, void* callback, void* userdata)
1207 {
1208     QPointer<CvWindow> w = icvFindWindowByName(name);
1209
1210     if (w)
1211         w->setOpenGlDrawCallback((CvOpenGlDrawCallback) callback, userdata);
1212 }
1213
1214 void GuiReceiver::setOpenGlContext(QString name)
1215 {
1216     QPointer<CvWindow> w = icvFindWindowByName(name);
1217
1218     if (w)
1219         w->makeCurrentOpenGlContext();
1220 }
1221
1222 void GuiReceiver::updateWindow(QString name)
1223 {
1224     QPointer<CvWindow> w = icvFindWindowByName(name);
1225
1226     if (w)
1227         w->updateGl();
1228 }
1229
1230 double GuiReceiver::isOpenGl(QString name)
1231 {
1232     double result = -1;
1233
1234     QPointer<CvWindow> w = icvFindWindowByName(name);
1235
1236     if (w)
1237         result = (double) w->isOpenGl();
1238
1239     return result;
1240 }
1241
1242
1243 //////////////////////////////////////////////////////
1244 // CvTrackbar
1245
1246
1247 CvTrackbar::CvTrackbar(CvWindow* arg, QString name, int* value, int _count, CvTrackbarCallback2 on_change, void* data)
1248 {
1249     callback = NULL;
1250     callback2 = on_change;
1251     userdata = data;
1252
1253     create(arg, name, value, _count);
1254 }
1255
1256
1257 CvTrackbar::CvTrackbar(CvWindow* arg, QString name, int* value, int _count, CvTrackbarCallback on_change)
1258 {
1259     callback = on_change;
1260     callback2 = NULL;
1261     userdata = NULL;
1262
1263     create(arg, name, value, _count);
1264 }
1265
1266
1267 void CvTrackbar::create(CvWindow* arg, QString name, int* value, int _count)
1268 {
1269     type = type_CvTrackbar;
1270     myparent = arg;
1271     name_bar = name;
1272     setObjectName(name_bar);
1273     dataSlider = value;
1274
1275     slider = new QSlider(Qt::Horizontal);
1276     slider->setFocusPolicy(Qt::StrongFocus);
1277     slider->setMinimum(0);
1278     slider->setMaximum(_count);
1279     slider->setPageStep(5);
1280     slider->setValue(*value);
1281     slider->setTickPosition(QSlider::TicksBelow);
1282
1283
1284     //Change style of the Slider
1285     //slider->setStyleSheet(str_Trackbar_css);
1286
1287     QFile qss(":/stylesheet-trackbar");
1288     if (qss.open(QFile::ReadOnly))
1289     {
1290         slider->setStyleSheet(QLatin1String(qss.readAll()));
1291         qss.close();
1292     }
1293
1294
1295     //this next line does not work if we change the style with a stylesheet, why ? (bug in QT ?)
1296     //slider->setTickPosition(QSlider::TicksBelow);
1297     label = new QPushButton;
1298     label->setFlat(true);
1299     setLabel(slider->value());
1300
1301
1302     QObject::connect(slider, SIGNAL(valueChanged(int)), this, SLOT(update(int)));
1303
1304     QObject::connect(label, SIGNAL(clicked()), this, SLOT(createDialog()));
1305
1306     //label->setStyleSheet("QPushButton:disabled {color: black}");
1307
1308     addWidget(label, Qt::AlignLeft);//name + value
1309     addWidget(slider, Qt::AlignCenter);//slider
1310 }
1311
1312
1313 void CvTrackbar::createDialog()
1314 {
1315     bool ok = false;
1316
1317     //crash if I access the values directly and give them to QInputDialog, so do a copy first.
1318     int value = slider->value();
1319     int step = slider->singleStep();
1320     int min = slider->minimum();
1321     int max = slider->maximum();
1322
1323     int i =
1324 #if QT_VERSION >= 0x040500
1325         QInputDialog::getInt
1326 #else
1327         QInputDialog::getInteger
1328 #endif
1329         (this->parentWidget(),
1330         tr("Slider %1").arg(name_bar),
1331         tr("New value:"),
1332         value,
1333         min,
1334         max,
1335         step,
1336         &ok);
1337
1338     if (ok)
1339         slider->setValue(i);
1340 }
1341
1342
1343 void CvTrackbar::update(int myvalue)
1344 {
1345     setLabel(myvalue);
1346
1347     *dataSlider = myvalue;
1348     if (callback)
1349     {
1350         callback(myvalue);
1351         return;
1352     }
1353
1354     if (callback2)
1355     {
1356         callback2(myvalue, userdata);
1357         return;
1358     }
1359 }
1360
1361
1362 void CvTrackbar::setLabel(int myvalue)
1363 {
1364     QString nameNormalized = name_bar.leftJustified( 10, ' ', true );
1365     QString valueMaximum = QString("%1").arg(slider->maximum());
1366     QString str = QString("%1 (%2/%3)").arg(nameNormalized).arg(myvalue,valueMaximum.length(),10,QChar('0')).arg(valueMaximum);
1367     label->setText(str);
1368 }
1369
1370
1371 //////////////////////////////////////////////////////
1372 // CvButtonbar
1373
1374
1375 //here CvButtonbar class
1376 CvButtonbar::CvButtonbar(QWidget* arg,  QString arg2)
1377 {
1378     type = type_CvButtonbar;
1379     myparent = arg;
1380     name_bar = arg2;
1381     setObjectName(name_bar);
1382
1383     group_button = new QButtonGroup(this);
1384 }
1385
1386
1387 void CvButtonbar::setLabel()
1388 {
1389     QString nameNormalized = name_bar.leftJustified(10, ' ', true);
1390     label->setText(nameNormalized);
1391 }
1392
1393
1394 void CvButtonbar::addButton(QString name, CvButtonCallback call, void* userdata,  int button_type, int initial_button_state)
1395 {
1396     QString button_name = name;
1397
1398     if (button_name == "")
1399         button_name = tr("button %1").arg(this->count());
1400
1401     QPointer<QAbstractButton> button;
1402
1403     if (button_type == CV_PUSH_BUTTON)
1404         button = (QAbstractButton*) new CvPushButton(this, button_name,call, userdata);
1405
1406     if (button_type == CV_CHECKBOX)
1407         button = (QAbstractButton*) new CvCheckBox(this, button_name,call, userdata, initial_button_state);
1408
1409     if (button_type == CV_RADIOBOX)
1410     {
1411         button = (QAbstractButton*) new CvRadioButton(this, button_name,call, userdata, initial_button_state);
1412         group_button->addButton(button);
1413     }
1414
1415     if (button)
1416     {
1417         if (button_type == CV_PUSH_BUTTON)
1418             QObject::connect(button, SIGNAL(clicked(bool)), button, SLOT(callCallBack(bool)));
1419         else
1420             QObject::connect(button, SIGNAL(toggled(bool)), button, SLOT(callCallBack(bool)));
1421
1422         addWidget(button, Qt::AlignCenter);
1423     }
1424 }
1425
1426
1427 //////////////////////////////////////////////////////
1428 // Buttons
1429
1430
1431 //buttons here
1432 CvPushButton::CvPushButton(CvButtonbar* arg1, QString arg2, CvButtonCallback arg3, void* arg4)
1433 {
1434     myparent = arg1;
1435     button_name = arg2;
1436     callback = arg3;
1437     userdata = arg4;
1438
1439     setObjectName(button_name);
1440     setText(button_name);
1441
1442     if (isChecked())
1443         callCallBack(true);
1444 }
1445
1446
1447 void CvPushButton::callCallBack(bool checked)
1448 {
1449     if (callback)
1450         callback(checked, userdata);
1451 }
1452
1453
1454 CvCheckBox::CvCheckBox(CvButtonbar* arg1, QString arg2, CvButtonCallback arg3, void* arg4, int initial_button_state)
1455 {
1456     myparent = arg1;
1457     button_name = arg2;
1458     callback = arg3;
1459     userdata = arg4;
1460
1461     setObjectName(button_name);
1462     setCheckState((initial_button_state == 1 ? Qt::Checked : Qt::Unchecked));
1463     setText(button_name);
1464
1465     if (isChecked())
1466         callCallBack(true);
1467 }
1468
1469
1470 void CvCheckBox::callCallBack(bool checked)
1471 {
1472     if (callback)
1473         callback(checked, userdata);
1474 }
1475
1476
1477 CvRadioButton::CvRadioButton(CvButtonbar* arg1, QString arg2, CvButtonCallback arg3, void* arg4, int initial_button_state)
1478 {
1479     myparent = arg1;
1480     button_name = arg2;
1481     callback = arg3;
1482     userdata = arg4;
1483
1484     setObjectName(button_name);
1485     setChecked(initial_button_state);
1486     setText(button_name);
1487
1488     if (isChecked())
1489         callCallBack(true);
1490 }
1491
1492 void CvRadioButton::callCallBack(bool checked)
1493 {
1494     if (callback)
1495         callback(checked, userdata);
1496 }
1497
1498
1499 //////////////////////////////////////////////////////
1500 // CvWinProperties
1501
1502
1503 //here CvWinProperties class
1504 CvWinProperties::CvWinProperties(QString name_paraWindow, QObject* /*parent*/)
1505 {
1506     //setParent(parent);
1507     type = type_CvWinProperties;
1508     setWindowFlags(Qt::Tool);
1509     setContentsMargins(0, 0, 0, 0);
1510     setWindowTitle(name_paraWindow);
1511     setObjectName(name_paraWindow);
1512     resize(100, 50);
1513
1514     myLayout = new QBoxLayout(QBoxLayout::TopToBottom);
1515     myLayout->setObjectName(QString::fromUtf8("boxLayout"));
1516     myLayout->setContentsMargins(0, 0, 0, 0);
1517     myLayout->setSpacing(0);
1518     myLayout->setMargin(0);
1519     myLayout->setSizeConstraint(QLayout::SetFixedSize);
1520     setLayout(myLayout);
1521
1522     hide();
1523 }
1524
1525
1526 void CvWinProperties::closeEvent(QCloseEvent* e)
1527 {
1528     e->accept(); //intersept the close event (not sure I really need it)
1529     //an hide event is also sent. I will intercept it and do some processing
1530 }
1531
1532
1533 void CvWinProperties::showEvent(QShowEvent* evnt)
1534 {
1535     //why -1,-1 ?: do this trick because the first time the code is run,
1536     //no value pos was saved so we let Qt move the window in the middle of its parent (event ignored).
1537     //then hide will save the last position and thus, we want to retreive it (event accepted).
1538     QPoint mypos(-1, -1);
1539     QSettings settings("OpenCV2", objectName());
1540     mypos = settings.value("pos", mypos).toPoint();
1541
1542     if (mypos.x() >= 0)
1543     {
1544         move(mypos);
1545         evnt->accept();
1546     }
1547     else
1548     {
1549         evnt->ignore();
1550     }
1551 }
1552
1553
1554 void CvWinProperties::hideEvent(QHideEvent* evnt)
1555 {
1556     QSettings settings("OpenCV2", objectName());
1557     settings.setValue("pos", pos()); //there is an offset of 6 pixels (so the window's position is wrong -- why ?)
1558     evnt->accept();
1559 }
1560
1561
1562 CvWinProperties::~CvWinProperties()
1563 {
1564     //clear the setting pos
1565     QSettings settings("OpenCV2", objectName());
1566     settings.remove("pos");
1567 }
1568
1569
1570 //////////////////////////////////////////////////////
1571 // CvWindow
1572
1573
1574 CvWindow::CvWindow(QString name, int arg2)
1575 {
1576     type = type_CvWindow;
1577
1578     param_flags = arg2 & 0x0000000F;
1579     param_gui_mode = arg2 & 0x000000F0;
1580     param_ratio_mode =  arg2 & 0x00000F00;
1581
1582     //setAttribute(Qt::WA_DeleteOnClose); //in other case, does not release memory
1583     setContentsMargins(0, 0, 0, 0);
1584     setWindowTitle(name);
1585     setObjectName(name);
1586
1587     setFocus( Qt::PopupFocusReason ); //#1695 arrow keys are not received without the explicit focus
1588
1589     resize(400, 300);
1590     setMinimumSize(1, 1);
1591
1592     //1: create control panel
1593     if (!global_control_panel)
1594         global_control_panel = createParameterWindow();
1595
1596     //2: Layouts
1597     createBarLayout();
1598     createGlobalLayout();
1599
1600     //3: my view
1601 #ifndef HAVE_QT_OPENGL
1602     if (arg2 & CV_WINDOW_OPENGL)
1603         CV_Error( CV_OpenGlNotSupported, "Library was built without OpenGL support" );
1604     mode_display = CV_MODE_NORMAL;
1605 #else
1606     mode_display = arg2 & CV_WINDOW_OPENGL ? CV_MODE_OPENGL : CV_MODE_NORMAL;
1607     if (mode_display == CV_MODE_OPENGL)
1608         param_gui_mode = CV_GUI_NORMAL;
1609 #endif
1610     createView();
1611
1612     //4: shortcuts and actions
1613     //5: toolBar and statusbar
1614     if (param_gui_mode == CV_GUI_EXPANDED)
1615     {
1616         createActions();
1617         createShortcuts();
1618
1619         createToolBar();
1620         createStatusBar();
1621     }
1622
1623     //Now attach everything
1624     if (myToolBar)
1625         myGlobalLayout->addWidget(myToolBar, Qt::AlignCenter);
1626
1627     myGlobalLayout->addWidget(myView->getWidget(), Qt::AlignCenter);
1628
1629     myGlobalLayout->addLayout(myBarLayout, Qt::AlignCenter);
1630
1631     if (myStatusBar)
1632         myGlobalLayout->addWidget(myStatusBar, Qt::AlignCenter);
1633
1634     setLayout(myGlobalLayout);
1635     show();
1636 }
1637
1638
1639 CvWindow::~CvWindow()
1640 {
1641     if (guiMainThread)
1642         guiMainThread->isLastWindow();
1643 }
1644
1645
1646 void CvWindow::setMouseCallBack(CvMouseCallback callback, void* param)
1647 {
1648     myView->setMouseCallBack(callback, param);
1649 }
1650
1651
1652 void CvWindow::writeSettings()
1653 {
1654     //organisation and application's name
1655     QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName());
1656
1657     settings.setValue("pos", pos());
1658     settings.setValue("size", size());
1659     settings.setValue("mode_resize" ,param_flags);
1660     settings.setValue("mode_gui", param_gui_mode);
1661
1662     myView->writeSettings(settings);
1663
1664     icvSaveTrackbars(&settings);
1665
1666     if (global_control_panel)
1667     {
1668         icvSaveControlPanel();
1669         settings.setValue("posPanel", global_control_panel->pos());
1670     }
1671 }
1672
1673
1674
1675 //TODO: load CV_GUI flag (done) and act accordingly (create win property if needed and attach trackbars)
1676 void CvWindow::readSettings()
1677 {
1678     //organisation and application's name
1679     QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName());
1680
1681     QPoint _pos = settings.value("pos", QPoint(200, 200)).toPoint();
1682     QSize _size = settings.value("size", QSize(400, 400)).toSize();
1683
1684     param_flags = settings.value("mode_resize", param_flags).toInt();
1685     param_gui_mode = settings.value("mode_gui", param_gui_mode).toInt();
1686
1687     param_flags = settings.value("mode_resize", param_flags).toInt();
1688
1689     myView->readSettings(settings);
1690
1691     //trackbar here
1692     icvLoadTrackbars(&settings);
1693
1694     resize(_size);
1695     move(_pos);
1696
1697     if (global_control_panel)
1698     {
1699         icvLoadControlPanel();
1700         global_control_panel->move(settings.value("posPanel", global_control_panel->pos()).toPoint());
1701     }
1702 }
1703
1704
1705 double CvWindow::getRatio()
1706 {
1707     return myView->getRatio();
1708 }
1709
1710
1711 void CvWindow::setRatio(int flags)
1712 {
1713     myView->setRatio(flags);
1714 }
1715
1716
1717 int CvWindow::getPropWindow()
1718 {
1719     return param_flags;
1720 }
1721
1722
1723 void CvWindow::setPropWindow(int flags)
1724 {
1725     if (param_flags == flags) //nothing to do
1726         return;
1727
1728     switch(flags)
1729     {
1730     case CV_WINDOW_NORMAL:
1731         myGlobalLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);
1732         param_flags = flags;
1733
1734         break;
1735
1736     case CV_WINDOW_AUTOSIZE:
1737         myGlobalLayout->setSizeConstraint(QLayout::SetFixedSize);
1738         param_flags = flags;
1739
1740         break;
1741
1742     default:
1743         ;
1744     }
1745 }
1746
1747 void CvWindow::toggleFullScreen(int flags)
1748 {
1749     if (isFullScreen() && flags == CV_WINDOW_NORMAL)
1750     {
1751         showTools();
1752         showNormal();
1753         return;
1754     }
1755
1756     if (!isFullScreen() && flags == CV_WINDOW_FULLSCREEN)
1757     {
1758         hideTools();
1759         showFullScreen();
1760         return;
1761     }
1762 }
1763
1764
1765 void CvWindow::updateImage(void* arr)
1766 {
1767     myView->updateImage(arr);
1768 }
1769
1770
1771 void CvWindow::displayInfo(QString text, int delayms)
1772 {
1773     myView->startDisplayInfo(text, delayms);
1774 }
1775
1776
1777 void CvWindow::displayStatusBar(QString text, int delayms)
1778 {
1779     if (myStatusBar)
1780         myStatusBar->showMessage(text, delayms);
1781 }
1782
1783
1784 void CvWindow::enablePropertiesButton()
1785 {
1786     if (!vect_QActions.empty())
1787         vect_QActions[9]->setDisabled(false);
1788 }
1789
1790
1791 CvButtonbar* CvWindow::createButtonBar(QString name_bar)
1792 {
1793     QPointer<CvButtonbar> t = new CvButtonbar(global_control_panel, name_bar);
1794     t->setAlignment(Qt::AlignHCenter);
1795
1796     QPointer<QBoxLayout> myLayout = global_control_panel->myLayout;
1797
1798     myLayout->insertLayout(myLayout->count(), t);
1799
1800     return t;
1801 }
1802
1803
1804 void CvWindow::addSlider(CvWindow* w, QString name, int* value, int count, CvTrackbarCallback on_change)
1805 {
1806     QPointer<CvTrackbar> t = new CvTrackbar(w, name, value, count, on_change);
1807     t->setAlignment(Qt::AlignHCenter);
1808
1809     QPointer<QBoxLayout> myLayout;
1810
1811     if (w)
1812     {
1813         myLayout = w->myBarLayout;
1814     }
1815     else
1816     {
1817         myLayout = global_control_panel->myLayout;
1818
1819         //if first one, enable control panel
1820         if (myLayout->count() == 0)
1821             guiMainThread->enablePropertiesButtonEachWindow();
1822     }
1823
1824     myLayout->insertLayout(myLayout->count(), t);
1825 }
1826
1827
1828 void CvWindow::addSlider2(CvWindow* w, QString name, int* value, int count, CvTrackbarCallback2 on_change, void* userdata)
1829 {
1830     QPointer<CvTrackbar> t = new CvTrackbar(w, name, value, count, on_change, userdata);
1831     t->setAlignment(Qt::AlignHCenter);
1832
1833     QPointer<QBoxLayout> myLayout;
1834
1835     if (w)
1836     {
1837         myLayout = w->myBarLayout;
1838     }
1839     else
1840     {
1841         myLayout = global_control_panel->myLayout;
1842
1843         //if first one, enable control panel
1844         if (myLayout->count() == 0)
1845             guiMainThread->enablePropertiesButtonEachWindow();
1846     }
1847
1848     myLayout->insertLayout(myLayout->count(), t);
1849 }
1850
1851
1852 void CvWindow::setOpenGlDrawCallback(CvOpenGlDrawCallback callback, void* userdata)
1853 {
1854     myView->setOpenGlDrawCallback(callback, userdata);
1855 }
1856
1857
1858 void CvWindow::makeCurrentOpenGlContext()
1859 {
1860     myView->makeCurrentOpenGlContext();
1861 }
1862
1863
1864 void CvWindow::updateGl()
1865 {
1866     myView->updateGl();
1867 }
1868
1869
1870 bool CvWindow::isOpenGl()
1871 {
1872     return mode_display == CV_MODE_OPENGL;
1873 }
1874
1875
1876 void CvWindow::setViewportSize(QSize _size)
1877 {
1878     myView->getWidget()->resize(_size);
1879     myView->setSize(_size);
1880 }
1881
1882
1883 void CvWindow::createBarLayout()
1884 {
1885     myBarLayout = new QBoxLayout(QBoxLayout::TopToBottom);
1886     myBarLayout->setObjectName(QString::fromUtf8("barLayout"));
1887     myBarLayout->setContentsMargins(0, 0, 0, 0);
1888     myBarLayout->setSpacing(0);
1889     myBarLayout->setMargin(0);
1890 }
1891
1892
1893 void CvWindow::createGlobalLayout()
1894 {
1895     myGlobalLayout = new QBoxLayout(QBoxLayout::TopToBottom);
1896     myGlobalLayout->setObjectName(QString::fromUtf8("boxLayout"));
1897     myGlobalLayout->setContentsMargins(0, 0, 0, 0);
1898     myGlobalLayout->setSpacing(0);
1899     myGlobalLayout->setMargin(0);
1900     setMinimumSize(1, 1);
1901
1902     if (param_flags == CV_WINDOW_AUTOSIZE)
1903         myGlobalLayout->setSizeConstraint(QLayout::SetFixedSize);
1904     else if (param_flags == CV_WINDOW_NORMAL)
1905         myGlobalLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);
1906 }
1907
1908
1909 void CvWindow::createView()
1910 {
1911 #ifdef HAVE_QT_OPENGL
1912     if (isOpenGl())
1913         myView = new OpenGlViewPort(this);
1914     else
1915 #endif
1916         myView = new DefaultViewPort(this, param_ratio_mode);
1917 }
1918
1919
1920 void CvWindow::createActions()
1921 {
1922     vect_QActions.resize(10);
1923
1924     QWidget* view = myView->getWidget();
1925
1926     //if the shortcuts are changed in window_QT.h, we need to update the tooltip manually
1927     vect_QActions[0] = new QAction(QIcon(":/left-icon"), "Panning left (CTRL+arrowLEFT)", this);
1928     vect_QActions[0]->setIconVisibleInMenu(true);
1929     QObject::connect(vect_QActions[0], SIGNAL(triggered()), view, SLOT(siftWindowOnLeft()));
1930
1931     vect_QActions[1] = new QAction(QIcon(":/right-icon"), "Panning right (CTRL+arrowRIGHT)", this);
1932     vect_QActions[1]->setIconVisibleInMenu(true);
1933     QObject::connect(vect_QActions[1], SIGNAL(triggered()), view, SLOT(siftWindowOnRight()));
1934
1935     vect_QActions[2] = new QAction(QIcon(":/up-icon"), "Panning up (CTRL+arrowUP)", this);
1936     vect_QActions[2]->setIconVisibleInMenu(true);
1937     QObject::connect(vect_QActions[2], SIGNAL(triggered()), view, SLOT(siftWindowOnUp()));
1938
1939     vect_QActions[3] = new QAction(QIcon(":/down-icon"), "Panning down (CTRL+arrowDOWN)", this);
1940     vect_QActions[3]->setIconVisibleInMenu(true);
1941     QObject::connect(vect_QActions[3], SIGNAL(triggered()), view, SLOT(siftWindowOnDown()) );
1942
1943     vect_QActions[4] = new QAction(QIcon(":/zoom_x1-icon"), "Zoom x1 (CTRL+P)", this);
1944     vect_QActions[4]->setIconVisibleInMenu(true);
1945     QObject::connect(vect_QActions[4], SIGNAL(triggered()), view, SLOT(resetZoom()));
1946
1947     vect_QActions[5] = new QAction(QIcon(":/imgRegion-icon"), tr("Zoom x%1 (see label) (CTRL+X)").arg(threshold_zoom_img_region), this);
1948     vect_QActions[5]->setIconVisibleInMenu(true);
1949     QObject::connect(vect_QActions[5], SIGNAL(triggered()), view, SLOT(imgRegion()));
1950
1951     vect_QActions[6] = new QAction(QIcon(":/zoom_in-icon"), "Zoom in (CTRL++)", this);
1952     vect_QActions[6]->setIconVisibleInMenu(true);
1953     QObject::connect(vect_QActions[6], SIGNAL(triggered()), view, SLOT(ZoomIn()));
1954
1955     vect_QActions[7] = new QAction(QIcon(":/zoom_out-icon"), "Zoom out (CTRL+-)", this);
1956     vect_QActions[7]->setIconVisibleInMenu(true);
1957     QObject::connect(vect_QActions[7], SIGNAL(triggered()), view, SLOT(ZoomOut()));
1958
1959     vect_QActions[8] = new QAction(QIcon(":/save-icon"), "Save current image (CTRL+S)", this);
1960     vect_QActions[8]->setIconVisibleInMenu(true);
1961     QObject::connect(vect_QActions[8], SIGNAL(triggered()), view, SLOT(saveView()));
1962
1963     vect_QActions[9] = new QAction(QIcon(":/properties-icon"), "Display properties window (CTRL+P)", this);
1964     vect_QActions[9]->setIconVisibleInMenu(true);
1965     QObject::connect(vect_QActions[9], SIGNAL(triggered()), this, SLOT(displayPropertiesWin()));
1966
1967     if (global_control_panel->myLayout->count() == 0)
1968         vect_QActions[9]->setDisabled(true);
1969 }
1970
1971
1972 void CvWindow::createShortcuts()
1973 {
1974     vect_QShortcuts.resize(10);
1975
1976     QWidget* view = myView->getWidget();
1977
1978     vect_QShortcuts[0] = new QShortcut(shortcut_panning_left, this);
1979     QObject::connect(vect_QShortcuts[0], SIGNAL(activated()), view, SLOT(siftWindowOnLeft()));
1980
1981     vect_QShortcuts[1] = new QShortcut(shortcut_panning_right, this);
1982     QObject::connect(vect_QShortcuts[1], SIGNAL(activated()), view, SLOT(siftWindowOnRight()));
1983
1984     vect_QShortcuts[2] = new QShortcut(shortcut_panning_up, this);
1985     QObject::connect(vect_QShortcuts[2], SIGNAL(activated()), view, SLOT(siftWindowOnUp()));
1986
1987     vect_QShortcuts[3] = new QShortcut(shortcut_panning_down, this);
1988     QObject::connect(vect_QShortcuts[3], SIGNAL(activated()), view, SLOT(siftWindowOnDown()));
1989
1990     vect_QShortcuts[4] = new QShortcut(shortcut_zoom_normal, this);
1991     QObject::connect(vect_QShortcuts[4], SIGNAL(activated()), view, SLOT(resetZoom()));
1992
1993     vect_QShortcuts[5] = new QShortcut(shortcut_zoom_imgRegion, this);
1994     QObject::connect(vect_QShortcuts[5], SIGNAL(activated()), view, SLOT(imgRegion()));
1995
1996     vect_QShortcuts[6] = new QShortcut(shortcut_zoom_in, this);
1997     QObject::connect(vect_QShortcuts[6], SIGNAL(activated()), view, SLOT(ZoomIn()));
1998
1999     vect_QShortcuts[7] = new QShortcut(shortcut_zoom_out, this);
2000     QObject::connect(vect_QShortcuts[7], SIGNAL(activated()), view, SLOT(ZoomOut()));
2001
2002     vect_QShortcuts[8] = new QShortcut(shortcut_save_img, this);
2003     QObject::connect(vect_QShortcuts[8], SIGNAL(activated()), view, SLOT(saveView()));
2004
2005     vect_QShortcuts[9] = new QShortcut(shortcut_properties_win, this);
2006     QObject::connect(vect_QShortcuts[9], SIGNAL(activated()), this, SLOT(displayPropertiesWin()));
2007 }
2008
2009
2010 void CvWindow::createToolBar()
2011 {
2012     myToolBar = new QToolBar(this);
2013     myToolBar->setFloatable(false); //is not a window
2014     myToolBar->setFixedHeight(28);
2015     myToolBar->setMinimumWidth(1);
2016
2017     foreach (QAction *a, vect_QActions)
2018         myToolBar->addAction(a);
2019 }
2020
2021
2022 void CvWindow::createStatusBar()
2023 {
2024     myStatusBar = new QStatusBar(this);
2025     myStatusBar->setSizeGripEnabled(false);
2026     myStatusBar->setFixedHeight(20);
2027     myStatusBar->setMinimumWidth(1);
2028     myStatusBar_msg = new QLabel;
2029
2030     //I comment this because if we change the style, myview (the picture)
2031     //will not be the correct size anymore (will lost 2 pixel because of the borders)
2032
2033     //myStatusBar_msg->setFrameStyle(QFrame::Raised);
2034
2035     myStatusBar_msg->setAlignment(Qt::AlignHCenter);
2036     myStatusBar->addWidget(myStatusBar_msg);
2037 }
2038
2039
2040 void CvWindow::hideTools()
2041 {
2042     if (myToolBar)
2043         myToolBar->hide();
2044
2045     if (myStatusBar)
2046         myStatusBar->hide();
2047
2048     if (global_control_panel)
2049         global_control_panel->hide();
2050 }
2051
2052
2053 void CvWindow::showTools()
2054 {
2055     if (myToolBar)
2056         myToolBar->show();
2057
2058     if (myStatusBar)
2059         myStatusBar->show();
2060 }
2061
2062
2063 CvWinProperties* CvWindow::createParameterWindow()
2064 {
2065     QString name_paraWindow = QFileInfo(QApplication::applicationFilePath()).fileName() + " settings";
2066
2067     CvWinProperties* result = new CvWinProperties(name_paraWindow, guiMainThread);
2068
2069     return result;
2070 }
2071
2072
2073 void CvWindow::displayPropertiesWin()
2074 {
2075     if (global_control_panel->isHidden())
2076         global_control_panel->show();
2077     else
2078         global_control_panel->hide();
2079 }
2080
2081
2082 //Need more test here !
2083 void CvWindow::keyPressEvent(QKeyEvent *evnt)
2084 {
2085     //see http://doc.trolltech.com/4.6/qt.html#Key-enum
2086     int key = evnt->key();
2087
2088         Qt::Key qtkey = static_cast<Qt::Key>(key);
2089         char asciiCode = QTest::keyToAscii(qtkey);
2090         if (asciiCode != 0)
2091             key = static_cast<int>(asciiCode);
2092         else
2093             key = evnt->nativeVirtualKey(); //same codes as returned by GTK-based backend
2094
2095     //control plus (Z, +, -, up, down, left, right) are used for zoom/panning functions
2096         if (evnt->modifiers() != Qt::ControlModifier)
2097         {
2098         mutexKey.lock();
2099         last_key = key;
2100         mutexKey.unlock();
2101         key_pressed.wakeAll();
2102         //evnt->accept();
2103     }
2104
2105     QWidget::keyPressEvent(evnt);
2106 }
2107
2108
2109 void CvWindow::icvLoadControlPanel()
2110 {
2111     QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName() + " control panel");
2112
2113     int bsize = settings.beginReadArray("bars");
2114
2115     if (bsize == global_control_panel->myLayout->layout()->count())
2116     {
2117         for (int i = 0; i < bsize; ++i)
2118         {
2119             CvBar* t = (CvBar*) global_control_panel->myLayout->layout()->itemAt(i);
2120             settings.setArrayIndex(i);
2121             if (t->type == type_CvTrackbar)
2122             {
2123                 if (t->name_bar == settings.value("namebar").toString())
2124                 {
2125                     ((CvTrackbar*)t)->slider->setValue(settings.value("valuebar").toInt());
2126                 }
2127             }
2128             if (t->type == type_CvButtonbar)
2129             {
2130                 int subsize = settings.beginReadArray(QString("buttonbar")+i);
2131
2132                 if ( subsize == ((CvButtonbar*)t)->layout()->count() )
2133                     icvLoadButtonbar((CvButtonbar*)t,&settings);
2134
2135                 settings.endArray();
2136             }
2137         }
2138     }
2139
2140     settings.endArray();
2141 }
2142
2143
2144 void CvWindow::icvSaveControlPanel()
2145 {
2146     QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName()+" control panel");
2147
2148     settings.beginWriteArray("bars");
2149
2150     for (int i = 0; i < global_control_panel->myLayout->layout()->count(); ++i)
2151     {
2152         CvBar* t = (CvBar*) global_control_panel->myLayout->layout()->itemAt(i);
2153         settings.setArrayIndex(i);
2154         if (t->type == type_CvTrackbar)
2155         {
2156             settings.setValue("namebar", QString(t->name_bar));
2157             settings.setValue("valuebar",((CvTrackbar*)t)->slider->value());
2158         }
2159         if (t->type == type_CvButtonbar)
2160         {
2161             settings.beginWriteArray(QString("buttonbar")+i);
2162             icvSaveButtonbar((CvButtonbar*)t,&settings);
2163             settings.endArray();
2164         }
2165     }
2166
2167     settings.endArray();
2168 }
2169
2170
2171 void CvWindow::icvSaveButtonbar(CvButtonbar* b, QSettings* settings)
2172 {
2173     for (int i = 0, count = b->layout()->count(); i < count; ++i)
2174     {
2175         settings->setArrayIndex(i);
2176
2177         QWidget* temp = (QWidget*) b->layout()->itemAt(i)->widget();
2178         QString myclass(QLatin1String(temp->metaObject()->className()));
2179
2180         if (myclass == "CvPushButton")
2181         {
2182             CvPushButton* button = (CvPushButton*) temp;
2183             settings->setValue("namebutton", button->text());
2184             settings->setValue("valuebutton", int(button->isChecked()));
2185         }
2186         else if (myclass == "CvCheckBox")
2187         {
2188             CvCheckBox* button = (CvCheckBox*) temp;
2189             settings->setValue("namebutton", button->text());
2190             settings->setValue("valuebutton", int(button->isChecked()));
2191         }
2192         else if (myclass == "CvRadioButton")
2193         {
2194             CvRadioButton* button = (CvRadioButton*) temp;
2195             settings->setValue("namebutton", button->text());
2196             settings->setValue("valuebutton", int(button->isChecked()));
2197         }
2198     }
2199 }
2200
2201
2202 void CvWindow::icvLoadButtonbar(CvButtonbar* b, QSettings* settings)
2203 {
2204     for (int i = 0, count = b->layout()->count(); i < count; ++i)
2205     {
2206         settings->setArrayIndex(i);
2207
2208         QWidget* temp = (QWidget*) b->layout()->itemAt(i)->widget();
2209         QString myclass(QLatin1String(temp->metaObject()->className()));
2210
2211         if (myclass == "CvPushButton")
2212         {
2213             CvPushButton* button = (CvPushButton*) temp;
2214
2215             if (button->text() == settings->value("namebutton").toString())
2216                 button->setChecked(settings->value("valuebutton").toInt());
2217         }
2218         else if (myclass == "CvCheckBox")
2219         {
2220             CvCheckBox* button = (CvCheckBox*) temp;
2221
2222             if (button->text() == settings->value("namebutton").toString())
2223                 button->setChecked(settings->value("valuebutton").toInt());
2224         }
2225         else if (myclass == "CvRadioButton")
2226         {
2227             CvRadioButton* button = (CvRadioButton*) temp;
2228
2229             if (button->text() == settings->value("namebutton").toString())
2230                 button->setChecked(settings->value("valuebutton").toInt());
2231         }
2232
2233     }
2234 }
2235
2236
2237 void CvWindow::icvLoadTrackbars(QSettings* settings)
2238 {
2239     int bsize = settings->beginReadArray("trackbars");
2240
2241     //trackbar are saved in the same order, so no need to use icvFindTrackbarByName
2242
2243     if (myBarLayout->layout()->count() == bsize) //if not the same number, the window saved and loaded is not the same (nb trackbar not equal)
2244     {
2245         for (int i = 0; i < bsize; ++i)
2246         {
2247             settings->setArrayIndex(i);
2248
2249             CvTrackbar* t = (CvTrackbar*) myBarLayout->layout()->itemAt(i);
2250
2251             if (t->name_bar == settings->value("name").toString())
2252                 t->slider->setValue(settings->value("value").toInt());
2253
2254         }
2255     }
2256
2257     settings->endArray();
2258 }
2259
2260
2261 void CvWindow::icvSaveTrackbars(QSettings* settings)
2262 {
2263     settings->beginWriteArray("trackbars");
2264
2265     for (int i = 0; i < myBarLayout->layout()->count(); ++i)
2266     {
2267         settings->setArrayIndex(i);
2268
2269         CvTrackbar* t = (CvTrackbar*) myBarLayout->layout()->itemAt(i);
2270
2271         settings->setValue("name", t->name_bar);
2272         settings->setValue("value", t->slider->value());
2273     }
2274
2275     settings->endArray();
2276 }
2277
2278
2279 //////////////////////////////////////////////////////
2280 // DefaultViewPort
2281
2282
2283 DefaultViewPort::DefaultViewPort(CvWindow* arg, int arg2) : QGraphicsView(arg), image2Draw_mat(0)
2284 {
2285     centralWidget = arg;
2286     param_keepRatio = arg2;
2287
2288     setContentsMargins(0, 0, 0, 0);
2289     setMinimumSize(1, 1);
2290     setAlignment(Qt::AlignHCenter);
2291
2292     setObjectName(QString::fromUtf8("graphicsView"));
2293
2294     timerDisplay = new QTimer(this);
2295     timerDisplay->setSingleShot(true);
2296     connect(timerDisplay, SIGNAL(timeout()), this, SLOT(stopDisplayInfo()));
2297
2298     drawInfo = false;
2299     positionGrabbing = QPointF(0, 0);
2300     positionCorners = QRect(0, 0, size().width(), size().height());
2301
2302     on_mouse = 0;
2303     on_mouse_param = 0;
2304     mouseCoordinate = QPoint(-1, -1);
2305
2306     //no border
2307     setStyleSheet( "QGraphicsView { border-style: none; }" );
2308
2309     image2Draw_mat = cvCreateMat(viewport()->height(), viewport()->width(), CV_8UC3);
2310     cvZero(image2Draw_mat);
2311
2312     nbChannelOriginImage = 0;
2313
2314     setInteractive(false);
2315     setMouseTracking(true); //receive mouse event everytime
2316 }
2317
2318
2319 DefaultViewPort::~DefaultViewPort()
2320 {
2321     if (image2Draw_mat)
2322         cvReleaseMat(&image2Draw_mat);
2323 }
2324
2325
2326 QWidget* DefaultViewPort::getWidget()
2327 {
2328     return this;
2329 }
2330
2331
2332 void DefaultViewPort::setMouseCallBack(CvMouseCallback m, void* param)
2333 {
2334     on_mouse = m;
2335
2336     on_mouse_param = param;
2337 }
2338
2339 void DefaultViewPort::writeSettings(QSettings& settings)
2340 {
2341     settings.setValue("matrix_view.m11", param_matrixWorld.m11());
2342     settings.setValue("matrix_view.m12", param_matrixWorld.m12());
2343     settings.setValue("matrix_view.m13", param_matrixWorld.m13());
2344     settings.setValue("matrix_view.m21", param_matrixWorld.m21());
2345     settings.setValue("matrix_view.m22", param_matrixWorld.m22());
2346     settings.setValue("matrix_view.m23", param_matrixWorld.m23());
2347     settings.setValue("matrix_view.m31", param_matrixWorld.m31());
2348     settings.setValue("matrix_view.m32", param_matrixWorld.m32());
2349     settings.setValue("matrix_view.m33", param_matrixWorld.m33());
2350 }
2351
2352
2353 void DefaultViewPort::readSettings(QSettings& settings)
2354 {
2355     qreal m11 = settings.value("matrix_view.m11", param_matrixWorld.m11()).toDouble();
2356     qreal m12 = settings.value("matrix_view.m12", param_matrixWorld.m12()).toDouble();
2357     qreal m13 = settings.value("matrix_view.m13", param_matrixWorld.m13()).toDouble();
2358     qreal m21 = settings.value("matrix_view.m21", param_matrixWorld.m21()).toDouble();
2359     qreal m22 = settings.value("matrix_view.m22", param_matrixWorld.m22()).toDouble();
2360     qreal m23 = settings.value("matrix_view.m23", param_matrixWorld.m23()).toDouble();
2361     qreal m31 = settings.value("matrix_view.m31", param_matrixWorld.m31()).toDouble();
2362     qreal m32 = settings.value("matrix_view.m32", param_matrixWorld.m32()).toDouble();
2363     qreal m33 = settings.value("matrix_view.m33", param_matrixWorld.m33()).toDouble();
2364
2365     param_matrixWorld = QTransform(m11, m12, m13, m21, m22, m23, m31, m32, m33);
2366 }
2367
2368
2369 double DefaultViewPort::getRatio()
2370 {
2371     return param_keepRatio;
2372 }
2373
2374
2375 void DefaultViewPort::setRatio(int flags)
2376 {
2377     if (getRatio() == flags) //nothing to do
2378         return;
2379
2380     //if valid flags
2381     if (flags == CV_WINDOW_FREERATIO || flags == CV_WINDOW_KEEPRATIO)
2382     {
2383         centralWidget->param_ratio_mode = flags;
2384         param_keepRatio = flags;
2385         updateGeometry();
2386         viewport()->update();
2387     }
2388 }
2389
2390
2391 void DefaultViewPort::updateImage(const CvArr* arr)
2392 {
2393     CV_Assert(arr);
2394
2395     CvMat* mat, stub;
2396     int origin = 0;
2397
2398     if (CV_IS_IMAGE_HDR(arr))
2399         origin = ((IplImage*)arr)->origin;
2400
2401     mat = cvGetMat(arr, &stub);
2402
2403     if (!image2Draw_mat || !CV_ARE_SIZES_EQ(image2Draw_mat, mat))
2404     {
2405         if (image2Draw_mat)
2406             cvReleaseMat(&image2Draw_mat);
2407
2408         //the image in ipl (to do a deep copy with cvCvtColor)
2409         image2Draw_mat = cvCreateMat(mat->rows, mat->cols, CV_8UC3);
2410         image2Draw_qt = QImage(image2Draw_mat->data.ptr, image2Draw_mat->cols, image2Draw_mat->rows, image2Draw_mat->step, QImage::Format_RGB888);
2411
2412         //use to compute mouse coordinate, I need to update the ratio here and in resizeEvent
2413         ratioX = width() / float(image2Draw_mat->cols);
2414         ratioY = height() / float(image2Draw_mat->rows);
2415         updateGeometry();
2416     }
2417
2418     nbChannelOriginImage = cvGetElemType(mat);
2419
2420     cvConvertImage(mat, image2Draw_mat, (origin != 0 ? CV_CVTIMG_FLIP : 0) + CV_CVTIMG_SWAP_RB);
2421
2422     viewport()->update();
2423 }
2424
2425
2426 void DefaultViewPort::startDisplayInfo(QString text, int delayms)
2427 {
2428     if (timerDisplay->isActive())
2429         stopDisplayInfo();
2430
2431     infoText = text;
2432     if (delayms > 0) timerDisplay->start(delayms);
2433     drawInfo = true;
2434 }
2435
2436
2437 void DefaultViewPort::setOpenGlDrawCallback(CvOpenGlDrawCallback /*callback*/, void* /*userdata*/)
2438 {
2439     CV_Error(CV_OpenGlNotSupported, "Window doesn't support OpenGL");
2440 }
2441
2442
2443 void DefaultViewPort::makeCurrentOpenGlContext()
2444 {
2445     CV_Error(CV_OpenGlNotSupported, "Window doesn't support OpenGL");
2446 }
2447
2448
2449 void DefaultViewPort::updateGl()
2450 {
2451     CV_Error(CV_OpenGlNotSupported, "Window doesn't support OpenGL");
2452 }
2453
2454
2455 //Note: move 2 percent of the window
2456 void DefaultViewPort::siftWindowOnLeft()
2457 {
2458     float delta = 2 * width() / (100.0 * param_matrixWorld.m11());
2459     moveView(QPointF(delta, 0));
2460 }
2461
2462
2463 //Note: move 2 percent of the window
2464 void DefaultViewPort::siftWindowOnRight()
2465 {
2466     float delta = -2 * width() / (100.0 * param_matrixWorld.m11());
2467     moveView(QPointF(delta, 0));
2468 }
2469
2470
2471 //Note: move 2 percent of the window
2472 void DefaultViewPort::siftWindowOnUp()
2473 {
2474     float delta = 2 * height() / (100.0 * param_matrixWorld.m11());
2475     moveView(QPointF(0, delta));
2476 }
2477
2478
2479 //Note: move 2 percent of the window
2480 void DefaultViewPort::siftWindowOnDown()
2481 {
2482     float delta = -2 * height() / (100.0 * param_matrixWorld.m11());
2483     moveView(QPointF(0, delta));
2484 }
2485
2486
2487 void DefaultViewPort::imgRegion()
2488 {
2489     scaleView((threshold_zoom_img_region / param_matrixWorld.m11() - 1) * 5, QPointF(size().width() / 2, size().height() / 2));
2490 }
2491
2492
2493 void DefaultViewPort::resetZoom()
2494 {
2495     param_matrixWorld.reset();
2496     controlImagePosition();
2497 }
2498
2499
2500 void DefaultViewPort::ZoomIn()
2501 {
2502     scaleView(0.5, QPointF(size().width() / 2, size().height() / 2));
2503 }
2504
2505
2506 void DefaultViewPort::ZoomOut()
2507 {
2508     scaleView(-0.5, QPointF(size().width() / 2, size().height() / 2));
2509 }
2510
2511
2512 //can save as JPG, JPEG, BMP, PNG
2513 void DefaultViewPort::saveView()
2514 {
2515     QDate date_d = QDate::currentDate();
2516     QString date_s = date_d.toString("dd.MM.yyyy");
2517     QString name_s = centralWidget->windowTitle() + "_screenshot_" + date_s;
2518
2519     QString fileName = QFileDialog::getSaveFileName(this, tr("Save File %1").arg(name_s), name_s + ".png", tr("Images (*.png *.jpg *.bmp *.jpeg)"));
2520
2521     if (!fileName.isEmpty()) //save the picture
2522     {
2523         QString extension = fileName.right(3);
2524
2525         // Create a new pixmap to render the viewport into
2526         QPixmap viewportPixmap(viewport()->size());
2527         viewport()->render(&viewportPixmap);
2528
2529         // Save it..
2530         if (QString::compare(extension, "png", Qt::CaseInsensitive) == 0)
2531         {
2532             viewportPixmap.save(fileName, "PNG");
2533             return;
2534         }
2535
2536         if (QString::compare(extension, "jpg", Qt::CaseInsensitive) == 0)
2537         {
2538             viewportPixmap.save(fileName, "JPG");
2539             return;
2540         }
2541
2542         if (QString::compare(extension, "bmp", Qt::CaseInsensitive) == 0)
2543         {
2544             viewportPixmap.save(fileName, "BMP");
2545             return;
2546         }
2547
2548         if (QString::compare(extension, "jpeg", Qt::CaseInsensitive) == 0)
2549         {
2550             viewportPixmap.save(fileName, "JPEG");
2551             return;
2552         }
2553
2554         CV_Error(CV_StsNullPtr, "file extension not recognized, please choose between JPG, JPEG, BMP or PNG");
2555     }
2556 }
2557
2558
2559 void DefaultViewPort::contextMenuEvent(QContextMenuEvent* evnt)
2560 {
2561     if (centralWidget->vect_QActions.size() > 0)
2562     {
2563         QMenu menu(this);
2564
2565         foreach (QAction *a, centralWidget->vect_QActions)
2566             menu.addAction(a);
2567
2568         menu.exec(evnt->globalPos());
2569     }
2570 }
2571
2572
2573 void DefaultViewPort::resizeEvent(QResizeEvent* evnt)
2574 {
2575     controlImagePosition();
2576
2577     //use to compute mouse coordinate, I need to update the ratio here and in resizeEvent
2578     ratioX = width() / float(image2Draw_mat->cols);
2579     ratioY = height() / float(image2Draw_mat->rows);
2580
2581     if (param_keepRatio == CV_WINDOW_KEEPRATIO)//to keep the same aspect ratio
2582     {
2583         QSize newSize = QSize(image2Draw_mat->cols, image2Draw_mat->rows);
2584         newSize.scale(evnt->size(), Qt::KeepAspectRatio);
2585
2586         //imageWidth/imageHeight = newWidth/newHeight +/- epsilon
2587         //ratioX = ratioY +/- epsilon
2588         //||ratioX - ratioY|| = epsilon
2589         if (fabs(ratioX - ratioY) * 100 > ratioX) //avoid infinity loop / epsilon = 1% of ratioX
2590         {
2591             resize(newSize);
2592
2593             //move to the middle
2594             //newSize get the delta offset to place the picture in the middle of its parent
2595             newSize = (evnt->size() - newSize) / 2;
2596
2597             //if the toolbar is displayed, avoid drawing myview on top of it
2598             if (centralWidget->myToolBar)
2599                 if(!centralWidget->myToolBar->isHidden())
2600                     newSize += QSize(0, centralWidget->myToolBar->height());
2601
2602             move(newSize.width(), newSize.height());
2603         }
2604     }
2605
2606     return QGraphicsView::resizeEvent(evnt);
2607 }
2608
2609
2610 void DefaultViewPort::wheelEvent(QWheelEvent* evnt)
2611 {
2612     scaleView(evnt->delta() / 240.0, evnt->pos());
2613     viewport()->update();
2614 }
2615
2616
2617 void DefaultViewPort::mousePressEvent(QMouseEvent* evnt)
2618 {
2619     int cv_event = -1, flags = 0;
2620     QPoint pt = evnt->pos();
2621
2622     //icvmouseHandler: pass parameters for cv_event, flags
2623     icvmouseHandler(evnt, mouse_down, cv_event, flags);
2624     icvmouseProcessing(QPointF(pt), cv_event, flags);
2625
2626     if (param_matrixWorld.m11()>1)
2627     {
2628         setCursor(Qt::ClosedHandCursor);
2629         positionGrabbing = evnt->pos();
2630     }
2631
2632     QWidget::mousePressEvent(evnt);
2633 }
2634
2635
2636 void DefaultViewPort::mouseReleaseEvent(QMouseEvent* evnt)
2637 {
2638     int cv_event = -1, flags = 0;
2639     QPoint pt = evnt->pos();
2640
2641     //icvmouseHandler: pass parameters for cv_event, flags
2642     icvmouseHandler(evnt, mouse_up, cv_event, flags);
2643     icvmouseProcessing(QPointF(pt), cv_event, flags);
2644
2645     if (param_matrixWorld.m11()>1)
2646         setCursor(Qt::OpenHandCursor);
2647
2648     QWidget::mouseReleaseEvent(evnt);
2649 }
2650
2651
2652 void DefaultViewPort::mouseDoubleClickEvent(QMouseEvent* evnt)
2653 {
2654     int cv_event = -1, flags = 0;
2655     QPoint pt = evnt->pos();
2656
2657     //icvmouseHandler: pass parameters for cv_event, flags
2658     icvmouseHandler(evnt, mouse_dbclick, cv_event, flags);
2659     icvmouseProcessing(QPointF(pt), cv_event, flags);
2660
2661     QWidget::mouseDoubleClickEvent(evnt);
2662 }
2663
2664
2665 void DefaultViewPort::mouseMoveEvent(QMouseEvent* evnt)
2666 {
2667     int cv_event = CV_EVENT_MOUSEMOVE, flags = 0;
2668     QPoint pt = evnt->pos();
2669
2670     //icvmouseHandler: pass parameters for cv_event, flags
2671     icvmouseHandler(evnt, mouse_move, cv_event, flags);
2672     icvmouseProcessing(QPointF(pt), cv_event, flags);
2673
2674     if (param_matrixWorld.m11() > 1 && evnt->buttons() == Qt::LeftButton)
2675     {
2676         QPointF dxy = (pt - positionGrabbing)/param_matrixWorld.m11();
2677         positionGrabbing = evnt->pos();
2678         moveView(dxy);
2679     }
2680
2681     //I update the statusbar here because if the user does a cvWaitkey(0) (like with inpaint.cpp)
2682     //the status bar will only be repaint when a click occurs.
2683     if (centralWidget->myStatusBar)
2684         viewport()->update();
2685
2686     QWidget::mouseMoveEvent(evnt);
2687 }
2688
2689
2690 void DefaultViewPort::paintEvent(QPaintEvent* evnt)
2691 {
2692     QPainter myPainter(viewport());
2693     myPainter.setWorldTransform(param_matrixWorld);
2694
2695     draw2D(&myPainter);
2696
2697     //Now disable matrixWorld for overlay display
2698     myPainter.setWorldMatrixEnabled(false);
2699
2700     //overlay pixel values if zoomed in far enough
2701     if (param_matrixWorld.m11()*ratioX >= threshold_zoom_img_region &&
2702         param_matrixWorld.m11()*ratioY >= threshold_zoom_img_region)
2703     {
2704         drawImgRegion(&myPainter);
2705     }
2706
2707     //in mode zoom/panning
2708     if (param_matrixWorld.m11() > 1)
2709     {
2710         drawViewOverview(&myPainter);
2711     }
2712
2713     //for information overlay
2714     if (drawInfo)
2715         drawInstructions(&myPainter);
2716
2717     //for statusbar
2718     if (centralWidget->myStatusBar)
2719         drawStatusBar();
2720
2721     QGraphicsView::paintEvent(evnt);
2722 }
2723
2724
2725 void DefaultViewPort::stopDisplayInfo()
2726 {
2727     timerDisplay->stop();
2728     drawInfo = false;
2729 }
2730
2731
2732 inline bool DefaultViewPort::isSameSize(IplImage* img1, IplImage* img2)
2733 {
2734     return img1->width == img2->width && img1->height == img2->height;
2735 }
2736
2737
2738 void DefaultViewPort::controlImagePosition()
2739 {
2740     qreal left, top, right, bottom;
2741
2742     //after check top-left, bottom right corner to avoid getting "out" during zoom/panning
2743     param_matrixWorld.map(0,0,&left,&top);
2744
2745     if (left > 0)
2746     {
2747         param_matrixWorld.translate(-left,0);
2748         left = 0;
2749     }
2750     if (top > 0)
2751     {
2752         param_matrixWorld.translate(0,-top);
2753         top = 0;
2754     }
2755     //-------
2756
2757     QSize sizeImage = size();
2758     param_matrixWorld.map(sizeImage.width(),sizeImage.height(),&right,&bottom);
2759     if (right < sizeImage.width())
2760     {
2761         param_matrixWorld.translate(sizeImage.width()-right,0);
2762         right = sizeImage.width();
2763     }
2764     if (bottom < sizeImage.height())
2765     {
2766         param_matrixWorld.translate(0,sizeImage.height()-bottom);
2767         bottom = sizeImage.height();
2768     }
2769
2770     //save corner position
2771     positionCorners.setTopLeft(QPoint(left,top));
2772     positionCorners.setBottomRight(QPoint(right,bottom));
2773     //save also the inv matrix
2774     matrixWorld_inv = param_matrixWorld.inverted();
2775
2776     //viewport()->update();
2777 }
2778
2779 void DefaultViewPort::moveView(QPointF delta)
2780 {
2781     param_matrixWorld.translate(delta.x(),delta.y());
2782     controlImagePosition();
2783     viewport()->update();
2784 }
2785
2786 //factor is -0.5 (zoom out) or 0.5 (zoom in)
2787 void DefaultViewPort::scaleView(qreal factor,QPointF center)
2788 {
2789     factor/=5;//-0.1 <-> 0.1
2790     factor+=1;//0.9 <-> 1.1
2791
2792     //limit zoom out ---
2793     if (param_matrixWorld.m11()==1 && factor < 1)
2794         return;
2795
2796     if (param_matrixWorld.m11()*factor<1)
2797         factor = 1/param_matrixWorld.m11();
2798
2799
2800     //limit zoom int ---
2801     if (param_matrixWorld.m11()>100 && factor > 1)
2802         return;
2803
2804     //inverse the transform
2805     int a, b;
2806     matrixWorld_inv.map(center.x(),center.y(),&a,&b);
2807
2808     param_matrixWorld.translate(a-factor*a,b-factor*b);
2809     param_matrixWorld.scale(factor,factor);
2810
2811     controlImagePosition();
2812
2813     //display new zoom
2814     if (centralWidget->myStatusBar)
2815         centralWidget->displayStatusBar(tr("Zoom: %1%").arg(param_matrixWorld.m11()*100),1000);
2816
2817     if (param_matrixWorld.m11()>1)
2818         setCursor(Qt::OpenHandCursor);
2819     else
2820         unsetCursor();
2821 }
2822
2823
2824 //up, down, dclick, move
2825 void DefaultViewPort::icvmouseHandler(QMouseEvent *evnt, type_mouse_event category, int &cv_event, int &flags)
2826 {
2827     Qt::KeyboardModifiers modifiers = evnt->modifiers();
2828     Qt::MouseButtons buttons = evnt->buttons();
2829
2830     flags = 0;
2831     if(modifiers & Qt::ShiftModifier)
2832         flags |= CV_EVENT_FLAG_SHIFTKEY;
2833     if(modifiers & Qt::ControlModifier)
2834         flags |= CV_EVENT_FLAG_CTRLKEY;
2835     if(modifiers & Qt::AltModifier)
2836         flags |= CV_EVENT_FLAG_ALTKEY;
2837
2838     if(buttons & Qt::LeftButton)
2839         flags |= CV_EVENT_FLAG_LBUTTON;
2840     if(buttons & Qt::RightButton)
2841         flags |= CV_EVENT_FLAG_RBUTTON;
2842     if(buttons & Qt::MidButton)
2843         flags |= CV_EVENT_FLAG_MBUTTON;
2844
2845     cv_event = CV_EVENT_MOUSEMOVE;
2846     switch(evnt->button())
2847     {
2848     case Qt::LeftButton:
2849         cv_event = tableMouseButtons[category][0];
2850         flags |= CV_EVENT_FLAG_LBUTTON;
2851         break;
2852     case Qt::RightButton:
2853         cv_event = tableMouseButtons[category][1];
2854         flags |= CV_EVENT_FLAG_RBUTTON;
2855         break;
2856     case Qt::MidButton:
2857         cv_event = tableMouseButtons[category][2];
2858         flags |= CV_EVENT_FLAG_MBUTTON;
2859         break;
2860     default:;
2861     }
2862 }
2863
2864
2865 void DefaultViewPort::icvmouseProcessing(QPointF pt, int cv_event, int flags)
2866 {
2867     //to convert mouse coordinate
2868     qreal pfx, pfy;
2869     matrixWorld_inv.map(pt.x(),pt.y(),&pfx,&pfy);
2870
2871     mouseCoordinate.rx()=floor(pfx/ratioX);
2872     mouseCoordinate.ry()=floor(pfy/ratioY);
2873
2874     if (on_mouse)
2875         on_mouse( cv_event, mouseCoordinate.x(),
2876             mouseCoordinate.y(), flags, on_mouse_param );
2877 }
2878
2879
2880 QSize DefaultViewPort::sizeHint() const
2881 {
2882     if(image2Draw_mat)
2883         return QSize(image2Draw_mat->cols, image2Draw_mat->rows);
2884     else
2885         return QGraphicsView::sizeHint();
2886 }
2887
2888
2889 void DefaultViewPort::draw2D(QPainter *painter)
2890 {
2891     image2Draw_qt = QImage(image2Draw_mat->data.ptr, image2Draw_mat->cols, image2Draw_mat->rows,image2Draw_mat->step,QImage::Format_RGB888);
2892     painter->drawImage(QRect(0,0,viewport()->width(),viewport()->height()), image2Draw_qt, QRect(0,0, image2Draw_qt.width(), image2Draw_qt.height()) );
2893 }
2894
2895 //only if CV_8UC1 or CV_8UC3
2896 void DefaultViewPort::drawStatusBar()
2897 {
2898     if (nbChannelOriginImage!=CV_8UC1 && nbChannelOriginImage!=CV_8UC3)
2899         return;
2900
2901     if (mouseCoordinate.x()>=0 &&
2902         mouseCoordinate.y()>=0 &&
2903         mouseCoordinate.x()<image2Draw_qt.width() &&
2904         mouseCoordinate.y()<image2Draw_qt.height())
2905 //  if (mouseCoordinate.x()>=0 && mouseCoordinate.y()>=0)
2906     {
2907         QRgb rgbValue = image2Draw_qt.pixel(mouseCoordinate);
2908
2909         if (nbChannelOriginImage==CV_8UC3 )
2910         {
2911             centralWidget->myStatusBar_msg->setText(tr("<font color='black'>(x=%1, y=%2) ~ </font>")
2912                 .arg(mouseCoordinate.x())
2913                 .arg(mouseCoordinate.y())+
2914                 tr("<font color='red'>R:%3 </font>").arg(qRed(rgbValue))+//.arg(value.val[0])+
2915                 tr("<font color='green'>G:%4 </font>").arg(qGreen(rgbValue))+//.arg(value.val[1])+
2916                 tr("<font color='blue'>B:%5</font>").arg(qBlue(rgbValue))//.arg(value.val[2])
2917                 );
2918         }
2919
2920         if (nbChannelOriginImage==CV_8UC1)
2921         {
2922             //all the channel have the same value (because of cvconvertimage), so only the r channel is dsplayed
2923             centralWidget->myStatusBar_msg->setText(tr("<font color='black'>(x=%1, y=%2) ~ </font>")
2924                 .arg(mouseCoordinate.x())
2925                 .arg(mouseCoordinate.y())+
2926                 tr("<font color='grey'>L:%3 </font>").arg(qRed(rgbValue))
2927                 );
2928         }
2929     }
2930 }
2931
2932 //accept only CV_8UC1 and CV_8UC8 image for now
2933 void DefaultViewPort::drawImgRegion(QPainter *painter)
2934 {
2935     if (nbChannelOriginImage!=CV_8UC1 && nbChannelOriginImage!=CV_8UC3)
2936         return;
2937
2938     double pixel_width = param_matrixWorld.m11()*ratioX;
2939     double pixel_height = param_matrixWorld.m11()*ratioY;
2940
2941     qreal offsetX = param_matrixWorld.dx()/pixel_width;
2942     offsetX = offsetX - floor(offsetX);
2943     qreal offsetY = param_matrixWorld.dy()/pixel_height;
2944     offsetY = offsetY - floor(offsetY);
2945
2946     QSize view = size();
2947     QVarLengthArray<QLineF, 30> linesX;
2948     for (qreal _x = offsetX*pixel_width; _x < view.width(); _x += pixel_width )
2949         linesX.append(QLineF(_x, 0, _x, view.height()));
2950
2951     QVarLengthArray<QLineF, 30> linesY;
2952     for (qreal _y = offsetY*pixel_height; _y < view.height(); _y += pixel_height )
2953         linesY.append(QLineF(0, _y, view.width(), _y));
2954
2955
2956     QFont f = painter->font();
2957     int original_font_size = f.pointSize();
2958     //change font size
2959     //f.setPointSize(4+(param_matrixWorld.m11()-threshold_zoom_img_region)/5);
2960     f.setPixelSize(10+(pixel_height-threshold_zoom_img_region)/5);
2961     painter->setFont(f);
2962
2963
2964     for (int j=-1;j<height()/pixel_height;j++)//-1 because display the pixels top rows left columns
2965         for (int i=-1;i<width()/pixel_width;i++)//-1
2966         {
2967             // Calculate top left of the pixel's position in the viewport (screen space)
2968             QPointF pos_in_view((i+offsetX)*pixel_width, (j+offsetY)*pixel_height);
2969
2970             // Calculate top left of the pixel's position in the image (image space)
2971             QPointF pos_in_image = matrixWorld_inv.map(pos_in_view);// Top left of pixel in view
2972             pos_in_image.rx() = pos_in_image.x()/ratioX;
2973             pos_in_image.ry() = pos_in_image.y()/ratioY;
2974             QPoint point_in_image(pos_in_image.x() + 0.5f,pos_in_image.y() + 0.5f);// Add 0.5 for rounding
2975
2976             QRgb rgbValue;
2977             if (image2Draw_qt.valid(point_in_image))
2978                 rgbValue = image2Draw_qt.pixel(point_in_image);
2979             else
2980                 rgbValue = qRgb(0,0,0);
2981
2982             if (nbChannelOriginImage==CV_8UC3)
2983             {
2984                 //for debug
2985                 /*
2986                 val = tr("%1 %2").arg(point2.x()).arg(point2.y());
2987                 painter->setPen(QPen(Qt::black, 1));
2988                 painter->drawText(QRect(point1.x(),point1.y(),param_matrixWorld.m11(),param_matrixWorld.m11()/2),
2989                     Qt::AlignCenter, val);
2990                 */
2991                 QString val;
2992
2993                 val = tr("%1").arg(qRed(rgbValue));
2994                 painter->setPen(QPen(Qt::red, 1));
2995                 painter->drawText(QRect(pos_in_view.x(),pos_in_view.y(),pixel_width,pixel_height/3),
2996                     Qt::AlignCenter, val);
2997
2998                 val = tr("%1").arg(qGreen(rgbValue));
2999                 painter->setPen(QPen(Qt::green, 1));
3000                 painter->drawText(QRect(pos_in_view.x(),pos_in_view.y()+pixel_height/3,pixel_width,pixel_height/3),
3001                     Qt::AlignCenter, val);
3002
3003                 val = tr("%1").arg(qBlue(rgbValue));
3004                 painter->setPen(QPen(Qt::blue, 1));
3005                 painter->drawText(QRect(pos_in_view.x(),pos_in_view.y()+2*pixel_height/3,pixel_width,pixel_height/3),
3006                     Qt::AlignCenter, val);
3007
3008             }
3009
3010             if (nbChannelOriginImage==CV_8UC1)
3011             {
3012                 QString val = tr("%1").arg(qRed(rgbValue));
3013                 painter->drawText(QRect(pos_in_view.x(),pos_in_view.y(),pixel_width,pixel_height),
3014                     Qt::AlignCenter, val);
3015             }
3016         }
3017
3018         painter->setPen(QPen(Qt::black, 1));
3019         painter->drawLines(linesX.data(), linesX.size());
3020         painter->drawLines(linesY.data(), linesY.size());
3021
3022         //restore font size
3023         f.setPointSize(original_font_size);
3024         painter->setFont(f);
3025
3026 }
3027
3028 void DefaultViewPort::drawViewOverview(QPainter *painter)
3029 {
3030     QSize viewSize = size();
3031     viewSize.scale ( 100, 100,Qt::KeepAspectRatio );
3032
3033     const int margin = 5;
3034
3035     //draw the image's location
3036     painter->setBrush(QColor(0, 0, 0, 127));
3037     painter->setPen(Qt::darkGreen);
3038     painter->drawRect(QRect(width()-viewSize.width()-margin, 0,viewSize.width(),viewSize.height()));
3039
3040     //daw the view's location inside the image
3041     qreal ratioSize = 1/param_matrixWorld.m11();
3042     qreal ratioWindow = (qreal)(viewSize.height())/(qreal)(size().height());
3043     painter->setPen(Qt::darkBlue);
3044     painter->drawRect(QRectF(width()-viewSize.width()-positionCorners.left()*ratioSize*ratioWindow-margin,
3045         -positionCorners.top()*ratioSize*ratioWindow,
3046         (viewSize.width()-1)*ratioSize,
3047         (viewSize.height()-1)*ratioSize)
3048         );
3049 }
3050
3051 void DefaultViewPort::drawInstructions(QPainter *painter)
3052 {
3053     QFontMetrics metrics = QFontMetrics(font());
3054     int border = qMax(4, metrics.leading());
3055
3056     QRect qrect = metrics.boundingRect(0, 0, width() - 2*border, int(height()*0.125),
3057         Qt::AlignCenter | Qt::TextWordWrap, infoText);
3058     painter->setRenderHint(QPainter::TextAntialiasing);
3059     painter->fillRect(QRect(0, 0, width(), qrect.height() + 2*border),
3060         QColor(0, 0, 0, 127));
3061     painter->setPen(Qt::white);
3062     painter->fillRect(QRect(0, 0, width(), qrect.height() + 2*border),
3063         QColor(0, 0, 0, 127));
3064
3065     painter->drawText((width() - qrect.width())/2, border,
3066         qrect.width(), qrect.height(),
3067         Qt::AlignCenter | Qt::TextWordWrap, infoText);
3068 }
3069
3070
3071 void DefaultViewPort::setSize(QSize /*size_*/)
3072 {
3073 }
3074
3075
3076 //////////////////////////////////////////////////////
3077 // OpenGlViewPort
3078
3079 #ifdef HAVE_QT_OPENGL
3080
3081 OpenGlViewPort::OpenGlViewPort(QWidget* _parent) : QGLWidget(_parent), size(-1, -1)
3082 {
3083     mouseCallback = 0;
3084     mouseData = 0;
3085
3086     glDrawCallback = 0;
3087     glDrawData = 0;
3088 }
3089
3090 OpenGlViewPort::~OpenGlViewPort()
3091 {
3092 }
3093
3094 QWidget* OpenGlViewPort::getWidget()
3095 {
3096     return this;
3097 }
3098
3099 void OpenGlViewPort::setMouseCallBack(CvMouseCallback callback, void* param)
3100 {
3101     mouseCallback = callback;
3102     mouseData = param;
3103 }
3104
3105 void OpenGlViewPort::writeSettings(QSettings& /*settings*/)
3106 {
3107 }
3108
3109 void OpenGlViewPort::readSettings(QSettings& /*settings*/)
3110 {
3111 }
3112
3113 double OpenGlViewPort::getRatio()
3114 {
3115     return (double)width() / height();
3116 }
3117
3118 void OpenGlViewPort::setRatio(int /*flags*/)
3119 {
3120 }
3121
3122 void OpenGlViewPort::updateImage(const CvArr* /*arr*/)
3123 {
3124 }
3125
3126 void OpenGlViewPort::startDisplayInfo(QString /*text*/, int /*delayms*/)
3127 {
3128 }
3129
3130 void OpenGlViewPort::setOpenGlDrawCallback(CvOpenGlDrawCallback callback, void* userdata)
3131 {
3132     glDrawCallback = callback;
3133     glDrawData = userdata;
3134 }
3135
3136 void OpenGlViewPort::makeCurrentOpenGlContext()
3137 {
3138     makeCurrent();
3139 }
3140
3141 void OpenGlViewPort::updateGl()
3142 {
3143     QGLWidget::updateGL();
3144 }
3145
3146 void OpenGlViewPort::initializeGL()
3147 {
3148     glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
3149 }
3150
3151 void OpenGlViewPort::resizeGL(int w, int h)
3152 {
3153     glViewport(0, 0, w, h);
3154 }
3155
3156 void OpenGlViewPort::paintGL()
3157 {
3158     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
3159
3160     if (glDrawCallback)
3161         glDrawCallback(glDrawData);
3162 }
3163
3164 void OpenGlViewPort::mousePressEvent(QMouseEvent* evnt)
3165 {
3166     int cv_event = -1, flags = 0;
3167     QPoint pt = evnt->pos();
3168
3169     icvmouseHandler(evnt, mouse_down, cv_event, flags);
3170     icvmouseProcessing(QPointF(pt), cv_event, flags);
3171
3172     QGLWidget::mousePressEvent(evnt);
3173 }
3174
3175
3176 void OpenGlViewPort::mouseReleaseEvent(QMouseEvent* evnt)
3177 {
3178     int cv_event = -1, flags = 0;
3179     QPoint pt = evnt->pos();
3180
3181     icvmouseHandler(evnt, mouse_up, cv_event, flags);
3182     icvmouseProcessing(QPointF(pt), cv_event, flags);
3183
3184     QGLWidget::mouseReleaseEvent(evnt);
3185 }
3186
3187
3188 void OpenGlViewPort::mouseDoubleClickEvent(QMouseEvent* evnt)
3189 {
3190     int cv_event = -1, flags = 0;
3191     QPoint pt = evnt->pos();
3192
3193     icvmouseHandler(evnt, mouse_dbclick, cv_event, flags);
3194     icvmouseProcessing(QPointF(pt), cv_event, flags);
3195
3196     QGLWidget::mouseDoubleClickEvent(evnt);
3197 }
3198
3199
3200 void OpenGlViewPort::mouseMoveEvent(QMouseEvent* evnt)
3201 {
3202     int cv_event = CV_EVENT_MOUSEMOVE, flags = 0;
3203     QPoint pt = evnt->pos();
3204
3205     //icvmouseHandler: pass parameters for cv_event, flags
3206     icvmouseHandler(evnt, mouse_move, cv_event, flags);
3207     icvmouseProcessing(QPointF(pt), cv_event, flags);
3208
3209     QGLWidget::mouseMoveEvent(evnt);
3210 }
3211
3212 void OpenGlViewPort::icvmouseHandler(QMouseEvent* evnt, type_mouse_event category, int& cv_event, int& flags)
3213 {
3214     Qt::KeyboardModifiers modifiers = evnt->modifiers();
3215     Qt::MouseButtons buttons = evnt->buttons();
3216
3217     flags = 0;
3218     if (modifiers & Qt::ShiftModifier)
3219         flags |= CV_EVENT_FLAG_SHIFTKEY;
3220     if (modifiers & Qt::ControlModifier)
3221         flags |= CV_EVENT_FLAG_CTRLKEY;
3222     if (modifiers & Qt::AltModifier)
3223         flags |= CV_EVENT_FLAG_ALTKEY;
3224
3225     if (buttons & Qt::LeftButton)
3226         flags |= CV_EVENT_FLAG_LBUTTON;
3227     if (buttons & Qt::RightButton)
3228         flags |= CV_EVENT_FLAG_RBUTTON;
3229     if (buttons & Qt::MidButton)
3230         flags |= CV_EVENT_FLAG_MBUTTON;
3231
3232     cv_event = CV_EVENT_MOUSEMOVE;
3233     switch (evnt->button())
3234     {
3235     case Qt::LeftButton:
3236         cv_event = tableMouseButtons[category][0];
3237         flags |= CV_EVENT_FLAG_LBUTTON;
3238         break;
3239
3240     case Qt::RightButton:
3241         cv_event = tableMouseButtons[category][1];
3242         flags |= CV_EVENT_FLAG_RBUTTON;
3243         break;
3244
3245     case Qt::MidButton:
3246         cv_event = tableMouseButtons[category][2];
3247         flags |= CV_EVENT_FLAG_MBUTTON;
3248         break;
3249
3250     default:
3251         ;
3252     }
3253 }
3254
3255
3256 void OpenGlViewPort::icvmouseProcessing(QPointF pt, int cv_event, int flags)
3257 {
3258     if (mouseCallback)
3259         mouseCallback(cv_event, pt.x(), pt.y(), flags, mouseData);
3260 }
3261
3262
3263 QSize OpenGlViewPort::sizeHint() const
3264 {
3265     if (size.width() > 0 && size.height() > 0)
3266         return size;
3267
3268     return QGLWidget::sizeHint();
3269 }
3270
3271 void OpenGlViewPort::setSize(QSize size_)
3272 {
3273     size = size_;
3274     updateGeometry();
3275 }
3276
3277 #endif
3278
3279 #endif // HAVE_QT