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.
40 //M*/// Hawk.cpp : Defines the class behaviors for the application.
62 //#include "eicdllwrap.h"
67 static char THIS_FILE[] = __FILE__;
70 char* cline = "-D_EiC";
71 char* std_inc[] = {"assert", "ctype", "errno", /*"float", "limits",*/ "math",
72 "stdarg", "stddef", "stdio", "stdlib", "string", "time"};
76 #include "CVEiCL\EiC\src\eic.h"
77 #include "CVEiCL\EiC\src\typemod.h"
78 #include "CVEiCL\EiC\src\global.h"
79 #include "CVEiCL\EiC\src\func.h"
80 #include "CVEiCL\EiC\src\error.h"
81 #include "CVEiCL\EiC\src\symbol.h"
86 void EiC_init_EiC(void);
88 void module_ippiwrap(void);
90 void EiC_switches(char*);
91 void module_highguiwrap();
92 void set_highgui_errlevel(errlevel_t level);
93 void set_highgui_mark(jmp_buf* mark);
94 symentry_t * EiC_lookup(char nspace, char *id);
95 void EiC_xalloc_CleanUp(size_t, size_t);
97 extern void (*EiC_messageDisplay)(char*);
99 void set_hawk_errlevel(errlevel_t level);
100 void set_hawk_mark(jmp_buf* mark);
101 void module_convertwrap();
102 void set_eic_errlevel(errlevel_t level);
103 void set_eic_mark(jmp_buf* mark);
105 int FindStringInArray(const CStringArray& array, const CString& string)
107 for(int i = 0; i < array.GetSize(); i++)
109 if(strcmp(LPCTSTR(array.GetData()[i]), LPCTSTR(string)) == 0)
118 template<> void AFXAPI DestructElements<CMenu*> (CMenu** pElements, int nCount)
120 for(int i = 0; i < nCount; i++)
124 template<> void AFXAPI DestructElements<plugin_t> (plugin_t* pElements, int nCount)
126 for(int i = 0; i < nCount; i++)
127 delete pElements[i].m_functions;
131 /////////////////////////////////////////////////////////////////////////////
134 BEGIN_MESSAGE_MAP(CHawkApp, CWinApp)
135 //{{AFX_MSG_MAP(CHawkApp)
136 ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
137 // NOTE - the ClassWizard will add and remove mapping macros here.
138 // DO NOT EDIT what you see in these blocks of generated code!
140 // Standard file based document commands
141 ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
142 ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)
143 // Standard print setup command
144 ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup)
147 /////////////////////////////////////////////////////////////////////////////
148 // CHawkApp construction
152 m_eicOut.write = m_eicOut.read = NULL;
153 m_eicErr.write = m_eicErr.read = NULL;
154 m_mainMenu.m_hMenu = NULL;
162 CHawkApp::~CHawkApp()
164 for(int i = 0; i < m_funcDialogs.GetSize(); i++)
166 delete (CFuncDialog*)m_funcDialogs.GetData()[i];
170 /////////////////////////////////////////////////////////////////////////////
171 // The one and only CHawkApp object
175 /////////////////////////////////////////////////////////////////////////////
176 // CHawkApp initialization
178 BOOL CHawkApp::InitInstance()
180 AfxEnableControlContainer();
182 // Standard initialization
183 // If you are not using these features and wish to reduce the size
184 // of your final executable, you should remove from the following
185 // the specific initialization routines you do not need.
188 Enable3dControls(); // Call this when using MFC in a shared DLL
190 Enable3dControlsStatic(); // Call this when linking to MFC statically
193 // Change the registry key under which our settings are stored.
194 // TODO: You should modify this string to be something appropriate
195 // such as the name of your company or organization.
196 SetRegistryKey(_T("Intel"));
198 LoadStdProfileSettings(); // Load standard INI file options (including MRU)
200 // Register the application's document templates. Document templates
201 // serve as the connection between documents, frame windows and views.
203 CMultiDocTemplate* pDocTemplate;
204 pDocTemplate = new CMultiDocTemplate(
206 RUNTIME_CLASS(CHawkDoc),
207 RUNTIME_CLASS(CChildFrame), // custom MDI child frame
208 RUNTIME_CLASS(CHawkView));
209 AddDocTemplate(pDocTemplate);
211 pDocTemplate = new CMultiDocTemplate(
213 RUNTIME_CLASS(CDocument),
214 RUNTIME_CLASS(CChildFrame), // custom MDI child frame
215 RUNTIME_CLASS(CLogView));
216 AddDocTemplate(pDocTemplate);
219 // create main MDI Frame window
220 CMainFrame* pMainFrame = new CMainFrame;
221 if (!pMainFrame->LoadFrame(IDR_MAINFRAME))
223 m_pMainWnd = pMainFrame;
225 // Parse command line for standard shell commands, DDE, file open
226 CCommandLineInfo cmdInfo;
227 ParseCommandLine(cmdInfo);
229 // Dispatch commands specified on the command line
230 if (!ProcessShellCommand(cmdInfo))
233 // The main window has been initialized, so show and update it.
234 pMainFrame->ShowWindow(m_nCmdShow);
235 pMainFrame->UpdateWindow();
237 // Creating a headband
238 m_headband.Create(IDD_HEADBAND, AfxGetMainWnd());
240 // Centering a headband
241 CRect rect, drect, nrect;
242 AfxGetMainWnd()->GetWindowRect(&rect);
243 m_headband.GetWindowRect(&drect);
244 CPoint DUpLeft = CPoint((rect.Width() - drect.Width())/2, (rect.Height() - drect.Height())/2);
245 drect.OffsetRect(DUpLeft);
246 m_headband.MoveWindow(&drect);
247 m_headband.ShowWindow(SW_SHOW);
248 m_headband.UpdateWindow();
250 InitCommonControls();
252 BOOL ret = InitEiC();
253 m_headband.DestroyWindow();
259 /////////////////////////////////////////////////////////////////////////////
260 // CAboutDlg dialog used for App About
262 class CAboutDlg : public CDialog
268 //{{AFX_DATA(CAboutDlg)
269 enum { IDD = IDD_ABOUTBOX };
272 // ClassWizard generated virtual function overrides
273 //{{AFX_VIRTUAL(CAboutDlg)
275 virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
280 //{{AFX_MSG(CAboutDlg)
281 // No message handlers
283 DECLARE_MESSAGE_MAP()
286 CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
288 //{{AFX_DATA_INIT(CAboutDlg)
292 void CAboutDlg::DoDataExchange(CDataExchange* pDX)
294 CDialog::DoDataExchange(pDX);
295 //{{AFX_DATA_MAP(CAboutDlg)
299 BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
300 //{{AFX_MSG_MAP(CAboutDlg)
301 // No message handlers
305 // App command to run the dialog
306 void CHawkApp::OnAppAbout()
312 /////////////////////////////////////////////////////////////////////////////
313 // CHawkApp message handlers
315 /* My version of printf function... */
316 int eic_hawk_charout(int c, void* buf)
318 CHawkApp* app = (CHawkApp*)AfxGetApp();
319 // if(app->m_pipeDataSize > )
320 CString& str = *(CString*)buf;
322 str += CString(text);
324 /* if(WaitForSingleObject(app->m_printfMutex, INFINITE) != WAIT_OBJECT_0)
335 int _eicUprintf(int (*output)(int, void*), void *arg, char *fmt, arg_list ap);
338 static val_t eic_hawk_printf()
340 CHawkApp* app = (CHawkApp*)AfxGetApp();
341 CMainFrame* frame = (CMainFrame*)AfxGetMainWnd();
344 arg_list ag = getargs();
345 char *fmt = (char*)nextarg(ag,ptr_t).p;
347 v.ival = _eicUprintf(eic_hawk_charout, (void*)&buf, fmt, ag);
349 frame->m_pRunDoc->GetLogView()->AddString(LPCTSTR(buf));
350 // ReleaseMutex(app->m_printfMutex);
355 static void _Hawk_MessageDisplay(char* str)
360 /*static val_t eic_Hawk_uni_wrap()
364 uni_wrap(stub_f(arg(0, getargs(), ptr_t).p),
365 (int*)arg(1, getargs(), ptr_t).p,
366 (char*)arg(2, getargs(), ptr_t).p,
372 BOOL CHawkApp::InitEiC()
376 // Initialize the module's path string
379 SetStatusString("Initializing EiC...");
382 char *_pargv[2] = {_argv, 0};
383 EiC_startEiC(1, _pargv);
384 SetStatusString("Initializing standard C library...");
386 EiC_add_builtinfunc("printf", eic_hawk_printf);
388 // Setup the signals messaging
389 EiC_messageDisplay = _Hawk_MessageDisplay;*/
391 // Initializing EiC plugin functions
392 SetStatusString("Initializing HighGUI library...");
393 module_highguiwrap();
394 SetStatusString("Initializing converters library...");
395 module_convertwrap();
398 EiC_parseString("typedef struct _a {double v;int w;char t;} a;");
399 EiC_parseString("int f(a b) {return b.w;};");
400 EiC_parseString("struct a b;f(b);\\int e");
401 EiC_parseString("struct a c;");
403 EiC_parseString("struct _b {char t;};");
404 EiC_parseString("struct _a b;");
405 symentry_t* sym = EiC_lookup(1, "a");
406 struct_t* s = (struct_t*)sym->type->nxt->u.inf;
407 func_t* funcDesc = (func_t*)sym->type->u.inf;
408 parm_t* parmDesc = funcDesc->parm;
409 s = (struct_t*)parmDesc->type->u.inf;*/
411 // Initializing HighGUI
412 cvInitSystem(0,0); // SetInstance(AfxGetApp()->m_hInstance);
413 cvAddSearchPath(LPCTSTR(m_modulePath + CString("bitmaps")));
414 cvAddSearchPath(LPCTSTR(m_modulePath + CString("..\\..\\..\\apps\\Hawk\\bitmaps")));
415 AddVideoPath(m_modulePath + CString("Video"));
416 AddVideoPath(m_modulePath + CString("..\\..\\..\\apps\\Hawk\\Video"));
421 // Define the universal wrapper function
422 EiC_parseString("void _Hawk_uniwrap(void*,int*,char*,int*, void*);");
424 // First lets find the wrappers directory
425 m_wrappersPath = m_modulePath + CString("wrappers");
426 CString inc = CString(":-I ") + m_wrappersPath;
427 // EiC_parseString(const_cast<char*>(LPCTSTR(inc)));
428 inc += CString("\\std");
429 // EiC_parseString(const_cast<char*>(LPCTSTR(inc)));
431 EiC_parseString("#pragma push_unsafeptr");
433 /* Make the source compatible with C standard */
434 EiC_parseString("#define __stdcall");
435 EiC_parseString("#define __cdecl");
436 EiC_parseString("#define __declspec(a)");
437 EiC_parseString("typedef struct{int l,h;} __int64;");
439 /* Definitions for IPL */
440 /*EiC_parseString("#define IPL_WINDOWS");*/
441 /*EiC_parseString("#define IPLAPI(type, name, arg) type name arg;");*/
443 /* Definitions for OpenCV */
444 EiC_parseString("#define CV_INLINE");
445 /*EiC_parseString("#define HAVE_IPL");*/
447 /* Temporary! Inserted because of EiC bug. */
448 //EiC_parseString("struct CvSubdiv2DPoint;");
450 /* Enum all include dirs and headers */
451 char curDir[_MAX_PATH];
452 GetCurrentDirectory(_MAX_PATH, curDir);
453 SetCurrentDirectory(m_wrappersPath);
454 EnumHeaders(m_wrappersPath);
456 // Set include directories
457 for(int i = 0; i < m_includeDirs.size(); i++)
459 EiC_parseString(":-I %s", m_includeDirs[i].c_str());
463 for(i = 0; i < m_includeFiles.size(); i++)
466 str = string("Parsing header ") + m_includeFiles[i] + "...";
467 SetStatusString(str.c_str());
468 Attach(m_includeFiles[i]);
470 SetCurrentDirectory(curDir);
472 char textBuffer[2048];
473 rewind(m_eicErr.read);
474 int err = _read(_fileno(m_eicErr.read), textBuffer, 2047);
478 AfxMessageBox(textBuffer);
480 _chsize(_fileno(m_eicErr.read), 0);
482 const char* libName = "cv.dll";
484 const char* libName = "cvd.dll";
487 LoadModuleFunctions(libName, "OpenCV");
490 const char* auxlibName = "cvaux.dll";
492 const char* auxlibName = "cvauxd.dll";
495 LoadModuleFunctions(auxlibName, "OpenCVAux");
499 const char* hglibName = "HighGUI.dll";
501 const char* hglibName = "HighGUId.dll";
504 LoadModuleFunctions(hglibName, "OpenCVHighGUI");
509 EiC_parseString("#pragma pop_ptr");
511 SetStatusString("Almost done...");
512 // Initialize context menus
515 // Update error marks
517 // Loading Hawk configuration
518 m_errlevel = (errlevel_t)GetProfileInt("Configuration", "Error level", (int)unsafe);
519 SetErrLevel(m_errlevel);
520 m_sbRun = GetProfileInt("Configuration", "Autosave before run", TRUE);
522 // Remember EiC's state
523 EiC_parseString(":reset here");
528 BOOL CHawkApp::InitModulePath()
530 // Find the full path for this executable
531 HMODULE hnd = GetModuleHandle(LPCTSTR(m_pszExeName));
533 GetModuleFileName(hnd, buff, 128);
535 char drive[_MAX_DRIVE], dir[_MAX_DIR], fName[_MAX_FNAME], ext[_MAX_EXT];
536 _splitpath(buff, drive, dir, fName, ext);
538 m_modulePath.Format("%s%s",drive,dir);
543 BOOL CHawkApp::FindAndAttach(LPCTSTR path, LPCTSTR fileName)
548 int length = SearchPath(path, fileName, ".h", 2048, buffer, &pFinal);
551 return Attach(buffer);
555 CString str = CString("Wrapper file ") + CString(fileName) +
556 CString(".h has not been found!\n") +
557 CString("Functions declared in the file will not be ") +
558 CString("available during current session.");
565 LPCTSTR CHawkApp::GetModulePath()
567 return LPCTSTR(m_modulePath);
570 void CHawkApp::LoadPlugins()
573 BOOL isAnother = TRUE;
576 dir = m_modulePath + CString("\\plugins\\");
577 str = dir + CString("*.dll");
579 searchHandle = _findfirst(LPCTSTR(str), &data);
580 if(searchHandle == -1)
588 str.Format("Loading %s plugin...", data.name);
589 SetStatusString(LPCTSTR(str));
591 module = LoadLibrary(LPCTSTR(dir + CString(data.name)));
592 if(module && LoadPluginFunctions(module))
594 CString str(data.name);
595 m_plugins.GetData()[m_plugins.GetSize() - 1].m_path = str.Left(str.GetLength() - 4);
600 str.Format("Failed to load %s plugin!", data.name);
609 isAnother = !_findnext(searchHandle, &data);
613 BOOL CHawkApp::LoadPluginFunctions(HMODULE module)
617 // Check if this is Hawk dll
618 plugin.m_GetInfo = (void (*)(plugin_info*))GetProcAddress(module, "PluginGetInfo");
619 plugin.m_SetEiCStack = (void (*)(AR_t**))GetProcAddress(module, "SetEiCStack");
620 plugin.m_SetEiCCallback = (void (*)(void(*)(void*)))GetProcAddress(module, "SetEiCCallback");
621 plugin.m_GetFunctions = (void (*)(char***, val_t (***)(void), int*))
622 GetProcAddress(module, "GetFunctions");
623 plugin.m_SetErrLevel = (void(*)(errlevel_t))GetProcAddress(module, "SetErrLevel");
624 plugin.m_SetErrMark = (void(*)(jmp_buf*))GetProcAddress(module, "SetErrMark");
625 if(!plugin.m_SetEiCStack || !plugin.m_GetFunctions || !plugin.m_SetEiCCallback ||
626 !plugin.m_SetErrLevel || !plugin.m_SetErrMark)
631 // Get the plugin info
632 plugin.m_GetInfo(&plugin.m_info);
635 plugin.m_SetEiCStack(AR);
636 plugin.m_SetEiCCallback(EiC_callBack);
637 plugin.m_SetErrMark(&m_mark);
639 // Get all functions wrappers
641 val_t(**funcs)(void);
643 plugin.m_GetFunctions(&func_names, &funcs, &funcs_count);
645 // Register functions in EiC and update names array
646 CStringArray* names = new CStringArray;
647 for(int i = 0; i < funcs_count; i++)
651 EiC_add_builtinfunc(func_names[i], funcs[i]);
654 if(j < names->GetSize())
656 if(strcmp(func_names[i], LPCTSTR(names->GetData()[j])) < 0)
658 names->InsertAt(j, CString(func_names[i]));
664 names->Add(CString(func_names[i]));
670 plugin.m_functions = names;
671 plugin.m_handle = module;
672 m_plugins.Add(plugin);
677 void CHawkApp::InitPopupMenu()
679 m_mainMenu.CreatePopupMenu();
680 for(int i = 0; i < m_plugins.GetSize(); i++)
682 m_mainMenu.AppendMenu(MF_STRING | (i%30 || !i ? 0 : MF_MENUBARBREAK),
683 (i + 1)<<16, LPCTSTR(m_plugins.GetData()[i].m_info.name));
687 CMenu* CHawkApp::GetContextMenu()
692 CStringArray* CHawkApp::GetFunctions(int i)
694 return m_plugins.GetData()[i].m_functions;
697 void CHawkApp::ExitEiC()
699 for(int i = 0; i < m_eicFiles.GetSize(); i++)
702 sprintf(str, ":clear %s", LPCTSTR(m_eicFiles[i]));
703 EiC_parseString(str);
706 EiC_parseString(":clear ::EiC::");
708 EiC_xalloc_CleanUp(0, UINT_MAX);
711 int CHawkApp::ExitInstance()
716 // Save Hawk configuration
717 WriteProfileInt("Configuration", "Error level", m_errlevel);
718 return CWinApp::ExitInstance();
721 void CHawkApp::SetErrLevel(errlevel_t level)
724 set_highgui_errlevel(level);
725 set_hawk_errlevel(level);
726 set_eic_errlevel(level);
727 for(int i = 0; i < m_plugins.GetSize(); i++)
729 if(m_plugins.GetData()[i].m_SetErrLevel)
730 m_plugins.GetData()[i].m_SetErrLevel(level);
734 errlevel_t CHawkApp::GetErrLevel()
739 void CHawkApp::UpdateMark(jmp_buf *mark)
741 jmp_buf* realmark = mark ? mark : &m_mark;
743 set_highgui_mark(realmark);
744 set_hawk_mark(realmark);
745 set_eic_mark(realmark);
746 for(int i = 0; i < m_plugins.GetSize(); i++)
748 if(m_plugins.GetData()[i].m_SetErrMark)
749 m_plugins.GetData()[i].m_SetErrMark(realmark);
753 BOOL CHawkApp::GetSBRun()
758 void CHawkApp::SetSBRun(BOOL sbRun)
763 void CHawkApp::SetStatusString(LPCTSTR str)
765 m_headband.SetDlgItemText(IDC_STATUS, str);
768 void CHawkApp::AddVideoPath(const CString& path)
770 m_videoPath.Add(path);
773 const CStringArray& CHawkApp::GetVideoPath()
778 BOOL CHawkApp::InitEiCHandles()
780 // Open a pipe to read EiC's stdout
783 // Creating a pipe for eicout:
784 int error = _pipe(handles, 9128, _O_TEXT);
787 AfxMessageBox("Failed to create an output buffer for EiC...");
791 m_eicOut.read = fdopen(handles[0], "r");
792 m_eicOut.write = fdopen(handles[1], "w");
794 // Creating a pipe for eicerr:
795 error = _pipe(handles, 9128, _O_BINARY);
798 AfxMessageBox("Failed to create an output buffer for EiC...");
802 m_eicErr.read = fdopen(handles[0], "r");
803 m_eicErr.write = fdopen(handles[1], "w");*/
805 m_printfMutex = CreateMutex(NULL, FALSE, "EiC stdout");
806 // m_eicOut.read = m_eicOut.write = freopen("__stdout.temp", "w+", stdout);
808 char* tn = tempnam(GetModulePath(), "__eiCErrTemp.");
809 m_EiCErrFile = CString(tn);
811 m_eicErr.read = freopen(LPCTSTR(m_EiCErrFile), "w+", stderr);
812 m_eicErr.write = m_eicErr.read;
813 rewind(m_eicErr.read);
818 void CHawkApp::CloseEiCHandles()
820 CloseHandle(m_printfMutex);
821 // fclose(m_eicOut.write);
822 fclose(m_eicErr.write);
823 remove(LPCTSTR(m_EiCErrFile));
827 int get_uweic_type(type_expr* type)
830 #define _TYPE_CASE(x) case t_##x: return sizeof(x)
831 #define _TYPE_UCASE(x) case t_##x: case t_u##x: return sizeof(x)
843 return sizeof(void*);
847 s = (struct_t*)(type->u.inf);
863 BOOL CHawkApp::GenAutoWrapper(void* func, LPCTSTR func_name)
865 // Find EiC description for the function
866 symentry_t* sym = (symentry_t*)EiC_lookup(1, const_cast<char*>(func_name));
870 /* Function not found */
874 // Get the function return type string
875 CString ret = GetTypeString(sym->type->nxt);
877 // Generate the argument list: (type0 x0, type1 x1, etc..., typen xn)
879 func_t* funcDesc = (func_t*)sym->type->u.inf;
880 parm_t* parmDesc = funcDesc->parm;
883 for(int p = 0; p < funcDesc->Num - 1; p++)
885 type_expr* type = parmDesc[p].type;
886 if(type->obj == t_pointer && type->nxt->obj == t_funcdec)
888 /* Function contains callbacks */
891 _argstr.Format("x%d", p);
892 argstr += GetTypeString(parmDesc[p].type, _argstr) /*+ " " + _argstr */ + ",";
894 if(funcDesc->Num == 1 && parmDesc[p].type->obj == t_var)
900 _argstr.Format("x%d", p);
901 argstr += GetTypeString(parmDesc[p].type, _argstr) /*+ " " + _argstr*/ + ")";
904 // Define auxiliary EiC function
905 // First, the return type and function name
906 CString str = ret + " " + CString(func_name);
908 // Then, the function parameters
911 // Now, the function body:
912 // First of all, generate the argi array of arguments types
914 argistr.Format("int argi[%d] = ", funcDesc->Num + 3);
917 int* argi = new int[funcDesc->Num + 3];
919 argi[1] = funcDesc->Num;
920 arginitstr.Format("%d,", funcDesc->Num);
923 if(sym->type->nxt->obj == t_float)
925 argi[2] = EICEX_TYPE_FLOAT;
926 temp.Format("%d,", EICEX_TYPE_FLOAT);
928 else if(sym->type->nxt->obj == t_double)
930 argi[2] = EICEX_TYPE_DOUBLE;
931 temp.Format("%d,", EICEX_TYPE_DOUBLE);
935 argi[2] = get_uweic_type(sym->type->nxt);
936 temp.Format("%d,", argi[2]);
940 for(p = 0; p < funcDesc->Num - 1; p++)
942 argi[3 + p] = get_uweic_type(parmDesc[p].type);
943 temp.Format("%d,",argi[3 + p]);
946 argi[3 + p] = get_uweic_type(parmDesc[p].type);
947 temp.Format("%d", argi[3 + p]);
950 argi[0] = stack_size(argi + 1);
951 temp.Format("%d,", argi[0]);
952 arginitstr = temp + arginitstr;
953 argistr += CString("{") + arginitstr + "};";
954 str += CString("{") + argistr;
956 // argi is not needed any more...
959 // Generate the nonscalar arguments list
961 argistr.Format("int nslist[] = {%d", 0/*funcDesc->Num - 1*/);
962 for(p = 0; p < funcDesc->Num; p++)
964 if(parmDesc[p].type->obj == t_struct || parmDesc[p].type->obj == t_union)
965 argistr += CString(",1");
967 argistr += CString(",0");
969 argistr += CString("};");
972 // Generate the function address
974 addrstr.Format("%d", (int)func);
975 str += "void* xr=" + addrstr + ";";
976 // Now generate the return buffer
977 if(sym->type->nxt->obj != t_void)
979 argistr.Format("(char*)%d", 1);
980 str += GetTypeString(sym->type->nxt) + " ret;";
981 str += CString("_Hawk_uniwrap(xr, argi, " + argistr + ", nslist, (void*)&ret);return ret;};");
985 argistr.Format("(char*)%d", 0);
986 str += CString("_Hawk_uniwrap(xr, argi, " + argistr + ", nslist, 0);};");
988 EiC_parseString(const_cast<char*>(LPCTSTR(str)));
995 m_wrapperStrings.Add(str);
1000 CString CHawkApp::GetTypeString(void* _type, const char* name)
1009 type_expr* type = (type_expr*)_type;
1014 symentry_t* sym = (symentry_t*)type->sym;
1015 if(sym->sclass == c_typedef)
1016 return CString(sym->id) + " " + name;
1019 #define _TYPE_CASE(x) case t_##x: return CString(#x) + " " + name
1020 #define _TYPE_UCASE(x) case t_u##x: return CString("unsigned " #x) + " " + name;
1039 type_expr* t = type;
1040 while(t && t->obj != t_array) t = t->nxt;
1044 size.Format("[%d]", type->u.sz);
1045 _name = name + size;
1050 _name = CString("*") + name;
1051 if(type->nxt->obj == t_func || type->nxt->obj == t_funcdec)
1052 _name = CString("(") + _name + ")";
1054 return GetTypeString(type->nxt, _name) /*+
1055 (type->nxt->obj == t_funcdec || flag ? CString() : CString("*"))*/;
1061 CString str = type->obj == t_struct ? CString("struct ") : CString("union ");
1064 symentry_t* sym = (symentry_t*)type->sym;
1065 if(sym->sclass & c_typedef)
1066 str = CString(sym->id);
1068 str += CString(sym->id);
1069 return str + " " + name;
1074 ptr.Format("struct_%d", (unsigned int)type);
1076 if(AddStructType(type))
1079 struct_t* s = (struct_t*)type->u.inf;
1080 for(int i = 0; i < s->n; i++)
1082 str += GetTypeString(s->type[i]) + CString(";");
1084 str += CString("}");
1085 return str + " " + name;
1090 return str + " " + name;
1099 if(!type->nxt && !type->u.inf)
1101 CString str = GetTypeString(type->nxt);
1103 str1.Format("%s ( ", name);
1105 func_t* funcDesc = (func_t*)type->u.inf;
1106 parm_t* parmDesc = funcDesc->parm;
1107 for(int i = 0; i < funcDesc->Num - 1; i++)
1109 str += GetTypeString(parmDesc[i].type) + " ,";
1111 str += GetTypeString(parmDesc[i].type) + " )";
1120 ptr.Format("_%d", (int)type);
1121 CString _name = CString(name).IsEmpty() ? CString("array") + ptr : CString(name);
1122 ptr.Format("%d", type->u.sz);
1123 str = GetTypeString(type->nxt) + " " + name + "[" + ptr + "]";
1137 void CHawkApp::LoadModuleFunctions(LPCTSTR filename, LPCTSTR modulename)
1140 str.Format("Attaching module %s...", filename);
1141 SetStatusString(str);
1143 CStringArray* names = new CStringArray;
1144 EnumModuleFunctions(filename, *names);
1146 /* Now load all functions... */
1147 HMODULE module = LoadLibrary(filename);
1148 for(int j = 0; j < names->GetSize(); j++)
1150 LoadModuleFunction(module, (*names)[j], TRUE);
1154 plugin.m_handle = module;
1155 char buffer[_MAX_PATH];
1156 GetModuleFileName(module, buffer, _MAX_PATH);
1157 plugin.m_path = CString(buffer);
1158 strcpy(plugin.m_info.name, modulename);
1159 plugin.m_functions = names;
1160 plugin.m_GetFunctions = 0;
1161 plugin.m_GetInfo = 0;
1162 plugin.m_SetEiCCallback = 0;
1163 plugin.m_SetEiCStack = 0;
1164 plugin.m_SetErrLevel = 0;
1165 plugin.m_SetErrMark = 0;
1166 m_plugins.Add(plugin);
1169 BOOL CHawkApp::AddStructType(const type_expr *type)
1171 for(int i = 0; i < m_structTypes.GetSize(); i++)
1172 if(m_structTypes.GetData()[i] == (void*)type)
1175 m_structTypes.Add((void*)type);
1179 BOOL CHawkApp::Attach(string filename)
1182 str = string("#include \"") + filename + "\"";
1183 EiC_parseString(const_cast<char*>(str.c_str()));
1184 m_eicFiles.Add(CString(filename.c_str()));
1188 BOOL CHawkApp::EnumHeaders(LPCTSTR path)
1190 string data = string(path) + "\\wrappers.in";
1191 ifstream headers(data.c_str());
1193 while(!headers.eof())
1197 full = _path + "\\" + str;
1199 char _filename[_MAX_FNAME], _ext[_MAX_EXT];
1200 _splitpath(str.c_str(), 0, 0, _filename, _ext);
1201 string filename = string(_filename) + _ext;
1202 /* Found a header file or a folder. Remember it! */
1204 if(!finder.FindFile(full.c_str()))
1207 str.Format("Cannot find %s", full.c_str());
1211 finder.FindNextFile();
1212 if(finder.IsDirectory())
1214 m_includeDirs.push_back(str);
1218 m_includeFiles.push_back(filename);
1219 m_includeFilePath.push_back(full);
1226 BOOL CHawkApp::EnumModuleFunctions(LPCTSTR filename, CStringArray &names)
1229 HANDLE hFileMapping;
1232 CString errorMessage;
1233 errorMessage.Format("Failed to load the library %s", filename);
1235 char buffer[_MAX_PATH];
1237 int ret = SearchPath(0, filename, 0, _MAX_PATH, buffer, &filePart);
1240 AfxMessageBox(errorMessage);
1244 hFile = CreateFile(buffer, GENERIC_READ, FILE_SHARE_READ, NULL,
1245 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
1247 if ( hFile == INVALID_HANDLE_VALUE )
1249 AfxMessageBox(errorMessage);
1253 hFileMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
1254 if ( hFileMapping == 0 )
1257 AfxMessageBox(errorMessage);
1261 lpFileBase = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);
1262 if ( lpFileBase == 0 )
1264 CloseHandle(hFileMapping);
1266 AfxMessageBox(errorMessage);
1270 PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)lpFileBase;
1271 if(dosHeader->e_magic != IMAGE_DOS_SIGNATURE)
1273 CString errorMessage;
1274 errorMessage.Format("The file %s does not appear to be a valid dynamic link library.", buffer);
1275 AfxMessageBox(errorMessage);
1279 #define MakePtr( cast, ptr, addValue ) (cast)( (DWORD)(ptr) + (addValue) )
1281 PIMAGE_NT_HEADERS pNTHeader;
1282 DWORD base = (DWORD)dosHeader;
1283 PIMAGE_EXPORT_DIRECTORY exportDir;
1286 pNTHeader = MakePtr( PIMAGE_NT_HEADERS, dosHeader,
1287 dosHeader->e_lfanew );
1288 PIMAGE_OPTIONAL_HEADER optionalHeader = &pNTHeader->OptionalHeader;
1289 exportDir = MakePtr(PIMAGE_EXPORT_DIRECTORY, base,
1290 optionalHeader->DataDirectory[0].VirtualAddress);
1291 char** name = MakePtr(char**, base, exportDir->AddressOfNames);
1293 for (UINT i = 0; i < exportDir->NumberOfNames; i++)
1295 const char* str = *(name + i) + base;
1297 for(const char* p = str; *p != 0; p++)
1300 if((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_' || (c >= '0' && c <= '9'))
1313 UnmapViewOfFile(lpFileBase);
1314 CloseHandle(hFileMapping);
1320 BOOL CHawkApp::LoadModuleFunction(HMODULE handle, LPCTSTR name, BOOL isOpenCV)
1322 if( !strcmp(name, "cvCreateTrackbar" ) ||
1323 !strcmp(name, "cvSetMouseCallback" ) )
1324 return TRUE; //the wrapper should not be created automatically
1326 FARPROC addr = GetProcAddress(handle, name);
1327 if(GenAutoWrapper(addr, name) == -2)
1332 str.Format("Function %s takes a function pointer as input.\n\
1333 This function will not be available in the current Hawk session.\nRefer fo the documentation for further details",
1341 BOOL CHawkApp::LoadModules()
1343 /* First of all, look for plugins that have a PLUG_ALL option */
1344 for(int i = 0; i < m_plugins.GetSize(); i++)
1346 plugin_t& plugin = m_plugins[i];
1347 if(plugin.m_info.type == PLUG_ALL)
1349 /* Initialize the rest of functions with universal wrappers */
1351 EnumModuleFunctions(plugin.m_info.library_path, all);
1352 HMODULE module = LoadLibrary(plugin.m_info.library_path);
1353 for(int i = 0; i < all.GetSize(); i++)
1356 if(!FindStringInArray(*plugin.m_functions, all[i]))
1358 LoadModuleFunction(module, all[i], TRUE);
1369 extern keyword_t cwords[];
1371 CString CHawkApp::GenDecl(const char *name)
1373 symentry_t* sym = EiC_lookup(1, const_cast<char*>(name));
1375 return CString(""); // Name not found
1377 // Make sure this is not a simple keyword or typedef
1378 if(EiC_iskeyword(cwords, const_cast<char*>(name), 36) ||
1379 (sym->sclass & c_typedef))
1383 return GetTypeString(sym->type, name);
1386 CFuncDialog* CHawkApp::GetFuncDialog(int index)
1388 return (CFuncDialog*)m_funcDialogs[index];
1391 void CHawkApp::InitPopupDialogs()
1393 for(int i = 0; i < m_plugins.GetSize(); i++)
1395 /* Initialize the context dialog */
1396 CFuncDialog* dlg = new CFuncDialog;
1397 dlg->SetModuleName(m_plugins.GetData()[i].m_info.name);
1398 m_funcDialogs.Add(dlg);