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