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