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