1 /*M///////////////////////////////////////////////////////////////////////////////////////
3 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
5 // By downloading, copying, installing or using the software you agree to this license.
6 // If you do not agree to this license, do not download, install,
7 // copy or use the software.
10 // Intel License Agreement
11 // For Open Source Computer Vision Library
13 // Copyright (C) 2000, Intel Corporation, all rights reserved.
14 // Third party copyrights are property of their respective owners.
16 // Redistribution and use in source and binary forms, with or without modification,
17 // are permitted provided that the following conditions are met:
19 // * Redistribution's of source code must retain the above copyright notice,
20 // this list of conditions and the following disclaimer.
22 // * Redistribution's in binary form must reproduce the above copyright notice,
23 // this list of conditions and the following disclaimer in the documentation
24 // and/or other materials provided with the distribution.
26 // * The name of Intel Corporation may not be used to endorse or promote products
27 // derived from this software without specific prior written permission.
29 // This software is provided by the copyright holders and contributors "as is" and
30 // any express or implied warranties, including, but not limited to, the implied
31 // warranties of merchantability and fitness for a particular purpose are disclaimed.
32 // In no event shall the Intel Corporation or contributors be liable for any direct,
33 // indirect, incidental, special, exemplary, or consequential damages
34 // (including, but not limited to, procurement of substitute goods or services;
35 // loss of use, data, or profits; or business interruption) however caused
36 // and on any theory of liability, whether in contract, strict liability,
37 // or tort (including negligence or otherwise) arising in any way out of
38 // the use of this software, even if advised of the possibility of such damage.
42 #include "precomp.hpp"
46 #include <windowsx.h> // required for GET_X_LPARAM() and GET_Y_LPARAM() macros
51 # pragma GCC diagnostic ignored "-Wmissing-declarations"
54 #if (_WIN32_IE < 0x0500)
55 #pragma message("WARNING: Win32 UI needs to be compiled with _WIN32_IE >= 0x0500 (_WIN32_IE_IE50)")
56 #define _WIN32_IE 0x0500
70 #include "opencv2/highgui.hpp"
72 #include "opencv2/core/opengl.hpp"
75 static const char* trackbar_text =
78 #if defined _M_X64 || defined __x86_64 || defined _M_ARM64
80 #define icvGetWindowLongPtr GetWindowLongPtr
81 #define icvSetWindowLongPtr( hwnd, id, ptr ) SetWindowLongPtr( hwnd, id, (LONG_PTR)(ptr) )
82 #define icvGetClassLongPtr GetClassLongPtr
84 #define CV_USERDATA GWLP_USERDATA
85 #define CV_WNDPROC GWLP_WNDPROC
86 #define CV_HCURSOR GCLP_HCURSOR
87 #define CV_HBRBACKGROUND GCLP_HBRBACKGROUND
91 #define icvGetWindowLongPtr GetWindowLong
92 #define icvSetWindowLongPtr( hwnd, id, ptr ) SetWindowLong( hwnd, id, (size_t)ptr )
93 #define icvGetClassLongPtr GetClassLong
95 #define CV_USERDATA GWL_USERDATA
96 #define CV_WNDPROC GWL_WNDPROC
97 #define CV_HCURSOR GCL_HCURSOR
98 #define CV_HBRBACKGROUND GCL_HBRBACKGROUND
102 #ifndef WM_MOUSEHWHEEL
103 #define WM_MOUSEHWHEEL 0x020E
106 #if defined(__MINGW32__) || defined(__MINGW64__)
107 static inline void mingw_strcpy_s(char *dest, size_t destsz, const char *src){
111 static inline void mingw_strcat_s(char *dest, size_t destsz, const char *src){
115 #define strcpy_s mingw_strcpy_s
116 #define strcat_s mingw_strcat_s
119 static void FillBitmapInfo( BITMAPINFO* bmi, int width, int height, int bpp, int origin )
121 assert( bmi && width >= 0 && height >= 0 && (bpp == 8 || bpp == 24 || bpp == 32));
123 BITMAPINFOHEADER* bmih = &(bmi->bmiHeader);
125 memset( bmih, 0, sizeof(*bmih));
126 bmih->biSize = sizeof(BITMAPINFOHEADER);
127 bmih->biWidth = width;
128 bmih->biHeight = origin ? abs(height) : -abs(height);
130 bmih->biBitCount = (unsigned short)bpp;
131 bmih->biCompression = BI_RGB;
135 RGBQUAD* palette = bmi->bmiColors;
137 for( i = 0; i < 256; i++ )
139 palette[i].rgbBlue = palette[i].rgbGreen = palette[i].rgbRed = (BYTE)i;
140 palette[i].rgbReserved = 0;
147 typedef struct CvTrackbar
160 void (*notify2)(int, void*);
167 typedef struct CvWindow
180 int status;//0 normal, 1 fullscreen (YV)
182 CvMouseCallback on_mouse;
183 void* on_mouse_param;
204 CvOpenGlDrawCallback glDrawCallback;
210 #define HG_BUDDY_WIDTH 130
213 #define TBIF_SIZE 0x40
216 #ifndef TB_SETBUTTONINFO
217 #define TB_SETBUTTONINFO (WM_USER + 66)
220 #ifndef TBM_GETTOOLTIPS
221 #define TBM_GETTOOLTIPS (WM_USER + 30)
224 static LRESULT CALLBACK HighGUIProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
225 static LRESULT CALLBACK WindowProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
226 static LRESULT CALLBACK MainWindowProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
227 static void icvUpdateWindowPos( CvWindow* window );
229 static CvWindow* hg_windows = 0;
231 typedef int (CV_CDECL * CvWin32WindowCallback)(HWND, UINT, WPARAM, LPARAM, int*);
232 static CvWin32WindowCallback hg_on_preprocess = 0, hg_on_postprocess = 0;
233 static HINSTANCE hg_hinstance = 0;
235 static const char* highGUIclassName = "HighGUI class";
236 static const char* mainHighGUIclassName = "Main HighGUI class";
238 static void icvCleanupHighgui()
240 cvDestroyAllWindows();
241 UnregisterClass(highGUIclassName, hg_hinstance);
242 UnregisterClass(mainHighGUIclassName, hg_hinstance);
245 CV_IMPL int cvInitSystem( int, char** )
247 static int wasInitialized = 0;
249 // check initialization status
250 if( !wasInitialized )
252 // Initialize the storage
255 // Register the class
257 wndc.style = CS_OWNDC | CS_VREDRAW | CS_HREDRAW | CS_DBLCLKS;
258 wndc.lpfnWndProc = WindowProc;
261 wndc.hInstance = hg_hinstance;
262 wndc.lpszClassName = highGUIclassName;
263 wndc.lpszMenuName = highGUIclassName;
264 wndc.hIcon = LoadIcon(0, IDI_APPLICATION);
265 wndc.hCursor = (HCURSOR)LoadCursor(0, (LPSTR)(size_t)IDC_CROSS );
266 wndc.hbrBackground = (HBRUSH)GetStockObject(DKGRAY_BRUSH);
268 RegisterClass(&wndc);
270 wndc.lpszClassName = mainHighGUIclassName;
271 wndc.lpszMenuName = mainHighGUIclassName;
272 wndc.hbrBackground = (HBRUSH)GetStockObject(DKGRAY_BRUSH);
273 wndc.lpfnWndProc = MainWindowProc;
275 RegisterClass(&wndc);
276 atexit( icvCleanupHighgui );
281 setlocale(LC_NUMERIC,"C");
286 CV_IMPL int cvStartWindowThread(){
290 static CvWindow* icvFindWindowByName( const char* name )
292 CvWindow* window = hg_windows;
294 for( ; window != 0 && strcmp( name, window->name) != 0; window = window->next )
301 static CvWindow* icvWindowByHWND( HWND hwnd )
303 CvWindow* window = (CvWindow*)icvGetWindowLongPtr( hwnd, CV_USERDATA );
304 return window != 0 && hg_windows != 0 &&
305 window->signature == CV_WINDOW_MAGIC_VAL ? window : 0;
309 static CvTrackbar* icvTrackbarByHWND( HWND hwnd )
311 CvTrackbar* trackbar = (CvTrackbar*)icvGetWindowLongPtr( hwnd, CV_USERDATA );
312 return trackbar != 0 && trackbar->signature == CV_TRACKBAR_MAGIC_VAL &&
313 trackbar->hwnd == hwnd ? trackbar : 0;
317 static const char* icvWindowPosRootKey = "Software\\OpenCV\\HighGUI\\Windows\\";
319 // Window positions saving/loading added by Philip Gruebele.
320 //<a href="mailto:pgruebele@cox.net">pgruebele@cox.net</a>
321 // Restores the window position from the registry saved position.
323 icvLoadWindowPos( const char* name, CvRect& rect )
327 strcpy_s( szKey, 1024, icvWindowPosRootKey );
328 strcat_s( szKey, 1024, name );
330 rect.x = rect.y = CW_USEDEFAULT;
331 rect.width = rect.height = 320;
333 if( RegOpenKeyEx(HKEY_CURRENT_USER,szKey,0,KEY_QUERY_VALUE,&hkey) == ERROR_SUCCESS )
335 // Yes we are installed.
337 DWORD dwSize = sizeof(int);
339 RegQueryValueEx(hkey, "Left", NULL, &dwType, (BYTE*)&rect.x, &dwSize);
340 RegQueryValueEx(hkey, "Top", NULL, &dwType, (BYTE*)&rect.y, &dwSize);
341 RegQueryValueEx(hkey, "Width", NULL, &dwType, (BYTE*)&rect.width, &dwSize);
342 RegQueryValueEx(hkey, "Height", NULL, &dwType, (BYTE*)&rect.height, &dwSize);
344 // Snap rect into closest monitor in case it falls outside it. // Adi Shavit
345 // set WIN32 RECT to be the loaded size
346 POINT tl_w32 = { rect.x, rect.y };
347 POINT tr_w32 = { rect.x + rect.width, rect.y };
349 // find monitor containing top-left and top-right corners, or NULL
350 HMONITOR hMonitor_l = MonitorFromPoint(tl_w32, MONITOR_DEFAULTTONULL);
351 HMONITOR hMonitor_r = MonitorFromPoint(tr_w32, MONITOR_DEFAULTTONULL);
353 // if neither are contained - the move window to origin of closest.
354 if (NULL == hMonitor_l && NULL == hMonitor_r)
356 // find monitor nearest to top-left corner
357 HMONITOR hMonitor_closest = MonitorFromPoint(tl_w32, MONITOR_DEFAULTTONEAREST);
359 // get coordinates of nearest monitor
361 mi.cbSize = sizeof(mi);
362 GetMonitorInfo(hMonitor_closest, &mi);
364 rect.x = mi.rcWork.left;
365 rect.y = mi.rcWork.top;
368 if (rect.width != (int)CW_USEDEFAULT && (rect.width < 0 || rect.width > 3000))
370 if (rect.height != (int)CW_USEDEFAULT && (rect.height < 0 || rect.height > 3000))
378 // Window positions saving/loading added by Philip Gruebele.
379 //<a href="mailto:pgruebele@cox.net">pgruebele@cox.net</a>
380 // philipg. Saves the window position in the registry
382 icvSaveWindowPos( const char* name, CvRect rect )
384 static const DWORD MAX_RECORD_COUNT = 100;
388 strcpy_s( szKey, 1024, icvWindowPosRootKey );
389 strcat_s( szKey, 1024, name );
391 if( RegOpenKeyEx( HKEY_CURRENT_USER,szKey,0,KEY_READ,&hkey) != ERROR_SUCCESS )
395 FILETIME oldestTime = { UINT_MAX, UINT_MAX };
396 char oldestKey[1024];
397 char currentKey[1024];
399 strcpy_s( rootKey, 1024, icvWindowPosRootKey );
400 rootKey[strlen(rootKey)-1] = '\0';
401 if( RegCreateKeyEx(HKEY_CURRENT_USER, rootKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_READ+KEY_WRITE, 0, &hroot, NULL) != ERROR_SUCCESS )
402 //RegOpenKeyEx( HKEY_CURRENT_USER,rootKey,0,KEY_READ,&hroot) != ERROR_SUCCESS )
407 DWORD csize = sizeof(currentKey);
408 FILETIME accesstime = { 0, 0 };
409 LONG code = RegEnumKeyEx( hroot, count, currentKey, &csize, NULL, NULL, NULL, &accesstime );
410 if( code != ERROR_SUCCESS && code != ERROR_MORE_DATA )
413 if( oldestTime.dwHighDateTime > accesstime.dwHighDateTime ||
414 (oldestTime.dwHighDateTime == accesstime.dwHighDateTime &&
415 oldestTime.dwLowDateTime > accesstime.dwLowDateTime) )
417 oldestTime = accesstime;
418 strcpy_s( oldestKey, 1024, currentKey );
422 if( count >= MAX_RECORD_COUNT )
423 RegDeleteKey( hroot, oldestKey );
424 RegCloseKey( hroot );
426 if( RegCreateKeyEx(HKEY_CURRENT_USER,szKey,0,NULL,REG_OPTION_NON_VOLATILE, KEY_WRITE, 0, &hkey, NULL) != ERROR_SUCCESS )
432 if( RegOpenKeyEx( HKEY_CURRENT_USER,szKey,0,KEY_WRITE,&hkey) != ERROR_SUCCESS )
436 RegSetValueEx(hkey, "Left", 0, REG_DWORD, (BYTE*)&rect.x, sizeof(rect.x));
437 RegSetValueEx(hkey, "Top", 0, REG_DWORD, (BYTE*)&rect.y, sizeof(rect.y));
438 RegSetValueEx(hkey, "Width", 0, REG_DWORD, (BYTE*)&rect.width, sizeof(rect.width));
439 RegSetValueEx(hkey, "Height", 0, REG_DWORD, (BYTE*)&rect.height, sizeof(rect.height));
443 CvRect cvGetWindowRect_W32(const char* name)
446 CvRect result = cvRect(-1, -1, -1, -1);
448 CV_FUNCNAME( "cvGetWindowRect_W32" );
455 CV_ERROR( CV_StsNullPtr, "NULL name string" );
456 window = icvFindWindowByName( name );
458 EXIT; // keep silence here
460 GetClientRect(window->hwnd, &rect);
462 POINT pt = {rect.left, rect.top};
463 ClientToScreen(window->hwnd, &pt);
464 result = cvRect(pt.x, pt.y, rect.right - rect.left, rect.bottom - rect.top);
470 double cvGetModeWindow_W32(const char* name)//YV
474 CV_FUNCNAME( "cvGetModeWindow_W32" );
481 CV_ERROR( CV_StsNullPtr, "NULL name string" );
483 window = icvFindWindowByName( name );
485 EXIT; // keep silence here
487 result = window->status;
493 void cvSetModeWindow_W32( const char* name, double prop_value)//Yannick Verdie
495 CV_FUNCNAME( "cvSetModeWindow_W32" );
502 CV_ERROR( CV_StsNullPtr, "NULL name string" );
504 window = icvFindWindowByName( name );
506 CV_ERROR( CV_StsNullPtr, "NULL window" );
508 if(window->flags & CV_WINDOW_AUTOSIZE)//if the flag CV_WINDOW_AUTOSIZE is set
512 DWORD dwStyle = (DWORD)GetWindowLongPtr(window->frame, GWL_STYLE);
515 if (window->status==CV_WINDOW_FULLSCREEN && prop_value==CV_WINDOW_NORMAL)
517 icvLoadWindowPos(window->name,position );
518 SetWindowLongPtr(window->frame, GWL_STYLE, dwStyle | WS_CAPTION | WS_THICKFRAME);
520 SetWindowPos(window->frame, HWND_TOP, position.x, position.y , position.width,position.height, SWP_NOZORDER | SWP_FRAMECHANGED);
521 window->status=CV_WINDOW_NORMAL;
526 if (window->status==CV_WINDOW_NORMAL && prop_value==CV_WINDOW_FULLSCREEN)
530 GetWindowRect(window->frame, &rect);
531 CvRect RectCV = cvRect(rect.left, rect.top,rect.right - rect.left, rect.bottom - rect.top);
532 icvSaveWindowPos(window->name,RectCV );
534 //Look at coordinate for fullscreen
537 hMonitor = MonitorFromRect(&rect, MONITOR_DEFAULTTONEAREST);
539 mi.cbSize = sizeof(mi);
540 GetMonitorInfo(hMonitor, &mi);
543 position.x=mi.rcMonitor.left;position.y=mi.rcMonitor.top;
544 position.width=mi.rcMonitor.right - mi.rcMonitor.left;position.height=mi.rcMonitor.bottom - mi.rcMonitor.top;
545 SetWindowLongPtr(window->frame, GWL_STYLE, dwStyle & ~WS_CAPTION & ~WS_THICKFRAME);
547 SetWindowPos(window->frame, HWND_TOP, position.x, position.y , position.width,position.height, SWP_NOZORDER | SWP_FRAMECHANGED);
548 window->status=CV_WINDOW_FULLSCREEN;
557 double cvGetPropTopmost_W32(const char* name)
563 CvWindow* window = icvFindWindowByName(name);
565 CV_Error(Error::StsNullPtr, "NULL window");
567 LONG style = GetWindowLongA(window->frame, GWL_EXSTYLE); // -20
570 std::ostringstream errorMsg;
571 errorMsg << "window(" << name << "): failed to retrieve extended window style using GetWindowLongA(); error code: " << GetLastError();
572 CV_Error(Error::StsError, errorMsg.str().c_str());
575 result = (style & WS_EX_TOPMOST) == WS_EX_TOPMOST;
580 void cvSetPropTopmost_W32(const char* name, const bool topmost)
584 CvWindow* window = icvFindWindowByName(name);
586 CV_Error(Error::StsNullPtr, "NULL window");
588 HWND flag = topmost ? HWND_TOPMOST : HWND_TOP;
589 BOOL success = SetWindowPos(window->frame, flag, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
593 std::ostringstream errorMsg;
594 errorMsg << "window(" << name << "): error reported by SetWindowPos(" << (topmost ? "HWND_TOPMOST" : "HWND_TOP") << "), error code: " << GetLastError();
595 CV_Error(Error::StsError, errorMsg.str().c_str());
599 void cv::setWindowTitle(const String& winname, const String& title)
601 CvWindow* window = icvFindWindowByName(winname.c_str());
605 namedWindow(winname);
606 window = icvFindWindowByName(winname.c_str());
610 CV_Error(Error::StsNullPtr, "NULL window");
612 if (!SetWindowText(window->frame, title.c_str()))
613 CV_Error_(Error::StsError, ("Failed to set \"%s\" window title to \"%s\"", winname.c_str(), title.c_str()));
616 double cvGetPropWindowAutoSize_W32(const char* name)
620 CV_FUNCNAME( "cvSetCloseCallback" );
627 CV_ERROR( CV_StsNullPtr, "NULL name string" );
629 window = icvFindWindowByName( name );
631 EXIT; // keep silence here
633 result = window->flags & CV_WINDOW_AUTOSIZE;
640 double cvGetRatioWindow_W32(const char* name)
644 CV_FUNCNAME( "cvGetRatioWindow_W32" );
651 CV_ERROR( CV_StsNullPtr, "NULL name string" );
653 window = icvFindWindowByName( name );
655 EXIT; // keep silence here
657 result = static_cast<double>(window->width) / window->height;
664 double cvGetOpenGlProp_W32(const char* name)
669 CV_FUNCNAME( "cvGetOpenGlProp_W32" );
676 CV_ERROR( CV_StsNullPtr, "NULL name string" );
678 window = icvFindWindowByName( name );
680 EXIT; // keep silence here
682 result = window->useGl;
691 double cvGetPropVisible_W32(const char* name)
695 CV_FUNCNAME( "cvGetPropVisible_W32" );
700 CV_ERROR( CV_StsNullPtr, "NULL name string" );
702 result = (icvFindWindowByName( name ) != NULL);
716 void createGlContext(HWND hWnd, HDC& hGLDC, HGLRC& hGLRC, bool& useGl)
718 CV_FUNCNAME( "createGlContext" );
726 static PIXELFORMATDESCRIPTOR pfd =
728 sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
730 PFD_DRAW_TO_WINDOW | // Format Must Support Window
731 PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
732 PFD_DOUBLEBUFFER, // Must Support Double Buffering
733 PFD_TYPE_RGBA, // Request An RGBA Format
734 32, // Select Our Color Depth
735 0, 0, 0, 0, 0, 0, // Color Bits Ignored
736 0, // No Alpha Buffer
737 0, // Shift Bit Ignored
738 0, // No Accumulation Buffer
739 0, 0, 0, 0, // Accumulation Bits Ignored
740 32, // 32 Bit Z-Buffer (Depth Buffer)
741 0, // No Stencil Buffer
742 0, // No Auxiliary Buffer
743 PFD_MAIN_PLANE, // Main Drawing Layer
745 0, 0, 0 // Layer Masks Ignored
750 CV_ERROR( CV_OpenGlApiCallError, "Can't Create A GL Device Context" );
752 PixelFormat = ChoosePixelFormat(hGLDC, &pfd);
754 CV_ERROR( CV_OpenGlApiCallError, "Can't Find A Suitable PixelFormat" );
756 if (!SetPixelFormat(hGLDC, PixelFormat, &pfd))
757 CV_ERROR( CV_OpenGlApiCallError, "Can't Set The PixelFormat" );
759 hGLRC = wglCreateContext(hGLDC);
761 CV_ERROR( CV_OpenGlApiCallError, "Can't Create A GL Rendering Context" );
763 if (!wglMakeCurrent(hGLDC, hGLRC))
764 CV_ERROR( CV_OpenGlApiCallError, "Can't Activate The GL Rendering Context" );
771 void releaseGlContext(CvWindow* window)
773 //CV_FUNCNAME( "releaseGlContext" );
779 wglDeleteContext(window->hGLRC);
780 window->hGLRC = NULL;
785 ReleaseDC(window->hwnd, window->dc);
789 window->useGl = false;
794 void drawGl(CvWindow* window)
796 CV_FUNCNAME( "drawGl" );
800 if (!wglMakeCurrent(window->dc, window->hGLRC))
801 CV_ERROR( CV_OpenGlApiCallError, "Can't Activate The GL Rendering Context" );
803 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
805 if (window->glDrawCallback)
806 window->glDrawCallback(window->glDrawData);
808 if (!SwapBuffers(window->dc))
809 CV_ERROR( CV_OpenGlApiCallError, "Can't swap OpenGL buffers" );
814 void resizeGl(CvWindow* window)
816 CV_FUNCNAME( "resizeGl" );
820 if (!wglMakeCurrent(window->dc, window->hGLRC))
821 CV_ERROR( CV_OpenGlApiCallError, "Can't Activate The GL Rendering Context" );
823 glViewport(0, 0, window->width, window->height);
829 #endif // HAVE_OPENGL
832 CV_IMPL int cvNamedWindow( const char* name, int flags )
835 CV_FUNCNAME( "cvNamedWindow" );
841 DWORD defStyle = WS_VISIBLE | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_SYSMENU;
853 CV_ERROR( CV_StsNullPtr, "NULL name string" );
855 // Check the name in the storage
856 window = icvFindWindowByName( name );
863 if( !(flags & CV_WINDOW_AUTOSIZE))//YV add border in order to resize the window
864 defStyle |= WS_SIZEBOX;
867 if (flags & CV_WINDOW_OPENGL)
868 defStyle |= WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
871 icvLoadWindowPos( name, rect );
873 mainhWnd = CreateWindow( "Main HighGUI class", name, defStyle | WS_OVERLAPPED,
874 rect.x, rect.y, rect.width, rect.height, 0, 0, hg_hinstance, 0 );
876 CV_ERROR( CV_StsError, "Frame window can not be created" );
878 ShowWindow(mainhWnd, SW_SHOW);
880 //YV- remove one border by changing the style
881 hWnd = CreateWindow("HighGUI class", "", (defStyle & ~WS_SIZEBOX) | WS_CHILD, CW_USEDEFAULT, 0, rect.width, rect.height, mainhWnd, 0, hg_hinstance, 0);
883 CV_ERROR( CV_StsError, "Frame window can not be created" );
886 if (flags & CV_WINDOW_OPENGL)
887 CV_ERROR( CV_OpenGlNotSupported, "Library was built without OpenGL support" );
893 if (flags & CV_WINDOW_OPENGL)
894 createGlContext(hWnd, hGLDC, hGLRC, useGl);
897 ShowWindow(hWnd, SW_SHOW);
899 len = (int)strlen(name);
900 CV_CALL( window = (CvWindow*)cvAlloc(sizeof(CvWindow) + len + 1));
902 window->signature = CV_WINDOW_MAGIC_VAL;
904 window->frame = mainhWnd;
905 window->name = (char*)(window + 1);
906 memcpy( window->name, name, len + 1 );
907 window->flags = flags;
911 window->dc = CreateCompatibleDC(0);
915 window->dc = CreateCompatibleDC(0);
917 window->useGl = false;
922 window->hGLRC = hGLRC;
923 window->useGl = true;
926 window->glDrawCallback = 0;
927 window->glDrawData = 0;
930 window->last_key = 0;
931 window->status = CV_WINDOW_NORMAL;//YV
933 window->on_mouse = 0;
934 window->on_mouse_param = 0;
936 memset( &window->toolbar, 0, sizeof(window->toolbar));
938 window->next = hg_windows;
941 hg_windows->prev = window;
943 icvSetWindowLongPtr( hWnd, CV_USERDATA, window );
944 icvSetWindowLongPtr( mainhWnd, CV_USERDATA, window );
946 // Recalculate window pos
947 icvUpdateWindowPos( window );
957 CV_IMPL void cvSetOpenGlContext(const char* name)
959 CV_FUNCNAME( "cvSetOpenGlContext" );
966 CV_ERROR( CV_StsNullPtr, "NULL name string" );
968 window = icvFindWindowByName( name );
970 CV_ERROR( CV_StsNullPtr, "NULL window" );
973 CV_ERROR( CV_OpenGlNotSupported, "Window doesn't support OpenGL" );
975 if (!wglMakeCurrent(window->dc, window->hGLRC))
976 CV_ERROR( CV_OpenGlApiCallError, "Can't Activate The GL Rendering Context" );
981 CV_IMPL void cvUpdateWindow(const char* name)
983 CV_FUNCNAME( "cvUpdateWindow" );
990 CV_ERROR( CV_StsNullPtr, "NULL name string" );
992 window = icvFindWindowByName( name );
996 InvalidateRect(window->hwnd, 0, 0);
1001 CV_IMPL void cvSetOpenGlDrawCallback(const char* name, CvOpenGlDrawCallback callback, void* userdata)
1003 CV_FUNCNAME( "cvCreateOpenGLCallback" );
1010 CV_ERROR( CV_StsNullPtr, "NULL name string" );
1012 window = icvFindWindowByName( name );
1017 CV_ERROR( CV_OpenGlNotSupported, "Window was created without OpenGL context" );
1019 window->glDrawCallback = callback;
1020 window->glDrawData = userdata;
1025 #endif // HAVE_OPENGL
1027 static void icvRemoveWindow( CvWindow* window )
1029 CvTrackbar* trackbar = NULL;
1030 RECT wrect={0,0,0,0};
1034 releaseGlContext(window);
1038 GetWindowRect( window->frame, &wrect );
1040 icvSaveWindowPos( window->name, cvRect(wrect.left, wrect.top,
1041 wrect.right-wrect.left, wrect.bottom-wrect.top) );
1044 icvSetWindowLongPtr( window->hwnd, CV_USERDATA, 0 );
1046 icvSetWindowLongPtr( window->frame, CV_USERDATA, 0 );
1048 if( window->toolbar.toolbar )
1049 icvSetWindowLongPtr(window->toolbar.toolbar, CV_USERDATA, 0);
1052 window->prev->next = window->next;
1054 hg_windows = window->next;
1057 window->next->prev = window->prev;
1059 window->prev = window->next = 0;
1061 if( window->dc && window->image )
1062 DeleteObject(SelectObject(window->dc,window->image));
1065 DeleteDC(window->dc);
1067 for( trackbar = window->toolbar.first; trackbar != 0; )
1069 CvTrackbar* next = trackbar->next;
1070 if( trackbar->hwnd )
1072 icvSetWindowLongPtr( trackbar->hwnd, CV_USERDATA, 0 );
1073 cvFree( &trackbar );
1082 CV_IMPL void cvDestroyWindow( const char* name )
1084 CV_FUNCNAME( "cvDestroyWindow" );
1092 CV_ERROR( CV_StsNullPtr, "NULL name string" );
1094 window = icvFindWindowByName( name );
1098 mainhWnd = window->frame;
1100 SendMessage(window->hwnd, WM_CLOSE, 0, 0);
1101 SendMessage( mainhWnd, WM_CLOSE, 0, 0);
1102 // Do NOT call _remove_window -- CvWindow list will be updated automatically ...
1108 static void icvScreenToClient( HWND hwnd, RECT* rect )
1113 ScreenToClient(hwnd, &p);
1114 OffsetRect( rect, p.x - rect->left, p.y - rect->top );
1118 /* Calculatess the window coordinates relative to the upper left corner of the mainhWnd window */
1119 static RECT icvCalcWindowRect( CvWindow* window )
1121 RECT crect = { 0 }, trect = { 0 }, rect = { 0 };
1125 GetClientRect(window->frame, &crect);
1126 if (window->toolbar.toolbar)
1128 GetWindowRect(window->toolbar.toolbar, &trect);
1129 icvScreenToClient(window->frame, &trect);
1130 SubtractRect(&rect, &crect, &trect);
1138 // returns TRUE if there is a problem such as ERROR_IO_PENDING.
1139 static bool icvGetBitmapData( CvWindow* window, SIZE* size, int* channels, void** data )
1143 HGDIOBJ h = GetCurrentObject( window->dc, OBJ_BITMAP );
1145 size->cx = size->cy = 0;
1151 if (GetObject(h, sizeof(bmp), &bmp) == 0)
1156 size->cx = abs(bmp.bmWidth);
1157 size->cy = abs(bmp.bmHeight);
1161 *channels = bmp.bmBitsPixel/8;
1170 static void icvUpdateWindowPos( CvWindow* window )
1175 if( (window->flags & CV_WINDOW_AUTOSIZE) && window->image )
1179 icvGetBitmapData( window, &size, 0, 0 );
1181 // Repeat two times because after the first resizing of the mainhWnd window
1182 // toolbar may resize too
1183 for(i = 0; i < (window->toolbar.toolbar ? 2 : 1); i++)
1185 RECT rmw = { 0 }, rw = icvCalcWindowRect(window );
1186 MoveWindow(window->hwnd, rw.left, rw.top,
1187 rw.right - rw.left, rw.bottom - rw.top, FALSE);
1188 GetClientRect(window->hwnd, &rw);
1189 GetWindowRect(window->frame, &rmw);
1190 // Resize the mainhWnd window in order to make the bitmap fit into the child window
1191 MoveWindow(window->frame, rmw.left, rmw.top,
1192 size.cx + (rmw.right - rmw.left) - (rw.right - rw.left),
1193 size.cy + (rmw.bottom - rmw.top) - (rw.bottom - rw.top), TRUE );
1197 rect = icvCalcWindowRect(window);
1198 MoveWindow(window->hwnd, rect.left, rect.top,
1199 rect.right - rect.left,
1200 rect.bottom - rect.top, TRUE );
1204 cvShowImage( const char* name, const CvArr* arr )
1206 CV_FUNCNAME( "cvShowImage" );
1211 SIZE size = { 0, 0 };
1214 const int channels0 = 3;
1216 bool changed_size = false; // philipg
1219 CV_ERROR( CV_StsNullPtr, "NULL name" );
1221 window = icvFindWindowByName(name);
1224 cvNamedWindow(name, CV_WINDOW_AUTOSIZE);
1225 window = icvFindWindowByName(name);
1228 if( !window || !arr )
1229 EXIT; // keep silence here.
1231 CV_CALL( image = cvGetMat( arr, &stub ));
1236 cv::imshow(name, cv::cvarrToMat(image));
1242 // if there is something wrong with these system calls, we cannot display image...
1243 if (icvGetBitmapData( window, &size, &channels, &dst_ptr ))
1246 if( size.cx != image->width || size.cy != image->height || channels != channels0 )
1248 changed_size = true;
1250 uchar buffer[sizeof(BITMAPINFO) + 255*sizeof(RGBQUAD)];
1251 BITMAPINFO* binfo = (BITMAPINFO*)buffer;
1253 DeleteObject( SelectObject( window->dc, window->image ));
1256 size.cx = image->width;
1257 size.cy = image->height;
1258 channels = channels0;
1260 FillBitmapInfo( binfo, size.cx, size.cy, channels*8, 1 );
1262 window->image = SelectObject( window->dc, CreateDIBSection(window->dc, binfo,
1263 DIB_RGB_COLORS, &dst_ptr, 0, 0));
1267 cv::Mat dst(size.cy, size.cx, CV_8UC3, dst_ptr, (size.cx * channels + 3) & -4);
1268 convertToShow(cv::cvarrToMat(image), dst, false);
1269 CV_Assert(dst.data == (uchar*)dst_ptr);
1270 cv::flip(dst, dst, 0);
1273 // only resize window if needed
1275 icvUpdateWindowPos(window);
1276 InvalidateRect(window->hwnd, 0, 0);
1277 // philipg: this is not needed and just slows things down
1278 // UpdateWindow(window->hwnd);
1283 CV_IMPL void cvResizeWindow(const char* name, int width, int height )
1285 CV_FUNCNAME( "cvResizeWindow" );
1291 RECT rmw = { 0 }, rw = { 0 }, rect = { 0 };
1294 CV_ERROR( CV_StsNullPtr, "NULL name" );
1296 window = icvFindWindowByName(name);
1300 // Repeat two times because after the first resizing of the mainhWnd window
1301 // toolbar may resize too
1302 for(i = 0; i < (window->toolbar.toolbar ? 2 : 1); i++)
1304 rw = icvCalcWindowRect(window);
1305 MoveWindow(window->hwnd, rw.left, rw.top,
1306 rw.right - rw.left, rw.bottom - rw.top, FALSE);
1307 GetClientRect(window->hwnd, &rw);
1308 GetWindowRect(window->frame, &rmw);
1309 // Resize the mainhWnd window in order to make the bitmap fit into the child window
1310 MoveWindow(window->frame, rmw.left, rmw.top,
1311 width + (rmw.right - rmw.left) - (rw.right - rw.left),
1312 height + (rmw.bottom - rmw.top) - (rw.bottom - rw.top), TRUE);
1315 rect = icvCalcWindowRect(window);
1316 MoveWindow(window->hwnd, rect.left, rect.top,
1317 rect.right - rect.left, rect.bottom - rect.top, TRUE);
1323 CV_IMPL void cvMoveWindow( const char* name, int x, int y )
1325 CV_FUNCNAME( "cvMoveWindow" );
1333 CV_ERROR( CV_StsNullPtr, "NULL name" );
1335 window = icvFindWindowByName(name);
1339 GetWindowRect( window->frame, &rect );
1340 MoveWindow( window->frame, x, y, rect.right - rect.left, rect.bottom - rect.top, TRUE);
1346 static LRESULT CALLBACK
1347 MainWindowProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
1349 CvWindow* window = icvWindowByHWND( hwnd );
1351 return DefWindowProc(hwnd, uMsg, wParam, lParam);
1356 ::SendMessage(window->hwnd, uMsg, wParam, lParam);
1361 icvRemoveWindow(window);
1363 //PostQuitMessage(0);
1366 case WM_GETMINMAXINFO:
1367 if( !(window->flags & CV_WINDOW_AUTOSIZE) )
1369 MINMAXINFO* minmax = (MINMAXINFO*)lParam;
1371 LRESULT retval = DefWindowProc(hwnd, uMsg, wParam, lParam);
1373 minmax->ptMinTrackSize.y = 100;
1374 minmax->ptMinTrackSize.x = 100;
1376 if( window->toolbar.first )
1378 GetWindowRect( window->toolbar.first->hwnd, &rect );
1379 minmax->ptMinTrackSize.y += window->toolbar.rows*(rect.bottom - rect.top);
1380 minmax->ptMinTrackSize.x = MAX(rect.right - rect.left + HG_BUDDY_WIDTH, HG_BUDDY_WIDTH*2);
1386 case WM_WINDOWPOSCHANGED:
1388 WINDOWPOS* pos = (WINDOWPOS*)lParam;
1390 // Update the toolbar pos/size
1391 if(window->toolbar.toolbar)
1394 GetWindowRect(window->toolbar.toolbar, &rect);
1395 MoveWindow(window->toolbar.toolbar, 0, 0, pos->cx, rect.bottom - rect.top, TRUE);
1398 if(!(window->flags & CV_WINDOW_AUTOSIZE))
1399 icvUpdateWindowPos(window);
1404 case WM_WINDOWPOSCHANGING:
1406 // Snap window to screen edges with multi-monitor support. // Adi Shavit
1407 LPWINDOWPOS pos = (LPWINDOWPOS)lParam;
1410 GetWindowRect(window->frame, &rect);
1413 hMonitor = MonitorFromRect(&rect, MONITOR_DEFAULTTONEAREST);
1416 mi.cbSize = sizeof(mi);
1417 GetMonitorInfo(hMonitor, &mi);
1419 const int SNAP_DISTANCE = 15;
1421 if (abs(pos->x - mi.rcMonitor.left) <= SNAP_DISTANCE)
1422 pos->x = mi.rcMonitor.left; // snap to left edge
1424 if (abs(pos->x + pos->cx - mi.rcMonitor.right) <= SNAP_DISTANCE)
1425 pos->x = mi.rcMonitor.right - pos->cx; // snap to right edge
1427 if (abs(pos->y - mi.rcMonitor.top) <= SNAP_DISTANCE)
1428 pos->y = mi.rcMonitor.top; // snap to top edge
1430 if (abs(pos->y + pos->cy - mi.rcMonitor.bottom) <= SNAP_DISTANCE)
1431 pos->y = mi.rcMonitor.bottom - pos->cy; // snap to bottom edge
1435 if(LOWORD(wParam) == WA_ACTIVE || LOWORD(wParam) == WA_CLICKACTIVE)
1436 SetFocus(window->hwnd);
1440 case WM_MOUSEHWHEEL:
1441 if( window->on_mouse )
1443 int flags = (wParam & MK_LBUTTON ? CV_EVENT_FLAG_LBUTTON : 0)|
1444 (wParam & MK_RBUTTON ? CV_EVENT_FLAG_RBUTTON : 0)|
1445 (wParam & MK_MBUTTON ? CV_EVENT_FLAG_MBUTTON : 0)|
1446 (wParam & MK_CONTROL ? CV_EVENT_FLAG_CTRLKEY : 0)|
1447 (wParam & MK_SHIFT ? CV_EVENT_FLAG_SHIFTKEY : 0)|
1448 (GetKeyState(VK_MENU) < 0 ? CV_EVENT_FLAG_ALTKEY : 0);
1449 int event = (uMsg == WM_MOUSEWHEEL ? CV_EVENT_MOUSEWHEEL : CV_EVENT_MOUSEHWHEEL);
1451 // Set the wheel delta of mouse wheel to be in the upper word of 'event'
1452 int delta = GET_WHEEL_DELTA_WPARAM(wParam);
1453 flags |= (delta << 16);
1456 pt.x = GET_X_LPARAM( lParam );
1457 pt.y = GET_Y_LPARAM( lParam );
1458 ::ScreenToClient(hwnd, &pt); // Convert screen coordinates to client coordinates.
1461 GetClientRect( window->hwnd, &rect );
1467 cv::ogl::Texture2D* texObj = static_cast<cv::ogl::Texture2D*>(window->glDrawData);
1468 size.cx = texObj->cols();
1469 size.cy = texObj->rows();
1473 icvGetBitmapData(window, &size, 0, 0);
1476 icvGetBitmapData(window, &size, 0, 0);
1479 window->on_mouse( event, pt.x*size.cx/MAX(rect.right - rect.left,1),
1480 pt.y*size.cy/MAX(rect.bottom - rect.top,1), flags,
1481 window->on_mouse_param );
1487 RECT cr = { 0 }, tr = { 0 }, wrc = { 0 };
1488 HRGN rgn, rgn1, rgn2;
1490 HDC hdc = (HDC)wParam;
1491 GetWindowRect(window->hwnd, &cr);
1492 icvScreenToClient(window->frame, &cr);
1493 if(window->toolbar.toolbar)
1495 GetWindowRect(window->toolbar.toolbar, &tr);
1496 icvScreenToClient(window->frame, &tr);
1499 tr.left = tr.top = tr.right = tr.bottom = 0;
1501 GetClientRect(window->frame, &wrc);
1503 rgn = CreateRectRgn(0, 0, wrc.right, wrc.bottom);
1504 rgn1 = CreateRectRgn(cr.left, cr.top, cr.right, cr.bottom);
1505 rgn2 = CreateRectRgn(tr.left, tr.top, tr.right, tr.bottom);
1506 CV_Assert_N(rgn != 0, rgn1 != 0, rgn2 != 0);
1508 ret = CombineRgn(rgn, rgn, rgn1, RGN_DIFF);
1509 ret = CombineRgn(rgn, rgn, rgn2, RGN_DIFF);
1511 if(ret != NULLREGION && ret != ERROR)
1512 FillRgn(hdc, rgn, (HBRUSH)icvGetClassLongPtr(hwnd, CV_HBRBACKGROUND));
1521 return DefWindowProc(hwnd, uMsg, wParam, lParam);
1525 static LRESULT CALLBACK HighGUIProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
1527 CvWindow* window = icvWindowByHWND(hwnd);
1529 // This window is not mentioned in HighGUI storage
1530 // Actually, this should be error except for the case of calls to CreateWindow
1531 return DefWindowProc(hwnd, uMsg, wParam, lParam);
1533 // Process the message
1538 if (!::OpenClipboard(hwnd) )
1545 // We'll use a do-while(0){} scope as a single-run breakable scope
1546 // Upon any error we can jump out of the single-time while scope to clean up the resources.
1549 if (!::EmptyClipboard())
1555 // Get window device context
1556 if (0 == (hDC = ::GetDC(hwnd)))
1559 // Create another DC compatible with hDC
1560 if (0 == (memDC = ::CreateCompatibleDC( hDC )))
1563 // Determine the bitmap's dimensions
1566 icvGetBitmapData( window, &size, &nchannels, 0 );
1568 // Create bitmap to draw on and it in the new DC
1569 if (0 == (memBM = ::CreateCompatibleBitmap ( hDC, size.cx, size.cy)))
1572 if (!::SelectObject( memDC, memBM ))
1575 // Begin drawing to DC
1576 if (!::SetStretchBltMode(memDC, COLORONCOLOR))
1580 if( 1 == nchannels )
1582 for(int i = 0; i < 256; ++i)
1584 table[i].rgbBlue = (unsigned char)i;
1585 table[i].rgbGreen = (unsigned char)i;
1586 table[i].rgbRed = (unsigned char)i;
1588 if (!::SetDIBColorTable(window->dc, 0, 255, table))
1592 // The image copied to the clipboard will be in its original size, regardless if the window itself was resized.
1594 // Render the image to the dc/bitmap (at original size).
1595 if (!::BitBlt( memDC, 0, 0, size.cx, size.cy, window->dc, 0, 0, SRCCOPY ))
1598 // Finally, set bitmap to clipboard
1599 ::SetClipboardData(CF_BITMAP, memBM);
1600 } while (0,0); // (0,0) instead of (0) to avoid MSVC compiler warning C4127: "conditional expression is constant"
1602 //////////////////////////////////////////////////////////////////////////
1603 // if handle is allocated (i.e. != 0) then clean-up.
1604 if (memBM) ::DeleteObject(memBM);
1605 if (memDC) ::DeleteDC(memDC);
1606 if (hDC) ::ReleaseDC(hwnd, hDC);
1611 case WM_WINDOWPOSCHANGING:
1613 LPWINDOWPOS pos = (LPWINDOWPOS)lParam;
1614 RECT rect = icvCalcWindowRect(window);
1617 pos->cx = rect.right - rect.left;
1618 pos->cy = rect.bottom - rect.top;
1622 case WM_LBUTTONDOWN:
1623 case WM_RBUTTONDOWN:
1624 case WM_MBUTTONDOWN:
1625 case WM_LBUTTONDBLCLK:
1626 case WM_RBUTTONDBLCLK:
1627 case WM_MBUTTONDBLCLK:
1632 if( window->on_mouse )
1636 int flags = (wParam & MK_LBUTTON ? CV_EVENT_FLAG_LBUTTON : 0)|
1637 (wParam & MK_RBUTTON ? CV_EVENT_FLAG_RBUTTON : 0)|
1638 (wParam & MK_MBUTTON ? CV_EVENT_FLAG_MBUTTON : 0)|
1639 (wParam & MK_CONTROL ? CV_EVENT_FLAG_CTRLKEY : 0)|
1640 (wParam & MK_SHIFT ? CV_EVENT_FLAG_SHIFTKEY : 0)|
1641 (GetKeyState(VK_MENU) < 0 ? CV_EVENT_FLAG_ALTKEY : 0);
1642 int event = uMsg == WM_LBUTTONDOWN ? CV_EVENT_LBUTTONDOWN :
1643 uMsg == WM_RBUTTONDOWN ? CV_EVENT_RBUTTONDOWN :
1644 uMsg == WM_MBUTTONDOWN ? CV_EVENT_MBUTTONDOWN :
1645 uMsg == WM_LBUTTONUP ? CV_EVENT_LBUTTONUP :
1646 uMsg == WM_RBUTTONUP ? CV_EVENT_RBUTTONUP :
1647 uMsg == WM_MBUTTONUP ? CV_EVENT_MBUTTONUP :
1648 uMsg == WM_LBUTTONDBLCLK ? CV_EVENT_LBUTTONDBLCLK :
1649 uMsg == WM_RBUTTONDBLCLK ? CV_EVENT_RBUTTONDBLCLK :
1650 uMsg == WM_MBUTTONDBLCLK ? CV_EVENT_MBUTTONDBLCLK :
1652 if( uMsg == WM_LBUTTONDOWN || uMsg == WM_RBUTTONDOWN || uMsg == WM_MBUTTONDOWN )
1654 if( uMsg == WM_LBUTTONUP || uMsg == WM_RBUTTONUP || uMsg == WM_MBUTTONUP )
1657 pt.x = GET_X_LPARAM( lParam );
1658 pt.y = GET_Y_LPARAM( lParam );
1660 if (window->flags & CV_WINDOW_AUTOSIZE)
1662 // As user can't change window size, do not scale window coordinates. Underlying windowing system
1663 // may prevent full window from being displayed and in this case coordinates should not be scaled.
1664 window->on_mouse( event, pt.x, pt.y, flags, window->on_mouse_param );
1666 // Full window is displayed using different size. Scale coordinates to match underlying positions.
1670 GetClientRect( window->hwnd, &rect );
1675 cv::ogl::Texture2D* texObj = static_cast<cv::ogl::Texture2D*>(window->glDrawData);
1676 size.cx = texObj->cols();
1677 size.cy = texObj->rows();
1681 icvGetBitmapData(window, &size, 0, 0);
1684 icvGetBitmapData( window, &size, 0, 0 );
1687 window->on_mouse( event, pt.x*size.cx/MAX(rect.right - rect.left,1),
1688 pt.y*size.cy/MAX(rect.bottom - rect.top,1), flags,
1689 window->on_mouse_param );
1695 if(window->image != 0)
1703 // Determine the bitmap's dimensions
1704 icvGetBitmapData( window, &size, &nchannels, 0 );
1706 hdc = BeginPaint(hwnd, &paint);
1707 SetStretchBltMode(hdc, COLORONCOLOR);
1709 if( nchannels == 1 )
1712 for(i = 0; i < 256; i++)
1714 table[i].rgbBlue = (unsigned char)i;
1715 table[i].rgbGreen = (unsigned char)i;
1716 table[i].rgbRed = (unsigned char)i;
1718 SetDIBColorTable(window->dc, 0, 255, table);
1721 if(window->flags & CV_WINDOW_AUTOSIZE)
1723 BitBlt( hdc, 0, 0, size.cx, size.cy, window->dc, 0, 0, SRCCOPY );
1728 GetClientRect(window->hwnd, &rect);
1729 StretchBlt( hdc, 0, 0, rect.right - rect.left, rect.bottom - rect.top,
1730 window->dc, 0, 0, size.cx, size.cy, SRCCOPY );
1733 EndPaint(hwnd, &paint);
1736 else if(window->useGl)
1739 return DefWindowProc(hwnd, uMsg, wParam, lParam);
1744 return DefWindowProc(hwnd, uMsg, wParam, lParam);
1755 icvRemoveWindow(window);
1757 //PostQuitMessage(0);
1761 SetCursor((HCURSOR)icvGetClassLongPtr(hwnd, CV_HCURSOR));
1765 window->last_key = (int)wParam;
1769 window->width = LOWORD(lParam);
1770 window->height = HIWORD(lParam);
1778 return DefWindowProc(hwnd, uMsg, wParam, lParam);
1782 static LRESULT CALLBACK WindowProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
1786 if( hg_on_preprocess )
1788 int was_processed = 0;
1789 int rethg = hg_on_preprocess(hwnd, uMsg, wParam, lParam, &was_processed);
1793 ret = HighGUIProc(hwnd, uMsg, wParam, lParam);
1795 if(hg_on_postprocess)
1797 int was_processed = 0;
1798 int rethg = hg_on_postprocess(hwnd, uMsg, wParam, lParam, &was_processed);
1807 static void icvUpdateTrackbar( CvTrackbar* trackbar, int pos )
1809 const int max_name_len = 10;
1810 const char* suffix = "";
1814 if( trackbar->data )
1815 *trackbar->data = pos;
1817 if( trackbar->pos != pos )
1819 trackbar->pos = pos;
1820 if( trackbar->notify2 )
1821 trackbar->notify2(pos, trackbar->userdata);
1822 if( trackbar->notify )
1823 trackbar->notify(pos);
1825 name_len = (int)strlen(trackbar->name);
1827 if( name_len > max_name_len )
1829 int start_len = max_name_len*2/3;
1830 int end_len = max_name_len - start_len - 2;
1831 memcpy( pos_text, trackbar->name, start_len );
1832 memcpy( pos_text + start_len, "...", 3 );
1833 memcpy( pos_text + start_len + 3, trackbar->name + name_len - end_len, end_len + 1 );
1837 memcpy( pos_text, trackbar->name, name_len + 1);
1840 sprintf( pos_text + strlen(pos_text), "%s: %d\n", suffix, pos );
1841 SetWindowText( trackbar->buddy, pos_text );
1846 static LRESULT CALLBACK HGToolbarProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
1848 CvWindow* window = icvWindowByHWND( hwnd );
1850 return DefWindowProc(hwnd, uMsg, wParam, lParam);
1852 // Control messages processing
1855 // Slider processing
1858 HWND slider = (HWND)lParam;
1859 int pos = (int)SendMessage(slider, TBM_GETPOS, 0, 0);
1860 CvTrackbar* trackbar = icvTrackbarByHWND( slider );
1864 if( trackbar->pos != pos )
1865 icvUpdateTrackbar( trackbar, pos );
1868 SetFocus( window->hwnd );
1874 LRESULT ret = CallWindowProc(window->toolbar.toolBarProc, hwnd, uMsg, wParam, lParam);
1875 int rows = (int)SendMessage(hwnd, TB_GETROWS, 0, 0);
1877 if(window->toolbar.rows != rows)
1879 SendMessage(window->toolbar.toolbar, TB_BUTTONCOUNT, 0, 0);
1880 CvTrackbar* trackbar = window->toolbar.first;
1882 for( ; trackbar != 0; trackbar = trackbar->next )
1885 SendMessage(window->toolbar.toolbar, TB_GETITEMRECT,
1886 (WPARAM)trackbar->id, (LPARAM)&rect);
1887 MoveWindow(trackbar->hwnd, rect.left + HG_BUDDY_WIDTH, rect.top,
1888 rect.right - rect.left - HG_BUDDY_WIDTH,
1889 rect.bottom - rect.top, FALSE);
1890 MoveWindow(trackbar->buddy, rect.left, rect.top,
1891 HG_BUDDY_WIDTH, rect.bottom - rect.top, FALSE);
1893 window->toolbar.rows = rows;
1899 return CallWindowProc(window->toolbar.toolBarProc, hwnd, uMsg, wParam, lParam);
1904 cvDestroyAllWindows(void)
1906 CvWindow* window = hg_windows;
1910 HWND mainhWnd = window->frame;
1911 HWND hwnd = window->hwnd;
1912 window = window->next;
1914 SendMessage( hwnd, WM_CLOSE, 0, 0 );
1915 SendMessage( mainhWnd, WM_CLOSE, 0, 0 );
1919 static void showSaveDialog(CvWindow* window)
1921 if (!window || !window->image)
1927 if (icvGetBitmapData(window, &sz, &channels, &data))
1928 return; // nothing to save
1930 char szFileName[MAX_PATH] = "";
1931 // try to use window title as file name
1932 GetWindowText(window->frame, szFileName, MAX_PATH);
1935 ZeroMemory(&ofn, sizeof(ofn));
1936 #ifdef OPENFILENAME_SIZE_VERSION_400
1937 // we are not going to use new fields any way
1938 ofn.lStructSize = OPENFILENAME_SIZE_VERSION_400;
1940 ofn.lStructSize = sizeof(ofn);
1942 ofn.hwndOwner = window->hwnd;
1945 "Portable Network Graphics files (*.png)\0*.png\0"
1947 "Windows bitmap (*.bmp;*.dib)\0*.bmp;*.dib\0"
1949 "JPEG files (*.jpeg;*.jpg;*.jpe)\0*.jpeg;*.jpg;*.jpe\0"
1952 "TIFF Files (*.tiff;*.tif)\0*.tiff;*.tif\0"
1955 "JPEG-2000 files (*.jp2)\0*.jp2\0"
1958 "WebP files (*.webp)\0*.webp\0"
1960 "Portable image format (*.pbm;*.pgm;*.ppm;*.pxm;*.pnm)\0*.pbm;*.pgm;*.ppm;*.pxm;*.pnm\0"
1962 "OpenEXR Image files (*.exr)\0*.exr\0"
1964 "Radiance HDR (*.hdr;*.pic)\0*.hdr;*.pic\0"
1965 "Sun raster files (*.sr;*.ras)\0*.sr;*.ras\0"
1966 "All Files (*.*)\0*.*\0";
1967 ofn.lpstrFile = szFileName;
1968 ofn.nMaxFile = MAX_PATH;
1969 ofn.Flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT | OFN_NOREADONLYRETURN | OFN_NOCHANGEDIR;
1971 ofn.lpstrDefExt = "png";
1973 ofn.lpstrDefExt = "bmp";
1976 if (GetSaveFileName(&ofn))
1979 cv::flip(cv::Mat(sz.cy, sz.cx, CV_8UC(channels), data, (sz.cx * channels + 3) & -4), tmp, 0);
1980 cv::imwrite(szFileName, tmp);
1985 cvWaitKey( int delay )
1987 int64 time0 = cv::getTickCount();
1988 int64 timeEnd = time0 + (int64)(delay * 0.001f * cv::getTickFrequency());
1994 int is_processed = 0;
1996 if( (delay <= 0) && hg_windows)
1997 GetMessage(&message, 0, 0, 0);
1998 else if( PeekMessage(&message, 0, 0, 0, PM_REMOVE) == FALSE )
2000 int64 t = cv::getTickCount();
2001 if (t - timeEnd >= 0)
2002 return -1; // no messages and no more time
2007 for( window = hg_windows; window != 0 && is_processed == 0; window = window->next )
2009 if( window->hwnd == message.hwnd || window->frame == message.hwnd )
2012 switch(message.message)
2016 DispatchMessage(&message);
2017 return (int)message.wParam;
2020 if( message.wParam == VK_F10 )
2023 return (int)(message.wParam << 16);
2028 TranslateMessage(&message);
2029 if( (message.wParam >= VK_F1 && message.wParam <= VK_F24) ||
2030 message.wParam == VK_HOME || message.wParam == VK_END ||
2031 message.wParam == VK_UP || message.wParam == VK_DOWN ||
2032 message.wParam == VK_LEFT || message.wParam == VK_RIGHT ||
2033 message.wParam == VK_INSERT || message.wParam == VK_DELETE ||
2034 message.wParam == VK_PRIOR || message.wParam == VK_NEXT )
2036 DispatchMessage(&message);
2038 return (int)(message.wParam << 16);
2041 // Intercept Ctrl+C for copy to clipboard
2042 if ('C' == message.wParam && (::GetKeyState(VK_CONTROL)>>15))
2043 ::SendMessage(message.hwnd, WM_COPY, 0, 0);
2045 // Intercept Ctrl+S for "save as" dialog
2046 if ('S' == message.wParam && (::GetKeyState(VK_CONTROL)>>15))
2047 showSaveDialog(window);
2050 DispatchMessage(&message);
2059 TranslateMessage(&message);
2060 DispatchMessage(&message);
2067 icvFindTrackbarByName( const CvWindow* window, const char* name )
2069 CvTrackbar* trackbar = window->toolbar.first;
2071 for( ; trackbar != 0 && strcmp( trackbar->name, name ) != 0; trackbar = trackbar->next )
2079 icvCreateTrackbar( const char* trackbar_name, const char* window_name,
2080 int* val, int count, CvTrackbarCallback on_notify,
2081 CvTrackbarCallback2 on_notify2, void* userdata )
2085 CV_FUNCNAME( "icvCreateTrackbar" );
2089 char slider_name[32];
2090 CvWindow* window = 0;
2091 CvTrackbar* trackbar = 0;
2094 if( !window_name || !trackbar_name )
2095 CV_ERROR( CV_StsNullPtr, "NULL window or trackbar name" );
2098 CV_ERROR( CV_StsOutOfRange, "Bad trackbar maximal value" );
2100 window = icvFindWindowByName(window_name);
2104 trackbar = icvFindTrackbarByName(window,trackbar_name);
2108 TBBUTTONINFO tbis = {};
2111 int len = (int)strlen( trackbar_name );
2113 // create toolbar if it is not created yet
2114 if( !window->toolbar.toolbar )
2116 const int default_height = 30;
2118 // CreateToolbarEx is deprecated and forces linking against Comctl32.lib.
2119 window->toolbar.toolbar = CreateWindowEx(0, TOOLBARCLASSNAME, NULL,
2120 WS_CHILD | CCS_TOP | TBSTYLE_WRAPABLE | BTNS_AUTOSIZE | BTNS_BUTTON,
2122 window->frame, NULL, GetModuleHandle(NULL), NULL);
2123 // CreateToolbarEx automatically sends this but CreateWindowEx doesn't.
2124 SendMessage(window->toolbar.toolbar, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0);
2126 GetClientRect(window->frame, &rect);
2127 MoveWindow( window->toolbar.toolbar, 0, 0,
2128 rect.right - rect.left, default_height, TRUE);
2129 SendMessage(window->toolbar.toolbar, TB_AUTOSIZE, 0, 0);
2130 ShowWindow(window->toolbar.toolbar, SW_SHOW);
2132 window->toolbar.first = 0;
2133 window->toolbar.pos = 0;
2134 window->toolbar.rows = 0;
2135 window->toolbar.toolBarProc =
2136 (WNDPROC)icvGetWindowLongPtr(window->toolbar.toolbar, CV_WNDPROC);
2138 icvUpdateWindowPos(window);
2140 // Subclassing from toolbar
2141 icvSetWindowLongPtr(window->toolbar.toolbar, CV_WNDPROC, HGToolbarProc);
2142 icvSetWindowLongPtr(window->toolbar.toolbar, CV_USERDATA, window);
2145 /* Retrieve current buttons count */
2146 bcount = (int)SendMessage(window->toolbar.toolbar, TB_BUTTONCOUNT, 0, 0);
2150 /* If this is not the first button then we need to
2151 separate it from the previous one */
2153 tbs.idCommand = bcount; // Set button id to it's number
2155 tbs.fsStyle = TBSTYLE_SEP;
2156 tbs.fsState = TBSTATE_ENABLED;
2157 SendMessage(window->toolbar.toolbar, TB_ADDBUTTONS, 1, (LPARAM)&tbs);
2159 // Retrieve current buttons count
2160 bcount = (int)SendMessage(window->toolbar.toolbar, TB_BUTTONCOUNT, 0, 0);
2163 /* Add a button which we're going to cover with the slider */
2165 tbs.idCommand = bcount; // Set button id to it's number
2166 tbs.fsState = TBSTATE_ENABLED;
2167 #if 0/*!defined WIN64 && !defined EM64T*/
2172 #ifndef TBSTYLE_AUTOSIZE
2173 #define TBSTYLE_AUTOSIZE 0x0010
2176 #ifndef TBSTYLE_GROUP
2177 #define TBSTYLE_GROUP 0x0004
2179 //tbs.fsStyle = TBSTYLE_AUTOSIZE;
2180 tbs.fsStyle = TBSTYLE_GROUP;
2181 tbs.iString = (INT_PTR)trackbar_text;
2183 SendMessage(window->toolbar.toolbar, TB_ADDBUTTONS, 1, (LPARAM)&tbs);
2185 /* Adjust button size to the slider */
2186 tbis.cbSize = sizeof(tbis);
2187 tbis.dwMask = TBIF_SIZE;
2189 GetClientRect(window->hwnd, &rect);
2190 tbis.cx = (unsigned short)(rect.right - rect.left);
2192 SendMessage(window->toolbar.toolbar, TB_SETBUTTONINFO,
2193 (WPARAM)tbs.idCommand, (LPARAM)&tbis);
2195 /* Get button pos */
2196 SendMessage(window->toolbar.toolbar, TB_GETITEMRECT,
2197 (WPARAM)tbs.idCommand, (LPARAM)&rect);
2199 /* Create a slider */
2200 trackbar = (CvTrackbar*)cvAlloc( sizeof(CvTrackbar) + len + 1 );
2201 trackbar->signature = CV_TRACKBAR_MAGIC_VAL;
2202 trackbar->notify = 0;
2203 trackbar->notify2 = 0;
2204 trackbar->parent = window;
2207 trackbar->id = bcount;
2208 trackbar->next = window->toolbar.first;
2209 trackbar->name = (char*)(trackbar + 1);
2210 memcpy( trackbar->name, trackbar_name, len + 1 );
2211 window->toolbar.first = trackbar;
2213 sprintf(slider_name, "Trackbar%p", val);
2214 trackbar->hwnd = CreateWindowEx(0, TRACKBAR_CLASS, slider_name,
2215 WS_CHILD | WS_VISIBLE | TBS_AUTOTICKS |
2216 TBS_FIXEDLENGTH | TBS_HORZ | TBS_BOTTOM,
2217 rect.left + HG_BUDDY_WIDTH, rect.top,
2218 rect.right - rect.left - HG_BUDDY_WIDTH,
2219 rect.bottom - rect.top, window->toolbar.toolbar,
2220 (HMENU)(size_t)bcount, hg_hinstance, 0);
2222 sprintf(slider_name,"Buddy%p", val);
2223 trackbar->buddy = CreateWindowEx(0, "STATIC", slider_name,
2224 WS_CHILD | SS_RIGHT,
2225 rect.left, rect.top,
2226 HG_BUDDY_WIDTH, rect.bottom - rect.top,
2227 window->toolbar.toolbar, 0, hg_hinstance, 0);
2229 icvSetWindowLongPtr( trackbar->hwnd, CV_USERDATA, trackbar );
2231 /* Minimize the number of rows */
2232 SendMessage( window->toolbar.toolbar, TB_SETROWS,
2233 MAKEWPARAM(1, FALSE), (LPARAM)&rect );
2238 trackbar->notify = 0;
2239 trackbar->notify2 = 0;
2242 trackbar->maxval = count;
2244 /* Adjust slider parameters */
2245 SendMessage(trackbar->hwnd, TBM_SETRANGEMIN, (WPARAM)TRUE, (LPARAM)0);
2246 SendMessage(trackbar->hwnd, TBM_SETRANGEMAX, (WPARAM)TRUE, (LPARAM)count);
2247 SendMessage(trackbar->hwnd, TBM_SETTICFREQ, (WPARAM)1, (LPARAM)0 );
2251 SendMessage(trackbar->hwnd, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)pos );
2252 SendMessage(window->toolbar.toolbar, TB_AUTOSIZE, 0, 0);
2255 icvUpdateTrackbar( trackbar, pos );
2256 ShowWindow( trackbar->buddy, SW_SHOW );
2257 ShowWindow( trackbar->hwnd, SW_SHOW );
2259 trackbar->notify = on_notify;
2260 trackbar->notify2 = on_notify2;
2261 trackbar->userdata = userdata;
2262 trackbar->data = val;
2264 /* Resize the window to reflect the toolbar resizing*/
2265 icvUpdateWindowPos(window);
2275 cvCreateTrackbar( const char* trackbar_name, const char* window_name,
2276 int* val, int count, CvTrackbarCallback on_notify )
2278 return icvCreateTrackbar( trackbar_name, window_name, val, count,
2283 cvCreateTrackbar2( const char* trackbar_name, const char* window_name,
2284 int* val, int count, CvTrackbarCallback2 on_notify2,
2287 return icvCreateTrackbar( trackbar_name, window_name, val, count,
2288 0, on_notify2, userdata );
2292 cvSetMouseCallback( const char* window_name, CvMouseCallback on_mouse, void* param )
2294 CV_FUNCNAME( "cvSetMouseCallback" );
2298 CvWindow* window = 0;
2301 CV_ERROR( CV_StsNullPtr, "NULL window name" );
2303 window = icvFindWindowByName(window_name);
2307 window->on_mouse = on_mouse;
2308 window->on_mouse_param = param;
2314 CV_IMPL int cvGetTrackbarPos( const char* trackbar_name, const char* window_name )
2318 CV_FUNCNAME( "cvGetTrackbarPos" );
2323 CvTrackbar* trackbar = 0;
2325 if( trackbar_name == 0 || window_name == 0 )
2326 CV_ERROR( CV_StsNullPtr, "NULL trackbar or window name" );
2328 window = icvFindWindowByName( window_name );
2330 trackbar = icvFindTrackbarByName( window, trackbar_name );
2333 pos = trackbar->pos;
2341 CV_IMPL void cvSetTrackbarPos( const char* trackbar_name, const char* window_name, int pos )
2343 CV_FUNCNAME( "cvSetTrackbarPos" );
2348 CvTrackbar* trackbar = 0;
2350 if( trackbar_name == 0 || window_name == 0 )
2351 CV_ERROR( CV_StsNullPtr, "NULL trackbar or window name" );
2353 window = icvFindWindowByName( window_name );
2355 trackbar = icvFindTrackbarByName( window, trackbar_name );
2362 if( pos > trackbar->maxval )
2363 pos = trackbar->maxval;
2365 SendMessage( trackbar->hwnd, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)pos );
2366 icvUpdateTrackbar( trackbar, pos );
2373 CV_IMPL void cvSetTrackbarMax(const char* trackbar_name, const char* window_name, int maxval)
2375 CV_FUNCNAME( "cvSetTrackbarMax" );
2381 CvWindow* window = 0;
2382 CvTrackbar* trackbar = 0;
2383 if (trackbar_name == 0 || window_name == 0)
2385 CV_ERROR(CV_StsNullPtr, "NULL trackbar or window name");
2388 window = icvFindWindowByName(window_name);
2391 trackbar = icvFindTrackbarByName(window, trackbar_name);
2394 // The position will be min(pos, maxval).
2395 trackbar->maxval = (trackbar->minval>maxval)?trackbar->minval:maxval;
2396 SendMessage(trackbar->hwnd, TBM_SETRANGEMAX, (WPARAM)TRUE, (LPARAM)maxval);
2405 CV_IMPL void cvSetTrackbarMin(const char* trackbar_name, const char* window_name, int minval)
2407 CV_FUNCNAME( "cvSetTrackbarMin" );
2413 CvWindow* window = 0;
2414 CvTrackbar* trackbar = 0;
2415 if (trackbar_name == 0 || window_name == 0)
2417 CV_ERROR(CV_StsNullPtr, "NULL trackbar or window name");
2420 window = icvFindWindowByName(window_name);
2423 trackbar = icvFindTrackbarByName(window, trackbar_name);
2426 // The position will be min(pos, maxval).
2427 trackbar->minval = (minval<trackbar->maxval)?minval:trackbar->maxval;
2428 SendMessage(trackbar->hwnd, TBM_SETRANGEMIN, (WPARAM)TRUE, (LPARAM)minval);
2437 CV_IMPL void* cvGetWindowHandle( const char* window_name )
2441 CV_FUNCNAME( "cvGetWindowHandle" );
2447 if( window_name == 0 )
2448 CV_ERROR( CV_StsNullPtr, "NULL window name" );
2450 window = icvFindWindowByName( window_name );
2452 hwnd = (void*)window->hwnd;
2460 CV_IMPL const char* cvGetWindowName( void* window_handle )
2462 const char* window_name = "";
2464 CV_FUNCNAME( "cvGetWindowName" );
2470 if( window_handle == 0 )
2471 CV_ERROR( CV_StsNullPtr, "NULL window" );
2473 window = icvWindowByHWND( (HWND)window_handle );
2475 window_name = window->name;
2484 cvSetPreprocessFuncWin32_(const void* callback)
2486 hg_on_preprocess = (CvWin32WindowCallback)callback;
2490 cvSetPostprocessFuncWin32_(const void* callback)
2492 hg_on_postprocess = (CvWin32WindowCallback)callback;