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